text:
#include "Common/Common.h"
#include "Demos/Visualization/MiniGL.h"
#include "Demos/Visualization/Selection.h"
#include "GL/glut.h"
#include "Simulation/TimeManager.h"
#include <Eigen/Dense>
#include "Simulation/SimulationModel.h"
#include "Simulation/TimeStepController.h"
#include <iostream>
#include "Demos/Visualization/Visualization.h"
#include "Simulation/DistanceFieldCollisionDetection.h"
#include "Utils/OBJLoader.h"
#include "Utils/Logger.h"
#include "Utils/Timing.h"
#include "Utils/FileSystem.h"
#include "Demos/Common/DemoBase.h"
#include "Demos/Common/TweakBarParameters.h"
#include "Simulation/Simulation.h"

#include "Utils/PDPJConverter.h"
 #include "ShapeOpGL/mesh.h"
 #include "Utils/MyUtil.h"

 #include <memory>
 #include <opencv2/opencv.hpp>
 #include <unistd.h>
#include <string>
#include <jsoncpp/json/json.h>
#include <sys/stat.h>
#include <boost/filesystem/path.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/filesystem/exception.hpp>
#include <boost/filesystem/convenience.hpp>

#include <stdlib.h>

// Enable memory leak detection
#if defined(_DEBUG) && !defined(EIGEN_ALIGN)
	#define new DEBUG_NEW
#endif

using namespace PBD;
using namespace Eigen;
using namespace std;
using namespace Utilities;

void timeStep ();
void buildModel ();
void createMesh();
void render ();
void reset();
void initParameters();
void TW_CALL setBendingMethod(const void *value, void *clientData);
void TW_CALL getBendingMethod(void *value, void *clientData);
void TW_CALL setSimulationMethod(const void *value, void *clientData);
void TW_CALL getSimulationMethod(void *value, void *clientData);

// const int nRows = 50;
// const int nCols = 50;
// const Real width = 10.0;
// const Real height = 10.0;
// short simulationMethod = 2;
// short bendingMethod = 2;
// bool doPause = true;
// DemoBase *base;

/////シミュレーション設定
const int nRows = 41;
const int nCols = nRows;

const int reducted = 2;
const int span = (nRows-1)/reducted;
// const int rad = 2;
// float radius =
const Real width = 10.0;
const Real height = 10.0;
short simulationMethod = 2;
short bendingMethod = 2;
DemoBase *base;

/////実験設定GLOBAL
std::string idf = "default_collision";
std::string idf_itr = "0";
int max_itr = 1;
int precompute_max_itr = 40;
int substeps = 40;
double frametime;
float rate = 1.0;
double num_frames  = 1500;
float k = 0.8;
float coll_max_speed = 2.0;
int precompute_substeps = 1;
float adap_rate = 0.01;

float custom;

//SLOPE
bool slope = false;
float ikichi = -1;

bool if_render = true;
bool img_render = if_render;
bool output_position = false;
bool if_dummy = false;
bool if_dummy_3 = false;
bool custom_bool = true;
bool custom_bool2 = true;
bool custom_bool3 = true;
bool custom_bool4 = true;
bool output_obj = false;
bool adap_dummy = false;
bool adams_1 = false;

/////GLOBAL変数
float old_energy = -1;
float old_inc = -1;
int image_itr = 0;
std::shared_ptr<ShapeOpSurfaceMesh> s1;
MAverage a(3);
MAverage amp(30);
// std::make_shared<std::vector<bool>> violated;
int neo_dummy = 1;

int hold_phase = 0;
//0: neutral N
//1: up to zero S - L
//2: up from zero L - S
//3: down to zero S - L
//4: down from zero L - S
float hold_phase_inc = 0;

////ファイル出力
std::ofstream o_pos;
// std::ofstream o_vel;

std::ofstream energy;
// std::ofstream energy_inc;
// std::ofstream inc_inc;

// std::ofstream neo_substep;
// std::ofstream sub_force;

// std::ofstream estimate_force;
std::ofstream precompute_error;

// std::ofstream slope_state;

// std::ofstream est_amp;
// std::ofstream out_offset;

// std::ofstream ConstError;

std::ofstream dummy_violate;

std::ofstream cost_log;

DistanceFieldCollisionDetection cd;

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

	//LOCAL Configure
	bool config_file = false;
	double hz = 30.0;
	double damping = 1.0;
	double masses = 0.1;
	double TriangleConstraint = 1000.0;

	//引数回収
	if (argc > 1){//ファイルから設定
		config_file = (bool)atoi(argv[1]);
		if (config_file) std::cout << "Configure by File" << std::endl;
	}
	std::cout << argc << std::endl;
	if(argc > 6){
		for(int i=2; i<argc; i++){
			switch(i){
			case 2: substeps = (float)atoi(argv[i]);
			case 3: max_itr =  atoi(argv[i]);
			case 4: hz =  atoi(argv[i]);
			case 5: damping =  atoi(argv[i]);
			case 6: idf =  argv[i];
			case 7: idf_itr =  argv[i];
			case 8: output_position = (bool)atoi(argv[i]);
			case 9: slope = (bool)atoi(argv[i]);
			case 10: ikichi = (float)atof(argv[i]);
			case 11: num_frames = atoi(argv[i]);
			case 12: rate = atof(argv[i]);
			case 13: if_render = (bool)atoi(argv[i]);
			case 14: custom = (float)atof(argv[i]);
			case 15: if_dummy = (bool)atoi(argv[i]);
			case 16: custom_bool = (bool)atoi(argv[i]);
			case 17: custom_bool2 = (bool)atoi(argv[i]);
			case 18: neo_dummy =  atoi(argv[i]);
			case 19: if_dummy_3 = (bool)atoi(argv[i]);
			case 20: custom_bool3 = (bool)atoi(argv[i]);
			case 21: precompute_max_itr = atoi(argv[i]);
			case 22: k = (float)atof(argv[i]);
			case 23: coll_max_speed = (float)atof(argv[i]);
			case 24: output_obj = (bool)atoi(argv[i]);
			case 25: adap_dummy = (bool)atoi(argv[i]);
			case 26: precompute_substeps = (int)atoi(argv[i]);
			case 27: adap_rate = (float)atof(argv[i]);
			case 28: adams_1 = (bool)atoi(argv[i]);
			}
		}
	}
	if_render = img_render || if_render;

	if(config_file){
		std::ifstream ifs("/home/octan/デスクトップ/PositionBasedDynamics/Demos/ClothDemo/ClothConfig");
		std::string str;

		if (ifs.fail()) {
			std::cerr << "Failed to open file." << std::endl;
			return -1;
		}
		while (getline(ifs, str)) {
			int num = str.find_first_of(":");
			std::string key = str.substr(0, num);
			std::string value = str.substr(num+1, str.size());
			if(key == "damping") damping = std::stod(value.c_str());
			if(key == "substeps") substeps = std::stod(value.c_str());
			if(key == "max_itr") max_itr = std::stod(value.c_str());
			if(key == "TriangleConstraint") TriangleConstraint  = std::stod(value.c_str());
			if(key == "hz") hz  = std::stod(value.c_str());
			if(key == "masses") masses  = std::stod(value.c_str());
		}
	}
	img_render = if_render;

	frametime = 1.0/hz;
	std::cout << "frametime: " << frametime << "substeps: " << substeps << " , max_itr: " << max_itr << std::endl;
	if(if_dummy){
		if(if_dummy_3){
			if(substeps != 1 && substeps%3 != 0){
				std::cout << "ステップ数が不正です" << std::endl;
				exit(1);
			}

		}
		else{
			if(substeps != 1 && substeps%2 != 0){
				std::cout << "ステップ数が不正です" << std::endl;
				exit(1);
			}

		}
	}

	//フォルダ初期化
	const char *dir = ("../output/"+idf).c_str();
    struct stat statBuf;

    if (stat(("../output/"+idf).c_str(), &statBuf) == 0)
        printf("ディレクトリ%sは存在します。\n", dir);
    else{
		mkdir(("../output/"+idf).c_str(),  0777);
        printf("ディレクトリ%sは存在しません。\n。", dir);
	}

	mkdir(("../output/"+idf+"/"+idf_itr).c_str(),  0777);
	mkdir(("../output/"+idf+"/"+idf_itr+"/images").c_str(),  0777);
	boost::filesystem::remove_all("../output/"+idf+"/"+idf_itr+"/image");

		mkdir(("../output/"+idf+"/"+idf_itr+"/objs").c_str(),  0777);
	// boost::filesystem::remove_all("../output/"+idf+"/"+idf_itr+"/objs");

	boost::filesystem::remove("../output/"+idf+"/"+idf_itr+"/enrgy_data");
	energy = std::ofstream("../output/"+idf+"/"+idf_itr+"/enrgy_data", std::ios::app);

	boost::filesystem::remove("../output/"+idf+"/"+idf_itr+"/positions_data");
	o_pos = std::ofstream("../output/"+idf+"/"+idf_itr+"/positions_data", std::ios::app);

	boost::filesystem::remove("../output/"+idf+"/"+idf_itr+"/outputconfig");
	std::ofstream outputconfig("../output/"+idf+"/"+idf_itr+"/outputconfig", std::ios::app);

	boost::filesystem::remove("../output/"+idf+"/"+idf_itr+"/precompute_error");
	precompute_error = std::ofstream("../output/"+idf+"/"+idf_itr+"/precompute_error", std::ios::app);

	boost::filesystem::remove("../output/"+idf+"/"+idf_itr+"/cost_log");
	cost_log = std::ofstream("../output/"+idf+"/"+idf_itr+"/cost_log", std::ios::app);

	boost::filesystem::remove("../output/"+idf+"/"+idf_itr+"/dummy_violate");
	dummy_violate = std::ofstream("../output/"+idf+"/"+idf_itr+"/dummy_violate", std::ios::app);

	REPORT_MEMORY_LEAKS

	base = new DemoBase();
	base->init(argc, argv, "Cloth demo");

	SimulationModel *model = new SimulationModel();
	model->init();
	Simulation::getCurrent()->setModel(model);

	buildModel();

	initParameters();

	Simulation::getCurrent()->setSimulationMethodChangedCallback([&]() { reset(); initParameters(); base->getSceneLoader()->readParameterObject(Simulation::getCurrent()->getTimeStep()); });

	// OpenGL
	MiniGL::setClientIdleFunc (5, timeStep);
	MiniGL::setKeyFunc(0, 'r', reset);
	MiniGL::setClientSceneFunc(render);
	MiniGL::setViewport (40.0f, 0.1f, 500.0f, Vector3r (5.0, 10.0, 30.0), Vector3r (5.0, 0.0, 0.0));

	// TwType enumType2 = TwDefineEnum("SimulationMethodType", NULL, 0);
	// TwAddVarCB(MiniGL::getTweakBar(), "SimulationMethod", enumType2, setSimulationMethod, getSimulationMethod, &simulationMethod, " label='Simulation method' enum='0 {None}, 1 {Distance constraints}, 2 {FEM based PBD}, 3 {Strain based dynamics}' group=Simulation");
	// TwType enumType3 = TwDefineEnum("BendingMethodType", NULL, 0);
	// TwAddVarCB(MiniGL::getTweakBar(), "BendingMethod", enumType3, setBendingMethod, getBendingMethod, &bendingMethod, " label='Bending method' enum='0 {None}, 1 {Dihedral angle}, 2 {Isometric bending}' group=Bending");

	auto n1 = std::make_shared<GLSurfaceMeshObject>("buf_cloth_collision.obj", Eigen::Vector3f(1.0f, 0.5f, 0.5f));
    Eigen::Matrix4f mat = Eigen::Matrix4f::Identity();  mat(0, 3) = -1.4;

	float stretching = 1000;
	// float pin  = 1000;

    s1 = std::make_shared<ShapeOpSurfaceMesh>(n1, frametime / substeps, damping, masses, TriangleConstraint);
    s1->addStretching(stretching);
    s1->addTriangleStrain(TriangleConstraint);
	s1->initsolver(true, masses, damping, frametime / substeps);//kokoppoi
	s1->Solver().set_coll_max_speed(coll_max_speed);
	s1->Solver().setPBDmodel(model);

	outputconfig << "/////////////////////////////////////////////////////////" << std::endl;
	outputconfig <<  "substeps: " <<  substeps  << std::endl;
	outputconfig <<  "max_itr: "  <<  max_itr  << std::endl;
	outputconfig <<  "hz: " <<  hz  << std::endl;
	outputconfig <<  "damping: " <<  damping  << std::endl;
	outputconfig <<  "idf: " <<  idf << std::endl;
	outputconfig <<  "idf_itr: " <<  idf_itr  << std::endl;
	outputconfig <<  "output_position: " <<  output_position  << std::endl;
	outputconfig <<  "slope: " <<  slope  << std::endl;
	outputconfig << "ikichi: "  << ikichi  << std::endl;
	outputconfig <<  "num_frames: " <<  num_frames  << std::endl;
	outputconfig <<  "rate: " << rate << std::endl;
	outputconfig <<  "if_render: " <<  if_render  << std::endl;
	outputconfig <<  "custom: " <<  custom << std::endl;
	outputconfig <<  "if_dummy: " <<  if_dummy  << std::endl;
	outputconfig <<  "custom_bool: " <<  custom_bool << std::endl;
	outputconfig <<  "custom_bool2: " <<  custom_bool2  << std::endl;
	outputconfig <<  "neo_dummy: " <<  neo_dummy << std::endl;
	outputconfig <<  "if_dummy_3: " <<  if_dummy_3  << std::endl;
	outputconfig <<  "custom_bool3: " <<  custom_bool3  << std::endl;

	outputconfig <<  "stretching: " <<  stretching  << std::endl;
	outputconfig <<  "TriangleConstraint: " <<  TriangleConstraint  << std::endl;
	// outputconfig <<  "pin: " <<  pin  << std::endl;
	outputconfig <<  "nRowss: " <<  nRows  << std::endl;
	outputconfig << "coll_max_speed: " << std::endl;

	outputconfig << "/////////////////////////" << std::endl;

	std::cout << "/////////////////////////////////////////////////////////" << std::endl;

    std::cout << "damping: " << damping << std::endl;
    std::cout << "timestep: " << frametime / substeps << std::endl;
	std::cout << "substeps: " << substeps << std::endl;
	std::cout << "frametime: " << frametime << std::endl;
    std::cout << "masses: " << masses << std::endl;
	std::cout << "ikichi(): " << ikichi << std::endl;
	std::cout << "slope: " << slope << std::endl;
	std::cout << "dummy: " << if_dummy << std::endl;
	std::cout << "num_frames: " << num_frames << std::endl;
	std::cout << "/////////////////////////" << std::endl;

	glutMainLoop ();

	base->cleanup ();

	Utilities::Timing::printAverageTimes();
	Utilities::Timing::printTimeSums();

	delete Simulation::getCurrent();
	delete base;
	delete model;

	return 0;
}

