<commit_before>#include "gl_texture.h"

#include <cmath>
#include <glad/glad.h>
#define STB_IMAGE_IMPLEMENTATION
#include <stb_image.h>
#define STB_RECT_PACK_IMPLEMENTATION
#include <stb_rect_pack.h>

#include <file_manager.h>
#include <log.h>

#include "texture.h"

namespace oak::graphics::GLTexture {

	static const GLenum formats[][3] = {
		{ GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE },
		{ GL_RGB8, GL_RGB, GL_UNSIGNED_BYTE },
		{ GL_R8, GL_RED, GL_UNSIGNED_BYTE },
		{ GL_RGBA32F, GL_RGBA, GL_FLOAT },
		{ GL_RGB32F, GL_RGB, GL_FLOAT },
		{ GL_R32F, GL_RED, GL_FLOAT },
		{ GL_DEPTH_COMPONENT32F, GL_DEPTH_COMPONENT, GL_FLOAT },
		{ GL_DEPTH_COMPONENT32, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT },
		{ GL_DEPTH_COMPONENT24, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT },
		{ GL_DEPTH_COMPONENT16, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT }
	};

	static const int components[] = {
		4,
		3,
		1,
		4,
		3,
		1,
		1,
		1,
		1,
		1
	};

	static const GLenum types[] = {
		GL_TEXTURE_2D,
		GL_TEXTURE_3D,
		GL_TEXTURE_2D_ARRAY,
		GL_TEXTURE_CUBE_MAP
	};

	static const GLenum filter[] = {
		GL_NEAREST,
		GL_LINEAR,
		GL_LINEAR_MIPMAP_LINEAR,
		GL_NEAREST_MIPMAP_NEAREST,
		GL_LINEAR_MIPMAP_NEAREST,
		GL_NEAREST_MIPMAP_LINEAR
	};

	static const GLenum wrap[] = {
		GL_REPEAT,
		GL_CLAMP_TO_EDGE
	};

	void bind(const Texture& texture, int slot) {
		glActiveTexture(GL_TEXTURE0 + slot);
		glBindTexture(types[static_cast<int>(texture.info.type)], texture.id);
	}

	Texture create(const char *path, const TextureInfo& info) {
		int w, h, comp;
		stbi_uc *data = stbi_load(FileManager::inst().resolvePath(path).c_str(), &w, &h, &comp, components[static_cast<int>(info.format)]);

		if (data == nullptr) {
			log_print_warn("failed to load texture: %s", path);
		}

		TextureInfo ti = info;
		ti.width = w;
		ti.height = h;

		const Texture& tex = create(ti, data);

		if (static_cast<int>(info.minFilter) >= static_cast<int>(TextureFilter::LINEAR_MIP_LINEAR)) {
			glGenerateMipmap(GL_TEXTURE_2D);
		}

		stbi_image_free(data);

		return tex;
	}

	Texture create(const TextureInfo& info, void *data) {

		const auto& format = formats[static_cast<int>(info.format)];

		GLenum type = types[static_cast<int>(info.type)];
		GLenum mag = filter[static_cast<int>(info.magFilter)];
		GLenum min = filter[static_cast<int>(info.minFilter)];

		GLenum xw = wrap[static_cast<int>(info.xWrap)];
		GLenum yw = wrap[static_cast<int>(info.yWrap)];

		GLuint tex;

		glGenTextures(1, &tex);
		glBindTexture(type, tex);
		if (data != nullptr) {
			glTexImage2D(type, 0, format[0], info.width, info.height, 0, format[1], format[2], data);
		} else {
			glTexStorage2D(type, info.mipLevels, format[0], info.width, info.height);
		}

		glTexParameteri(type, GL_TEXTURE_MAG_FILTER, mag);
		glTexParameteri(type, GL_TEXTURE_MIN_FILTER, min);
		glTexParameteri(type, GL_TEXTURE_WRAP_S, xw);
		glTexParameteri(type, GL_TEXTURE_WRAP_T, yw);

		return { tex, info };
	}

	TextureAtlas createAtlas(const oak::vector<const char*>& paths, const TextureInfo& info) {
		const auto& format = formats[static_cast<int>(info.format)];

		GLenum type = types[static_cast<int>(info.type)];
		GLenum mag = filter[static_cast<int>(info.magFilter)];
		GLenum min = filter[static_cast<int>(info.minFilter)];

		GLenum xw = wrap[static_cast<int>(info.xWrap)];
		GLenum yw = wrap[static_cast<int>(info.yWrap)];

		int rcomp = components[static_cast<int>(info.format)];

		struct ImageInfo {
			const char *name;
			stbi_uc *data;
			int width, height, comp;
		};

		oak::vector<ImageInfo> images;

		//load textures
		for (auto path : paths) {
			int w, h, c;
			stbi_uc *data = stbi_load(FileManager::inst().resolvePath(path).c_str(), &w, &h, &c, rcomp);
			images.push_back({ path, data, w, h, c});
		}

		TextureAtlas atlas;
		atlas.regions.resize(images.size());

		//pack rects
		oak::vector<stbrp_node> nodes;
		nodes.resize(info.width+1);

		stbrp_context c;
		stbrp_init_target(&c, info.width, info.height, nodes.data(), nodes.size());

		oak::vector<stbrp_rect> rects;
		rects.resize(images.size());

		for (size_t i = 0; i < rects.size(); i++) {
			auto& rect = rects[i];
			const auto& it = images[i];
			rect.id = i;
			rect.w = it.width;
			rect.h = it.height;
		}

		stbrp_pack_rects(&c, rects.data(), rects.size());

		//create texture and upload it to opengl
		Texture texture;
		texture.info = info;
		glGenTextures(1, &texture.id);
		glBindTexture(type, texture.id);
		glTexStorage2D(type, 8, format[0], info.width, info.height);

		glTexParameteri(type, GL_TEXTURE_MAG_FILTER, mag);
		glTexParameteri(type, GL_TEXTURE_MIN_FILTER, min);
		glTexParameteri(type, GL_TEXTURE_WRAP_S, xw);
		glTexParameteri(type, GL_TEXTURE_WRAP_T, yw);

		float tx = 1.0f / info.width;
		float ty = 1.0f / info.height;

		if (static_cast<int>(info.minFilter) >= static_cast<int>(TextureFilter::LINEAR_MIP_LINEAR)) {
			GLuint tex;
			glGenTextures(1, &tex);
			glBindTexture(type, tex);
			for (const auto& rect : rects) {
				const auto& image = images[rect.id];
				auto& region = atlas.regions[rect.id];
				region.first = oak::string{ image.name };

				region.second.pos = { rect.x * tx, rect.y * ty };
				region.second.extent = { rect.w * ty, rect.h * ty };

				glTexImage2D(type, 0, format[0], image.width, image.height, 0, format[1], format[2], image.data);
				glGenerateMipmap(type);

				int mipLevels = 1 + floor(log2(std::max(image.width, image.height)));

				for (int i = 0; i < mipLevels && i < 8; i++) {
					glCopyImageSubData(tex, type, i, 0, 0, 0, texture.id, type, i, rect.x >> i, rect.y >> i, 0, image.width >> i, image.height >> i, 1);
				}
			}
			glDeleteTextures(1, &tex);
		} else {
			for (const auto& rect : rects) {
				const auto& image = images[rect.id];
				auto& region = atlas.regions[rect.id];
				region.first = oak::string{ image.name };

				region.second.pos = { rect.x * tx, rect.y * ty };
				region.second.extent = { rect.w * ty, rect.h * ty };

				glTexSubImage2D(type, 0, rect.x, rect.y, rect.w, rect.h, format[1], format[2], image.data);
			}
		}

		//free image data
		for (auto& image : images) {
			stbi_image_free(image.data);
		}

		atlas.texture = texture;

		return atlas;
	}

	Texture createCubemap(const oak::vector<const char*>& paths, const TextureInfo& info) {
		Texture texture;

		if (info.type != TextureType::CUBEMAP || paths.size() != 6) {
			log_print_warn("cubemap not valid");
			return texture;
		}
		texture.info = info;

		const auto& format = formats[static_cast<int>(info.format)];

		GLenum type = types[static_cast<int>(info.type)];
		GLenum mag = filter[static_cast<int>(info.magFilter)];
		GLenum min = filter[static_cast<int>(info.minFilter)];

		GLenum xw = wrap[static_cast<int>(info.xWrap)];
		GLenum yw = wrap[static_cast<int>(info.yWrap)];

		int rcomp = components[static_cast<int>(info.format)];

		glGenTextures(1, &texture.id);
		glBindTexture(type, texture.id);

		int w, h, comp, i = 0;
		stbi_uc *data;
		for (auto path : paths) {
			data = stbi_load(FileManager::inst().resolvePath(path).c_str(), &w, &h, &comp, rcomp);

			if (data == nullptr) {
				log_print_warn("failed to load texture: %s", path);
			}

			glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, format[0], w, h, 0, format[1], format[2], data);

			stbi_image_free(data);
			i++;
		}

		glTexParameteri(type, GL_TEXTURE_MAG_FILTER, mag);
		glTexParameteri(type, GL_TEXTURE_MIN_FILTER, min);
		glTexParameteri(type, GL_TEXTURE_WRAP_S, xw);
		glTexParameteri(type, GL_TEXTURE_WRAP_T, yw);
		glTexParameteri(type, GL_TEXTURE_WRAP_R, yw);

		if (min >= static_cast<int>(TextureFilter::LINEAR_MIP_LINEAR)) {
			glGenerateMipmap(GL_TEXTURE_CUBE_MAP);
		}

		glBindTexture(type, 0);

		texture.info.width = w;
		texture.info.height = h;

		return texture;
	}

	void destroy(Texture& texture) {
		if (texture.id) {
			glDeleteTextures(1, &texture.id);
			texture.id = 0;
		}
	}

}<commit_msg>fixed texture loading bug<commit_after>#include "gl_texture.h"

#include <cmath>
#include <glad/glad.h>
#define STB_IMAGE_IMPLEMENTATION
#include <stb_image.h>
#define STB_RECT_PACK_IMPLEMENTATION
#include <stb_rect_pack.h>

#include <file_manager.h>
#include <log.h>

#include "texture.h"

namespace oak::graphics::GLTexture {

	static const GLenum formats[][3] = {
		{ GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE },
		{ GL_RGB8, GL_RGB, GL_UNSIGNED_BYTE },
		{ GL_R8, GL_RED, GL_UNSIGNED_BYTE },
		{ GL_RGBA32F, GL_RGBA, GL_FLOAT },
		{ GL_RGB32F, GL_RGB, GL_FLOAT },
		{ GL_R32F, GL_RED, GL_FLOAT },
		{ GL_DEPTH_COMPONENT32F, GL_DEPTH_COMPONENT, GL_FLOAT },
		{ GL_DEPTH_COMPONENT32, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT },
		{ GL_DEPTH_COMPONENT24, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT },
		{ GL_DEPTH_COMPONENT16, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT }
	};

	static const int components[] = {
		4,
		3,
		1,
		4,
		3,
		1,
		1,
		1,
		1,
		1
	};

	static const GLenum types[] = {
		GL_TEXTURE_2D,
		GL_TEXTURE_3D,
		GL_TEXTURE_2D_ARRAY,
		GL_TEXTURE_CUBE_MAP
	};

	static const GLenum filter[] = {
		GL_NEAREST,
		GL_LINEAR,
		GL_LINEAR_MIPMAP_LINEAR,
		GL_NEAREST_MIPMAP_NEAREST,
		GL_LINEAR_MIPMAP_NEAREST,
		GL_NEAREST_MIPMAP_LINEAR
	};

	static const GLenum wrap[] = {
		GL_REPEAT,
		GL_CLAMP_TO_EDGE
	};

	void bind(const Texture& texture, int slot) {
		glActiveTexture(GL_TEXTURE0 + slot);
		glBindTexture(types[static_cast<int>(texture.info.type)], texture.id);
	}

	Texture create(const char *path, const TextureInfo& info) {
		int w, h, comp;
		stbi_uc *data = stbi_load(FileManager::inst().resolvePath(path).c_str(), &w, &h, &comp, components[static_cast<int>(info.format)]);

		if (!data) {
			log_print_warn("failed to load texture: %s", path);
		}

		TextureInfo ti = info;
		ti.width = w;
		ti.height = h;

		const Texture& tex = create(ti, data);

		if (static_cast<int>(info.minFilter) >= static_cast<int>(TextureFilter::LINEAR_MIP_LINEAR)) {
			glGenerateMipmap(GL_TEXTURE_2D);
		}

		if (data) {
			stbi_image_free(data);
		}

		return tex;
	}