void initParameters()
{
	TwRemoveAllVars(MiniGL::getTweakBar());
	TweakBarParameters::cleanup();

	MiniGL::initTweakBarParameters();

	TweakBarParameters::createParameterGUI();
	TweakBarParameters::createParameterObjectGUI(base);
	TweakBarParameters::createParameterObjectGUI(Simulation::getCurrent());
	TweakBarParameters::createParameterObjectGUI(Simulation::getCurrent()->getModel());
	TweakBarParameters::createParameterObjectGUI(Simulation::getCurrent()->getTimeStep());
}

void reset()
{
	Utilities::Timing::printAverageTimes();
	Utilities::Timing::reset();

	Simulation::getCurrent()->reset();
	base->getSelectedParticles().clear();

	Simulation::getCurrent()->getModel()->cleanup();

	buildModel();
}

void timeStep ()
{
	if(image_itr > num_frames) {
		std::cout << "EXIT by num_Frames" << std::endl;
		std::cout << std::endl;
		Utilities::Timing::printAverageTimes();
		Utilities::Timing::printTimeSums();
		Utilities::Timing::printAverageTimes_F(cost_log);
		Utilities::Timing::printTimeSums_F(cost_log);
		exit(1);
	}

	START_TIMING("Frame");

	const Real pauseAt = base->getValue<Real>(DemoBase::PAUSE_AT);
	if ((pauseAt > 0.0) && (pauseAt < TimeManager::getCurrent()->getTime()))
		base->setValue(DemoBase::PAUSE, true);

	if (base->getValue<bool>(DemoBase::PAUSE))
		return;

	// Simulation code
	SimulationModel *model = Simulation::getCurrent()->getModel();
	// const unsigned int numSteps = base->getValue<unsigned int>(DemoBase::NUM_STEPS_PER_RENDER);

	// for (unsigned int i = 0; i < numSteps; i++)
	// {
	// 	START_TIMING("SimStep");
	// 	// Simulation::getCurrent()->getTimeStep()->step(*model);
	// 	STOP_TIMING_AVG;
	// }

	//Precompute_error
	START_TIMING("PrecomputeError");
	if(custom_bool3){
		s1->Solver().init_alternative();
		s1->Solver().advance_collision(max_itr, frametime);
		for (unsigned int i = 0; i < substeps; i++){
			s1->Solver().alt_solve(precompute_max_itr, frametime/substeps);
		}
	}
	STOP_TIMING_AVG;

	int dum_num;
	if(if_dummy_3) dum_num = 3;
	else dum_num = 2;
	int num_violate = 0;

	START_TIMING("Simulation");
	if(if_dummy){
		s1->Solver().advance_collision(max_itr, frametime);
		for(unsigned int i = 0; i < substeps; i++){
			START_TIMING("SimStep");
			if(i%dum_num == 0){
				s1->Solver().initDummy();
				for(int j=0; j<neo_dummy; j++) s1->Solver().dummy_solve( ((frametime/substeps) * 1 ) / neo_dummy, false, true);
			}
			else if(i%dum_num == 1){
				s1->Solver().solve(max_itr, (frametime/substeps) * 1, false, true);
				if(custom_bool) num_violate = s1->Solver().closeDummy((frametime/substeps)  * 1, nRows, k);
				dummy_violate << num_violate << ", ";
			}
			else if(i%dum_num == 2) s1->Solver().solve(max_itr, (frametime/substeps) * 1, false, true);
			STOP_TIMING_AVG;
		}

		// if(if_dummy_3){
		// 	s1->Solver().advance_collision(max_itr, frametime);
		// 	for (unsigned int i = 0; i < substeps/3; i++){
		// 		START_TIMING("SimStep");
		// 			s1->Solver().initDummy();
		// 			for(int j=0; j<neo_dummy; j++) s1->Solver().dummy_solve( ((frametime/substeps) * 1 ) / neo_dummy, false, true);
		// 			s1->Solver().solve(max_itr, (frametime/substeps) * 1, false, true);
		// 			if(custom_bool) s1->Solver().closeDummy((frametime/substeps)  * 1, nRows);
		// 			s1->Solver().solve(max_itr, (frametime/substeps) * 1, false, true);
		// 		STOP_TIMING_AVG;
		// 	}
		// }
		// else{
		// 	s1->Solver().advance_collision(max_itr, frametime);
		// 	for (unsigned int i = 0; i < substeps/2; i++){
		// 		START_TIMING("SimStep");
		// 			s1->Solver().initDummy();
		// 			for(int j=0; j<neo_dummy; j++) s1->Solver().dummy_solve( ((frametime/substeps) * 1 ) / neo_dummy, false, true);
		// 			s1->Solver().solve(max_itr, (frametime/substeps) * 1, false, true);
		// 			if(custom_bool) s1->Solver().closeDummy((frametime/substeps)  * 1, nRows);
		// 		STOP_TIMING_AVG;
		// 	}
		// }

	}
	else{
	if(adams_1){
			s1->Solver().advance_collision(max_itr, frametime);
			for (unsigned int i = 0; i < substeps; i++)
			{
				START_TIMING("SimStep");
					// s1->process(max_itr, image_itr, frametime/substeps);//ここが一番スタンダード
					s1->Solver().adams_solve_1(max_itr, frametime/substeps, false, true);//ここが一番スタンダード
				STOP_TIMING_AVG;
			}
			// record_velocities(o_vel, solver_.getVelocities());
			// record_velocities(o_pos, solver_.getPoints());

		}
		else{
			//通常営業
				s1->Solver().advance_collision(max_itr, frametime);
				for (unsigned int i = 0; i < substeps; i++)
				{
					START_TIMING("SimStep");
						s1->Solver().solve(max_itr, frametime/substeps, false, true);	//ここが一番スタンダード
					STOP_TIMING_AVG;
					// record_velocities(o_vel, solver_.getVelocities());
					// record_velocities(o_pos, solver_.getPoints());
				}
			//通常営業
		}
	}

	STOP_TIMING_AVG;

	START_TIMING("PostProcessing");

	ParticleData &pd = model->getParticles();
	const ShapeOp::Matrix3X p = s1->getSolver();
	if(custom_bool3){
		const ShapeOp::Matrix3X p2 = s1->Solver().getPoints2();
		float error = 0;
		for (int i = 0; i < (int) pd.size(); i++){
			error += (p2.col(i) - p.col(i)).norm();
		}
		precompute_error << error/(float)p.cols() << ", ";
	}

	#pragma omp for schedule(static)
	for (int i = 0; i < (int) pd.size(); i++) updatePJ(pd.getPosition(i), p, i);
	#pragma omp for schedule(static)
	for (int i = 0; i < (int) pd.size(); i++) updatePJ(pd.getVelocity(i), s1->Solver().getVelocities(), i);

	#pragma omp for schedule(static)
	for (unsigned int i = 0; i < model->getTriangleModels().size(); i++) model->getTriangleModels()[i]->updateMeshNormals(model->getParticles());

	for (unsigned int i = 0; i < model->getTriangleModels().size(); i++)
		model->getTriangleModels()[i]->updateMeshNormals(model->getParticles());

	//OpenCV
	if(img_render&&if_render){
		MiniGL::display ();
		int w = 1024;    int h = 768;
		cv::Mat_<cv::Vec3b> image(h,w);
		glReadPixels(0, 0, w, h, GL_BGR, GL_UNSIGNED_BYTE, image.data);
		cv::flip(image, image, 0);
		cv::imwrite("../output/"+idf+"/"+idf_itr+"/images/"+std::to_string(image_itr)+".png", image);
	}

	energy << (float)s1->compute_energy() << ", ";
	record_positions(o_pos, pd);
	TriangleModel::ParticleMesh &VM = model->getTriangleModels()[0]->getParticleMesh();
	if(output_obj) record__vismesh_obj(VM, pd, "../output/"+idf+"/"+idf_itr+"/objs/meshes"+std::to_string(image_itr)+".obj");
	image_itr++;

	STOP_TIMING_AVG;//PostProcessing
	STOP_TIMING_AVG;//Frame
}

void loadObj(const std::string &filename, VertexData &vd, IndexedFaceMesh &mesh, const Vector3r &scale)
{
	std::vector<OBJLoader::Vec3f> x;
	std::vector<OBJLoader::Vec3f> normals;
	std::vector<OBJLoader::Vec2f> texCoords;
	std::vector<MeshFaceIndices> faces;
	OBJLoader::Vec3f s = { (float)scale[0], (float)scale[1], (float)scale[2] };
	OBJLoader::loadObj(filename, &x, &faces, &normals, &texCoords, s);

	mesh.release();
	const unsigned int nPoints = (unsigned int)x.size();
	const unsigned int nFaces = (unsigned int)faces.size();
	const unsigned int nTexCoords = (unsigned int)texCoords.size();
	mesh.initMesh(nPoints, nFaces * 2, nFaces);
	vd.reserve(nPoints);
	for (unsigned int i = 0; i < nPoints; i++)
	{
		vd.addVertex(Vector3r(x[i][0], x[i][1], x[i][2]));
	}
	for (unsigned int i = 0; i < nTexCoords; i++)
	{
		mesh.addUV(texCoords[i][0], texCoords[i][1]);
	}
	for (unsigned int i = 0; i < nFaces; i++)
	{
		// Reduce the indices by one
		int posIndices[3];
		int texIndices[3];
		for (int j = 0; j < 3; j++)
		{
			posIndices[j] = faces[i].posIndices[j] - 1;
			if (nTexCoords > 0)
			{
				texIndices[j] = faces[i].texIndices[j] - 1;
				mesh.addUVIndex(texIndices[j]);
			}
		}

		mesh.addFace(&posIndices[0]);
	}
	mesh.buildNeighbors();

	mesh.updateNormals(vd, 0);
	mesh.updateVertexNormals(vd);

	LOG_INFO << "Number of triangles: " << nFaces;
	LOG_INFO << "Number of vertices: " << nPoints;
}

void buildModel ()
{
	TimeManager::getCurrent ()->setTimeStepSize (static_cast<Real>(0.005));

	createMesh();

	// create static rigid body
	string fileName = FileSystem::normalizePath(base->getDataPath() + "/models/cube.obj");
	IndexedFaceMesh mesh;
	VertexData vd;
	loadObj(fileName, vd, mesh, Vector3r::Ones());

	string fileNameTorus = FileSystem::normalizePath(base->getDataPath() + "/models/torus.obj");
	IndexedFaceMesh meshTorus;
	VertexData vdTorus;
	loadObj(fileNameTorus, vdTorus, meshTorus, Vector3r::Ones());

	SimulationModel *model = Simulation::getCurrent()->getModel();
	SimulationModel::RigidBodyVector &rb = model->getRigidBodies();
	rb.resize(2);

	// floor
	rb[0] = new RigidBody();
	rb[0]->initBody(1.0,
		Vector3r(0.0, -5.5, 0.0),
		Quaternionr(1.0, 0.0, 0.0, 0.0),
		vd, mesh,
		Vector3r(100.0, 1.0, 100.0));
	rb[0]->setMass(0.0);

	// torus
	rb[1] = new RigidBody();
	rb[1]->initBody(1.0,
		Vector3r(5.0, -1.5, 5.0),
		Quaternionr(1.0, 0.0, 0.0, 0.0),
		vdTorus, meshTorus,
		Vector3r(2.0, 2.0, 2.0));
	rb[1]->setMass(0.0);
	rb[1]->setFrictionCoeff(static_cast<Real>(0.1));

	Simulation::getCurrent()->getTimeStep()->setCollisionDetection(*model, &cd);
	cd.setTolerance(static_cast<Real>(0.1));

	const std::vector<Vector3r> *vertices1 = rb[0]->getGeometry().getVertexDataLocal().getVertices();
	const unsigned int nVert1 = static_cast<unsigned int>(vertices1->size());
	cd.addCollisionBox(0, CollisionDetection::CollisionObject::RigidBodyCollisionObjectType, &(*vertices1)[0], nVert1, Vector3r(100.0, 1.0, 100.0));

	const std::vector<Vector3r> *vertices2 = rb[1]->getGeometry().getVertexDataLocal().getVertices();
	const unsigned int nVert2 = static_cast<unsigned int>(vertices2->size());
	cd.addCollisionTorus(1, CollisionDetection::CollisionObject::RigidBodyCollisionObjectType, &(*vertices2)[0], nVert2, Vector2r(2.0, 1.0));

	SimulationModel::TriangleModelVector &tm = model->getTriangleModels();
	ParticleData &pd = model->getParticles();
	for (unsigned int i = 0; i < tm.size(); i++)
	{
		const unsigned int nVert = tm[i]->getParticleMesh().numVertices();
		unsigned int offset = tm[i]->getIndexOffset();
		tm[i]->setFrictionCoeff(static_cast<Real>(0.1));
		cd.addCollisionObjectWithoutGeometry(i, CollisionDetection::CollisionObject::TriangleModelCollisionObjectType, &pd.getPosition(offset), nVert, true);
	}
}

void render ()
{
	base->render();
}

/** Create a particle model mesh
*/
void createMesh()
{
	TriangleModel::ParticleMesh::UVs uvs;
	uvs.resize(nRows*nCols);

	const Real dy = width / (Real)(nCols-1);
	const Real dx = height / (Real)(nRows-1);

	Vector3r points[nRows*nCols];
	for (int i = 0; i < nRows; i++)
	{
		for (int j = 0; j < nCols; j++)
		{
			const Real y = (Real)dy*j;
			const Real x = (Real)dx*i;
			points[i*nCols + j] = Vector3r(x, 1.0, y);

			uvs[i*nCols + j][0] = x/width;
			uvs[i*nCols + j][1] = y/height;
		}
	}
	const int nIndices = 6 * (nRows - 1)*(nCols - 1);

	TriangleModel::ParticleMesh::UVIndices uvIndices;
	uvIndices.resize(nIndices);

	unsigned int indices[nIndices];
	int index = 0;
	for (int i = 0; i < nRows - 1; i++)
	{
		for (int j = 0; j < nCols - 1; j++)
		{
			int helper = 0;
			if (i % 2 == j % 2)
				helper = 1;

			indices[index] = i*nCols + j;
			indices[index + 1] = i*nCols + j + 1;
			indices[index + 2] = (i + 1)*nCols + j + helper;

			uvIndices[index] = i*nCols + j;
			uvIndices[index + 1] = i*nCols + j + 1;
			uvIndices[index + 2] = (i + 1)*nCols + j + helper;
			index += 3;

			indices[index] = (i + 1)*nCols + j + 1;
			indices[index + 1] = (i + 1)*nCols + j;
			indices[index + 2] = i*nCols + j + 1 - helper;

			uvIndices[index] = (i + 1)*nCols + j + 1;
			uvIndices[index + 1] = (i + 1)*nCols + j;
			uvIndices[index + 2] = i*nCols + j + 1 - helper;
			index += 3;
		}
	}

	SimulationModel *model = Simulation::getCurrent()->getModel();
	model->addTriangleModel(nRows*nCols, nIndices / 3, &points[0], &indices[0], uvIndices, uvs);

	write_mymesh(nRows*nCols, nIndices / 3, &points[0], &indices[0], uvIndices, uvs,
				model->getTriangleModels()[0]->getParticleMesh().getVertexNormals(),
				"buf_cloth_collision.obj");
	//頂点数、三角形数、頂点配列、三角形配列、uv配列、uv配列

	ParticleData &pd = model->getParticles();
	for (unsigned int i = 0; i < pd.getNumberOfParticles(); i++)
	{
		pd.setMass(i, 1.0);
	}

	// init constraints
	for (unsigned int cm = 0; cm < model->getTriangleModels().size(); cm++)
	{
		if (simulationMethod == 1)
		{
			const unsigned int offset = model->getTriangleModels()[cm]->getIndexOffset();
			const unsigned int nEdges = model->getTriangleModels()[cm]->getParticleMesh().numEdges();
			const IndexedFaceMesh::Edge *edges = model->getTriangleModels()[cm]->getParticleMesh().getEdges().data();
			for (unsigned int i = 0; i < nEdges; i++)
			{
				const unsigned int v1 = edges[i].m_vert[0] + offset;
				const unsigned int v2 = edges[i].m_vert[1] + offset;

				model->addDistanceConstraint(v1, v2);
			}
		}
		else if (simulationMethod == 2)
		{
			const unsigned int offset = model->getTriangleModels()[cm]->getIndexOffset();
			TriangleModel::ParticleMesh &mesh = model->getTriangleModels()[cm]->getParticleMesh();
			const unsigned int *tris = mesh.getFaces().data();
			const unsigned int nFaces = mesh.numFaces();
			for (unsigned int i = 0; i < nFaces; i++)
			{
				const unsigned int v1 = tris[3 * i] + offset;
				const unsigned int v2 = tris[3 * i + 1] + offset;
				const unsigned int v3 = tris[3 * i + 2] + offset;
				model->addFEMTriangleConstraint(v1, v2, v3);
			}
		}
		else if (simulationMethod == 3)
		{
			const unsigned int offset = model->getTriangleModels()[cm]->getIndexOffset();
			TriangleModel::ParticleMesh &mesh = model->getTriangleModels()[cm]->getParticleMesh();
			const unsigned int *tris = mesh.getFaces().data();
			const unsigned int nFaces = mesh.numFaces();
			for (unsigned int i = 0; i < nFaces; i++)
			{
				const unsigned int v1 = tris[3 * i] + offset;
				const unsigned int v2 = tris[3 * i + 1] + offset;
				const unsigned int v3 = tris[3 * i + 2] + offset;
				model->addStrainTriangleConstraint(v1, v2, v3);
			}
		}
		if (bendingMethod != 0)
		{
			const unsigned int offset = model->getTriangleModels()[cm]->getIndexOffset();
			TriangleModel::ParticleMesh &mesh = model->getTriangleModels()[cm]->getParticleMesh();
			unsigned int nEdges = mesh.numEdges();
			const TriangleModel::ParticleMesh::Edge *edges = mesh.getEdges().data();
			const unsigned int *tris = mesh.getFaces().data();
			for (unsigned int i = 0; i < nEdges; i++)
			{
				const int tri1 = edges[i].m_face[0];
				const int tri2 = edges[i].m_face[1];
				if ((tri1 != 0xffffffff) && (tri2 != 0xffffffff))
				{
					// Find the triangle points which do not lie on the axis
					const int axisPoint1 = edges[i].m_vert[0];
					const int axisPoint2 = edges[i].m_vert[1];
					int point1 = -1;
					int point2 = -1;
					for (int j = 0; j < 3; j++)
					{
						if ((tris[3 * tri1 + j] != axisPoint1) && (tris[3 * tri1 + j] != axisPoint2))
						{
							point1 = tris[3 * tri1 + j];
							break;
						}
					}
					for (int j = 0; j < 3; j++)
					{
						if ((tris[3 * tri2 + j] != axisPoint1) && (tris[3 * tri2 + j] != axisPoint2))
						{
							point2 = tris[3 * tri2 + j];
							break;
						}
					}
					if ((point1 != -1) && (point2 != -1))
					{
						const unsigned int vertex1 = point1 + offset;
						const unsigned int vertex2 = point2 + offset;
						const unsigned int vertex3 = edges[i].m_vert[0] + offset;
						const unsigned int vertex4 = edges[i].m_vert[1] + offset;
						if (bendingMethod == 1)
							model->addDihedralConstraint(vertex1, vertex2, vertex3, vertex4);
						else if (bendingMethod == 2)
							model->addIsometricBendingConstraint(vertex1, vertex2, vertex3, vertex4);
					}
				}
			}
		}
	}

	LOG_INFO << "Number of triangles: " << nIndices / 3;
	LOG_INFO << "Number of vertices: " << nRows*nCols;

}

void TW_CALL setBendingMethod(const void *value, void *clientData)
{
	const short val = *(const short *)(value);
	*((short*)clientData) = val;
	reset();
}

void TW_CALL getBendingMethod(void *value, void *clientData)
{
	*(short *)(value) = *((short*)clientData);
}

void TW_CALL setSimulationMethod(const void *value, void *clientData)
{
	const short val = *(const short *)(value);
	*((short*)clientData) = val;
	reset();
}

void TW_CALL getSimulationMethod(void *value, void *clientData)
{
	*(short *)(value) = *((short*)clientData);
}


text:
//          Copyright Oliver Kowalke 2009.
// Distributed under the Boost Software License, Version 1.0.
//    (See accompanying file LICENSE_1_0.txt or copy at
//          http://www.boost.org/LICENSE_1_0.txt)

#define BOOST_COROUTINES_SOURCE

#include "boost/coroutine/detail/standard_stack_allocator.hpp"

extern "C" {
#include <windows.h>
}

//#if defined (BOOST_WINDOWS) || _POSIX_C_SOURCE >= 200112L

#include <algorithm>
#include <cmath>
#include <cstddef>
#include <cstring>
#include <stdexcept>

#include <boost/assert.hpp>
#include <boost/context/detail/config.hpp>
#include <boost/context/fcontext.hpp>

#include <boost/coroutine/stack_context.hpp>

# if defined(BOOST_MSVC)
# pragma warning(push)
# pragma warning(disable:4244 4267)
# endif

// x86_64
// test x86_64 before i386 because icc might
// define __i686__ for x86_64 too
#if defined(__x86_64__) || defined(__x86_64) \
    || defined(__amd64__) || defined(__amd64) \
    || defined(_M_X64) || defined(_M_AMD64)

// Windows seams not to provide a constant or function
// telling the minimal stacksize
# define MIN_STACKSIZE  8 * 1024
#else
# define MIN_STACKSIZE  4 * 1024
#endif

#ifdef BOOST_HAS_ABI_HEADERS
#  include BOOST_ABI_PREFIX
#endif

namespace boost {
namespace coroutines {
namespace detail {

SYSTEM_INFO system_info_()
{
    SYSTEM_INFO si;
    ::GetSystemInfo( & si);
    return si;
}

SYSTEM_INFO system_info()
{
    static SYSTEM_INFO si = system_info_();
    return si;
}

std::size_t pagesize()
{ return static_cast< std::size_t >( system_info().dwPageSize); }

std::size_t page_count( std::size_t stacksize)
{
    return static_cast< std::size_t >(
        std::ceil(
            static_cast< float >( stacksize) / pagesize() ) );
}

// Windows seams not to provide a limit for the stacksize
bool
standard_stack_allocator::is_stack_unbound()
{ return true; }

std::size_t
standard_stack_allocator::default_stacksize()
{
    std::size_t size = 64 * 1024; // 64 kB
    if ( is_stack_unbound() )
        return (std::max)( size, minimum_stacksize() );

    BOOST_ASSERT( maximum_stacksize() >= minimum_stacksize() );
    return maximum_stacksize() == minimum_stacksize()
        ? minimum_stacksize()
        : ( std::min)( size, maximum_stacksize() );
}

// because Windows seams not to provide a limit for minimum stacksize
std::size_t
standard_stack_allocator::minimum_stacksize()
{ return MIN_STACKSIZE; }

// because Windows seams not to provide a limit for maximum stacksize
// maximum_stacksize() can never be called (pre-condition ! is_stack_unbound() )
std::size_t
standard_stack_allocator::maximum_stacksize()
{
    BOOST_ASSERT( ! is_stack_unbound() );
    return  1 * 1024 * 1024 * 1024; // 1GB
}

void
standard_stack_allocator::allocate( stack_context & ctx, std::size_t size)
{
    BOOST_ASSERT( minimum_stacksize() <= size);
    BOOST_ASSERT( is_stack_unbound() || ( maximum_stacksize() >= size) );

    const std::size_t pages( detail::page_count( size) + 1); // add one guard page
    const std::size_t size_ = pages * detail::pagesize();
    BOOST_ASSERT( 0 < size && 0 < size_);

    void * limit = ::VirtualAlloc( 0, size_, MEM_COMMIT, PAGE_READWRITE);
    if ( ! limit) throw std::bad_alloc();

    std::memset( limit, '\0', size_);

    DWORD old_options;
#if defined(BOOST_DISABLE_ASSERTS)
    ::VirtualProtect(
        limit, detail::pagesize(), PAGE_READWRITE | PAGE_GUARD /*PAGE_NOACCESS*/, & old_options);
#else
    const BOOL result = ::VirtualProtect(
        limit, detail::pagesize(), PAGE_READWRITE | PAGE_GUARD /*PAGE_NOACCESS*/, & old_options);
    BOOST_ASSERT( FALSE != result);
#endif

    ctx.size = size_;
    ctx.sp = static_cast< char * >( limit) + ctx.size;
}

void
standard_stack_allocator::deallocate( stack_context & ctx)
{
    BOOST_ASSERT( ctx.sp);
    BOOST_ASSERT( minimum_stacksize() <= ctx.size);
    BOOST_ASSERT( is_stack_unbound() || ( maximum_stacksize() >= ctx.size) );

    void * limit = static_cast< char * >( ctx.sp) - ctx.size;
    ::VirtualFree( limit, 0, MEM_RELEASE);
}

}}}