	Texture create(const TextureInfo& info, void *data) {

		const auto& format = formats[static_cast<int>(info.format)];

		GLenum type = types[static_cast<int>(info.type)];
		GLenum mag = filter[static_cast<int>(info.magFilter)];
		GLenum min = filter[static_cast<int>(info.minFilter)];

		GLenum xw = wrap[static_cast<int>(info.xWrap)];
		GLenum yw = wrap[static_cast<int>(info.yWrap)];

		GLuint tex;

		glGenTextures(1, &tex);
		glBindTexture(type, tex);
		if (data != nullptr) {
			glTexImage2D(type, 0, format[0], info.width, info.height, 0, format[1], format[2], data);
		} else {
			glTexStorage2D(type, info.mipLevels, format[0], info.width, info.height);
		}

		glTexParameteri(type, GL_TEXTURE_MAG_FILTER, mag);
		glTexParameteri(type, GL_TEXTURE_MIN_FILTER, min);
		glTexParameteri(type, GL_TEXTURE_WRAP_S, xw);
		glTexParameteri(type, GL_TEXTURE_WRAP_T, yw);

		return { tex, info };
	}

	TextureAtlas createAtlas(const oak::vector<const char*>& paths, const TextureInfo& info) {
		const auto& format = formats[static_cast<int>(info.format)];

		GLenum type = types[static_cast<int>(info.type)];
		GLenum mag = filter[static_cast<int>(info.magFilter)];
		GLenum min = filter[static_cast<int>(info.minFilter)];

		GLenum xw = wrap[static_cast<int>(info.xWrap)];
		GLenum yw = wrap[static_cast<int>(info.yWrap)];

		int rcomp = components[static_cast<int>(info.format)];

		struct ImageInfo {
			const char *name;
			stbi_uc *data;
			int width, height, comp;
		};

		oak::vector<ImageInfo> images;

		//load textures
		for (auto path : paths) {
			int w, h, c;
			stbi_uc *data = stbi_load(FileManager::inst().resolvePath(path).c_str(), &w, &h, &c, rcomp);
			if (!data) {
				log_print_warn("failed to load texture: %s", path.c_str());
			}
			images.push_back({ path, data, w, h, c});
		}

		TextureAtlas atlas;
		atlas.regions.resize(images.size());

		//pack rects
		oak::vector<stbrp_node> nodes;
		nodes.resize(info.width+1);

		stbrp_context c;
		stbrp_init_target(&c, info.width, info.height, nodes.data(), nodes.size());

		oak::vector<stbrp_rect> rects;
		rects.resize(images.size());

		for (size_t i = 0; i < rects.size(); i++) {
			auto& rect = rects[i];
			const auto& it = images[i];
			rect.id = i;
			rect.w = it.width;
			rect.h = it.height;
		}

		stbrp_pack_rects(&c, rects.data(), rects.size());

		//create texture and upload it to opengl
		Texture texture;
		texture.info = info;
		glGenTextures(1, &texture.id);
		glBindTexture(type, texture.id);
		glTexStorage2D(type, 8, format[0], info.width, info.height);

		glTexParameteri(type, GL_TEXTURE_MAG_FILTER, mag);
		glTexParameteri(type, GL_TEXTURE_MIN_FILTER, min);
		glTexParameteri(type, GL_TEXTURE_WRAP_S, xw);
		glTexParameteri(type, GL_TEXTURE_WRAP_T, yw);

		float tx = 1.0f / info.width;
		float ty = 1.0f / info.height;

		if (static_cast<int>(info.minFilter) >= static_cast<int>(TextureFilter::LINEAR_MIP_LINEAR)) {
			GLuint tex;
			glGenTextures(1, &tex);
			glBindTexture(type, tex);
			for (const auto& rect : rects) {
				const auto& image = images[rect.id];
				auto& region = atlas.regions[rect.id];
				region.first = oak::string{ image.name };

				region.second.pos = { rect.x * tx, rect.y * ty };
				region.second.extent = { rect.w * ty, rect.h * ty };

				glTexImage2D(type, 0, format[0], image.width, image.height, 0, format[1], format[2], image.data);
				glGenerateMipmap(type);

				int mipLevels = 1 + floor(log2(std::max(image.width, image.height)));

				for (int i = 0; i < mipLevels && i < 8; i++) {
					glCopyImageSubData(tex, type, i, 0, 0, 0, texture.id, type, i, rect.x >> i, rect.y >> i, 0, image.width >> i, image.height >> i, 1);
				}
			}
			glDeleteTextures(1, &tex);
		} else {
			for (const auto& rect : rects) {
				const auto& image = images[rect.id];
				auto& region = atlas.regions[rect.id];
				region.first = oak::string{ image.name };

				region.second.pos = { rect.x * tx, rect.y * ty };
				region.second.extent = { rect.w * ty, rect.h * ty };

				glTexSubImage2D(type, 0, rect.x, rect.y, rect.w, rect.h, format[1], format[2], image.data);
			}
		}

		//free image data
		for (auto& image : images) {
			if (image.data) {
				stbi_image_free(image.data);
			}
		}

		atlas.texture = texture;

		return atlas;
	}

	Texture createCubemap(const oak::vector<const char*>& paths, const TextureInfo& info) {
		Texture texture;

		if (info.type != TextureType::CUBEMAP || paths.size() != 6) {
			log_print_warn("cubemap not valid");
			return texture;
		}
		texture.info = info;

		const auto& format = formats[static_cast<int>(info.format)];

		GLenum type = types[static_cast<int>(info.type)];
		GLenum mag = filter[static_cast<int>(info.magFilter)];
		GLenum min = filter[static_cast<int>(info.minFilter)];

		GLenum xw = wrap[static_cast<int>(info.xWrap)];
		GLenum yw = wrap[static_cast<int>(info.yWrap)];

		int rcomp = components[static_cast<int>(info.format)];

		glGenTextures(1, &texture.id);
		glBindTexture(type, texture.id);

		int w, h, comp, i = 0;
		stbi_uc *data;
		for (auto path : paths) {
			data = stbi_load(FileManager::inst().resolvePath(path).c_str(), &w, &h, &comp, rcomp);

			if (data == nullptr) {
				log_print_warn("failed to load texture: %s", path);
			}

			glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, format[0], w, h, 0, format[1], format[2], data);

			stbi_image_free(data);
			i++;
		}

		glTexParameteri(type, GL_TEXTURE_MAG_FILTER, mag);
		glTexParameteri(type, GL_TEXTURE_MIN_FILTER, min);
		glTexParameteri(type, GL_TEXTURE_WRAP_S, xw);
		glTexParameteri(type, GL_TEXTURE_WRAP_T, yw);
		glTexParameteri(type, GL_TEXTURE_WRAP_R, yw);

		if (min >= static_cast<int>(TextureFilter::LINEAR_MIP_LINEAR)) {
			glGenerateMipmap(GL_TEXTURE_CUBE_MAP);
		}

		glBindTexture(type, 0);

		texture.info.width = w;
		texture.info.height = h;

		return texture;
	}

	void destroy(Texture& texture) {
		if (texture.id) {
			glDeleteTextures(1, &texture.id);
			texture.id = 0;
		}
	}

}
<|endoftext|>


<commit_before>/* Begin CVS Header
   $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/semantic-test-suite/copasi_wrapper.cpp,v $
   $Revision: 1.9 $
   $Name:  $
   $Author: gauges $
   $Date: 2006/03/13 14:19:47 $
   End CVS Header */

#define COPASI_MAIN

#include <iostream>
#include <stdlib.h>

#include "copasi.h"
#include "CopasiDataModel/CCopasiDataModel.h"
#include "report/CCopasiContainer.h"
#include "model/CMetab.h"
#include "report/CCopasiObjectName.h"
#include "utilities/CCopasiVector.h"
#include "model/CModel.h"
#include "utilities/CCopasiException.h"
#include "commandline/COptionParser.h"
#include "commandline/COptions.h"

#include "trajectory/CTrajectoryTask.h"
#include "trajectory/CTrajectoryMethod.h"
#include "trajectory/CTrajectoryProblem.h"
#include "report/CReportDefinitionVector.h"
#include "report/CReportDefinition.h"

int main(int argc, char *argv[])
{
  // Parse the commandline options
  // first argument is the SBML filename
  // second argument is the endtime
  // third argument is the step number
  // fourth argument is the filename where the results are to be written
  // fifth argument is the tmp directory (this is not needed)
  // the rest of the arguments are species names for the result
  try
    {
      // Parse the commandline options
      COptions::init(argc, argv);
    }

  catch (copasi::autoexcept &e)
  {}

  catch (copasi::option_error &e)
  {}
  if (argc < 5)
    {
      std::cout << "Usage: semantic-test-suite SBMLFILENAME ENDTIME STEPNUMBER OUTFILENAME" << std::endl;
      exit(1);
    }
  char* pSBMLFilename = argv[1];
  char* pEndTime = argv[2];
  char* pStepNumber = argv[3];
  char* pOutputFilename = argv[4];
  //char* pTmpDirectory=argv[5];
  char** pSBMLSpeciesIds = new char * [argc - 6];
  unsigned int i, iMax = argc;
  CTrajectoryTask* pTrajectoryTask = NULL;

  double endTime = strtod(pEndTime, &pEndTime);
  double stepNumber = strtod(pStepNumber, &pStepNumber);
  if (endTime == 0.0)
    {
      std::cerr << "Invalid endtime " << pEndTime << std::endl;
      exit(1);
    }
  if (stepNumber == 0.0)
    {
      std::cerr << "Invalid step number " << pStepNumber << std::endl;
      exit(1);
    }

  for (i = 6; i < iMax;++i)
    {
      pSBMLSpeciesIds[i - 6] = argv[i];
      //std::cout << "Copying pointer to " <<  argv[i]  << "." << std::endl;
    }

  try
    {
      // Create the root container.
      CCopasiContainer::init();

      // Create the global data model.
      CCopasiDataModel::Global = new CCopasiDataModel;

      // Import the SBML File
      CCopasiDataModel::Global->importSBML(pSBMLFilename);

      //CCopasiDataModel::Global->getModel()->forceCompile();

      // create a report with the correct filename and all the species against
      // time.
      CReportDefinitionVector* pReports = CCopasiDataModel::Global->getReportDefinitionList();
      CReportDefinition* pReport = pReports->createReportDefinition("Report", "Output for SBML testsuite run");
      pReport->setTaskType(CCopasiTask::timeCourse);
      pReport->setIsTable(true);

      std::vector<CRegisteredObjectName>* pTable = pReport->getTableAddr();
      pTable->push_back(CCopasiObjectName("CN=Root,Model=" + CCopasiDataModel::Global->getModel()->getObjectName() + ",Reference=Time"));
      iMax = iMax - 6;
      const CCopasiVector<CMetab>& metabolites = CCopasiDataModel::Global->getModel()->getMetabolites();
      for (i = 0; i < iMax;++i)
        {
          unsigned int j, jMax = metabolites.size();
          for (j = 0; j < jMax;++j)
            {
              if (metabolites[j]->getSBMLId() == pSBMLSpeciesIds[i])
                {
                  pTable->push_back(metabolites[j]->getObject(CCopasiObjectName("Reference=Concentration"))->getCN());
                  //std::cout << "adding metabolite " << metabolites[j]->getObjectName() << " to report." << std::endl;
                  break;
                }
            }
          if (j == jMax)
            {
              std::cerr << "Could not find a metabolite for the SBML id " << pSBMLSpeciesIds[i] << std::endl;
              exit(1);
            }
        }

      // create a trajectory task
      pTrajectoryTask = new CTrajectoryTask();
      pTrajectoryTask->getProblem()->setModel(CCopasiDataModel::Global->getModel());

      pTrajectoryTask->setScheduled(true);

      pTrajectoryTask->getReport().setReportDefinition(pReport);
      pTrajectoryTask->getReport().setTarget(pOutputFilename);
      pTrajectoryTask->getReport().setAppend(false);

      CTrajectoryProblem* pProblem = dynamic_cast<CTrajectoryProblem*>(pTrajectoryTask->getProblem());

      pProblem->setStepNumber((const unsigned C_INT32)stepNumber);
      pProblem->setDuration((const C_FLOAT64)endTime);
      pProblem->setTimeSeriesRequested(true);
      //pProblem->setInitialState(CCopasiDataModel::Global->getModel()->getInitialState());

      CCopasiVectorN< CCopasiTask > & TaskList = * CCopasiDataModel::Global->getTaskList();

      TaskList.remove("Time-Course");
      TaskList.add(pTrajectoryTask, true);

      // save the file for control purposes
      std::string saveFilename = pSBMLFilename;
      saveFilename = saveFilename.substr(0, saveFilename.length() - 4) + ".cps";
      CCopasiDataModel::Global->saveModel(saveFilename, true);

      // Run the trajectory task

      pTrajectoryTask->initialize(CCopasiTask::OUTPUT_COMPLETE, NULL);
      pTrajectoryTask->process(true);
      pTrajectoryTask->restore();

      // create another report that will write to the directory where the input file came from
      // this can be used for debugging
      // create a trajectory task
      pTrajectoryTask->getReport().setTarget(saveFilename + std::string(".CSV"));

      pTrajectoryTask->initialize(CCopasiTask::OUTPUT_COMPLETE, NULL);
      pTrajectoryTask->process(true);
      pTrajectoryTask->restore();
    }
  catch (CCopasiException Exception)
    {
      std::cerr << Exception.getMessage().getText() << std::endl;
    }

  pdelete(CCopasiDataModel::Global);
  pdelete(CCopasiContainer::Root);

  return 0;
}
<commit_msg>OK. This is the correct usage.<commit_after>/* Begin CVS Header
   $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/semantic-test-suite/copasi_wrapper.cpp,v $
   $Revision: 1.10 $
   $Name:  $
   $Author: gauges $
   $Date: 2006/03/13 14:24:42 $
   End CVS Header */

#define COPASI_MAIN

#include <iostream>
#include <stdlib.h>

#include "copasi.h"
#include "CopasiDataModel/CCopasiDataModel.h"
#include "report/CCopasiContainer.h"
#include "model/CMetab.h"
#include "report/CCopasiObjectName.h"
#include "utilities/CCopasiVector.h"
#include "model/CModel.h"
#include "utilities/CCopasiException.h"
#include "commandline/COptionParser.h"
#include "commandline/COptions.h"

#include "trajectory/CTrajectoryTask.h"
#include "trajectory/CTrajectoryMethod.h"
#include "trajectory/CTrajectoryProblem.h"
#include "report/CReportDefinitionVector.h"
#include "report/CReportDefinition.h"

int main(int argc, char *argv[])
{
  // Parse the commandline options
  // first argument is the SBML filename
  // second argument is the endtime
  // third argument is the step number
  // fourth argument is the filename where the results are to be written
  // fifth argument is the tmp directory (this is not needed)
  // the rest of the arguments are species names for the result
  try
    {
      // Parse the commandline options
      COptions::init(argc, argv);
    }

  catch (copasi::autoexcept &e)
  {}

  catch (copasi::option_error &e)
  {}
  if (argc < 5)
    {
      std::cout << "Usage: semantic-test-suite SBMLFILENAME ENDTIME STEPNUMBER OUTFILENAME TMPDIR SPECIESID1 SPECIESID2 ..." << std::endl;
      exit(1);
    }
  char* pSBMLFilename = argv[1];
  char* pEndTime = argv[2];
  char* pStepNumber = argv[3];
  char* pOutputFilename = argv[4];
  //char* pTmpDirectory=argv[5];
  char** pSBMLSpeciesIds = new char * [argc - 6];
  unsigned int i, iMax = argc;
  CTrajectoryTask* pTrajectoryTask = NULL;

  double endTime = strtod(pEndTime, &pEndTime);
  double stepNumber = strtod(pStepNumber, &pStepNumber);
  if (endTime == 0.0)
    {
      std::cerr << "Invalid endtime " << pEndTime << std::endl;
      exit(1);
    }
  if (stepNumber == 0.0)
    {
      std::cerr << "Invalid step number " << pStepNumber << std::endl;
      exit(1);
    }

  for (i = 6; i < iMax;++i)
    {
      pSBMLSpeciesIds[i - 6] = argv[i];
      //std::cout << "Copying pointer to " <<  argv[i]  << "." << std::endl;
    }

  try
    {
      // Create the root container.
      CCopasiContainer::init();

      // Create the global data model.
      CCopasiDataModel::Global = new CCopasiDataModel;

      // Import the SBML File
      CCopasiDataModel::Global->importSBML(pSBMLFilename);

      //CCopasiDataModel::Global->getModel()->forceCompile();

      // create a report with the correct filename and all the species against
      // time.
      CReportDefinitionVector* pReports = CCopasiDataModel::Global->getReportDefinitionList();
      CReportDefinition* pReport = pReports->createReportDefinition("Report", "Output for SBML testsuite run");
      pReport->setTaskType(CCopasiTask::timeCourse);
      pReport->setIsTable(true);

      std::vector<CRegisteredObjectName>* pTable = pReport->getTableAddr();
      pTable->push_back(CCopasiObjectName("CN=Root,Model=" + CCopasiDataModel::Global->getModel()->getObjectName() + ",Reference=Time"));
      iMax = iMax - 6;
      const CCopasiVector<CMetab>& metabolites = CCopasiDataModel::Global->getModel()->getMetabolites();
      for (i = 0; i < iMax;++i)
        {
          unsigned int j, jMax = metabolites.size();
          for (j = 0; j < jMax;++j)
            {
              if (metabolites[j]->getSBMLId() == pSBMLSpeciesIds[i])
                {
                  pTable->push_back(metabolites[j]->getObject(CCopasiObjectName("Reference=Concentration"))->getCN());
                  //std::cout << "adding metabolite " << metabolites[j]->getObjectName() << " to report." << std::endl;
                  break;
                }
            }
          if (j == jMax)
            {
              std::cerr << "Could not find a metabolite for the SBML id " << pSBMLSpeciesIds[i] << std::endl;
              exit(1);
            }
        }

      // create a trajectory task
      pTrajectoryTask = new CTrajectoryTask();
      pTrajectoryTask->getProblem()->setModel(CCopasiDataModel::Global->getModel());

      pTrajectoryTask->setScheduled(true);

      pTrajectoryTask->getReport().setReportDefinition(pReport);
      pTrajectoryTask->getReport().setTarget(pOutputFilename);
      pTrajectoryTask->getReport().setAppend(false);

      CTrajectoryProblem* pProblem = dynamic_cast<CTrajectoryProblem*>(pTrajectoryTask->getProblem());

      pProblem->setStepNumber((const unsigned C_INT32)stepNumber);
      pProblem->setDuration((const C_FLOAT64)endTime);
      pProblem->setTimeSeriesRequested(true);
      //pProblem->setInitialState(CCopasiDataModel::Global->getModel()->getInitialState());

      CCopasiVectorN< CCopasiTask > & TaskList = * CCopasiDataModel::Global->getTaskList();

      TaskList.remove("Time-Course");
      TaskList.add(pTrajectoryTask, true);

      // save the file for control purposes
      std::string saveFilename = pSBMLFilename;
      saveFilename = saveFilename.substr(0, saveFilename.length() - 4) + ".cps";
      CCopasiDataModel::Global->saveModel(saveFilename, true);

      // Run the trajectory task

      pTrajectoryTask->initialize(CCopasiTask::OUTPUT_COMPLETE, NULL);
      pTrajectoryTask->process(true);
      pTrajectoryTask->restore();

      // create another report that will write to the directory where the input file came from
      // this can be used for debugging
      // create a trajectory task
      pTrajectoryTask->getReport().setTarget(saveFilename + std::string(".CSV"));

      pTrajectoryTask->initialize(CCopasiTask::OUTPUT_COMPLETE, NULL);
      pTrajectoryTask->process(true);
      pTrajectoryTask->restore();
    }
  catch (CCopasiException Exception)
    {
      std::cerr << Exception.getMessage().getText() << std::endl;
    }

  pdelete(CCopasiDataModel::Global);
  pdelete(CCopasiContainer::Root);

  return 0;
}
<|endoftext|>


<commit_before>/* Begin CVS Header
   $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/semantic-test-suite/copasi_wrapper.cpp,v $
   $Revision: 1.1 $
   $Name:  $
   $Author: gauges $
   $Date: 2005/07/27 12:46:46 $
   End CVS Header */

#define COPASI_MAIN

#include <iostream>
#include <stdlib.h>

#include "copasi.h"
#include "CopasiDataModel/CCopasiDataModel.h"
#include "report/CCopasiContainer.h"
#include "model/CMetab.h"
#include "report/CCopasiObjectName.h"
#include "utilities/CCopasiVector.h"
#include "model/CModel.h"
#include "utilities/CCopasiException.h"
#include "commandline/COptionParser.h"
#include "commandline/COptions.h"

#include "trajectory/CTrajectoryTask.h"
#include "trajectory/CTrajectoryMethod.h"
#include "trajectory/CTrajectoryProblem.h"
#include "report/CReportDefinitionVector.h"
#include "report/CReportDefinition.h"

int main(int argc, char *argv[])
{
  // Parse the commandline options
  // first argument is the SBML filename
  // second argument is the endtime
  // third argument is the step number
  // fourth argument is the filename where the results are to be written
  // fifth argument is the tmp directory (this is not needed)
  // the rest of the arguments are species names for the result
  try
    {
      // Parse the commandline options
      COptions::init(argc, argv);
    }

  catch (copasi::autoexcept &e)
  {}

  catch (copasi::option_error &e)
    {
    }

  char* pSBMLFilename = argv[1];
  char* pEndTime = argv[2];
  char* pStepNumber = argv[3];
  char* pOutputFilename = argv[4];
  //char* pTmpDirectory=argv[5];
  char** pSBMLSpeciesIds = new char * [argc - 6];
  unsigned int i, iMax = argc;
  CTrajectoryTask* pTrajectoryTask = NULL;

  double endTime = strtod(pEndTime, &pEndTime);
  double stepNumber = strtod(pStepNumber, &pStepNumber);
  if (endTime == 0.0)
    {
      std::cerr << "Invalid endtime " << pEndTime << std::endl;
      exit(1);
    }
  if (stepNumber == 0.0)
    {
      std::cerr << "Invalid step number " << pStepNumber << std::endl;
      exit(1);
    }

  for (i = 6; i < iMax;++i)
    {
      pSBMLSpeciesIds[i - 6] = argv[i];
    }

  try
    {
      // Create the root container.
      CCopasiContainer::init();

      // Create the global data model.
      CCopasiDataModel::Global = new CCopasiDataModel;

      // Import the SBML File
      CCopasiDataModel::Global->importSBML(pSBMLFilename);

      // create a report with the correct filename and all the species against
      // time.
      CReportDefinitionVector* pReports = CCopasiDataModel::Global->getReportDefinitionList();
      CReportDefinition* pReport = pReports->createReportDefinition("Report", "Output for SBML testsuite run");
      pReport->setTaskType(CCopasiTask::timeCourse);
      pReport->setIsTable(true);

      std::vector<CRegisteredObjectName>* pTable = pReport->getTableAddr();
      pTable->push_back(CCopasiObjectName("CN=Root,Model=" + CCopasiDataModel::Global->getModel()->getObjectName() + ",Reference=Time"));
      iMax = iMax - 6;
      const CCopasiVector<CMetab>& metabolites = CCopasiDataModel::Global->getModel()->getMetabolites();
      for (i = 0; i < iMax;++i)
        {
          unsigned int j, jMax = metabolites.size();
          for (j = 0; j < jMax;++j)
            {
              if (metabolites[j]->getSBMLId() == pSBMLSpeciesIds[i])
                {
                  pTable->push_back(metabolites[i]->getObject(CCopasiObjectName("Reference=Concentration"))->getCN());
                  break;
                }
            }
          if (j == jMax)
            {
              std::cerr << "Could not find a metabolite for the SBML id " << pSBMLSpeciesIds[i] << std::endl;
              exit(1);
            }
        }

      // create a trajectory task
      pTrajectoryTask = new CTrajectoryTask();
      pTrajectoryTask->getProblem()->setModel(CCopasiDataModel::Global->getModel());

      pTrajectoryTask->getReport().setReportDefinition(pReport);
      pTrajectoryTask->getReport().setTarget(pOutputFilename);
      pTrajectoryTask->getReport().setAppend(false);

      //CTrajectoryMethod* pMethod=dynamic_cast<CTrajectoryMethod*>(pTrajectoryTask->getMethod());
      CTrajectoryProblem* pProblem = dynamic_cast<CTrajectoryProblem*>(pTrajectoryTask->getProblem());

      pProblem->setStepNumber((const unsigned C_INT32)stepNumber);
      pProblem->setEndTime((const C_FLOAT64)endTime);
      pProblem->setTimeSeriesRequested(true);

      CCopasiVectorN< CCopasiTask > & TaskList = * CCopasiDataModel::Global->getTaskList();

      TaskList.remove("Time-Course");
      TaskList.add(pTrajectoryTask, true);

      // save the file for control purposes
      std::string saveFilename = pSBMLFilename;
      saveFilename = saveFilename.substr(0, saveFilename.length() - 4) + ".cps";
      CCopasiDataModel::Global->saveModel(saveFilename, true);

      // Run the trajectory task

      pTrajectoryTask->initialize();
      pTrajectoryTask->process();
      pTrajectoryTask->restore();
    }
  catch (CCopasiException Exception)
    {
      std::cerr << Exception.getMessage().getText() << std::endl;
    }

  pdelete(CCopasiDataModel::Global);
  pdelete(CCopasiContainer::Root);

  return 0;
}
<commit_msg>Write the results twice to file. One is written to the directory of the specific test. This is nice for debugging.<commit_after>/* Begin CVS Header
   $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/semantic-test-suite/copasi_wrapper.cpp,v $
   $Revision: 1.2 $
   $Name:  $
   $Author: gauges $
   $Date: 2005/07/27 13:14:07 $
   End CVS Header */