#ifdef BOOST_HAS_ABI_HEADERS
#  include BOOST_ABI_SUFFIX
#endif

ext: cpp

max_stars_repo_name: ballisticwhisper/boost

max_issues_repo_name: ballisticwhisper/boost

max_forks_repo_name: ballisticwhisper/boost


text:
#include "gui/ActionsContainer.h"
#include "gui/MainWindow.h"

#include <boost/filesystem.hpp>
#include <QFileDialog>
#include <iostream>

namespace gui
{

ActionsContainer::ActionsContainer(
        SetterType<InteractionModeType> interactionModeSetter,
        CrosshairsAlignerType crosshairsToActiveSlideAligner,
        CrosshairsAlignerType crosshairsToSlideStackAligner,
        CrosshairsAlignerType crosshairsToAnatomicalPlanesAligner,
        SetterType<bool> slideStackViews3dModeSetter,
        AllViewsResetterType viewResetter,
        ProjectSaverType projectSaver,

        QAction* refImageDockTogglerAction,
        QAction* slideStackDockTogglerAction,
        QMainWindow* mainWindow,
        QObject* parent )
    :
      QObject( parent ),
      m_mainWindow( mainWindow ),

      m_interactionModeSetter( interactionModeSetter ),
      m_crosshairsToActiveSlideAligner( crosshairsToActiveSlideAligner ),
      m_crosshairsToSlideStackAligner( crosshairsToSlideStackAligner ),
      m_crosshairsToAnatomicalPlanesAligner( crosshairsToAnatomicalPlanesAligner ),
      m_slideStackViews3dModeSetter( slideStackViews3dModeSetter ),
      m_allViewsResetter( viewResetter ),
      m_projectSaver( projectSaver ),

      m_pointerModeSelectionGroup( new QActionGroup( this ) ),

      m_crosshairsAction( new QAction( "&Crosshairs" ) ),
      m_cameraTranslateAction( new QAction( "&Pan View" ) ),
      m_cameraRotateAction( new QAction( "&Rotate View" ) ),
      m_cameraZoomAction( new QAction( "&Zoom View" ) ),
      m_refImageWindowLevelAction( new QAction( "&Window/Level Reference Image" ) ),

      m_refImageRotateAction( new QAction( "Rotate Reference Image" ) ),
      m_refImageTranslateAction( new QAction( "Translate Reference Image" ) ),

      m_stackRotateAction( new QAction( "Rotate Slide Stack" ) ),
      m_stackTranslateAction( new QAction( "Translate Slide Stack" ) ),

      m_slideRotateAction( new QAction( "Rotate Slide" ) ),
      m_slideStretchAction( new QAction( "Stretch Slide" ) ),
      m_slideTranslateAction( new QAction( "Translate Slide" ) ),

      m_saveProjectAction( new QAction( "Save Project" ) ),
      m_saveProjectAsAction( new QAction( "Save Project As..." ) ),

      m_alignCrosshairsToActiveSlideAction( new QAction( "Align Crosshairs to Slide Stack" ) ),
      m_alignCrosshairsToAnatomicalPlanesAction( new QAction( "Align Crosshairs to Anatomy" ) ),
      m_resetViewsAction( new QAction( "Reset Views" ) ),
      m_slideStackViews3dModeAction( new QAction( "Slide Stack 3D" ) ),

      m_refImageDockTogglerAction( refImageDockTogglerAction ),
      m_slideStackDockTogglerAction( slideStackDockTogglerAction )
{
    m_pointerModeSelectionGroup->setExclusive( true );

    m_crosshairsAction->setStatusTip( "Crosshairs" );
    m_crosshairsAction->setActionGroup( m_pointerModeSelectionGroup );
    m_crosshairsAction->setCheckable( true );
    m_crosshairsAction->setIcon( QIcon( ":/toolbars/icons8-cursor-96.png" ) );

    m_cameraTranslateAction->setStatusTip( "Pan View" );
    m_cameraTranslateAction->setActionGroup( m_pointerModeSelectionGroup );
    m_cameraTranslateAction->setCheckable( true );
    m_cameraTranslateAction->setIcon( QIcon( ":/toolbars/icons8-hand-96.png" ) );

    m_cameraRotateAction->setStatusTip( "Rotate View" );
    m_cameraRotateAction->setActionGroup( m_pointerModeSelectionGroup );
    m_cameraRotateAction->setCheckable( true );
    m_cameraRotateAction->setIcon( QIcon( ":/toolbars/icons8-rotate-camera-96.png" ) );

    m_cameraZoomAction->setStatusTip( "Zoom View" );
    m_cameraZoomAction->setActionGroup( m_pointerModeSelectionGroup );
    m_cameraZoomAction->setCheckable( true );
    m_cameraZoomAction->setIcon( QIcon( ":/toolbars/icons8-zoom-in-96.png" ) );

    m_refImageRotateAction->setStatusTip( "Rotate Reference Image" );
    m_refImageRotateAction->setActionGroup( m_pointerModeSelectionGroup );
    m_refImageRotateAction->setCheckable( true );
    m_refImageRotateAction->setIcon( QIcon( ":/toolbars/icons8-rotate-96.png" ) );

    m_refImageTranslateAction->setStatusTip( "Translate Reference Image" );
    m_refImageTranslateAction->setActionGroup( m_pointerModeSelectionGroup );
    m_refImageTranslateAction->setCheckable( true );
    m_refImageTranslateAction->setIcon( QIcon( ":/toolbars/icons8-move-96.png" ) );

    m_refImageWindowLevelAction->setStatusTip( "Window/Level" );
    m_refImageWindowLevelAction->setActionGroup( m_pointerModeSelectionGroup );
    m_refImageWindowLevelAction->setCheckable( true );
    m_refImageWindowLevelAction->setIcon( QIcon( ":/toolbars/icons8-automatic-contrast-96.png" ) );

    m_stackRotateAction->setStatusTip( "Rotate Slide Stack" );
    m_stackRotateAction->setActionGroup( m_pointerModeSelectionGroup );
    m_stackRotateAction->setCheckable( true );
    m_stackRotateAction->setIcon( QIcon( ":/toolbars/icons8-3d-rotate-96.png" ) );

    m_stackTranslateAction->setStatusTip( "Translate Slide Stack" );
    m_stackTranslateAction->setActionGroup( m_pointerModeSelectionGroup );
    m_stackTranslateAction->setCheckable( true );
    m_stackTranslateAction->setIcon( QIcon( ":/toolbars/icons8-portraits-96.png" ) );

    m_slideRotateAction->setStatusTip( "Rotate Slide" );
    m_slideRotateAction->setActionGroup( m_pointerModeSelectionGroup );
    m_slideRotateAction->setCheckable( true );
    m_slideRotateAction->setIcon( QIcon( ":/toolbars/icons8-manual-page-rotation-96.png" ) );

    m_slideStretchAction->setStatusTip( "Stretch Slide" );
    m_slideStretchAction->setActionGroup( m_pointerModeSelectionGroup );
    m_slideStretchAction->setCheckable( true );
    m_slideStretchAction->setIcon( QIcon( ":/toolbars/icons8-resize-96.png" ) );

    m_slideTranslateAction->setStatusTip( "Translate Slide" );
    m_slideTranslateAction->setActionGroup( m_pointerModeSelectionGroup );
    m_slideTranslateAction->setCheckable( true );
    m_slideTranslateAction->setIcon( QIcon( ":/toolbars/icons8-fit-to-page-96.png" ) );

    m_alignCrosshairsToActiveSlideAction->setStatusTip( "Align Crosshairs to Slide Stack" );
    m_alignCrosshairsToActiveSlideAction->setIcon( QIcon( ":/toolbars/icons8-ruler-combined-96.png" ) );

    m_alignCrosshairsToAnatomicalPlanesAction->setStatusTip( "Align Crosshairs to Anatomical Planes" );
    m_alignCrosshairsToAnatomicalPlanesAction->setIcon( QIcon( ":/toolbars/icons8-head-profile-96.png" ) );

    m_resetViewsAction->setStatusTip( "Reset Views" );
    m_resetViewsAction->setIcon( QIcon( ":/toolbars/icons8-target-96.png" ) );

    //    icons8-opened-folder-96.png

    m_saveProjectAction->setStatusTip( "Save Project" );
    m_saveProjectAction->setIcon( QIcon( ":/toolbars/icons8-save-96.png") );

    m_saveProjectAsAction->setStatusTip( "Save Project As..." );
    m_saveProjectAsAction->setIcon( QIcon( ":/toolbars/icons8-save-as-96.png") );

    m_slideStackViews3dModeAction->setStatusTip( "Slide Stack 3D" );
    m_slideStackViews3dModeAction->setCheckable( true );

    createConnections();
}

QActionGroup* ActionsContainer::pointerModeActionGroup()
{
    return m_pointerModeSelectionGroup;
}

QAction* ActionsContainer::pointerAction()
{
    return m_crosshairsAction;
}

QAction* ActionsContainer::translateAction()
{
    return m_cameraTranslateAction;
}

QAction* ActionsContainer::rotateAction()
{
    return m_cameraRotateAction;
}

QAction* ActionsContainer::zoomAction()
{
    return m_cameraZoomAction;
}

QAction* ActionsContainer::windowLevelAction()
{
    return m_refImageWindowLevelAction;
}

QAction* ActionsContainer::refImageRotateAction()
{
    return m_refImageRotateAction;
}

QAction* ActionsContainer::refImageTranslateAction()
{
    return m_refImageTranslateAction;
}

QAction* ActionsContainer::stackRotateAction()
{
    return m_stackRotateAction;
}

QAction* ActionsContainer::stackTranslateAction()
{
    return m_stackTranslateAction;
}

QAction* ActionsContainer::slideRotateAction()
{
    return m_slideRotateAction;
}

QAction* ActionsContainer::slideStretchAction()
{
    return m_slideStretchAction;
}

QAction* ActionsContainer::slideTranslateAction()
{
    return m_slideTranslateAction;
}

QAction* ActionsContainer::saveProjectAction()
{
    return m_saveProjectAction;
}

QAction* ActionsContainer::saveProjectAsAction()
{
    return m_saveProjectAsAction;
}

QAction* ActionsContainer::alignCrosshairsToSlideAction()
{
    return m_alignCrosshairsToActiveSlideAction;
}

QAction* ActionsContainer::alignCrosshairsToAnatomicalPlanes()
{
    return m_alignCrosshairsToAnatomicalPlanesAction;
}

QAction* ActionsContainer::resetViewsAction()
{
    return m_resetViewsAction;
}

QAction* ActionsContainer::slideStackViews3dModeAction()
{
    return m_slideStackViews3dModeAction;
}

QAction* ActionsContainer::refImageDockTogglerAction()
{
    return m_refImageDockTogglerAction;
}

QAction* ActionsContainer::slideStackDockTogglerAction()
{
    return m_slideStackDockTogglerAction;
}

void ActionsContainer::createConnections()
{
    auto& S = m_interactionModeSetter;

    connect( m_crosshairsAction, &QAction::triggered, [&S]() { if ( S ) S( InteractionModeType::CrosshairsPointer ); } );
    connect( m_cameraTranslateAction, &QAction::triggered, [&S]() { if ( S ) S( InteractionModeType::CameraTranslate ); } );
    connect( m_cameraRotateAction, &QAction::triggered, [&S]() { if ( S ) S( InteractionModeType::CameraRotate ); } );
    connect( m_cameraZoomAction, &QAction::triggered, [&S]() { if ( S ) S( InteractionModeType::CameraZoom ); } );

    connect( m_refImageRotateAction, &QAction::triggered, [&S]() { if ( S ) S( InteractionModeType::RefImageRotate ); } );
    connect( m_refImageTranslateAction, &QAction::triggered, [&S]() { if ( S ) S( InteractionModeType::RefImageTranslate ); } );
    connect( m_refImageWindowLevelAction, &QAction::triggered, [&S]() { if ( S ) S( InteractionModeType::RefImageWindowLevel ); } );

    connect( m_stackRotateAction, &QAction::triggered, [&S]() { if ( S ) S( InteractionModeType::StackRotate ); } );
    connect( m_stackTranslateAction, &QAction::triggered, [&S]() { if ( S ) S( InteractionModeType::StackTranslate ); } );

    connect( m_slideRotateAction, &QAction::triggered, [&S]() { if ( S ) S( InteractionModeType::SlideRotate ); } );
    connect( m_slideStretchAction, &QAction::triggered, [&S]() { if ( S ) S( InteractionModeType::SlideStretch ); } );
    connect( m_slideTranslateAction, &QAction::triggered, [&S]() { if ( S ) S( InteractionModeType::SlideTranslate ); } );

    connect( m_saveProjectAction, &QAction::triggered, [this] () { if ( m_projectSaver ) m_projectSaver( std::nullopt ); } );
    connect( m_saveProjectAsAction, &QAction::triggered, [this] () { saveProjectAs(); } );

    connect( m_alignCrosshairsToActiveSlideAction, &QAction::triggered,
             [this]() { if ( m_crosshairsToSlideStackAligner ) {
            m_crosshairsToSlideStackAligner(); } } );

    connect( m_alignCrosshairsToAnatomicalPlanesAction, &QAction::triggered,
             [this]() { if ( m_crosshairsToAnatomicalPlanesAligner ) {
            m_crosshairsToAnatomicalPlanesAligner(); } } );

    connect( m_resetViewsAction, &QAction::triggered,
             [this]() { if ( m_allViewsResetter ) m_allViewsResetter(); } );

    connect( m_slideStackViews3dModeAction, &QAction::triggered,
             [this]() { if ( m_slideStackViews3dModeSetter ) {
            m_slideStackViews3dModeSetter( m_slideStackViews3dModeAction->isChecked() ); } } );

    // Set default checked states:

    m_crosshairsAction->setChecked( true ); // default selection
    m_refImageWindowLevelAction->setChecked( false );
    m_cameraTranslateAction->setChecked( false );
    m_cameraRotateAction->setChecked( false );
    m_cameraZoomAction->setChecked( false );

    m_refImageRotateAction->setChecked( false );
    m_refImageTranslateAction->setChecked( false );

    m_stackRotateAction->setChecked( false );
    m_stackTranslateAction->setChecked( false );

    m_slideRotateAction->setChecked( false );
    m_slideStretchAction->setChecked( false );
    m_slideTranslateAction->setChecked( false );

    m_slideStackViews3dModeAction->setChecked( false );
}

void ActionsContainer::saveProjectAs()
{
    QStringList filters;

    filters << "All files (*.*)"
            << "JSON files (*.json)";

    QFileDialog dialog( m_mainWindow, "Save HistoloZee Project" );
    dialog.setFileMode( QFileDialog::AnyFile );
    dialog.setNameFilters( filters );
    dialog.selectNameFilter( "JSON files (*.json)" );
    dialog.setAcceptMode( QFileDialog::AcceptSave );
    dialog.setViewMode( QFileDialog::Detail );

    if ( QDialog::Accepted != dialog.exec() ||
         dialog.selectedFiles().empty() )
    {
        return;
    }

    if ( m_projectSaver )
    {
        const std::string filename = dialog.selectedFiles().first().toStdString();
        std::cout << "Saving project to " << filename << std::endl;
        m_projectSaver( filename );
    }
}

} // namespace gui

max_stars_repo_name: halfmvsq/histolozee

max_issues_repo_name: halfmvsq/histolozee

max_forks_repo_name: halfmvsq/histolozee


text:
// Copyright (c) 2021 Bitcoin Association.
// Distributed under the Open BSV software license, see the accompanying file LICENSE.

#include "block_index_store_loader.h"

#include "dbwrapper.h"
#include "disk_block_index.h"
#include "pow.h"
#include "util.h"

#include <utility>
#include <boost/thread/thread.hpp>

bool BlockIndexStoreLoader::ForceLoad(
    const Config& config,
    std::unique_ptr<CDBIterator> cursor )
{
    std::lock_guard lock{ mBlockIndexStore.mMutex };

    assert( mBlockIndexStore.mStore.empty() );

    constexpr char DB_BLOCK_INDEX = 'b';
    cursor->Seek(std::make_pair(DB_BLOCK_INDEX, uint256()));

    // Load mapBlockIndex
    for (; cursor->Valid(); cursor->Next())
    {
        boost::this_thread::interruption_point();
        std::pair<char, uint256> key;
        if (!cursor->GetKey(key) || key.first != DB_BLOCK_INDEX) {
            break;
        }

        // Create uninitialized block index object in array or return one that was created previously
        auto& indexNew = mBlockIndexStore.GetOrInsertNL( key.second );
        assert(indexNew.GetVersion()==0 && indexNew.GetPrev()==nullptr); // We must always get an uninitialized block index object.

        // Initialize object by reading it from database
        CDiskBlockIndex diskindex{ indexNew };
        if (!cursor->GetValue( diskindex ))
        {
            return error("LoadBlockIndex() : failed to read value");
        }

        if(!diskindex.IsGenesis())
        {
            // Set parent of this object. This is a second part part of logical object construction.
            // If parent does not already exist in an array, a new uninitialized object is created.
            indexNew.CBlockIndex_SetPrev( &mBlockIndexStore.GetOrInsertNL(diskindex.GetHashPrev()), CBlockIndex::PrivateTag{} );
        }

        if (!CheckProofOfWork(indexNew.GetBlockHash(), indexNew.GetBits(),
                              config)) {
            return error("LoadBlockIndex(): CheckProofOfWork failed: %s",
                         indexNew.ToString());
        }
    }

    return true;
}

max_stars_repo_name: AustEcon/bitcoin-sv

max_issues_repo_name: wjxee/bitcoin-sv

max_forks_repo_name: wjxee/bitcoin-sv


text:
#define ZLOG_ALLOW_TRACING
#include "Detail/Utils.h"
#include "ZLOg.h"
#include <atlbase.h>
#include <boost/bind.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/locks.hpp>
#include <io.h>
#include <stdarg.h>
#include <stdio.h>

#define NOMINMAX
#define WIN32_LEAN_AND_MEAN
#include <windows.h>

// TCHAR antipod
#ifdef UNICODE
#	define NONTCHAR CHAR
#else
#	define NONTCHAR WCHAR
#endif

namespace
{
	typedef boost::lock_guard<boost::mutex>	mutex_lock;

	/** Every operation with file is in critical section */
	class thread_safe_file
	{
	friend class log_message;
	public:
		thread_safe_file()
		:	hFile(INVALID_HANDLE_VALUE)
		{}

		~thread_safe_file()
		{
			//CloseHandle(hFile);
		}

		bool open(const char* fileName, bool append, bool writeThrough)
		{
			UINT mode = FILE_ATTRIBUTE_NORMAL;
			if (writeThrough) {
				mode |= FILE_FLAG_WRITE_THROUGH;
			}

			mutex_lock lock(mutex);
			hFile = CreateFileA(fileName, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, mode, NULL);
			return (hFile != INVALID_HANDLE_VALUE);
		}

		void close()
		{
			mutex_lock lock(mutex);
			if (hFile != INVALID_HANDLE_VALUE)
			{
				CloseHandle(hFile);
				hFile = INVALID_HANDLE_VALUE;
			}
		}

		bool is_open() const
		{
			mutex_lock lock(mutex);
			return (hFile != INVALID_HANDLE_VALUE);
		}

	private:
		HANDLE					hFile;
		mutable boost::mutex	mutex;
	};

	const size_t MAX_MESSAGE_LENGTH = 8096;

	/** Helper for constructing log message */
	class log_message :
		public boost::noncopyable
	{
	public:
		log_message(thread_safe_file& file)
		:	lock(file.mutex)
		,	hFile(file.hFile)
		,	offset(0)
		{}

		~log_message()
		{
			if (offset > 0)
			{
				if (hFile != INVALID_HANDLE_VALUE)
				{
					DWORD written;
					WriteFile(hFile, buffer, offset * sizeof(TCHAR), &written, NULL);
				}
				OutputDebugString(buffer);
			}
		}

		int puttc(TCHAR c)
		{
			if (offset < MAX_MESSAGE_LENGTH)
			{
				buffer[offset++] = c;
				buffer[offset] = '\0';
				return 1;
			}

			return 0;
		}

		int printf(const TCHAR* format, ...)
		{
			va_list args;
			va_start(args, format);
			int written = this->vprintf(format, args);
			va_end(args);
			return written;
		}

		int vprintf(const TCHAR* format, va_list args)
		{
			int written = 0;
			if (offset < MAX_MESSAGE_LENGTH)
			{
				written = _vsntprintf(buffer + offset, MAX_MESSAGE_LENGTH - offset, format, args);
				offset += written;
			}

			return written;
		}

		int printf(const NONTCHAR* format, ...)
		{
			va_list args;
			va_start(args, format);
			int written = this->vprintf(format, args);
			va_end(args);
			return written;
		}

		int vprintf(const NONTCHAR* format, va_list args)
		{
			if (offset < MAX_MESSAGE_LENGTH)
			{
				// write to non TCHAR buffer
			#ifdef UNICODE
				vsnprintf(transferBuffer, MAX_MESSAGE_LENGTH, format, args);
			#else
				_vsnwprintf(transferBuffer, MAX_MESSAGE_LENGTH, format, args);
			#endif

				// write as non TCHAR string '%S'
				return this->printf(_T("%S"), transferBuffer);
			}

			return 0;
		}

		operator bool () const { return hFile != INVALID_HANDLE_VALUE; }

	private:
		mutex_lock		lock;
		HANDLE			hFile;
		static TCHAR	buffer[MAX_MESSAGE_LENGTH];
		static NONTCHAR	transferBuffer[MAX_MESSAGE_LENGTH];
		DWORD			offset;
	};

	TCHAR				log_message::buffer[MAX_MESSAGE_LENGTH];
	NONTCHAR			log_message::transferBuffer[MAX_MESSAGE_LENGTH];

	thread_safe_file	g_File;
	zlog::string		g_LogFileName;
	zlog::SEVERITY		g_Severity;
	bool				g_WriteThrough = false;
	bool				g_Buffering = false;

	const wchar_t* SEVERITY_TO_WSTR[] =
	{
		L"FATAL_ERROR",
		L"ERROR",
		L"WARNING",
		L"MESSAGE",
		L"NOTICE",
		L"FLOOD"
	};

	const char* SEVERITY_TO_CSTR[] =
	{
		"FATAL_ERROR",
		"ERROR",
		"WARNING",
		"MESSAGE",
		"NOTICE",
		"FLOOD"
	};

#ifdef UNICODE
#	define SEVERITY_TO_TSTR SEVERITY_TO_WSTR
#else
#	define SEVERITY_TO_TSTR SEVERITY_TO_CSTR
#endif

	zlog::SEVERITY STR_TO_SEVERITY(const std::string& severity)
	{
		if (severity == "FLOOD") return zlog::SV_FLOOD;
		else if (severity == "NOTICE") return zlog::SV_NOTICE;
		else if (severity == "MESSAGE") return zlog::SV_MESSAGE;
		else if (severity == "WARNING") return zlog::SV_WARNING;
		else if (severity == "ERROR") return zlog::SV_ERROR;
		else if (severity == "FATAL_ERROR") return zlog::SV_FATAL_ERROR;

		assert(!"can't get here");
		return zlog::SEVERITY();
	}

	zlog::string w_to_a(const zlog::wstring& str)
	{
		CW2AEX<MAX_PATH> conv(str.c_str());
		return zlog::string(conv.m_psz);
	}

} // anonymous namespace