#define COPASI_MAIN

#include <iostream>
#include <stdlib.h>

#include "copasi.h"
#include "CopasiDataModel/CCopasiDataModel.h"
#include "report/CCopasiContainer.h"
#include "model/CMetab.h"
#include "report/CCopasiObjectName.h"
#include "utilities/CCopasiVector.h"
#include "model/CModel.h"
#include "utilities/CCopasiException.h"
#include "commandline/COptionParser.h"
#include "commandline/COptions.h"

#include "trajectory/CTrajectoryTask.h"
#include "trajectory/CTrajectoryMethod.h"
#include "trajectory/CTrajectoryProblem.h"
#include "report/CReportDefinitionVector.h"
#include "report/CReportDefinition.h"

int main(int argc, char *argv[])
{
  // Parse the commandline options
  // first argument is the SBML filename
  // second argument is the endtime
  // third argument is the step number
  // fourth argument is the filename where the results are to be written
  // fifth argument is the tmp directory (this is not needed)
  // the rest of the arguments are species names for the result
  try
    {
      // Parse the commandline options
      COptions::init(argc, argv);
    }

  catch (copasi::autoexcept &e)
  {}

  catch (copasi::option_error &e)
  {}

  char* pSBMLFilename = argv[1];
  char* pEndTime = argv[2];
  char* pStepNumber = argv[3];
  char* pOutputFilename = argv[4];
  //char* pTmpDirectory=argv[5];
  char** pSBMLSpeciesIds = new char * [argc - 6];
  unsigned int i, iMax = argc;
  CTrajectoryTask* pTrajectoryTask = NULL;

  double endTime = strtod(pEndTime, &pEndTime);
  double stepNumber = strtod(pStepNumber, &pStepNumber);
  if (endTime == 0.0)
    {
      std::cerr << "Invalid endtime " << pEndTime << std::endl;
      exit(1);
    }
  if (stepNumber == 0.0)
    {
      std::cerr << "Invalid step number " << pStepNumber << std::endl;
      exit(1);
    }

  for (i = 6; i < iMax;++i)
    {
      pSBMLSpeciesIds[i - 6] = argv[i];
    }

  try
    {
      // Create the root container.
      CCopasiContainer::init();

      // Create the global data model.
      CCopasiDataModel::Global = new CCopasiDataModel;

      // Import the SBML File
      CCopasiDataModel::Global->importSBML(pSBMLFilename);

      // create a report with the correct filename and all the species against
      // time.
      CReportDefinitionVector* pReports = CCopasiDataModel::Global->getReportDefinitionList();
      CReportDefinition* pReport = pReports->createReportDefinition("Report", "Output for SBML testsuite run");
      pReport->setTaskType(CCopasiTask::timeCourse);
      pReport->setIsTable(true);

      std::vector<CRegisteredObjectName>* pTable = pReport->getTableAddr();
      pTable->push_back(CCopasiObjectName("CN=Root,Model=" + CCopasiDataModel::Global->getModel()->getObjectName() + ",Reference=Time"));
      iMax = iMax - 6;
      const CCopasiVector<CMetab>& metabolites = CCopasiDataModel::Global->getModel()->getMetabolites();
      for (i = 0; i < iMax;++i)
        {
          unsigned int j, jMax = metabolites.size();
          for (j = 0; j < jMax;++j)
            {
              if (metabolites[j]->getSBMLId() == pSBMLSpeciesIds[i])
                {
                  pTable->push_back(metabolites[i]->getObject(CCopasiObjectName("Reference=Concentration"))->getCN());
                  break;
                }
            }
          if (j == jMax)
            {
              std::cerr << "Could not find a metabolite for the SBML id " << pSBMLSpeciesIds[i] << std::endl;
              exit(1);
            }
        }

      // create a trajectory task
      pTrajectoryTask = new CTrajectoryTask();
      pTrajectoryTask->getProblem()->setModel(CCopasiDataModel::Global->getModel());

      pTrajectoryTask->getReport().setReportDefinition(pReport);
      pTrajectoryTask->getReport().setTarget(pOutputFilename);
      pTrajectoryTask->getReport().setAppend(false);

      CTrajectoryProblem* pProblem = dynamic_cast<CTrajectoryProblem*>(pTrajectoryTask->getProblem());

      pProblem->setStepNumber((const unsigned C_INT32)stepNumber);
      pProblem->setEndTime((const C_FLOAT64)endTime);
      pProblem->setTimeSeriesRequested(true);

      CCopasiVectorN< CCopasiTask > & TaskList = * CCopasiDataModel::Global->getTaskList();

      TaskList.remove("Time-Course");
      TaskList.add(pTrajectoryTask, true);

      // save the file for control purposes
      std::string saveFilename = pSBMLFilename;
      saveFilename = saveFilename.substr(0, saveFilename.length() - 4) + ".cps";
      CCopasiDataModel::Global->saveModel(saveFilename, true);

      // Run the trajectory task

      pTrajectoryTask->initialize();
      pTrajectoryTask->process();
      pTrajectoryTask->restore();

      // create another report that will write to the directory where the input file came from
      // this can be used for debugging
      // create a trajectory task
      pTrajectoryTask->getReport().setTarget(saveFilename + std::string(".CSV"));

      pTrajectoryTask->initialize();
      pTrajectoryTask->process();
      pTrajectoryTask->restore();
    }
  catch (CCopasiException Exception)
    {
      std::cerr << Exception.getMessage().getText() << std::endl;
    }

  pdelete(CCopasiDataModel::Global);
  pdelete(CCopasiContainer::Root);

  return 0;
}
<|endoftext|>


<commit_before>#include "TEnum.h"
#include "TInterpreter.h"

#include "gtest/gtest.h"
#include "gmock/gmock.h"

TEST(TEnum, UnderlyingType)
{
   gInterpreter->Declare(R"CODE(
enum E0 { kE0One };
enum E1 { kE1One = LONG_MAX };
enum E2 { kE2One = ULONG_MAX };
enum E3: char { kE3One };

enum Eb: bool { kEbOne };
enum Euc: unsigned char { kEucOne };
enum Esc: signed char { kEscOne };
enum Eus: unsigned short { kEusOne };
enum Ess: signed short { kEssOne };
enum Eui: unsigned int { kEuiOne };
enum Esi: signed int { kEsiOne };
enum Eul: unsigned long { kEulOne };
enum Esl: signed long { kEslOne };
enum Eull: unsigned long long { kEullOne };
enum Esll: signed long long { kEsllOne };

enum Ecl: short;

enum class ECb: bool { kOne };
enum class ECuc: unsigned char { kOne };
enum class ECsc: signed char { kOne };
enum class ECus: unsigned short { kOne };
enum class ECss: signed short { kOne };
enum class ECui: unsigned int { kOne };
enum class ECsi: signed int { kOne };
enum class ECul: unsigned long { kOne };
enum class ECsl: signed long { kOne };
enum class ECull: unsigned long long { kOne };
enum class ECsll: signed long long { kOne };

enum class ECcl: short;
)CODE"
			);

   EXPECT_EQ(TEnum::GetEnum("E0")->GetUnderlyingType(), kUInt_t);
   EXPECT_EQ(TEnum::GetEnum("E1")->GetUnderlyingType(), kULong_t);
   EXPECT_EQ(TEnum::GetEnum("E2")->GetUnderlyingType(), kULong_t);
   EXPECT_EQ(TEnum::GetEnum("E3")->GetUnderlyingType(), kChar_t);

   EXPECT_EQ(TEnum::GetEnum("Eb")->GetUnderlyingType(), kBool_t);
   EXPECT_EQ(TEnum::GetEnum("Euc")->GetUnderlyingType(), kUChar_t);
   EXPECT_EQ(TEnum::GetEnum("Esc")->GetUnderlyingType(), kChar_t);
   EXPECT_EQ(TEnum::GetEnum("Eus")->GetUnderlyingType(), kUShort_t);
   EXPECT_EQ(TEnum::GetEnum("Ess")->GetUnderlyingType(), kShort_t);
   EXPECT_EQ(TEnum::GetEnum("Eui")->GetUnderlyingType(), kUInt_t);
   EXPECT_EQ(TEnum::GetEnum("Esi")->GetUnderlyingType(), kInt_t);
   EXPECT_EQ(TEnum::GetEnum("Eul")->GetUnderlyingType(), kULong_t);
   EXPECT_EQ(TEnum::GetEnum("Esl")->GetUnderlyingType(), kLong_t);
   EXPECT_EQ(TEnum::GetEnum("Eull")->GetUnderlyingType(), kULong64_t);
   EXPECT_EQ(TEnum::GetEnum("Esll")->GetUnderlyingType(), kLong64_t);
   EXPECT_EQ(TEnum::GetEnum("Ecl")->GetUnderlyingType(), kShort_t);
}

TEST(TEnum, Scoped)
{
   gInterpreter->Declare(R"CODE(
enum class EC { kOne };
enum class EC1: long { kOne };
enum ED { kEDOne };
)CODE"
			);
   EXPECT_EQ(TEnum::GetEnum("EC")->Property() & kIsScopedEnum, kIsScopedEnum);
   EXPECT_EQ(TEnum::GetEnum("EC1")->Property() & kIsScopedEnum, kIsScopedEnum);
   EXPECT_EQ(TEnum::GetEnum("ED")->Property() & kIsScopedEnum, 0);
}
<commit_msg>[meta] Fix testTEnum on 32bit:<commit_after>#include "TEnum.h"
#include "TInterpreter.h"

#include "gtest/gtest.h"
#include "gmock/gmock.h"

#include <type_traits>

TEST(TEnum, UnderlyingType)
{
   gInterpreter->Declare(R"CODE(
enum E0 { kE0One };
enum E1 { kE1One = LONG_MAX };
enum E2 { kE2One = ULONG_MAX };
enum E3: char { kE3One };

enum Eb: bool { kEbOne };
enum Euc: unsigned char { kEucOne };
enum Esc: signed char { kEscOne };
enum Eus: unsigned short { kEusOne };
enum Ess: signed short { kEssOne };
enum Eui: unsigned int { kEuiOne };
enum Esi: signed int { kEsiOne };
enum Eul: unsigned long { kEulOne };
enum Esl: signed long { kEslOne };
enum Eull: unsigned long long { kEullOne };
enum Esll: signed long long { kEsllOne };

enum Ecl: short;

enum class ECb: bool { kOne };
enum class ECuc: unsigned char { kOne };
enum class ECsc: signed char { kOne };
enum class ECus: unsigned short { kOne };
enum class ECss: signed short { kOne };
enum class ECui: unsigned int { kOne };
enum class ECsi: signed int { kOne };
enum class ECul: unsigned long { kOne };
enum class ECsl: signed long { kOne };
enum class ECull: unsigned long long { kOne };
enum class ECsll: signed long long { kOne };

enum class ECcl: short;
)CODE"
			);

   enum E0 { kE0One };
   enum E1 { kE1One = LONG_MAX };
   enum E2 { kE2One = ULONG_MAX };

   EXPECT_EQ(TEnum::GetEnum("E0")->GetUnderlyingType(), TDataType::GetType(typeid(std::underlying_type<E0>::type)));
   EXPECT_EQ(TEnum::GetEnum("E1")->GetUnderlyingType(), TDataType::GetType(typeid(std::underlying_type<E1>::type)));
   EXPECT_EQ(TEnum::GetEnum("E2")->GetUnderlyingType(), TDataType::GetType(typeid(std::underlying_type<E2>::type)));
   EXPECT_EQ(TEnum::GetEnum("E3")->GetUnderlyingType(), kChar_t);

   EXPECT_EQ(TEnum::GetEnum("Eb")->GetUnderlyingType(), kBool_t);
   EXPECT_EQ(TEnum::GetEnum("Euc")->GetUnderlyingType(), kUChar_t);
   EXPECT_EQ(TEnum::GetEnum("Esc")->GetUnderlyingType(), kChar_t);
   EXPECT_EQ(TEnum::GetEnum("Eus")->GetUnderlyingType(), kUShort_t);
   EXPECT_EQ(TEnum::GetEnum("Ess")->GetUnderlyingType(), kShort_t);
   EXPECT_EQ(TEnum::GetEnum("Eui")->GetUnderlyingType(), kUInt_t);
   EXPECT_EQ(TEnum::GetEnum("Esi")->GetUnderlyingType(), kInt_t);
   EXPECT_EQ(TEnum::GetEnum("Eul")->GetUnderlyingType(), kULong_t);
   EXPECT_EQ(TEnum::GetEnum("Esl")->GetUnderlyingType(), kLong_t);
   EXPECT_EQ(TEnum::GetEnum("Eull")->GetUnderlyingType(), kULong64_t);
   EXPECT_EQ(TEnum::GetEnum("Esll")->GetUnderlyingType(), kLong64_t);
   EXPECT_EQ(TEnum::GetEnum("Ecl")->GetUnderlyingType(), kShort_t);
}