namespace zlog {

bool ReopenLogger(const string& fileName, bool append)
{
	if ( !g_File.open(fileName.c_str(), append, g_WriteThrough) ) {
		return false;
	}

	g_LogFileName = fileName;
	return true;
}

bool ReopenLogger(const wstring& fileName, bool append)
{
	return ReopenLogger( w_to_a(fileName), append );
}

bool IsLoggerOpened()
{
	return g_File.is_open();
}

void CloseLogger()
{
	g_File.close();
	g_LogFileName.clear();
}

string GetLoggerFileName()
{
	return g_LogFileName;
}

void InitializeFromINI(const string& configFile)
{
	CloseLogger();
	{
		boost::property_tree::ptree properties;
		boost::property_tree::read_ini(configFile, properties);

		g_LogFileName	= properties.get("Output", g_LogFileName);
		g_Severity		= STR_TO_SEVERITY( properties.get("Severity", SEVERITY_TO_CSTR[g_Severity]) );
		g_WriteThrough	= properties.get("WriteThrough", g_WriteThrough);
	}

	if ( !g_LogFileName.empty() ) {
		ReopenLogger(g_LogFileName, true);
	}
}

void InitializeFromINI(const wstring& configFile)
{
	InitializeFromINI( w_to_a(configFile) );
}

void InitializeFromXML(const string& configFile, const string& section)
{
	CloseLogger();
	{
		boost::property_tree::ptree properties;
		boost::property_tree::read_xml(configFile, properties);

		string prefix;
		if ( !section.empty() ) {
			prefix = section + ".";
		}

		g_LogFileName	= properties.get(prefix + "Output", g_LogFileName);
		g_Severity		= STR_TO_SEVERITY( properties.get(prefix + "Severity", SEVERITY_TO_CSTR[g_Severity]) );
		g_WriteThrough	= properties.get(prefix + "WriteThrough", g_WriteThrough);
	}

	if ( !g_LogFileName.empty() ) {
		ReopenLogger(g_LogFileName, true);
	}
}

void InitializeFromXML(const wstring& configFile, const wstring& section)
{
	InitializeFromXML( w_to_a(configFile), w_to_a(section) );
}

void ToggleWriteThrough(bool toggle)
{
	if (g_File.is_open() && g_WriteThrough != toggle)
	{
		g_WriteThrough = toggle;
		ReopenLogger(g_LogFileName, true);
	}
	else {
		g_WriteThrough = toggle;
	}
}

void ToggleBuffering(bool toggle)
{
	g_Buffering = toggle;
}

void SetupSeverity(SEVERITY severity)
{
	g_Severity = severity;
}

SEVERITY GetSeverity()
{
	return g_Severity;
}

void GetSeverityPtr(SEVERITY** ppSeverity)
{
	if (ppSeverity == NULL)
		return;
	*ppSeverity = &g_Severity;
}

void LogMessage(SEVERITY severity, const char* module, bool addEndl, bool addMarker, const char* format, va_list args)
{
	if (g_Severity < severity || severity >= SV_COUNT) {
		return;
	}

	log_message message(g_File);

	if (addMarker)
	{
		DWORD dThreadId = GetCurrentThreadId();

	#ifdef UNICODE
		message.printf(L"[%S:%04x]<%s> ", module, dThreadId, SEVERITY_TO_TSTR[severity]);
	#else
		message.printf(L"[%s:%04x]<%s> ", module, dThreadId, SEVERITY_TO_TSTR[severity]);
	#endif
	}
	message.vprintf(format, args);

	// check for eoln
	if (addEndl)
	{
		bool hasEndl = false;
		if (format)
		{
			for (; *format != 0; ++format)
			{
				if (*format == '\n') {
					hasEndl = true;
				}
				else if ( !isspace(*format) ) {
					hasEndl = false;
				}
			}
		}

		if (!hasEndl) {
			message.puttc(_T('\n'));
		}
	}
}

void LogMessage(SEVERITY severity, const wchar_t* module, bool addEndl, bool addMarker, const wchar_t* format, va_list args)
{
	if (g_Severity < severity || severity >= SV_COUNT) {
		return;
	}

	log_message message(g_File);

	if (addMarker)
	{
		DWORD dThreadId = GetCurrentThreadId();

	#ifdef UNICODE
		message.printf(L"[%s:%04x]<%s> ", module, dThreadId, SEVERITY_TO_TSTR[severity]);
	#else
		message.printf(L"[%S:%04x]<%s> ", module, dThreadId, SEVERITY_TO_TSTR[severity]);
	#endif
	}
	message.vprintf(format, args);

	// check for eoln
	if (addEndl)
	{
		bool hasEndl = false;
		if (format)
		{
			for (; *format != 0; ++format)
			{
				if (*format == L'\n') {
					hasEndl = true;
				}
				else if ( !iswspace(*format) ) {
					hasEndl = false;
				}
			}
		}

		if (!hasEndl) {
			message.puttc(_T('\n'));
		}
	}
}

template<typename Char>
void LogMessage(SEVERITY severity, const Char* module, const Char* format, ...)
{
	va_list args;
	va_start(args, format);
	LogMessage(severity, module, true, true, format,  args);
	va_end(args);
}

template<typename Char>
void LogMessage(SEVERITY severity, const std::basic_string<Char>& module, const std::basic_string<Char>& format, ...)
{
	va_list args;
	va_start(args, format);
	LogMessage(severity, module.c_str(), true, true, format.c_str(), args);
	va_end(args);
}

template<typename Char>
void LogMessageEx(SEVERITY severity, const Char* module, bool addEndl, bool addMarker, const Char* format, ...)
{
	va_list args;
	va_start(args, format);
	LogMessage(severity, module, addEndl, addMarker, format, args);
	va_end(args);
}

template<typename Char>
void LogMessageEx(SEVERITY severity, const std::basic_string<Char>& module, bool addEndl, bool addMarker, const std::basic_string<Char>& format, ...)
{
	va_list args;
	va_start(args, format);
	LogMessage(severity, module.c_str(), addEndl, addMarker, format.c_str(), args);
	va_end(args);
}

int ZLOG_API __cdecl VldReportHook( int /*reportType*/, wchar_t *message, int* /*returnValue*/ )
{
	zlog::LogMessageEx(SV_NOTICE, _T("VLD"), false, false, message);
	return 1;
}

template void ZLOG_API LogMessage<char>(SEVERITY severity, const char* module, const char* format, ...);
template void ZLOG_API LogMessage<wchar_t>(SEVERITY severity, const wchar_t* module, const wchar_t* format, ...);
template void ZLOG_API LogMessage<char>(SEVERITY severity, const std::basic_string<char>& module, const std::basic_string<char>& format, ...);
template void ZLOG_API LogMessage<wchar_t>(SEVERITY severity, const std::basic_string<wchar_t>& module, const std::basic_string<wchar_t>& format, ...);

template void ZLOG_API LogMessageEx<char>(SEVERITY severity, const char* module, bool addEndl, bool addMarker, const char* format, ...);
template void ZLOG_API LogMessageEx<wchar_t>(SEVERITY severity, const wchar_t* module, bool addEndl, bool addMarker, const wchar_t* format, ...);
template void ZLOG_API LogMessageEx<char>(SEVERITY severity, const std::basic_string<char>& module, bool addEndl, bool addMarker, const std::basic_string<char>& format, ...);
template void ZLOG_API LogMessageEx<wchar_t>(SEVERITY severity, const std::basic_string<wchar_t>& module, bool addEndl, bool addMarker, const std::basic_string<wchar_t>& format, ...);

} // namespace zlog

#ifdef BOOST_NO_EXCEPTIONS

// to support compilation without exceptions /EHsc
void boost::throw_exception(const stdext::exception& ex)
{
	zlog::LogMessage( zlog::SV_ERROR, "ZLOg", "exception: %s", ex.what() );
}

#endif // BOOST_NO_EXCEPTIONS


text:
// Copyright 2020 Tier IV, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef SCENE_MODULE__NO_STOPPING_AREA__SCENE_NO_STOPPING_AREA_HPP_
#define SCENE_MODULE__NO_STOPPING_AREA__SCENE_NO_STOPPING_AREA_HPP_

#define EIGEN_MPL2_ONLY

#include "scene_module/scene_module_interface.hpp"
#include "utilization/boost_geometry_helper.hpp"
#include "utilization/state_machine.hpp"

#include <Eigen/Core>
#include <lanelet2_extension/regulatory_elements/no_stopping_area.hpp>
#include <rclcpp/rclcpp.hpp>

#include <autoware_auto_perception_msgs/msg/object_classification.hpp>
#include <autoware_auto_perception_msgs/msg/predicted_object.hpp>
#include <autoware_auto_perception_msgs/msg/predicted_objects.hpp>
#include <autoware_auto_planning_msgs/msg/path_with_lane_id.hpp>

#include <boost/optional.hpp>

#include <lanelet2_core/LaneletMap.h>
#include <tf2/LinearMath/Transform.h>

#include <memory>
#include <utility>
#include <vector>

namespace behavior_velocity_planner
{
using PathIndexWithPose = std::pair<size_t, geometry_msgs::msg::Pose>;  // front index, pose
using PathIndexWithPoint2d = std::pair<size_t, Point2d>;                // front index, point2d
using PathIndexWithOffset = std::pair<size_t, double>;                  // front index, offset

class NoStoppingAreaModule : public SceneModuleInterface
{
public:
  struct DebugData
  {
    double base_link2front;
    std::vector<geometry_msgs::msg::Pose> stop_poses;
    geometry_msgs::msg::Pose first_stop_pose;
    std::vector<geometry_msgs::msg::Point> stuck_points;
    geometry_msgs::msg::Polygon stuck_vehicle_detect_area;
    geometry_msgs::msg::Polygon stop_line_detect_area;
  };

  struct PlannerParam
  {
    /**
     * @brief representation of a parameter for no stopping area
     *
     * Ego --|<--stop line margin-->|NoStoppingArea|<--front margin-->|stuck vehicle|---> path
     * Ego --|<--stop line margin-->|NoStoppingArea|<-rear_overhang-->| stop point  |---> path
     *
     */
    double state_clear_time;       //! [s] time to clear stop state
    double stuck_vehicle_vel_thr;  //! [m/s] Threshold of the speed to be recognized as stopped
    double stop_margin;            //! [m] margin to stop line at no stopping area
    double dead_line_margin;       //! [m] dead line to go at no stopping area
    double stop_line_margin;       //! [m] distance from auto-generated stopline to no_stopping_area
    double detection_area_length;  //! [m] used to create detection area polygon
    double stuck_vehicle_front_margin;  //! [m] margin from area end to forward lane
    double path_expand_width;           //! [m] path width to calculate the edge line for both side
  };

public:
  NoStoppingAreaModule(
    const int64_t module_id, const lanelet::autoware::NoStoppingArea & no_stopping_area_reg_elem,
    const PlannerParam & planner_param, const rclcpp::Logger logger,
    const rclcpp::Clock::SharedPtr clock);

  bool modifyPathVelocity(
    autoware_auto_planning_msgs::msg::PathWithLaneId * path,
    autoware_planning_msgs::msg::StopReason * stop_reason) override;

  visualization_msgs::msg::MarkerArray createDebugMarkerArray() override;

private:
  mutable bool pass_judged_ = false;
  mutable bool is_stoppable_ = true;
  StateMachine state_machine_;  //! for state

  /**
   * @brief check if the object has a target type for stuck check
   * @param object target object
   * @return true if the object has a target type
   */
  bool isTargetStuckVehicleType(
    const autoware_auto_perception_msgs::msg::PredictedObject & object) const;

  /**
   * @brief Check if there is a stopped vehicle in stuck vehicle detect area.
   * @param poly            ego focusing area polygon
   * @param objects_ptr     target objects
   * @return true if exists
   */
  bool checkStuckVehiclesInNoStoppingArea(
    const Polygon2d & poly,
    const autoware_auto_perception_msgs::msg::PredictedObjects::ConstSharedPtr &
      predicted_obj_arr_ptr);

  /**
   * @brief Check if there is a stop line in "stop line detect area".
   * @param path            ego-car lane
   * @param poly            ego focusing area polygon
   * @return true if exists
   */
  bool checkStopLinesInNoStoppingArea(
    const autoware_auto_planning_msgs::msg::PathWithLaneId & path, const Polygon2d & poly);

  /**
   * @brief Calculate the polygon of the path from the ego-car position to the end of the
   * no stopping lanelet (+ extra distance).
   * @param path           ego-car lane
   * @param ego_pose       ego-car pose
   * @param margin         margin from the end point of the ego-no stopping area lane
   * @param extra_dist     extra distance from the end point of the no stopping area lanelet
   * @return generated polygon
   */
  Polygon2d generateEgoNoStoppingAreaLanePolygon(
    const autoware_auto_planning_msgs::msg::PathWithLaneId & path,
    const geometry_msgs::msg::Pose & ego_pose, const double margin, const double extra_dist) const;

  /**
   * @brief Calculate the polygon of the path from the ego-car position to the end of the
   * no stopping lanelet (+ extra distance).
   * @param path                  ego-car lane
   * @param stop_line_margin      stop line margin from the stopping area lane
   * @return generated stop line
   */
  boost::optional<LineString2d> getStopLineGeometry2d(
    const autoware_auto_planning_msgs::msg::PathWithLaneId & path,
    const double stop_line_margin) const;

  /**
   * @brief Calculate if ego-vehicle is in front of dead line or not
   * @param path          original path
   * @param self_pose       ego-car pose
   * @param line_pose       stop line pose on the lane
   * @return if over or not
   */
  bool isOverDeadLine(
    const autoware_auto_planning_msgs::msg::PathWithLaneId & path,
    const geometry_msgs::msg::Pose & self_pose, const geometry_msgs::msg::Pose & line_pose) const;

  /**
   * @brief Calculate if it's possible for ego-vehicle to stop before area consider jerk limit
   * @param self_pose       ego-car pose
   * @param line_pose       stop line pose on the lane
   * @return is stoppable in front of no stopping area
   */
  bool isStoppable(
    const geometry_msgs::msg::Pose & self_pose, const geometry_msgs::msg::Pose & line_pose) const;

  /**
   * @brief insert stop point on ego path
   * @param path          original path
   * @param stop_point    stop line point on the lane
   */
  void insertStopPoint(
    autoware_auto_planning_msgs::msg::PathWithLaneId & path, const PathIndexWithPose & stop_point);

  boost::optional<PathIndexWithPose> createTargetPoint(
    const autoware_auto_planning_msgs::msg::PathWithLaneId & path, const LineString2d & stop_line,
    const double margin) const;

  // Key Feature
  const lanelet::autoware::NoStoppingArea & no_stopping_area_reg_elem_;
  std::shared_ptr<const rclcpp::Time> last_obstacle_found_time_;

  // Parameter
  PlannerParam planner_param_;

  // Debug
  DebugData debug_data_;
};
}  // namespace behavior_velocity_planner

#endif  // SCENE_MODULE__NO_STOPPING_AREA__SCENE_NO_STOPPING_AREA_HPP_

ext: hpp


text:
// --------------------------------------------------------------------------
//                   OpenMS -- Open-Source Mass Spectrometry
// --------------------------------------------------------------------------
// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,
// ETH Zurich, and Freie Universitaet Berlin 2002-2020.
//
// This software is released under a three-clause BSD license:
//  * Redistributions of source code must retain the above copyright
//    notice, this list of conditions and the following disclaimer.
//  * Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in the
//    documentation and/or other materials provided with the distribution.
//  * Neither the name of any author or any participating institution
//    may be used to endorse or promote products derived from this software
//    without specific prior written permission.
// For a full list of authors, refer to the file AUTHORS.
// --------------------------------------------------------------------------
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL ANY OF THE AUTHORS OR THE CONTRIBUTING
// INSTITUTIONS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// --------------------------------------------------------------------------
// $Maintainer: Oliver Alka $
// $Authors: Oliver Alka, Timo Sachsenberg $
// --------------------------------------------------------------------------

#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/FORMAT/CsvFile.h>
#include <OpenMS/FORMAT/DATAACCESS/SiriusMzTabWriter.h>
#include <OpenMS/FORMAT/MzTabFile.h>
#include <OpenMS/METADATA/SpectrumLookup.h>
#include <OpenMS/SYSTEM/File.h>
#include <boost/regex.hpp>