TEST(TEnum, Scoped)
{
   gInterpreter->Declare(R"CODE(
enum class EC { kOne };
enum class EC1: long { kOne };
enum ED { kEDOne };
)CODE"
			);
   EXPECT_EQ(TEnum::GetEnum("EC")->Property() & kIsScopedEnum, kIsScopedEnum);
   EXPECT_EQ(TEnum::GetEnum("EC1")->Property() & kIsScopedEnum, kIsScopedEnum);
   EXPECT_EQ(TEnum::GetEnum("ED")->Property() & kIsScopedEnum, 0);
}
<|endoftext|>


<commit_before>/*
 * Copyright 2017 Root404, Co
 *                Alvaro Stagg [alvarostagg@openmailbox.org]
 *
 * 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 "Cipher.h"

#include <iostream>
#include <algorithm>

#include <cryptopp/hex.h>
#include <cryptopp/sha.h>

Cipher::Cipher(const std::string& key)
{
    CryptoPP::SHA256 hash;
    unsigned char digest[CryptoPP::SHA256::DIGESTSIZE];

    hash.CalculateDigest(digest, (unsigned char*)key.c_str(), key.length());

    CryptoPP::HexEncoder encoder;
    encoder.Attach(new CryptoPP::StringSink(password));
    encoder.Put(digest, sizeof(digest));
    encoder.MessageEnd();
    std::transform(password.begin(), password.end(), password.begin(), ::tolower);

    key_length = password.length() - 1;
    key_index = 0;
}

int Cipher::Process(std::string fileName)
{
    std::string new_file_name = fileName;
    size_t file_name_iter = new_file_name.find(".crypted");

    if (file_name_iter == std::string::npos)
        new_file_name += ".crypted";
    else
        new_file_name.replace(file_name_iter, 8, "");

    int ret = 0;

    std::ifstream file(fileName, std::fstream::in);
    if (!file.is_open())
    {
        std::cerr << "[*] unable to open \"" << fileName << "\" file. Omiting." << std::endl;
        return -1;
    }
    else
    {
        /* I don't know if this is the best way to get the size
         * of an opened file. But certainly it's better than
         * open the same file twice at time.
         */
        std::ifstream::pos_type file_size = file.tellg();
        file.seekg(0, std::ios::end);
        file_size += file.tellg();
        file.seekg(0, std::ios::beg);

        if (file_size <= 0)
        {
            std::cerr << "[*] unable to get \"" << fileName << "\" file size. Omiting." << std::endl;
            ret = -1;
        }
        else
        {
            long int blocks = 0;
            while (true)
            {
                long int start = (BLOCK_SIZE * blocks);
                long int end   = start + BLOCK_SIZE;

                if (end > file_size)
                    end = file_size;

                block_chunks.push_back(block_chunk{start, end});
                blocks++;

                if (start > file_size)
                    break;
            }

            std::ofstream encoded_file(new_file_name, std::fstream::out);
            if (!encoded_file.is_open())
            {
                std::cerr << "[*] unable to create \"" << new_file_name << "\" file for writing. Omiting." << std::endl;
                ret = -1;
            }
            else
            {
                long int data_counter = 0;
                std::vector<unsigned char> file_data;

                for (unsigned int i = 0; i < blocks; i++)
                {
                    std::cout << "\r" << fileName << ": Encoding block " << i << " of " << blocks - 1 << std::flush;
                    while (file >> std::noskipws >> a)
                    {
                        k = password[key_index];
                        r = a ^ k;

                        file_data.push_back(r);
                        data_counter++;

                        if ((data_counter + block_chunks[i].start) >= block_chunks[i].end)
                        {
                            key_index = data_counter = 0;
                            for (auto& _bytes : file_data)
                                encoded_file << _bytes;

                            file_data.clear();
                            break;
                        }

                        if (key_index >= key_length)
                            key_index = 0;
                        else
                            key_index++;
                    }
                }

                std::cout << ". Done." << std::endl;

                encoded_file.close();
                file.close();
            }
        }
    }

    return ret;
}

Cipher::~Cipher()
{
    if (block_chunks.size() != 0)
        block_chunks.clear();
}
<commit_msg>Using correct types<commit_after>/*
 * Copyright 2017 Root404, Co
 *                Alvaro Stagg [alvarostagg@openmailbox.org]
 *
 * 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 "Cipher.h"

#include <iostream>
#include <algorithm>

#include <cryptopp/hex.h>
#include <cryptopp/sha.h>

Cipher::Cipher(const std::string& key)
{
    CryptoPP::SHA256 hash;
    unsigned char digest[CryptoPP::SHA256::DIGESTSIZE];

    hash.CalculateDigest(digest, (unsigned char*)key.c_str(), key.length());

    CryptoPP::HexEncoder encoder;
    encoder.Attach(new CryptoPP::StringSink(password));
    encoder.Put(digest, sizeof(digest));
    encoder.MessageEnd();
    std::transform(password.begin(), password.end(), password.begin(), ::tolower);

    key_length = password.length() - 1;
    key_index = 0;
}

int Cipher::Process(std::string fileName)
{
    std::string new_file_name = fileName;
    std::string::size_type file_name_iter = new_file_name.find(".crypted");

    if (file_name_iter == std::string::npos)
        new_file_name += ".crypted";
    else
        new_file_name.replace(file_name_iter, 8, "");

    int ret = 0;

    std::ifstream file(fileName, std::fstream::in);
    if (!file.is_open())
    {
        std::cerr << "[*] unable to open \"" << fileName << "\" file. Omiting." << std::endl;
        return -1;
    }
    else
    {
        /* I don't know if this is the best way to get the size
         * of an opened file. But certainly it's better than
         * open the same file twice at time.
         */
        std::ifstream::pos_type file_size = file.tellg();
        file.seekg(0, std::ios::end);
        file_size += file.tellg();
        file.seekg(0, std::ios::beg);

        if (file_size <= 0)
        {
            std::cerr << "[*] unable to get \"" << fileName << "\" file size. Omiting." << std::endl;
            ret = -1;
        }
        else
        {
            long int blocks = 0;
            while (true)
            {
                long int start = (BLOCK_SIZE * blocks);
                long int end   = start + BLOCK_SIZE;

                if (end > file_size)
                    end = file_size;

                block_chunks.push_back(block_chunk{start, end});
                blocks++;

                if (start > file_size)
                    break;
            }

            std::ofstream encoded_file(new_file_name, std::fstream::out);
            if (!encoded_file.is_open())
            {
                std::cerr << "[*] unable to create \"" << new_file_name << "\" file for writing. Omiting." << std::endl;
                ret = -1;
            }
            else
            {
                long int data_counter = 0;
                std::vector<unsigned char> file_data;

                for (unsigned int i = 0; i < blocks; i++)
                {
                    std::cout << "\r" << fileName << ": Encoding block " << i << " of " << blocks - 1 << std::flush;
                    while (file >> std::noskipws >> a)
                    {
                        k = password[key_index];
                        r = a ^ k;

                        file_data.push_back(r);
                        data_counter++;

                        if ((data_counter + block_chunks[i].start) >= block_chunks[i].end)
                        {
                            key_index = data_counter = 0;
                            for (auto& _bytes : file_data)
                                encoded_file << _bytes;

                            file_data.clear();
                            break;
                        }

                        if (key_index >= key_length)
                            key_index = 0;
                        else
                            key_index++;
                    }
                }

                std::cout << ". Done." << std::endl;

                encoded_file.close();
                file.close();
            }
        }
    }

    return ret;
}

Cipher::~Cipher()
{
    if (block_chunks.size() != 0)
        block_chunks.clear();
}
<|endoftext|>


<commit_before><commit_msg>EQ_ANA_BNDY_0..26 ringId support<commit_after><|endoftext|>


<commit_before><commit_msg>fuchsia: Suspend process before manipulating it<commit_after><|endoftext|>


<commit_before>#include "Drawer.h"

#include <FL/fl_draw.H>

Drawer::Drawer()
{
    _iconImage = new Fl_PNG_Image("/tmp/nodes.png");
}

Drawer::~Drawer()
{
    delete _iconImage;
}

void Drawer::setColor(int red, int green, int blue) const
{
    fl_color(red, green, blue);
}

void Drawer::setOrigin(const Point& origin)
{
    _origin = origin;
}

void Drawer::drawLine(const Point& source, const Point& target) const
{
    Point p1 = _origin + source;
    Point p2 = _origin + target;
    fl_line(p1.getX(), p1.getY(), p2.getX(), p2.getY());
}

void Drawer::drawEdge(const Point& source, const Point& target) const
{
    // TODO: Determine the type of the curve!
    drawStepCurve(source, target);
}

void Drawer::drawStepCurve(const Point& source, const Point& target) const
{
    double middleX = (source.getX() + target.getX()) / 2;
    Point sourceSidePoint(middleX, source.getY());
    Point targetSidePoint(middleX, target.getY());
    drawLine(source, sourceSidePoint);
    drawLine(sourceSidePoint, targetSidePoint);
    drawLine(targetSidePoint, target);
}

void Drawer::drawZigzagCurve(const Point& source, const Point& target) const
{
}

void Drawer::drawShoeCurve(const Point& source, const Point& target) const
{
}

void Drawer::drawRectangle(const Point& position, int width, int height) const
{
    Point p = _origin + position;
    fl_rect(p.getX(), p.getY(), width, height);
}

void Drawer::fillRectangle(const Point& position, int width, int height) const
{
    Point p = _origin + position;
    fl_rectf(p.getX(), p.getY(), width, height);
}

void Drawer::drawCircle(const Point& position, int radius) const
{
    Point p = _origin + position;
    int diameter = 2 * radius;
    fl_arc(p.getX() - radius, p.getY() - radius, diameter, diameter, 0, 360);
}

void Drawer::drawIconImage(const Point& position) const
{
    Point p = _origin + position;
    _iconImage->draw(p.getX(), p.getY());
}

void Drawer::drawIcon(int index, const Point& position) const
{
    Point p = _origin + position;
    _iconImage->draw(p.getX(), p.getY(), 32, 32, index * 32, 0);
}

void Drawer::drawText(const std::string& text, const Point& position) const
{
    Point p = _origin + position;
    fl_draw(text.c_str(), p.getX(), p.getY());
}

<commit_msg>Shoe-like edge drawing<commit_after>#include "Drawer.h"

#include <FL/fl_draw.H>

#include <vector>

Drawer::Drawer()
{
    _iconImage = new Fl_PNG_Image("/tmp/nodes.png");
}

Drawer::~Drawer()
{
    delete _iconImage;
}

void Drawer::setColor(int red, int green, int blue) const
{
    fl_color(red, green, blue);
}

void Drawer::setOrigin(const Point& origin)
{
    _origin = origin;
}

void Drawer::drawLine(const Point& source, const Point& target) const
{
    Point p1 = _origin + source;
    Point p2 = _origin + target;
    fl_line(p1.getX(), p1.getY(), p2.getX(), p2.getY());
}

void Drawer::drawEdge(const Point& source, const Point& target) const
{
    // TODO: Determine the type of the curve!
    // drawStepCurve(source, target);
    drawShoeCurve(source, target);
}

void Drawer::drawStepCurve(const Point& source, const Point& target) const
{
    int middleX = (source.getX() + target.getX()) / 2;
    Point sourceSidePoint(middleX, source.getY());
    Point targetSidePoint(middleX, target.getY());
    drawLine(source, sourceSidePoint);
    drawLine(sourceSidePoint, targetSidePoint);
    drawLine(targetSidePoint, target);
}

void Drawer::drawZigzagCurve(const Point& source, const Point& target) const
{
}

void Drawer::drawShoeCurve(const Point& source, const Point& target) const
{
    int sourceSideX = source.getX() + 32;
    int targetSideX = target.getX() - 32;
    int supportY = target.getY();
    if (source.getY() < target.getY()) {
        supportY += 32;
    }
    else {
        supportY -= 32;
    }
    std::vector<Point> points;
    points.push_back(source);
    points.push_back(Point(sourceSideX, source.getY()));
    points.push_back(Point(sourceSideX, supportY));
    points.push_back(Point(targetSideX, supportY));
    points.push_back(Point(targetSideX, target.getY()));
    points.push_back(target);
    for (unsigned int i = 0; i < points.size() - 1; ++i) {
        drawLine(points[i], points[i + 1]);
    }
}

void Drawer::drawRectangle(const Point& position, int width, int height) const
{
    Point p = _origin + position;
    fl_rect(p.getX(), p.getY(), width, height);
}

void Drawer::fillRectangle(const Point& position, int width, int height) const
{
    Point p = _origin + position;
    fl_rectf(p.getX(), p.getY(), width, height);
}

void Drawer::drawCircle(const Point& position, int radius) const
{
    Point p = _origin + position;
    int diameter = 2 * radius;
    fl_arc(p.getX() - radius, p.getY() - radius, diameter, diameter, 0, 360);
}

void Drawer::drawIconImage(const Point& position) const
{
    Point p = _origin + position;
    _iconImage->draw(p.getX(), p.getY());
}

void Drawer::drawIcon(int index, const Point& position) const
{
    Point p = _origin + position;
    _iconImage->draw(p.getX(), p.getY(), 32, 32, index * 32, 0);
}

void Drawer::drawText(const std::string& text, const Point& position) const
{
    Point p = _origin + position;
    fl_draw(text.c_str(), p.getX(), p.getY());
}

<|endoftext|>


<commit_before>/**
 * \file Geodesic.hpp
 * \brief Header for GeographicLib::Geodesic class
 *
 * Copyright (c) Charles Karney (2008, 2009) <charles@karney.com>
 * and licensed under the LGPL.  For more information, see
 * http://charles.karney.info/geographic/
 **********************************************************************/

#if !defined(GEODESIC_HPP)
#define GEODESIC_HPP "$Id$"

#if !defined(GEOD_TAU_ORD)
/**
 * The order of the series relating \e s and \e sigma when expanded in powers
 * of \e u2 = e'2 cos2 alpha0.
 **********************************************************************/
#define GEOD_TAU_ORD 6
#endif

#if !defined(GEOD_ETA_ORD)
/**
 * The order of the series relating \e lambda and \e eta when expanded in
 * powers of \e f.  Typically, this can be one less that GEOD_TAU_ORD because
 * the convergence of the series is more rapid when \e f is used as the
 * expansion parameter (Rainsford 1955).
 **********************************************************************/
#define GEOD_ETA_ORD 5
#endif

#include <cmath>

namespace GeographicLib {

  class GeodesicLine;

  /**
   * \brief %Geodesic calculations
   *
   * The shortest path between two points on a spheroid at (\e lat1, \e lon1)
   * and (\e lat2, \e lon2) is called the geodesic.  Its length is \e s12 and
   * the geodesic from point 1 to point 2 has azimuths \e azi1 and \e azi2 at
   * the two end points.  (The azimuth is the heading measured clockwise from
   * north.  \e azi2 is the "forward" azimuth, i.e., the heading that takes you
   * beyond point 2 not back to point 1.)
   *
   * Given \e lat1, \e lon1, \e azi1, and \e s12, we can determine \e lat2, \e
   * lon2, \e azi2.  This is the \e direct geodesic problem.  (If \e s12 is
   * sufficiently large that the geodesic wraps more than halfway around the
   * earth, there will be another geodesic between the points with a smaller \e
   * s12.)
   *
   * Given \e lat1, \e lon1, \e lat2, and \e lon2, we can determine \e azi1, \e
   * azi2, \e s12.  This is the \e inverse geodesic problem.  Usually, the
   * solution to the inverse problem is unique.  In cases where there are
   * muliple solutions (all with the same \e s12, of course), all the solutions
   * can be easily generated once a particular solution is provided.
   *
   * As an alternative to using distance to measure \e s12, the class can also
   * use the arc length (in degrees) on the auxiliary sphere.  This is a
   * mathematical construct used in solving the geodesic problems.  However, an
   * arc length in excess of 180o indicates that the geodesic is not
   * a shortest path.  In addition, the arc length between an equatorial
   * crossing and the next extremum of latitude for a geodesic is
   * 90o.
   *
   * The calculations are accurate to better than 12 nm.  (See \ref geoderrors
   * for details.)
   **********************************************************************/

  class Geodesic {
  private:
    friend class GeodesicLine;
    static const int tauord = GEOD_TAU_ORD;
    static const int ntau = tauord;
    static const int nsig = tauord;
    static const int etaord = GEOD_TAU_ORD;
    // etaCoeff is multiplied by etaFactor which is O(f), so we reduce the
    // order to which etaCoeff is computed by 1.
    static const int neta = etaord > 0 ? etaord - 1 : 0;
    static const unsigned maxit = 50;

    static inline double sq(double x) throw() { return x * x; }
#if defined(_MSC_VER)
    static inline double hypot(double x, double y) throw()
    { return _hypot(x, y); }
    static inline double cbrt(double x) throw() {
      double y = std::pow(std::abs(x), 1/3.0);
      return x < 0 ? -y : y;
    }
#else
    static inline double hypot(double x, double y) throw()
    { return ::hypot(x, y); }
    static inline double cbrt(double x) throw() { return ::cbrt(x); }
#endif
    void InverseStart(double sbet1, double cbet1, double n1,
		      double sbet2, double cbet2,
		      double lam12, double slam12, double clam12,
		      double& salp1, double& calp1, double c[]) const throw();
    double Lambda12(double sbet1, double cbet1, double sbet2, double cbet2,
		    double salp1, double calp1,
		    double& salp2, double& calp2,
		    double& sig12,
		    double& ssig1, double& csig1, double& ssig2, double& csig2,
		    double& u2, bool diffp, double& dlam12, double c[])
      const throw();

    static const double eps2, tol0, tol1, tol2, xthresh;
    const double _a, _f, _f1, _e2, _ep2, _b;
    static double SinSeries(double sinx, double cosx, const double c[], int n)
      throw();
    static inline double AngNormalize(double x) throw() {
      // Place angle in [-180, 180).  Assumes x is in [-540, 540).
      return x >= 180 ? x - 360 : x < -180 ? x + 360 : x;
    }
    static inline double AngRound(double x) throw() {
      // The makes the smallest gap in x = 1/16 - nextafter(1/16, 0) = 1/2^57
      // for doubles = 0.7 pm on the earth if x is an angle in degrees.  (This
      // is about 1000 times more resolution than we get with angles around 90
      // degrees.)  We use this to avoid having to deal with near singular
      // cases when x is non-zero but tiny (e.g., 1.0e-200).
      const double z = 0.0625;	// 1/16
      double y = std::abs(x);
      // The compiler mustn't "simplify" z - (z - y) to y
      y = y < z ? z - (z - y) : y;
      return x < 0 ? -y : y;
    }
    static inline void SinCosNorm(double& sinx, double& cosx) throw() {
      double r = hypot(sinx, cosx);
      sinx /= r;
      cosx /= r;
    }

    // These are maxima generated functions to provide series approximations to
    // the integrals for the spheroidal geodesic.
    static double tauFactor(double u2) throw();
    static void tauCoeff(double u2, double t[]) throw();
    static void sigCoeff(double u2, double tp[]) throw();
    static double etaFactor(double f, double mu) throw();
    static void etaCoeff(double f, double mu, double h[]) throw();
    static double etaFactormu(double f, double mu) throw();
    static void etaCoeffmu(double f, double mu, double hp[]) throw();

  public:

    /**
     * Constructor for a spheroid with equatorial radius \e a (meters) and
     * reciprocal flattening \e r.  Setting \e r = 0 implies \e r = inf or
     * flattening = 0 (i.e., a sphere).  Negative \e r indicates a prolate
     * spheroid.
     **********************************************************************/
    Geodesic(double a, double r) throw();

    /**
     * Perform the direct geodesic calculation.  Given a latitude, \e lat1,
     * longitude, \e lon1, and azimuth \e azi1 (in degrees) for point 1 and a
     * range, \e s12 (in meters) from point 1 to point 2, return the latitude,
     * \e lat2, longitude, \e lon2, and forward azimuth, \e azi2 (in degrees)
     * for point 2.  If \e arcmode (default false) is set to true, \e s12 is
     * interpreted as the arc length (in degrees) on the auxiliary sphere.  An
     * arc length greater that 180 degrees results in a geodesic which is not a
     * shortest path.  For a prolate spheroid, an additional condition is
     * necessary for a shortest path: the longitudinal extent must not exceed
     * of 180 degrees.  Returned value is the arc length (in degrees).
     **********************************************************************/
    double Direct(double lat1, double lon1, double azi1, double s12,
		  double& lat2, double& lon2, double& azi2,
		  bool arcmode = false) const throw();

    /**
     * Perform the inverse geodesic calculation.  Given a latitude, \e lat1,
     * longitude, \e lon1, for point 1 and a latitude, \e lat2, longitude, \e
     * lon2, for point 2 (all in degrees), return the geodesic distance, \e s12
     * (in meters), and the forward azimuths, \e azi1 and \e azi2 (in degrees),
     * at points 1 and 2.  Returned value is the arc length (in degrees) on the
     * auxiliary sphere.  The routine uses an iterative method.  If the method
     * fails to converge, the negative of the distances (\e s12 and the
     * function value) and reverse of the azimuths are returned.  This is not
     * expected to happen with spheroidal models of the earth.  Please report
     * all cases where this occurs.
     **********************************************************************/
    double Inverse(double lat1, double lon1, double lat2, double lon2,
		   double& s12, double& azi1, double& azi2) const throw();

    /**
     * Set up to do a series of ranges.  This returns a GeodesicLine object
     * with point 1 given by latitude, \e lat1, longitude, \e lon1, and azimuth
     * \e azi1 (in degrees).  Calls to GeodesicLine::Position return the
     * position and azimuth for point 2 a specified distance away.  Using
     * GeodesicLine::Position is approximately 2.1 faster than calling
     * Geodesic::Direct.
     **********************************************************************/
    GeodesicLine Line(double lat1, double lon1, double azi1) const throw();

    /**
     * A global instantiation of Geodesic with the parameters for the WGS84
     * ellipsoid.
     **********************************************************************/
    const static Geodesic WGS84;
  };

  /**
   * \brief A geodesic line.
   *
   * GeodesicLine facilitates the determination of a series of points on a
   * single geodesic.  Geodesic.Line returns a GeodesicLine object with the
   * geodesic defined by by \e lat1, \e lon1, and \e azi1.
   * GeodesicLine.Position returns the \e lat2, \e lon2, and \e azi2 given \e
   * s12.  An example of use of this class is:
   \verbatim
   // Print positions on a geodesic going through latitude 30,
   // longitude 10 at azimuth 80.  Points at intervals of 10km
   // in the range [-1000km, 1000km] are given.
   GeodesicLine line(Geodesic::WGS84.Line(30.0, 10.0, 80.0));
   double step = 10e3;
   for (int s = -100; s <= 100; ++s) {
     double lat2, lon2, azi2;
     double s12 = s * step;
     line.Position(s12, lat2, lon2, azi2);
     cout << s12 << " " << lat2 << " " << lon2 << " " << azi2 << "\n";
   }
   \endverbatim
   * The default copy constructor and assignment operators work with this
   * class, so that, for example, the previous example could start
   \verbatim
   GeodesicLine line;
   line = Geodesic::WGS84.Line(30.0, 10.0, 80.0);
   ...
   \endverbatim
   * Similarly, a vector can be used to hold GeodesicLine objects.
   *
   * The calculations are accurate to better than 12 nm.  (See \ref geoderrors
   * for details.)
   **********************************************************************/

  class GeodesicLine {
  private:
    friend class Geodesic;
    static const int ntau = Geodesic::ntau;
    static const int nsig = Geodesic::nsig;
    static const int neta = Geodesic::neta;

    double _lat1, _lon1, _azi1;
    double  _f1, _salp0, _calp0,
      _ssig1, _csig1, _stau1, _ctau1, _schi1, _cchi1,
      _sScale, _etaFactor, _dtau1, _dlam1;
    double _sigCoeff[ntau > nsig ? (ntau ? ntau : 1) : (nsig ? nsig : 1)],
      _etaCoeff[neta ? neta : 1];

    GeodesicLine(const Geodesic& g, double lat1, double lon1, double azi1)
      throw();
    void ArcPosition(double sig12, double ssig12, double csig12,
		     double& lat2, double& lon2, double& azi2) const throw();
  public:

    /**
     * A default constructor.  If GeodesicLine::Position is called on the
     * resulting object, it returns immediately (without doing any
     * calculations).  The object should be set with a call to Geodesic::Line.
     * Use Init() to test whether object is still in this uninitialized state.
     **********************************************************************/
    GeodesicLine() throw() : _sScale(0) {};

    /**
     * Return the latitude, \e lat2, longitude, \e lon2, and forward azimuth,
     * \e azi2 (in degrees) of the point 2 which is a distance, \e s12 (in
     * meters), from point 1.  \e s12 can be signed.  If \e arcmode (default
     * false) is set to true, \e s12 is interpreted as the arc length (in
     * degrees) on the auxiliary sphere; this speeds up the calculation by a
     * factor of 1.6.  Returned value is the arc length (in degrees).
     **********************************************************************/
    double Position(double s12, double& lat2, double& lon2, double& azi2,
		    bool arcmode = false)
      const throw();

    /**
     * Has this object been initialize so that Position can be called?
     **********************************************************************/
    bool Init() const throw() { return _sScale > 0; }

    /**
     * Return the latitude of point 1 (in degrees).
     **********************************************************************/
    double Latitude() const throw() { return _lat1; }

    /**
     * Return the longitude of point 1 (in degrees).
     **********************************************************************/
    double Longitude() const throw() { return _lon1; }

    /**
     * Return the azimuth of the geodesic line as it passes through point 1.
     **********************************************************************/
    double Azimuth() const throw() { return _azi1; }
  };

} //namespace GeographicLib
#endif
<commit_msg>Get ready for release<commit_after>/**
 * \file Geodesic.hpp
 * \brief Header for GeographicLib::Geodesic class
 *
 * Copyright (c) Charles Karney (2008, 2009) <charles@karney.com>
 * and licensed under the LGPL.  For more information, see
 * http://charles.karney.info/geographic/
 **********************************************************************/

#if !defined(GEODESIC_HPP)
#define GEODESIC_HPP "$Id$"

#if !defined(GEOD_TAU_ORD)
/**
 * The order of the series relating \e s and \e sigma when expanded in powers
 * of \e u2 = e'2 cos2 alpha0.
 **********************************************************************/
#define GEOD_TAU_ORD 6
#endif

#if !defined(GEOD_ETA_ORD)
/**
 * The order of the series relating \e lambda and \e eta when expanded in
 * powers of \e f.  Typically, this can be one less that GEOD_TAU_ORD because
 * the convergence of the series is more rapid when \e f is used as the
 * expansion parameter (Rainsford 1955).
 **********************************************************************/
#define GEOD_ETA_ORD 5
#endif

#include <cmath>

namespace GeographicLib {

  class GeodesicLine;

  /**
   * \brief %Geodesic calculations
   *
   * The shortest path between two points on a spheroid at (\e lat1, \e lon1)
   * and (\e lat2, \e lon2) is called the geodesic.  Its length is \e s12 and
   * the geodesic from point 1 to point 2 has azimuths \e azi1 and \e azi2 at
   * the two end points.  (The azimuth is the heading measured clockwise from
   * north.  \e azi2 is the "forward" azimuth, i.e., the heading that takes you
   * beyond point 2 not back to point 1.)
   *
   * Given \e lat1, \e lon1, \e azi1, and \e s12, we can determine \e lat2, \e
   * lon2, \e azi2.  This is the \e direct geodesic problem.  (If \e s12 is
   * sufficiently large that the geodesic wraps more than halfway around the
   * earth, there will be another geodesic between the points with a smaller \e
   * s12.)
   *
   * Given \e lat1, \e lon1, \e lat2, and \e lon2, we can determine \e azi1, \e
   * azi2, \e s12.  This is the \e inverse geodesic problem.  Usually, the
   * solution to the inverse problem is unique.  In cases where there are
   * muliple solutions (all with the same \e s12, of course), all the solutions
   * can be easily generated once a particular solution is provided.
   *
   * As an alternative to using distance to measure \e s12, the class can also
   * use the arc length (in degrees) on the auxiliary sphere.  This is a
   * mathematical construct used in solving the geodesic problems.  However, an
   * arc length in excess of 180o indicates that the geodesic is not
   * a shortest path.  In addition, the arc length between an equatorial
   * crossing and the next extremum of latitude for a geodesic is
   * 90o.
   *
   * The calculations are accurate to better than 15 nm.  (See \ref geoderrors
   * for details.)
   **********************************************************************/

  class Geodesic {
  private:
    friend class GeodesicLine;
    static const int tauord = GEOD_TAU_ORD;
    static const int ntau = tauord;
    static const int nsig = tauord;
    static const int etaord = GEOD_TAU_ORD;
    // etaCoeff is multiplied by etaFactor which is O(f), so we reduce the
    // order to which etaCoeff is computed by 1.
    static const int neta = etaord > 0 ? etaord - 1 : 0;
    static const unsigned maxit = 50;

    static inline double sq(double x) throw() { return x * x; }
#if defined(_MSC_VER)
    static inline double hypot(double x, double y) throw()
    { return _hypot(x, y); }
    static inline double cbrt(double x) throw() {
      double y = std::pow(std::abs(x), 1/3.0);
      return x < 0 ? -y : y;
    }
#else
    static inline double hypot(double x, double y) throw()
    { return ::hypot(x, y); }
    static inline double cbrt(double x) throw() { return ::cbrt(x); }
#endif
    void InverseStart(double sbet1, double cbet1, double n1,
		      double sbet2, double cbet2,
		      double lam12, double slam12, double clam12,
		      double& salp1, double& calp1, double c[]) const throw();
    double Lambda12(double sbet1, double cbet1, double sbet2, double cbet2,
		    double salp1, double calp1,
		    double& salp2, double& calp2,
		    double& sig12,
		    double& ssig1, double& csig1, double& ssig2, double& csig2,
		    double& u2, bool diffp, double& dlam12, double c[])
      const throw();

    static const double eps2, tol0, tol1, tol2, xthresh;
    const double _a, _f, _f1, _e2, _ep2, _b;
    static double SinSeries(double sinx, double cosx, const double c[], int n)
      throw();
    static inline double AngNormalize(double x) throw() {
      // Place angle in [-180, 180).  Assumes x is in [-540, 540).
      return x >= 180 ? x - 360 : x < -180 ? x + 360 : x;
    }
    static inline double AngRound(double x) throw() {
      // The makes the smallest gap in x = 1/16 - nextafter(1/16, 0) = 1/2^57
      // for doubles = 0.7 pm on the earth if x is an angle in degrees.  (This
      // is about 1000 times more resolution than we get with angles around 90
      // degrees.)  We use this to avoid having to deal with near singular
      // cases when x is non-zero but tiny (e.g., 1.0e-200).
      const double z = 0.0625;	// 1/16
      double y = std::abs(x);
      // The compiler mustn't "simplify" z - (z - y) to y
      y = y < z ? z - (z - y) : y;
      return x < 0 ? -y : y;
    }
    static inline void SinCosNorm(double& sinx, double& cosx) throw() {
      double r = hypot(sinx, cosx);
      sinx /= r;
      cosx /= r;
    }

    // These are maxima generated functions to provide series approximations to
    // the integrals for the spheroidal geodesic.
    static double tauFactor(double u2) throw();
    static void tauCoeff(double u2, double t[]) throw();
    static void sigCoeff(double u2, double tp[]) throw();
    static double etaFactor(double f, double mu) throw();
    static void etaCoeff(double f, double mu, double h[]) throw();
    static double etaFactormu(double f, double mu) throw();
    static void etaCoeffmu(double f, double mu, double hp[]) throw();

  public:

    /**
     * Constructor for a spheroid with equatorial radius \e a (meters) and
     * reciprocal flattening \e r.  Setting \e r = 0 implies \e r = inf or
     * flattening = 0 (i.e., a sphere).  Negative \e r indicates a prolate
     * spheroid.
     **********************************************************************/
    Geodesic(double a, double r) throw();

    /**
     * Perform the direct geodesic calculation.  Given a latitude, \e lat1,
     * longitude, \e lon1, and azimuth \e azi1 (in degrees) for point 1 and a
     * range, \e s12 (in meters) from point 1 to point 2, return the latitude,
     * \e lat2, longitude, \e lon2, and forward azimuth, \e azi2 (in degrees)
     * for point 2.  If \e arcmode (default false) is set to true, \e s12 is
     * interpreted as the arc length (in degrees) on the auxiliary sphere.  An
     * arc length greater that 180 degrees results in a geodesic which is not a
     * shortest path.  For a prolate spheroid, an additional condition is
     * necessary for a shortest path: the longitudinal extent must not exceed
     * of 180 degrees.  Returned value is the arc length (in degrees).
     **********************************************************************/
    double Direct(double lat1, double lon1, double azi1, double s12,
		  double& lat2, double& lon2, double& azi2,
		  bool arcmode = false) const throw();

    /**
     * Perform the inverse geodesic calculation.  Given a latitude, \e lat1,
     * longitude, \e lon1, for point 1 and a latitude, \e lat2, longitude, \e
     * lon2, for point 2 (all in degrees), return the geodesic distance, \e s12
     * (in meters), and the forward azimuths, \e azi1 and \e azi2 (in degrees),
     * at points 1 and 2.  Returned value is the arc length (in degrees) on the
     * auxiliary sphere.  The routine uses an iterative method.  If the method
     * fails to converge, the negative of the distances (\e s12 and the
     * function value) and reverse of the azimuths are returned.  This is not
     * expected to happen with spheroidal models of the earth.  Please report
     * all cases where this occurs.
     **********************************************************************/
    double Inverse(double lat1, double lon1, double lat2, double lon2,
		   double& s12, double& azi1, double& azi2) const throw();

    /**
     * Set up to do a series of ranges.  This returns a GeodesicLine object
     * with point 1 given by latitude, \e lat1, longitude, \e lon1, and azimuth
     * \e azi1 (in degrees).  Calls to GeodesicLine::Position return the
     * position and azimuth for point 2 a specified distance away.  Using
     * GeodesicLine::Position is approximately 2.1 faster than calling
     * Geodesic::Direct.
     **********************************************************************/
    GeodesicLine Line(double lat1, double lon1, double azi1) const throw();

    /**
     * A global instantiation of Geodesic with the parameters for the WGS84
     * ellipsoid.
     **********************************************************************/
    const static Geodesic WGS84;
  };

  /**
   * \brief A geodesic line.
   *
   * GeodesicLine facilitates the determination of a series of points on a
   * single geodesic.  Geodesic.Line returns a GeodesicLine object with the
   * geodesic defined by by \e lat1, \e lon1, and \e azi1.
   * GeodesicLine.Position returns the \e lat2, \e lon2, and \e azi2 given \e
   * s12.  An example of use of this class is:
   \verbatim
   // Print positions on a geodesic going through latitude 30,
   // longitude 10 at azimuth 80.  Points at intervals of 10km
   // in the range [-1000km, 1000km] are given.
   GeodesicLine line(Geodesic::WGS84.Line(30.0, 10.0, 80.0));
   double step = 10e3;
   for (int s = -100; s <= 100; ++s) {
     double lat2, lon2, azi2;
     double s12 = s * step;
     line.Position(s12, lat2, lon2, azi2);
     cout << s12 << " " << lat2 << " " << lon2 << " " << azi2 << "\n";
   }
   \endverbatim
   * The default copy constructor and assignment operators work with this
   * class, so that, for example, the previous example could start
   \verbatim
   GeodesicLine line;
   line = Geodesic::WGS84.Line(30.0, 10.0, 80.0);
   ...
   \endverbatim
   * Similarly, a vector can be used to hold GeodesicLine objects.
   *
   * The calculations are accurate to better than 12 nm.  (See \ref geoderrors
   * for details.)
   **********************************************************************/

  class GeodesicLine {
  private:
    friend class Geodesic;
    static const int ntau = Geodesic::ntau;
    static const int nsig = Geodesic::nsig;
    static const int neta = Geodesic::neta;

    double _lat1, _lon1, _azi1;
    double  _f1, _salp0, _calp0,
      _ssig1, _csig1, _stau1, _ctau1, _schi1, _cchi1,
      _sScale, _etaFactor, _dtau1, _dlam1;
    double _sigCoeff[ntau > nsig ? (ntau ? ntau : 1) : (nsig ? nsig : 1)],
      _etaCoeff[neta ? neta : 1];

    GeodesicLine(const Geodesic& g, double lat1, double lon1, double azi1)
      throw();
    void ArcPosition(double sig12, double ssig12, double csig12,
		     double& lat2, double& lon2, double& azi2) const throw();
  public:

    /**
     * A default constructor.  If GeodesicLine::Position is called on the
     * resulting object, it returns immediately (without doing any
     * calculations).  The object should be set with a call to Geodesic::Line.
     * Use Init() to test whether object is still in this uninitialized state.
     **********************************************************************/
    GeodesicLine() throw() : _sScale(0) {};