using namespace OpenMS;
using namespace std;

int SiriusMzTabWriter::extract_scan_index(const String &path)
{
  return (path.substr(path.find_last_not_of("0123456789") + 1)).toInt();
}

void SiriusMzTabWriter::read(const std::vector<String>& sirius_output_paths,
                             const String& original_input_mzml,
                             const Size& top_n_hits,
                             MzTab& result)
{

  SiriusMzTabWriter::SiriusAdapterRun sirius_result;

  for (const auto& it : sirius_output_paths)
  {
    // extract mz, rt and nativeID of the corresponding precursor spectrum in the spectrum.ms file
    String ext_nid;
    double ext_mz = 0.0;
    double ext_rt = 0.0;
    const String sirius_spectrum_ms = it + "/spectrum.ms";
    ifstream spectrum_ms_file(sirius_spectrum_ms);
    if (spectrum_ms_file)
    {
      const String nid_prefix = "##nid";
      const String rt_prefix = "#rt";
      const String pmass_prefix = ">parentmass";
      const String ms1peaks = ">ms1peaks";
      String line;
      while (getline(spectrum_ms_file, line))
      {
        if (line.hasPrefix(pmass_prefix))
        {
           ext_mz = String(line.erase(line.find(pmass_prefix), pmass_prefix.size())).toDouble();
        }
        else if (line.hasPrefix(rt_prefix))
        {
           ext_rt = String(line.erase(line.find(rt_prefix), rt_prefix.size())).toDouble();
        }
        else if (line.hasPrefix(nid_prefix))
        {
           ext_nid = line.erase(line.find(nid_prefix), nid_prefix.size());
        }
        else if (line.hasPrefix(ms1peaks))
        {
           break; // only run till >ms1peaks
        }
      }
      spectrum_ms_file.close();
    }

    // extract data from summary_sirius.csv
    const std::string pathtosiriuscsv = it + "/summary_sirius.csv";

    ifstream file(pathtosiriuscsv);
    if (file)
    {
      CsvFile compounds(pathtosiriuscsv, '\t');
      const UInt rowcount = compounds.rowCount();

      if (rowcount > 1)
      {
        // correction if the rowcount is smaller than the number of hits used as parameter
        // rowcount-1 because the csv header will be skipped in the loop later on.
        int header = 1;
        const UInt top_n_hits_cor = (top_n_hits >= rowcount) ? rowcount-header : top_n_hits;

        // fill identification structure containing all candidate hits for a single spectrum
        SiriusMzTabWriter::SiriusAdapterIdentification sirius_id{};

        // extract scan_number from path
        OpenMS::String str = File::path(pathtosiriuscsv);
        int scan_index = SiriusMzTabWriter::extract_scan_index(str);

        // extract scan_number from string
        boost::regex regexp("-(?<SCAN>\\d+)-");
        int scan_number = SpectrumLookup::extractScanNumber(str, regexp, false);

        // extract feature_id from string
        boost::smatch match;
        String feature_id;
        boost::regex regexp_feature("_(?<SCAN>\\d+)-");

        bool found = boost::regex_search(str, match, regexp_feature);
        if (found && match["SCAN"].matched) {feature_id = "id_" + match["SCAN"].str();}
        String unassigned = "null";

        // j = 1 because of .csv file format (header)
        for (Size j = 1; j <= top_n_hits_cor; ++j)
        {
          StringList sl;
          compounds.getRow(j, sl);
          SiriusMzTabWriter::SiriusAdapterHit sirius_hit;

          // parse single candidate hit
          sirius_hit.formula = sl[0];
          sirius_hit.adduct = sl[1];
          sirius_hit.rank = sl[2].toInt();
          sirius_hit.score = sl[3].toDouble();
          sirius_hit.treescore = sl[4].toDouble();
          sirius_hit.isoscore = sl[5].toDouble();
          sirius_hit.explainedpeaks = sl[6].toInt();
          sirius_hit.explainedintensity = sl[7].toDouble();

          sirius_id.hits.push_back(sirius_hit);
        }

        sirius_id.mz = ext_mz;
        sirius_id.rt = ext_rt;
        sirius_id.native_id = ext_nid;
        sirius_id.scan_index = scan_index;
        sirius_id.scan_number = scan_number;
        // check if results were assigned to a feature
        if (feature_id != "id_0")
        {
          sirius_id.feature_id = feature_id;
        }
        else
        {
          sirius_id.feature_id = unassigned;
        }
        sirius_result.identifications.push_back(sirius_id);

        // write metadata to mzTab file
        MzTabMetaData md;
        MzTabMSRunMetaData md_run;
        md_run.location = MzTabString(original_input_mzml);
        md.ms_run[1] = md_run;
        md.description = MzTabString("Sirius-4.0.1");

        //needed for header generation (score)
        std::map<Size, MzTabParameter> smallmolecule_search_engine_score;
        smallmolecule_search_engine_score[1].setName("score");
        smallmolecule_search_engine_score[2].setName("treescore");
        smallmolecule_search_engine_score[3].setName("isoscore");
        md.smallmolecule_search_engine_score = smallmolecule_search_engine_score;
        result.setMetaData(md);

        // write results to mzTab file
        MzTabSmallMoleculeSectionRows smsd;
        for (Size i = 0; i < sirius_result.identifications.size(); ++i)
        {
          const SiriusMzTabWriter::SiriusAdapterIdentification &id = sirius_result.identifications[i];
          for (Size j = 0; j < id.hits.size(); ++j)
          {
            const SiriusMzTabWriter::SiriusAdapterHit &hit = id.hits[j];
            MzTabSmallMoleculeSectionRow smsr;

            map<Size, MzTabDouble> engine_score;
            engine_score[1] = MzTabDouble(hit.score);
            engine_score[2] = MzTabDouble(hit.treescore);
            engine_score[3] = MzTabDouble(hit.isoscore);
            smsr.best_search_engine_score = engine_score;

            smsr.chemical_formula = MzTabString(hit.formula);
            smsr.exp_mass_to_charge = MzTabDouble(id.mz);

            vector<MzTabDouble> v_rt;
            MzTabDoubleList rt_list;
            v_rt.emplace_back(id.rt);
            rt_list.set(v_rt);
            smsr.retention_time = rt_list;

            MzTabOptionalColumnEntry adduct = make_pair("opt_global_adduct", MzTabString(hit.adduct));
            MzTabOptionalColumnEntry rank = make_pair("opt_global_rank", MzTabString(hit.rank));
            MzTabOptionalColumnEntry explainedPeaks = make_pair("opt_global_explainedPeaks", MzTabString(hit.explainedpeaks));
            MzTabOptionalColumnEntry explainedIntensity = make_pair("opt_global_explainedIntensity", MzTabString(hit.explainedintensity));
            MzTabOptionalColumnEntry compoundId = make_pair("opt_global_compoundId", MzTabString(id.scan_index));
            MzTabOptionalColumnEntry compoundScanNumber = make_pair("opt_global_compoundScanNumber", MzTabString(id.scan_number));
            MzTabOptionalColumnEntry featureId = make_pair("opt_global_featureId", MzTabString(id.feature_id));
            MzTabOptionalColumnEntry native_id = make_pair("opt_global_native_id", MzTabString(id.native_id));

            smsr.opt_.push_back(adduct);
            smsr.opt_.push_back(rank);
            smsr.opt_.push_back(explainedPeaks);
            smsr.opt_.push_back(explainedIntensity);
            smsr.opt_.push_back(compoundId);
            smsr.opt_.push_back(compoundScanNumber);
            smsr.opt_.push_back(featureId);
            smsr.opt_.push_back(native_id);
            smsd.push_back(smsr);
          }
        }
        result.setSmallMoleculeSectionRows(smsd);
      }
      file.close();
    }
  }
}

/// @endcond

max_stars_repo_name: michalsta/OpenMS

max_issues_repo_name: michalsta/OpenMS

max_forks_repo_name: michalsta/OpenMS


text:
/* Copyright © 2017 Apple Inc. All rights reserved.
 *
 * Use of this source code is governed by a BSD-3-clause license that can
 * be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
 */
#ifndef TURI_SERIALIZE_UNORDERED_MAP_HPP
#define TURI_SERIALIZE_UNORDERED_MAP_HPP

#include <boost/unordered_map.hpp>
#include <core/storage/serialization/iarchive.hpp>
#include <core/storage/serialization/oarchive.hpp>
#include <core/storage/serialization/iterator.hpp>

namespace turi {

namespace archive_detail {
  /** Serializes a map */
  template <typename OutArcType, typename T, typename U>
  struct serialize_impl<OutArcType, boost::unordered_map<T,U>, false > {
  static void exec(OutArcType& oarc,
                   const boost::unordered_map<T,U>& vec){
    serialize_iterator(oarc,
                       vec.begin(), vec.end(), vec.size());
  }
  };

  /** deserializes a map  */

  template <typename InArcType, typename T, typename U>
  struct deserialize_impl<InArcType, boost::unordered_map<T,U>, false > {
  static void exec(InArcType& iarc, boost::unordered_map<T,U>& vec){
    vec.clear();
    // get the number of elements to deserialize
    size_t length = 0;
    iarc >> length;
    // iterate through and send to the output iterator
    for (size_t x = 0; x < length ; ++x){
      std::pair<T, U> v;
      iarc >> v;
      vec[v.first] = v.second;
    }
  }
  };

} // archive_detail
} // turicreate

#if defined(__cplusplus) && __cplusplus >= 201103L
#include <unordered_map>
namespace turi {

namespace archive_detail {
  /** Serializes a map */
  template <typename OutArcType, typename T, typename U>
  struct serialize_impl<OutArcType, std::unordered_map<T,U>, false > {
  static void exec(OutArcType& oarc,
                   const std::unordered_map<T,U>& vec){
    serialize_iterator(oarc,
                       vec.begin(), vec.end(), vec.size());
  }
  };

  /** deserializes a map  */

  template <typename InArcType, typename T, typename U>
  struct deserialize_impl<InArcType, std::unordered_map<T,U>, false > {
  static void exec(InArcType& iarc, std::unordered_map<T,U>& vec){
    vec.clear();
    // get the number of elements to deserialize
    size_t length = 0;
    iarc >> length;
    // iterate through and send to the output iterator
    for (size_t x = 0; x < length ; ++x){
      std::pair<T, U> v;
      iarc >> v;
      vec[v.first] = v.second;
    }
  }
  };

} // archive_detail
} // turicreate

#endif

#endif


text:
char const* NOTES =
  "Process (PLF format) lattice: sharpen distribution, nbest, graphviz, push weights\n"
  ;

#include <iostream>
#include <fstream>
#include <vector>

#include <boost/lexical_cast.hpp>
#include <boost/program_options.hpp>

#include "filelib.h"
#include "tdict.h"
#include "prob.h"
#include "hg.h"
#include "hg_io.h"
#include "viterbi.h"
#include "kbest.h"

namespace po = boost::program_options;
using namespace std;

void InitCommandLine(int argc, char** argv, po::variables_map* conf) {
  po::options_description opts("Configuration options");
  opts.add_options()
        ("input,i", po::value<string>(), "REQ. Lattice input file (PLF), - for STDIN")
        ("prior_scale,p", po::value<double>()->default_value(1.0), "Scale path probabilities by this amount < 1 flattens, > 1 sharpens")
        ("weight,w", po::value<vector<double> >(), "Weight(s) for arc features")
	("output,o", po::value<string>()->default_value("plf"), "Output format (text, plf)")
	("command,c", po::value<string>()->default_value("push"), "Operation to perform: push, graphviz, 1best, 2best ...")
        ("help,h", "Print this help message and exit");
  po::options_description clo("Command line options");
  po::options_description dcmdline_options;
  dcmdline_options.add(opts);

  po::store(parse_command_line(argc, argv, dcmdline_options), *conf);
  po::notify(*conf);

  if (conf->count("help") || conf->count("input") == 0) {
    cerr << dcmdline_options << endl << NOTES << endl;
    exit(1);
  }
}

int main(int argc, char **argv) {
  po::variables_map conf;
  InitCommandLine(argc, argv, &conf);
  string infile = conf["input"].as<string>();
  ReadFile rf(infile);
  istream* in = rf.stream();
  assert(*in);
  SparseVector<double> wts;
  vector<double> wv;
  if (conf.count("weight") > 0) wv = conf["weight"].as<vector<double> >();
  if (wv.empty()) wv.push_back(1.0);
  for (int i = 0; i < wv.size(); ++i) {
    const string fname = "Feature_" + boost::lexical_cast<string>(i);
    cerr << "[INFO] Arc weight " << (i+1) << " = " << wv[i] << endl;
    wts.set_value(FD::Convert(fname), wv[i]);
  }
  const string cmd = conf["command"].as<string>();
  const bool push_weights = cmd == "push";
  const bool output_plf = cmd == "plf";
  const bool graphviz = cmd == "graphviz";
  const bool kbest = cmd.rfind("best") == (cmd.size() - 4) && cmd.size() > 4;
  int k = 1;
  if (kbest) {
    k = boost::lexical_cast<int>(cmd.substr(0, cmd.size() - 4));
    cerr << "KBEST = " << k << endl;
  }
  const double scale = conf["prior_scale"].as<double>();
  int lc = 0;
  while(*in) {
    ++lc;
    string plf;
    getline(*in, plf);
    if (plf.empty()) continue;
    Hypergraph hg;
    HypergraphIO::ReadFromPLF(plf, &hg);
    hg.Reweight(wts);
    if (graphviz) hg.PrintGraphviz();
    if (push_weights) hg.PushWeightsToSource(scale);
    if (output_plf) {
      cout << HypergraphIO::AsPLF(hg) << endl;
    } else {
      KBest::KBestDerivations<vector<WordID>, ESentenceTraversal> kbest(hg, k);
      for (int i = 0; i < k; ++i) {
        const KBest::KBestDerivations<vector<WordID>, ESentenceTraversal>::Derivation* d =
          kbest.LazyKthBest(hg.nodes_.size() - 1, i);
        if (!d) break;
        cout << lc << " ||| " << TD::GetString(d->yield) << " ||| " << d->score << endl;
      }
    }
  }
  return 0;
}