    /**
     * Return the latitude, \e lat2, longitude, \e lon2, and forward azimuth,
     * \e azi2 (in degrees) of the point 2 which is a distance, \e s12 (in
     * meters), from point 1.  \e s12 can be signed.  If \e arcmode (default
     * false) is set to true, \e s12 is interpreted as the arc length (in
     * degrees) on the auxiliary sphere; this speeds up the calculation by a
     * factor of 1.6.  Returned value is the arc length (in degrees).
     **********************************************************************/
    double Position(double s12, double& lat2, double& lon2, double& azi2,
		    bool arcmode = false)
      const throw();

    /**
     * Has this object been initialize so that Position can be called?
     **********************************************************************/
    bool Init() const throw() { return _sScale > 0; }

    /**
     * Return the latitude of point 1 (in degrees).
     **********************************************************************/
    double Latitude() const throw() { return _lat1; }

    /**
     * Return the longitude of point 1 (in degrees).
     **********************************************************************/
    double Longitude() const throw() { return _lon1; }

    /**
     * Return the azimuth of the geodesic line as it passes through point 1.
     **********************************************************************/
    double Azimuth() const throw() { return _azi1; }
  };

} //namespace GeographicLib
#endif
<|endoftext|>


<commit_before>/*
GpuRamDrive proxy for ImDisk Virtual Disk Driver.

Copyright (C) 2016 Syahmi Azhar.

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

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

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

#include "stdafx.h"
#include "GpuRamDrive.h"
#include "GpuRamGui.h"

const wchar_t GPU_HELP_STRING[] = L"Usage:\n"
"  GpuRamDrive.exe --device CUDA --size 256 --mount j:\n"
"\n"
"Options:\n"
"  --device <Device Name>   Search string for GPU device\n"
"  --size <Size in MB>      Size to be allocated for ram drive\n"
"  --mount <Drive letter>   Mount drive\n"
"  --format <Parameters>    Format and pass parameters to Windows' format\n"
"  --hide                   Hide GUI to tray\n"
"  --help                   Show this help\n";

int APIENTRY wWinMain(
	_In_ HINSTANCE hInstance,
	_In_opt_ HINSTANCE hPrevInstance,
	_In_ LPWSTR lpCmdLine,
	_In_ int nCmdShow)
{
	GpuRamGui gui;

	LPWSTR *szArglist;
	int nArgs;
	szArglist = CommandLineToArgvW(GetCommandLineW(), &nArgs);

	LPWSTR GpuDevice = nullptr;
	size_t GpuSize = 0;
	LPWSTR GpuDriveLetter = nullptr;
	LPWSTR GpuFormatParam = L"";
	bool GpuMount = false;
	bool HelpRequest = false;

	if (szArglist) {
		for (int i = 0; i < nArgs; i++) {
			if (_wcsicmp(szArglist[i], L"--device") == 0 && i + 1 < nArgs)
			{
				GpuDevice = szArglist[i + 1];
			}
			else if (_wcsicmp(szArglist[i], L"--size") == 0 && i + 1 < nArgs)
			{
				GpuSize = _wtoi64(szArglist[i + 1]);
			}
			else if (_wcsicmp(szArglist[i], L"--mount") == 0 && i + 1 < nArgs)
			{
				GpuDriveLetter = szArglist[i + 1];
			}
			else if (_wcsicmp(szArglist[i], L"--format") == 0 && i + 1 < nArgs)
			{
				GpuFormatParam = szArglist[i + 1];
			}
			else if (_wcsicmp(szArglist[i], L"--hide") == 0)
			{
				nCmdShow = SW_HIDE;
			}
			else if (_wcsicmp(szArglist[i], L"--help") == 0 ||
				_wcsicmp(szArglist[i], L"-h") == 0 ||
				_wcsicmp(szArglist[i], L"/h") == 0 ||
				_wcsicmp(szArglist[i], L"/?") == 0)
			{
				HelpRequest = true;
			}
		}

		if (HelpRequest) {
			if (GetConsoleWindow() == NULL) {
				MessageBoxW(NULL, GPU_HELP_STRING, L"GpuRamDrive help", MB_OK);
			}
			wprintf(GPU_HELP_STRING);
			return 0;
		}

		GpuMount = GpuDevice && GpuSize && GpuDriveLetter;
	}

	if (!gui.Create(hInstance, L"GPU Ram Drive", nCmdShow)) {
		return -1;
	}

	if (GpuMount) {
		try
		{
			gui.Mount(GpuDevice, GpuSize, GpuDriveLetter, GpuFormatParam);
		}
		catch (const std::exception& ex)
		{
			gui.RestoreWindow();
			if (GetConsoleWindow() == NULL) {
				MessageBoxA(NULL, ex.what(), "GpuRamDrive error", MB_OK);
			}
			fprintf(stderr, "GpuRamDrive exception: %s\n", ex.what());
		}
	}

	return gui.Loop();
}<commit_msg>Show format example.<commit_after>/*
GpuRamDrive proxy for ImDisk Virtual Disk Driver.

Copyright (C) 2016 Syahmi Azhar.

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

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

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

#include "stdafx.h"
#include "GpuRamDrive.h"
#include "GpuRamGui.h"

const wchar_t GPU_HELP_STRING[] = L"Usage:\n"
"  GpuRamDrive.exe --device CUDA --size 256 --mount j: --format \"/fs:exfat /q\"\n"
"\n"
"Options:\n"
"  --device <Device Name>   Search string for GPU device\n"
"  --size <Size in MB>      Size to be allocated for ram drive\n"
"  --mount <Drive letter>   Mount drive\n"
"  --format <Parameters>    Format and pass parameters to Windows' format\n"
"  --hide                   Hide GUI to tray\n"
"  --help                   Show this help\n";

int APIENTRY wWinMain(
	_In_ HINSTANCE hInstance,
	_In_opt_ HINSTANCE hPrevInstance,
	_In_ LPWSTR lpCmdLine,
	_In_ int nCmdShow)
{
	GpuRamGui gui;

	LPWSTR *szArglist;
	int nArgs;
	szArglist = CommandLineToArgvW(GetCommandLineW(), &nArgs);

	LPWSTR GpuDevice = nullptr;
	size_t GpuSize = 0;
	LPWSTR GpuDriveLetter = nullptr;
	LPWSTR GpuFormatParam = L"";
	bool GpuMount = false;
	bool HelpRequest = false;

	if (szArglist) {
		for (int i = 0; i < nArgs; i++) {
			if (_wcsicmp(szArglist[i], L"--device") == 0 && i + 1 < nArgs)
			{
				GpuDevice = szArglist[i + 1];
			}
			else if (_wcsicmp(szArglist[i], L"--size") == 0 && i + 1 < nArgs)
			{
				GpuSize = _wtoi64(szArglist[i + 1]);
			}
			else if (_wcsicmp(szArglist[i], L"--mount") == 0 && i + 1 < nArgs)
			{
				GpuDriveLetter = szArglist[i + 1];
			}
			else if (_wcsicmp(szArglist[i], L"--format") == 0 && i + 1 < nArgs)
			{
				GpuFormatParam = szArglist[i + 1];
			}
			else if (_wcsicmp(szArglist[i], L"--hide") == 0)
			{
				nCmdShow = SW_HIDE;
			}
			else if (_wcsicmp(szArglist[i], L"--help") == 0 ||
				_wcsicmp(szArglist[i], L"-h") == 0 ||
				_wcsicmp(szArglist[i], L"/h") == 0 ||
				_wcsicmp(szArglist[i], L"/?") == 0)
			{
				HelpRequest = true;
			}
		}

		if (HelpRequest) {
			if (GetConsoleWindow() == NULL) {
				MessageBoxW(NULL, GPU_HELP_STRING, L"GpuRamDrive help", MB_OK);
			}
			wprintf(GPU_HELP_STRING);
			return 0;
		}

		GpuMount = GpuDevice && GpuSize && GpuDriveLetter;
	}

	if (!gui.Create(hInstance, L"GPU Ram Drive", nCmdShow)) {
		return -1;
	}

	if (GpuMount) {
		try
		{
			gui.Mount(GpuDevice, GpuSize, GpuDriveLetter, GpuFormatParam);
		}
		catch (const std::exception& ex)
		{
			gui.RestoreWindow();
			if (GetConsoleWindow() == NULL) {
				MessageBoxA(NULL, ex.what(), "GpuRamDrive error", MB_OK);
			}
			fprintf(stderr, "GpuRamDrive exception: %s\n", ex.what());
		}
	}

	return gui.Loop();
}<|endoftext|>


<commit_before>/* Program to log external IP-changes on NAT networks
 *
 * I have an ISP from Hell, and one problem I have noticed recently is that
 * my external IP address change a lot. To monitor this problem, I wrote this little
 * example program who checks the external IP every 5 minutes, and log changes.
 *
 * The program can be run in the background:
 *
 *      logip >> /var/tmp/ip.log 2>&1 &
 */

#include <ctime>
#include "restc-cpp/logging.h"

#include <boost/log/core.hpp>
#include <boost/log/trivial.hpp>
#include <boost/log/expressions.hpp>

#include "restc-cpp/restc-cpp.h"
#include "restc-cpp/RequestBuilder.h"
#include "restc-cpp/SerializeJson.h"

using namespace restc_cpp;
using namespace std;

// Data structure returned from api.ipify.org
struct Data {
    string ip;
};

BOOST_FUSION_ADAPT_STRUCT(
    Data,
    (string, ip)
)

int main(int argc, char *argv[]) {

    namespace logging = boost::log;
    logging::core::get()->set_filter
    (
        logging::trivial::severity >= logging::trivial::info
    );

    const string url = "https://api.ipify.org";

    auto client = RestClient::Create();
    client->Process([&](Context& ctx) {

        string current_ip;
        Data data;
        char date[32] = {};

        while(true) {
            SerializeFromJson(data, RequestBuilder(ctx)
                .Get(url)
                .Argument("format", "json")
                .Header("X-Client", "RESTC_CPP")
                .Execute());

            if (current_ip != data.ip) {
                auto now = time(NULL);
                strftime(date, sizeof(date), "%Y-%m-%d %H:%M", localtime(&now));

                clog << date
                    << ' '
                    << data.ip
                    << endl;
                current_ip = data.ip;
            }

            std::this_thread::sleep_for(std::chrono::minutes(5));
        }
    });

    return 0;
}
<commit_msg>Added error handling<commit_after>/* Program to log external IP-changes on NAT networks
 *
 * I have an ISP from Hell, and one problem I have noticed recently is that
 * my external IP address change a lot. To monitor this problem, I wrote this little
 * example program who checks the external IP every 5 minutes, and log changes.
 *
 * The program can be run in the background:
 *
 *      logip >> /var/tmp/ip.log 2>&1 &
 */

#include <ctime>
#include "restc-cpp/logging.h"

#include <boost/log/core.hpp>
#include <boost/log/trivial.hpp>
#include <boost/log/expressions.hpp>

#include "restc-cpp/restc-cpp.h"
#include "restc-cpp/RequestBuilder.h"
#include "restc-cpp/SerializeJson.h"

using namespace restc_cpp;
using namespace std;

// Data structure returned from api.ipify.org
struct Data {
    string ip;
};

BOOST_FUSION_ADAPT_STRUCT(
    Data,
    (string, ip)
)

string now() {
    char date[32] = {};
    auto now = time(NULL);
    strftime(date, sizeof(date), "%Y-%m-%d %H:%M", localtime(&now));
    return date;
}

int main(int argc, char *argv[]) {

    namespace logging = boost::log;
    logging::core::get()->set_filter
    (
        logging::trivial::severity >= logging::trivial::info
    );

    const string url = "https://api.ipify.org";

    auto client = RestClient::Create();
    client->Process([&](Context& ctx) {

        string current_ip;
        Data data;

        while(true) {
            bool valid = false;
            try {
                SerializeFromJson(data, RequestBuilder(ctx)
                    .Get(url)
                    .Argument("format", "json")
                    .Header("X-Client", "RESTC_CPP")
                    .Execute());
                valid = true;
            } catch (const boost::exception& ex) {
                clog << now()
                    << "Caught boost exception: "
                    << boost::diagnostic_information(ex)
                    << endl;
            } catch (const exception& ex) {
                clog << now()
                    << "Caught exception: "
                    << ex.what()
                    << endl;
            }

            if (valid && (current_ip != data.ip)) {
                clog << now()
                    << ' '
                    << data.ip
                    << endl;
                current_ip = data.ip;
            }

            std::this_thread::sleep_for(std::chrono::minutes(5));
        }
    });

    return 0;
}
<|endoftext|>