ext: cc

max_stars_repo_name: kho/cdec

max_issues_repo_name: kho/cdec

max_forks_repo_name: kho/cdec


text:
// SD Mod Manager

// Copyright (c) 2020 Aliaksei Karalenka <sydr1991@gmail.com>.
// Licensed under the MIT License <http://opensource.org/licenses/MIT>.

#include "stdafx.h"

#include "select_directory_view.h"

#include <boost/algorithm/string.hpp>
#include <wx/dir.h>
#include <wx/listctrl.h>
#include <wx/sizer.h>
#include <wx/imaglist.h>
#include <wx/checkbox.h>
#include <wx/button.h>
#include <wx/dirctrl.h>
#include <wx/statbox.h>
#include <wx/stattext.h>
#include <wx/dataview.h>

#include "interface/iapp_config.h"
#include "application.h"
#include "utility/sdlexcept.h"
#include "interface/service/iicon_storage.h"
#include "types/embedded_icon.h"

using namespace mm;

SelectDirectoryDialog::SelectDirectoryDialog(wxWindow *parent, IAppConfig& config, IIconStorage& iconStorage)
	: wxDialog(parent, wxID_ANY, "Select game directory for management"_lng, wxDefaultPosition, wxSize(800, 444))
	, _appConfig(config)
	, _iconStorage(iconStorage)
{
	SetIcon(_iconStorage.get(embedded_icon::main_icon));

	createControls();
	buildLayout();
	fillData();
	bindEvents();
}

wxString SelectDirectoryDialog::getSelectedPath() const
{
	return _selectedPathEdit->GetValue();
}

void SelectDirectoryDialog::createControls()
{
	auto selectedPath = _appConfig.getDataPath();
	auto dirToSelect = selectedPath.empty() ? wxDirDialogDefaultFolderStr : selectedPath.string();

	_explorerList = new wxGenericDirCtrl(this, wxID_ANY, dirToSelect,
		wxDefaultPosition, wxDefaultSize, wxDIRCTRL_DIR_ONLY | wxDIRCTRL_3D_INTERNAL);

	_recentDirsList = new wxDataViewListCtrl(this, wxID_ANY, wxDefaultPosition, wxDefaultSize,
		wxDV_HORIZ_RULES | wxDV_ROW_LINES | wxDV_NO_HEADER);
	_recentDirsList->AppendIconTextColumn("Path");

	_selectedLabel = new wxStaticText(this, wxID_ANY, "Selected:"_lng);
	_selectedPathEdit = new wxTextCtrl(this, wxID_ANY, _appConfig.getDataPath().string(), wxDefaultPosition,
		wxDefaultSize,	wxTE_READONLY);
	_accept = new wxButton(this, wxID_ANY, "Accept"_lng);

	_menu.starUnstar = _menu.menu.Append(wxID_ANY, "placeholder");
	_menu.removeFromList = _menu.menu.Append(wxID_ANY, "Remove from list"_lng);
}

void SelectDirectoryDialog::bindEvents()
{
	_explorerList->Bind(wxEVT_DIRCTRL_SELECTIONCHANGED, [=](wxCommandEvent&) {
		const wxString selected = _explorerList->GetPath();
		_selectedPathEdit->SetValue(selected);

		auto pathList = _appConfig.getKnownDataPathList();
		for (size_t i = 0; i < pathList.size(); ++i)
		{
			if (pathList[i].string() == selected)
			{
				_recentDirsList->SelectRow(i);
				return;
			}
		}

		_recentDirsList->UnselectAll();
	});

	_recentDirsList->Bind(wxEVT_DATAVIEW_SELECTION_CHANGED, [=](wxCommandEvent&) {
		auto row = _recentDirsList->GetSelectedRow();
		if (row < 0)
			return;

		auto path = wxString(_appConfig.getKnownDataPathList().at(row).string());
		_selectedPathEdit->SetValue(path);
		_explorerList->SetPath(path);
	});

	_recentDirsList->Bind(wxEVT_DATAVIEW_ITEM_ACTIVATED, [=](wxCommandEvent&) { EndModal(wxID_OK); });
	_accept->Bind(wxEVT_BUTTON, [=](wxCommandEvent&) { EndDialog(wxID_OK); });

	Bind(wxEVT_MENU, &SelectDirectoryDialog::OnMenuItemSelected, this);

	_recentDirsList->Bind(wxEVT_DATAVIEW_ITEM_CONTEXT_MENU, [=](wxDataViewEvent& event) {
		const wxDataViewItem item(event.GetItem());
		if (!item.IsOk())
		{
			event.Veto();
			return;
		}

		OnListItemContextMenu();
	});
}

void SelectDirectoryDialog::buildLayout()
{
	auto leftGroupSizer = new wxStaticBoxSizer(wxVERTICAL, this, "Explorer"_lng);
	leftGroupSizer->Add(_explorerList, wxSizerFlags(1).Expand().Border(wxALL, 4));

	auto rightGroupSizer = new wxStaticBoxSizer(wxVERTICAL, this, "Recent"_lng);
	rightGroupSizer->Add(_recentDirsList, wxSizerFlags(1).Expand().Border(wxALL, 4));

	auto contentSizer = new wxBoxSizer(wxHORIZONTAL);
	contentSizer->Add(leftGroupSizer, wxSizerFlags(1).Expand().Border(wxALL, 4));
	contentSizer->Add(rightGroupSizer, wxSizerFlags(1).Expand().Border(wxALL, 4));

	auto lastLineSizer = new wxBoxSizer(wxHORIZONTAL);
	lastLineSizer->Add(_selectedLabel, wxSizerFlags(0).CenterVertical().Border(wxALL, 4));
	lastLineSizer->Add(_selectedPathEdit, wxSizerFlags(1).CenterVertical().Border(wxALL, 4));
	lastLineSizer->Add(_accept, wxSizerFlags(0).CenterVertical().Border(wxALL, 4));

	auto mainSizer = new wxBoxSizer(wxVERTICAL);
	mainSizer->Add(contentSizer, wxSizerFlags(1).Expand().Border(wxALL, 4));
	mainSizer->Add(lastLineSizer, wxSizerFlags(0).Expand().Border(wxALL, 4));

	this->SetSizer(mainSizer);
}

void SelectDirectoryDialog::fillData()
{
	_recentDirsList->DeleteAllItems();

	for (const auto& value : _appConfig.getKnownDataPathList())
	{
		wxIcon icon = _iconStorage.get(_appConfig.dataPathHasStar(value) ? embedded_icon::bookmark : embedded_icon::blank);

		wxVector<wxVariant> data;
		data.emplace_back(wxVariant(wxDataViewIconText(value.string(), icon)));

		_recentDirsList->AppendItem(data);
		if (value == getSelectedPath().ToStdString())
			_recentDirsList->SelectRow(_recentDirsList->GetItemCount() - 1);
	}
}

void SelectDirectoryDialog::OnMenuItemSelected(const wxCommandEvent& event)
{
	const auto itemId = event.GetId();

	if (itemId == _menu.removeFromList->GetId())
		removeFromListRequested();
	else if (itemId == _menu.starUnstar->GetId())
		starUnstarRequested();
}

void SelectDirectoryDialog::removeFromListRequested()
{
	auto row = _recentDirsList->GetSelectedRow();
	if (row < 0)
		return;

	EX_TRY;
	auto path = _appConfig.getKnownDataPathList().at(row);

	_appConfig.forgetDataPath(path);
	fillData();

	EX_UNEXPECTED;
}

void SelectDirectoryDialog::starUnstarRequested()
{
	auto row = _recentDirsList->GetSelectedRow();
	if (row < 0)
		return;

	EX_TRY;

	auto path = _appConfig.getKnownDataPathList().at(row);
	_appConfig.starDataPath(path, !_appConfig.dataPathHasStar(path));
	fillData();

	EX_UNEXPECTED;
}

void SelectDirectoryDialog::OnListItemContextMenu()
{
	auto row = _recentDirsList->GetSelectedRow();
	if (row < 0)
		return;

	EX_TRY;

	auto path = _appConfig.getKnownDataPathList().at(row);
	_menu.starUnstar->SetItemLabel(!_appConfig.dataPathHasStar(path) ?
		"Add to favorites"_lng :
		"Remove from favorites"_lng);

	_recentDirsList->PopupMenu(&_menu.menu);
	EX_UNEXPECTED;
}

max_stars_repo_name: SyDr/sdmm

max_issues_repo_name: SyDr/sdmm

max_forks_repo_name: SyDr/sdmm


text:
/*
 * Copyright 2019, Offchain Labs, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "config.hpp"

#include <avm_values/tuple.hpp>
#include <avm_values/value.hpp>

#include <catch2/catch.hpp>
#include <nlohmann/json.hpp>

#include <boost/algorithm/hex.hpp>

#include <fstream>
#include <iostream>

std::vector<char> hexStringToBytes(const std::string& hexstr) {
    std::vector<char> bytes;
    boost::algorithm::unhex(hexstr.begin(), hexstr.end(),
                            std::back_inserter(bytes));
    return bytes;
}

TEST_CASE("Value hashing") {
    std::ifstream i(test_cases_path);
    nlohmann::json j;
    i >> j;
    for (auto valtest : j) {
        // Don't include codepoints in test
        if (valtest["is_codepoint"]) {
            continue;
        }
        DYNAMIC_SECTION("Test " << valtest["name"].get<std::string>()) {
            auto valBytes =
                hexStringToBytes(valtest["value"].get<std::string>());
            auto valRaw = reinterpret_cast<const char*>(valBytes.data());
            uint256_t givenHash = intx::from_string<uint256_t>(
                std::string("0x") + valtest["hash"].get<std::string>());
            auto val = deserialize_value(valRaw);
            auto calcHash = hash_value(val);
            REQUIRE(givenHash == calcHash);
        }
    }
}

// Test is disabled since it it incompatible with the new codepoint system
TEST_CASE("Value marshaling") {
    std::ifstream i(test_cases_path);
    nlohmann::json j;
    i >> j;
    for (auto valtest : j) {
        // Don't include codepoints in test
        if (valtest["is_codepoint"]) {
            continue;
        }
        DYNAMIC_SECTION("Test " << valtest["name"].get<std::string>()) {
            auto valBytes =
                hexStringToBytes(valtest["value"].get<std::string>());
            auto valRaw = reinterpret_cast<const char*>(valBytes.data());
            auto val = deserialize_value(valRaw);
            std::vector<unsigned char> buf;
            marshal_value(val, buf);
            auto valptr = (const char*)&buf[0];
            auto newval = deserialize_value(valptr);
            REQUIRE(values_equal(val, newval));
        }
    }
}

TEST_CASE("UnloadedValue equality") {
    Tuple tup;
    UnloadedValue uv(BigUnloadedValue{TUPLE, ::hash(tup), tup.getSize()});
    REQUIRE(values_equal(Value(tup), Value(uv)));
}

#define CHECK_UV_EQUALITY(uv, big)                  \
    {                                               \
        REQUIRE(uv.hash() == big.hash);             \
        REQUIRE(uv.value_size() == big.value_size); \
        REQUIRE(uv.type() == big.type);             \
        REQUIRE(uv.isHeaped() == shouldHeap);       \
    }

void checkUvIntegrity(BigUnloadedValue big, bool shouldHeap) {
    UnloadedValue uv(big);
    CHECK_UV_EQUALITY(uv, big);

    UnloadedValue copy(uv);
    CHECK_UV_EQUALITY(copy, big);

    UnloadedValue move(std::move(copy));
    CHECK_UV_EQUALITY(move, big);

    UnloadedValue copy_assign(BigUnloadedValue{ValueTypes::NUM, 0, 1});
    copy_assign = uv;
    CHECK_UV_EQUALITY(copy_assign, big);

    UnloadedValue move_assign(BigUnloadedValue{ValueTypes::NUM, 0, 1});
    move_assign = std::move(copy_assign);
    CHECK_UV_EQUALITY(move_assign, big);

    // Make sure uv isn't moved (though C++ probably wouldn't allow that
    // anyways)
    REQUIRE(uv.hash() == big.hash);
}

#undef CHYECK_UV_EQUALITY

TEST_CASE("UnloadedValue inlining") {
    Tuple tup;
    checkUvIntegrity({TUPLE, ::hash(tup), 8}, false);
    checkUvIntegrity({HASH_PRE_IMAGE, ::hash(tup), 1}, true);
    checkUvIntegrity({HASH_PRE_IMAGE, ::hash(tup), uint256_t(1) << 128}, true);
}