<commit_before>#define WIN32_LEAN_AND_MEAN
#define STRICT
#define _ATL_NO_AUTOMATIC_NAMESPACE
#include <windows.h>
#include <pathcch.h>
#include <atlalloc.h>
#include <atlbase.h>
#include <fcntl.h>
#include <io.h>
#include <cstdio>
#include <cstdlib>
#include <crtdbg.h>
#include "lxsstat.hpp"
#include "fileopen.hpp"

ATL::CHeapPtr<WCHAR> GetWindowsError(ULONG error_code = GetLastError())
{
	ATL::CHeapPtr<WCHAR> msg;
	ATLENSURE(msg.Allocate(USHRT_MAX));
	ATLENSURE(FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, error_code, 0, msg, USHRT_MAX, nullptr));
	return msg;
}
int __cdecl wmain(int argc, wchar_t* argv[])
{
	_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);
	_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
	_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE);
	_setmode(_fileno(stdout), _O_U8TEXT);
	_setmode(_fileno(stderr), _O_U8TEXT);
	if (argc <= 1)
	{
		fputws(L"lxsstat {POSIX_PATH|Windows_PATH} [...]\n", stderr);
		return EXIT_FAILURE;
	}

	for (int i = 1; i < argc; ++i)
	{
		auto windows_path = Lxss::realpath(argv[i]);
		struct Lxss::stat buf;
		if (Lxss::stat(windows_path.c_str(), &buf) != 0)
		{
			ULONG error = GetLastError();
			if (error == STATUS_NO_EAS_ON_FILE)
			{
				fwprintf(stderr, L"%ls\nThis file is not under the control of the Ubuntu on Windows\n", windows_path.c_str());
			}
			else
			{
				fwprintf(stderr, L"%ls\n%ls", windows_path.c_str(), (PCWSTR)GetWindowsError(error));
			}
		}
		else
		{
			wprintf(L"  File: '%ls'", argv[i]);
			if (Lxss::S_ISLNK(buf.st_mode))
			{
				static_assert(PATHCCH_MAX_CCH <= ULONG_MAX, "");
				if (buf.st_size <= PATHCCH_MAX_CCH)
				{
					ATL::CTempBuffer<BYTE> buffer(buf.st_size);
					ULONG read_size;
					ATL::CHandle h(OpenFileCaseSensitive(windows_path.c_str()));
					if (h && ReadFile(h, buffer, (ULONG)buf.st_size, &read_size, nullptr))
					{
						wprintf(L"  ->  '%.*hs'\n", read_size, (PBYTE)buffer);
					}
					else
					{
						wprintf(L"  ->  ?\?\?\?\?\?\?\?\n%ls", (PCWSTR)GetWindowsError());
					}
				}
				else
				{
					_putws(L"  ->  symlink too long");
				}
			}
			else
			{
				_putws(L"");
			}
			wprintf(
				L"  Size: %-15llu Blocks: %-10llu IO Block: %-6u ",
				buf.st_size,
				buf.st_blocks,
				buf.st_blksize
			);
			if (Lxss::S_ISLNK(buf.st_mode))
			{
				_putws(L"symbolic link");
			}
			else if (Lxss::S_ISDIR(buf.st_mode))
			{
				_putws(L"directory");
			}
			else if (Lxss::S_ISREG(buf.st_mode))
			{
				if (buf.st_size)
				{
					_putws(L"regular file");
				}
				else
				{
					_putws(L"regular empty file");
				}
			}
			else if (Lxss::S_ISCHR(buf.st_mode))
			{
				_putws(L"character special file");
			}
			else if (Lxss::S_ISFIFO(buf.st_mode))
			{
				_putws(L"fifo");
			}
			else
			{
				_putws(L"unknown");
			}
			wprintf(
				!Lxss::S_ISCHR(buf.st_mode)
				? L"Device: %xh/%ud   Inode: %llu  Links: %u\n"
				: L"Device: %xh/%ud   Inode: %llu  Links: %-5u Device type: %x,%x\n",
				buf.st_dev,
				buf.st_dev,
				buf.st_ino,
				buf.st_nlink,
				HIBYTE(buf.st_rdev),
				LOBYTE(buf.st_rdev)
			);
			wprintf(
				L"Access: (%04o/%hs)  Uid: (% 5u/% 8hs)   Gid: (% 5u/% 8hs)\n",
				buf.st_mode & 07777,
				Lxss::mode_tostring(buf.st_mode).data(),
				buf.st_uid,
				Lxss::UserNameFromUID(buf.st_uid),
				buf.st_gid,
				Lxss::GroupNameFromGID(buf.st_gid)
			);
			const struct _timespec64(&mactime)[3] = { buf.st_atim, buf.st_mtim ,buf.st_ctim };
			const PCSTR mactime_string[] = { "Access", "Modify", "Change" };
			for (int j = 0; j < _countof(mactime); ++j)
			{
				char str[80];
				strftime(
					str,
					sizeof str,
					"%F %T",
					__pragma(warning(suppress:4996)) gmtime(&mactime[j].tv_sec)
				);
				wprintf(L"%hs: %hs.%09lu +0000\n", mactime_string[j], str, mactime[j].tv_nsec);
			}
		}
	}
}<commit_msg>Fix error message not displayed correctly when launched from bash 3<commit_after>#define WIN32_LEAN_AND_MEAN
#define STRICT
#define _ATL_NO_AUTOMATIC_NAMESPACE
#include <windows.h>
#include <pathcch.h>
#include <atlalloc.h>
#include <atlbase.h>
#include <fcntl.h>
#include <io.h>
#include <cstdio>
#include <cstdlib>
#include <crtdbg.h>
#include "lxsstat.hpp"
#include "fileopen.hpp"

ATL::CHeapPtr<WCHAR> GetWindowsError(ULONG error_code = GetLastError())
{
	ATL::CHeapPtr<WCHAR> msg;
	ATLENSURE(msg.Allocate(USHRT_MAX));
	ATLENSURE(FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, error_code, 0, msg, USHRT_MAX, nullptr));
	return msg;
}
int __cdecl wmain(int argc, wchar_t* argv[])
{
	_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);
	_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
	_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE);
	(void)_setmode(_fileno(stdout), _O_U8TEXT);
	(void)_setmode(_fileno(stderr), _O_U8TEXT);
	if (argc <= 1)
	{
		fputws(L"lxsstat {POSIX_PATH|Windows_PATH} [...]\n", stderr);
		return EXIT_FAILURE;
	}

	for (int i = 1; i < argc; ++i)
	{
		auto windows_path = Lxss::realpath(argv[i]);
		struct Lxss::stat buf;
		if (Lxss::stat(windows_path.c_str(), &buf) != 0)
		{
			ULONG error = GetLastError();
			if (error == STATUS_NO_EAS_ON_FILE)
			{
				fwprintf(stderr, L"%ls\nThis file is not under the control of the Ubuntu on Windows\n", windows_path.c_str());
			}
			else
			{
				fwprintf(stderr, L"%ls\n%ls", windows_path.c_str(), (PCWSTR)GetWindowsError(error));
			}
		}
		else
		{
			wprintf(L"  File: '%ls'", argv[i]);
			if (Lxss::S_ISLNK(buf.st_mode))
			{
				static_assert(PATHCCH_MAX_CCH <= ULONG_MAX, "");
				if (buf.st_size <= PATHCCH_MAX_CCH)
				{
					ATL::CTempBuffer<BYTE> buffer(buf.st_size);
					ULONG read_size;
					ATL::CHandle h(OpenFileCaseSensitive(windows_path.c_str()));
					if (h && ReadFile(h, buffer, (ULONG)buf.st_size, &read_size, nullptr))
					{
						wprintf(L"  ->  '%.*hs'\n", read_size, (PBYTE)buffer);
					}
					else
					{
						wprintf(L"  ->  ?\?\?\?\?\?\?\?\n%ls", (PCWSTR)GetWindowsError());
					}
				}
				else
				{
					_putws(L"  ->  symlink too long");
				}
			}
			else
			{
				_putws(L"");
			}
			wprintf(
				L"  Size: %-15llu Blocks: %-10llu IO Block: %-6u ",
				buf.st_size,
				buf.st_blocks,
				buf.st_blksize
			);
			if (Lxss::S_ISLNK(buf.st_mode))
			{
				_putws(L"symbolic link");
			}
			else if (Lxss::S_ISDIR(buf.st_mode))
			{
				_putws(L"directory");
			}
			else if (Lxss::S_ISREG(buf.st_mode))
			{
				if (buf.st_size)
				{
					_putws(L"regular file");
				}
				else
				{
					_putws(L"regular empty file");
				}
			}
			else if (Lxss::S_ISCHR(buf.st_mode))
			{
				_putws(L"character special file");
			}
			else if (Lxss::S_ISFIFO(buf.st_mode))
			{
				_putws(L"fifo");
			}
			else
			{
				_putws(L"unknown");
			}
			wprintf(
				!Lxss::S_ISCHR(buf.st_mode)
				? L"Device: %xh/%ud   Inode: %llu  Links: %u\n"
				: L"Device: %xh/%ud   Inode: %llu  Links: %-5u Device type: %x,%x\n",
				buf.st_dev,
				buf.st_dev,
				buf.st_ino,
				buf.st_nlink,
				HIBYTE(buf.st_rdev),
				LOBYTE(buf.st_rdev)
			);
			wprintf(
				L"Access: (%04o/%hs)  Uid: (% 5u/% 8hs)   Gid: (% 5u/% 8hs)\n",
				buf.st_mode & 07777,
				Lxss::mode_tostring(buf.st_mode).data(),
				buf.st_uid,
				Lxss::UserNameFromUID(buf.st_uid),
				buf.st_gid,
				Lxss::GroupNameFromGID(buf.st_gid)
			);
			const struct _timespec64(&mactime)[3] = { buf.st_atim, buf.st_mtim ,buf.st_ctim };
			const PCSTR mactime_string[] = { "Access", "Modify", "Change" };
			for (int j = 0; j < _countof(mactime); ++j)
			{
				char str[80];
				strftime(
					str,
					sizeof str,
					"%F %T",
					__pragma(warning(suppress:4996)) gmtime(&mactime[j].tv_sec)
				);
				wprintf(L"%hs: %hs.%09lu +0000\n", mactime_string[j], str, mactime[j].tv_nsec);
			}
		}
	}
}<|endoftext|>


<commit_before>/**
 * @mainpage The Gaussian Optimization Analytical Tool (GOAT)
 *
 * Welcome to the Gaussian Optimization Analytical Tool (GOAT) documentation site!
 * Users may find relevant info related to this program, a program designed to provide
 * structural analyses of biomolecules successfully optimized using Gaussian software.
 *
 * @short   Main program
 * @file    main.cpp
 * @author  Kate Charbonnet, Hannah Lozano, and Thomas Summers
 * @param   none
 * @return  0 on success
 *
 * The purpose of this program is to provide preliminary structural information on biomolecules
 * optimized using Gaussian computational chemistry software.  Structural and chemical properties
 * identified include: element identification, bond length, bond angles, and dihedral
 * angles.  Input of the file to be analyzed will result in an output file listing all the structural
 * information of the molecule.
 */

#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <cmath>

#include "main.h"
#include "extraction.h"
#include "center_of_mass.h"
#include "bond_angle.h"
#include "dihedral_angle.h"
#include "elements.h"
#include "bond_length.h"
//#include "bond_number.h"
//#include "distance.h"

using namespace std;

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

    ofstream logfile;
    fstream bond_angle;
    fstream dihedral_angle;
    fstream bond_length;

    //Check that inputfile was directed into the command line
    if (argc < 2) {
        cout << "Error: Inputfile not specified in command line\n";
        return 1;
    }

    //Generate a logfile
    logfile.open("log.txt");
    if (!logfile.is_open()) {
        cout << "Error: Unable to open the logfile.";
        return 2;
    } else {
        logfile << "Logfile for Gaussian Optimization Analytical Tool" << endl;
    }

    //Extract the raw coordinates from the inputfile in the commandline
    if (extract_input(argv[1]) != 0) {
        cout << "Error occured in extracting the coordinates.\n";
    }

    //Print the vector size and vector contents
    if (print_vector_coords() != 0) {
        cout << "Error occured in printing the coordinates.\n";
    }

    //Open the file bond_length.cpp and check that it opened
    bond_length.open("bond_length.cpp");
    if (!bond_length.is_open()) {
         cout << "Error: Unable to open bond_length file.";
	       return 1;
    }

    //Close the file bond_length.cpp
    bond_length.close();
    cout << "Bond length calculation complete." ;

    //Calculate the model's total mass
    double model_mass = calculate_total_mass();

    //Calculate the model's center of mass coordinates
    double xcoord = calc_prod_coords_mass(2) / model_mass;
    double ycoord = calc_prod_coords_mass(3) / model_mass;
    double zcoord = calc_prod_coords_mass(4) / model_mass;

    cout << "Model's Center of Mass coordinates: " << endl
         << xcoord << "     " << ycoord << "     " << zcoord << endl;

    //Output the calculated interatomic distances
    Bond_Length model;
    model.atom_dist();

    //Calculate the molecule's bond angles

    //Calculate the molecule's dihedral angles

}
<commit_msg>deleted distance and added bond number<commit_after>/**
 * @mainpage The Gaussian Optimization Analytical Tool (GOAT)
 *
 * Welcome to the Gaussian Optimization Analytical Tool (GOAT) documentation site!
 * Users may find relevant info related to this program, a program designed to provide
 * structural analyses of biomolecules successfully optimized using Gaussian software.
 *
 * @short   Main program
 * @file    main.cpp
 * @author  Kate Charbonnet, Hannah Lozano, and Thomas Summers
 * @param   none
 * @return  0 on success
 *
 * The purpose of this program is to provide preliminary structural information on biomolecules
 * optimized using Gaussian computational chemistry software.  Structural and chemical properties
 * identified include: element identification, bond length, bond angles, and dihedral
 * angles.  Input of the file to be analyzed will result in an output file listing all the structural
 * information of the molecule.
 */

#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <cmath>

#include "main.h"
#include "extraction.h"
#include "center_of_mass.h"
#include "bond_angle.h"
#include "dihedral_angle.h"
#include "elements.h"
#include "bond_length.h"
#include "bond_number.h"

using namespace std;

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

    ofstream logfile;
    fstream bond_angle;
    fstream dihedral_angle;
    fstream bond_length;

    //Check that inputfile was directed into the command line
    if (argc < 2) {
        cout << "Error: Inputfile not specified in command line\n";
        return 1;
    }

    //Generate a logfile
    logfile.open("log.txt");
    if (!logfile.is_open()) {
        cout << "Error: Unable to open the logfile.";
        return 2;
    } else {
        logfile << "Logfile for Gaussian Optimization Analytical Tool" << endl;
    }

    //Extract the raw coordinates from the inputfile in the commandline
    if (extract_input(argv[1]) != 0) {
        cout << "Error occured in extracting the coordinates.\n";
    }

    //Print the vector size and vector contents
    if (print_vector_coords() != 0) {
        cout << "Error occured in printing the coordinates.\n";
    }

    //Calculate the model's total mass
    double model_mass = calculate_total_mass();

    //Calculate the model's center of mass coordinates
    double xcoord = calc_prod_coords_mass(2) / model_mass;
    double ycoord = calc_prod_coords_mass(3) / model_mass;
    double zcoord = calc_prod_coords_mass(4) / model_mass;

    cout << "Model's Center of Mass coordinates: " << endl
         << xcoord << "     " << ycoord << "     " << zcoord << endl;

    //Output the calculated interatomic distances
    Bond_Length model;
    model.atom_dist();

    //Output Bond numbers of atoms

    //Calculate the molecule's bond angles

    //Calculate the molecule's dihedral angles

}
<|endoftext|>


<commit_before>#include <irrlicht/irrlicht.h>
#include <irrlicht/driverChoice.h>

//#pragma comment(lib, "Irrlicht.lib")

using namespace irr;
//using namespace core;
//using namespace scene;
//using namespace video;
//using namespace io;
//using namespace gui;

int main() {
  // Uses driverChoiceConsole() from driverChoice.h
  IrrlichtDevice *device = createDevice(driverChoiceConsole(), core::dimension2d<u32>(512, 384), 16, false, false, false, 0);
  device->setWindowCaption(L"Hello World! - Irrlicht Engine Demo");
  video::IVideoDriver* driver = device->getVideoDriver();
  scene::ISceneManager* smgr = device->getSceneManager();
  gui::IGUIEnvironment* guienv = device->getGUIEnvironment();
  gui::IGUIFont* font = device->getGUIEnvironment()->getBuiltInFont();
  //gui::IGUIFont* font2 = device->getGUIEnvironment()->getFont("../../media/fonthaettenschweiler.bmp");
  if(!font){
    device->drop();
    return(1);
  }
  font->draw(L"I'm a little teapot", core::rect<s32>(10,10,200,22), video::SColor(255,255,255,255));
  guienv->addStaticText(L"Hello World! This is the Irrlicht Software engine!",
         core::rect<int>(10,10,200,22), true);
  device->getFileSystem()->addFileArchive("models/map-20kdm2.pk3");
  scene::IAnimatedMesh* sydney = smgr->getMesh("models/sydney.md2");
  if(!sydney){
    device->drop();
    return(1);
  }
  scene::IMeshSceneNode *cube = smgr->addCubeSceneNode(15.0f, 0, -1, core::vector3df(150,10,10));
  scene::IAnimatedMeshSceneNode* node = smgr->addAnimatedMeshSceneNode( sydney );
  if (node) {
    node->setMaterialFlag(video::EMF_LIGHTING, false);
    node->setFrameLoop(0, 310);
    node->setMaterialTexture( 0, driver->getTexture("models/sydney.bmp") );
  }
  //smgr->addLightSceneNode();
  //scene::ICameraSceneNode *camera = smgr->addCameraSceneNode(0, core::vector3df(0,30,-40), core::vector3df(0,5,0));
  scene::ICameraSceneNode *camera = smgr->addCameraSceneNodeFPS();
  device->getCursorControl()->setVisible(false);
  //camera->setTarget(cube->getAbsolutePosition());
  int lastFPS = -1;
  while(device->run()) {
    if(device->isWindowActive()){
      //int fps = driver->getFPS();
      //core::stringw status;
      //if(fps != lastFPS){
      //  status = L"grimmwa.re VR hackspace mkI [";
      //  status += driver->getName();
      //  status += "] FPS::";
      //  status += fps;
      //  lastFPS = fps;
      //}
      //font->draw(status, core::rect<s32>(10,10,200,22), video::SColor(255,255,255,255));

      driver->beginScene(true, true, video::SColor(255,100,101,140));
      smgr->drawAll();
      guienv->drawAll();
      driver->endScene();
    }
  }
  device->drop();
  return 0;

}
<commit_msg>Added some quake level<commit_after>#include <irrlicht/irrlicht.h>
#include <irrlicht/driverChoice.h>

//#pragma comment(lib, "Irrlicht.lib")

using namespace irr;
//using namespace core;
//using namespace scene;
//using namespace video;
//using namespace io;
//using namespace gui;

int main() {
  // Uses driverChoiceConsole() from driverChoice.h
  IrrlichtDevice *device = createDevice(driverChoiceConsole(), core::dimension2d<u32>(512, 384), 16, false, false, false, 0);
  device->setWindowCaption(L"Hello World! - Irrlicht Engine Demo");
  video::IVideoDriver* driver = device->getVideoDriver();
  scene::ISceneManager* smgr = device->getSceneManager();
  gui::IGUIEnvironment* guienv = device->getGUIEnvironment();
  gui::IGUIFont* font = device->getGUIEnvironment()->getBuiltInFont();
  //gui::IGUIFont* font2 = device->getGUIEnvironment()->getFont("../../media/fonthaettenschweiler.bmp");
  if(!font){
    device->drop();
    return(1);
  }
  font->draw(L"I'm a little teapot", core::rect<s32>(10,10,200,22), video::SColor(255,255,255,255));
  guienv->addStaticText(L"Hello World! This is the Irrlicht Software engine!",
         core::rect<int>(10,10,200,22), true);
  device->getFileSystem()->addFileArchive("models/map-20kdm2.pk3");
  scene::IAnimatedMesh* levelMesh = smgr->getMesh("20kdm2.bsp");
  scene::ISceneNode* levelNode = 0;
  if (levelMesh) {
    levelNode = smgr->addOctreeSceneNode(levelMesh->getMesh(0), 0, -1, 1024);
//      node = smgr->addMeshSceneNode(mesh->getMesh(0));
  }

  scene::IAnimatedMesh* sydneyMesh = smgr->getMesh("models/sydney.md2");
  if(!sydneyMesh){
    device->drop();
    return(1);
  }
  scene::IMeshSceneNode *cube = smgr->addCubeSceneNode(15.0f, 0, -1, core::vector3df(150,10,10));
  scene::IAnimatedMeshSceneNode* sydneyNode = smgr->addAnimatedMeshSceneNode( sydneyMesh );
  if (sydneyNode) {
    sydneyNode->setMaterialFlag(video::EMF_LIGHTING, false);
    sydneyNode->setFrameLoop(0, 310);
    sydneyNode->setMaterialTexture( 0, driver->getTexture("models/sydneyMesh.bmp") );
  }
  //smgr->addLightSceneNode();
  //scene::ICameraSceneNode *camera = smgr->addCameraSceneNode(0, core::vector3df(0,30,-40), core::vector3df(0,5,0));
  scene::ICameraSceneNode *camera = smgr->addCameraSceneNodeFPS();
  device->getCursorControl()->setVisible(false);
  //camera->setTarget(cube->getAbsolutePosition());
  int lastFPS = -1;
  while(device->run()) {
    if(device->isWindowActive()){
      //int fps = driver->getFPS();
      //core::stringw status;
      //if(fps != lastFPS){
      //  status = L"grimmwa.re VR hackspace mkI [";
      //  status += driver->getName();
      //  status += "] FPS::";
      //  status += fps;
      //  lastFPS = fps;
      //}
      //font->draw(status, core::rect<s32>(10,10,200,22), video::SColor(255,255,255,255));

      driver->beginScene(true, true, video::SColor(255,100,101,140));
      smgr->drawAll();
      guienv->drawAll();
      driver->endScene();
    }
  }
  device->drop();
  return 0;

}
<|endoftext|>


<commit_before>395a48a6-ad5a-11e7-aa7d-ac87a332f658<commit_msg>Initial commit.13<commit_after>39e20851-ad5a-11e7-b5ae-ac87a332f658<|endoftext|>


<commit_before>
#include "src/CmdLineOptions.h"
#include "src/MicroCore.h"
#include "src/page.h"

#include "ext/crow/crow.h"
#include "ext/member_checker.h"

#include <fstream>

using boost::filesystem::path;

using namespace std;

// needed for log system of momero
namespace epee {
    unsigned int g_test_dbg_lock_sleep = 0;
}

int main(int ac, const char* av[]) {

    // get command line options
    xmreg::CmdLineOptions opts {ac, av};

    auto help_opt = opts.get_option<bool>("help");

    // if help was chosen, display help text and finish
    if (*help_opt)
    {
        return EXIT_SUCCESS;
    }

    auto port_opt           = opts.get_option<string>("port");
    auto bc_path_opt        = opts.get_option<string>("bc-path");
    auto custom_db_path_opt = opts.get_option<string>("custom-db-path");
    auto deamon_url_opt     = opts.get_option<string>("deamon-url");

    //cast port number in string to uint16
    uint16_t app_port = boost::lexical_cast<uint16_t>(*port_opt);

    // get blockchain path
    path blockchain_path;

    if (!xmreg::get_blockchain_path(bc_path_opt, blockchain_path))
    {
        cerr << "Error getting blockchain path." << endl;
        return EXIT_FAILURE;
    }

     // enable basic monero log output
    xmreg::enable_monero_log();

    // create instance of our MicroCore
    // and make pointer to the Blockchain
    xmreg::MicroCore mcore;
    cryptonote::Blockchain* core_storage;

    // initialize mcore and core_storage
    if (!xmreg::init_blockchain(blockchain_path.string(),
                               mcore, core_storage))
    {
        cerr << "Error accessing blockchain." << endl;
        return EXIT_FAILURE;
    }

    // check if we have path to lmdb2 (i.e., custom db)
    // and if it exists

    string custom_db_path_str;

    if (custom_db_path_opt)
    {
        if (boost::filesystem::exists(boost::filesystem::path(*custom_db_path_opt)))
        {
            custom_db_path_str = *custom_db_path_opt;
        }
        else
        {
            cerr << "Custom db path: " << *custom_db_path_opt
                 << "does not exist" << endl;

            return EXIT_FAILURE;
        }
    }
    else
    {
        // if not given assume it is located in ~./bitmonero/lmdb2 folder
        custom_db_path_str = blockchain_path.parent_path().string()
                             + string("/lmdb2");
    }

    custom_db_path_str = xmreg::remove_trailing_path_separator(custom_db_path_str);

    // create instance of page class which
    // contains logic for the website
    xmreg::page xmrblocks(&mcore, core_storage,
                          *deamon_url_opt, custom_db_path_str);

    // crow instance
    crow::SimpleApp app;

    CROW_ROUTE(app, "/")
    ([&](const crow::request& req) {

        for (const auto& m : req.headers)
            cout << m.first << ": " << m.second << endl;

        return xmrblocks.index2();
    });

    CROW_ROUTE(app, "/page/<uint>")
    ([&](size_t page_no) {
        return xmrblocks.index2(page_no);
    });

    CROW_ROUTE(app, "/block/<uint>")
    ([&](const crow::request& req, size_t block_height) {

        // there is some robot scanning everything
        // on the explorer. I block it with this
        if (!xmreg::does_header_has(req, "Accept", "q=.2, */*; q=.2").empty())
        {
            cout << "Scanner with q=.2, */*; q=.2 blocked!" << endl;
            return crow::response(400);
        }

        return crow::response(xmrblocks.show_block(block_height));
    });

    CROW_ROUTE(app, "/block/<string>")
    ([&](const crow::request& req, string block_hash) {

        // there is some robot scanning everything
        // on the explorer. I block it with this
        if (!xmreg::does_header_has(req, "Accept", "q=.2, */*; q=.2").empty())
        {
            cout << "Scanner with q=.2, */*; q=.2 blocked!" << endl;
            return crow::response(400);
        }

        return crow::response(xmrblocks.show_block(block_hash));
    });

    CROW_ROUTE(app, "/tx/<string>")
    ([&](const crow::request& req, string tx_hash) {

        // there is some robot scanning everything
        // on the explorer. I block it with this
        if (!xmreg::does_header_has(req, "Accept", "q=.2, */*; q=.2").empty())
        {
            cout << "Scanner with q=.2, */*; q=.2 blocked!" << endl;
            return crow::response(400);
        }

        return crow::response(xmrblocks.show_tx(tx_hash));
    });

    CROW_ROUTE(app, "/tx/<string>/<uint>")
    ([&](string tx_hash, uint with_ring_signatures) {
        return xmrblocks.show_tx(tx_hash, with_ring_signatures);
    });

    CROW_ROUTE(app, "/myoutputs").methods("GET"_method)
    ([&](const crow::request& req) {

        string tx_hash     = string(req.url_params.get("tx_hash"));
        string xmr_address = string(req.url_params.get("xmr_address"));
        string viewkey     = string(req.url_params.get("viewkey"));

        return xmrblocks.show_my_outputs(tx_hash, xmr_address, viewkey);
    });

    CROW_ROUTE(app, "/search").methods("GET"_method)
    ([&](const crow::request& req) {
        return xmrblocks.search(string(req.url_params.get("value")));
    });

    CROW_ROUTE(app, "/robots.txt")
    ([&]() {
        string text = "User-agent: *\n"
                      "Disallow: ";
        return text;
    });

    CROW_ROUTE(app, "/autorefresh")
    ([&]() {
        uint64_t page_no {0};
        bool refresh_page {true};
        return xmrblocks.index2(page_no, refresh_page);
    });

    // run the crow http server
    app.port(app_port).multithreaded().run();

    return EXIT_SUCCESS;
}
<commit_msg>dont show header values<commit_after>
#include "src/CmdLineOptions.h"
#include "src/MicroCore.h"
#include "src/page.h"

#include "ext/crow/crow.h"
#include "ext/member_checker.h"

#include <fstream>

using boost::filesystem::path;

using namespace std;

// needed for log system of momero
namespace epee {
    unsigned int g_test_dbg_lock_sleep = 0;
}

int main(int ac, const char* av[]) {

    // get command line options
    xmreg::CmdLineOptions opts {ac, av};

    auto help_opt = opts.get_option<bool>("help");

    // if help was chosen, display help text and finish
    if (*help_opt)
    {
        return EXIT_SUCCESS;
    }

    auto port_opt           = opts.get_option<string>("port");
    auto bc_path_opt        = opts.get_option<string>("bc-path");
    auto custom_db_path_opt = opts.get_option<string>("custom-db-path");
    auto deamon_url_opt     = opts.get_option<string>("deamon-url");

    //cast port number in string to uint16
    uint16_t app_port = boost::lexical_cast<uint16_t>(*port_opt);

    // get blockchain path
    path blockchain_path;

    if (!xmreg::get_blockchain_path(bc_path_opt, blockchain_path))
    {
        cerr << "Error getting blockchain path." << endl;
        return EXIT_FAILURE;
    }

     // enable basic monero log output
    xmreg::enable_monero_log();

    // create instance of our MicroCore
    // and make pointer to the Blockchain
    xmreg::MicroCore mcore;
    cryptonote::Blockchain* core_storage;

    // initialize mcore and core_storage
    if (!xmreg::init_blockchain(blockchain_path.string(),
                               mcore, core_storage))
    {
        cerr << "Error accessing blockchain." << endl;
        return EXIT_FAILURE;
    }

    // check if we have path to lmdb2 (i.e., custom db)
    // and if it exists

    string custom_db_path_str;

    if (custom_db_path_opt)
    {
        if (boost::filesystem::exists(boost::filesystem::path(*custom_db_path_opt)))
        {
            custom_db_path_str = *custom_db_path_opt;
        }
        else
        {
            cerr << "Custom db path: " << *custom_db_path_opt
                 << "does not exist" << endl;

            return EXIT_FAILURE;
        }
    }
    else
    {
        // if not given assume it is located in ~./bitmonero/lmdb2 folder
        custom_db_path_str = blockchain_path.parent_path().string()
                             + string("/lmdb2");
    }

    custom_db_path_str = xmreg::remove_trailing_path_separator(custom_db_path_str);

    // create instance of page class which
    // contains logic for the website
    xmreg::page xmrblocks(&mcore, core_storage,
                          *deamon_url_opt, custom_db_path_str);

    // crow instance
    crow::SimpleApp app;

    CROW_ROUTE(app, "/")
    ([&](const crow::request& req) {

        //for (const auto& m : req.headers)
        //    cout << m.first << ": " << m.second << endl;

        return xmrblocks.index2();
    });

    CROW_ROUTE(app, "/page/<uint>")
    ([&](size_t page_no) {
        return xmrblocks.index2(page_no);
    });

    CROW_ROUTE(app, "/block/<uint>")
    ([&](const crow::request& req, size_t block_height) {

        // there is some robot scanning everything
        // on the explorer. I block it with this
        if (!xmreg::does_header_has(req, "Accept", "q=.2, */*; q=.2").empty())
        {
            cout << "Scanner with q=.2, */*; q=.2 blocked!" << endl;
            return crow::response(400);
        }

        return crow::response(xmrblocks.show_block(block_height));
    });

    CROW_ROUTE(app, "/block/<string>")
    ([&](const crow::request& req, string block_hash) {

        // there is some robot scanning everything
        // on the explorer. I block it with this
        if (!xmreg::does_header_has(req, "Accept", "q=.2, */*; q=.2").empty())
        {
            cout << "Scanner with q=.2, */*; q=.2 blocked!" << endl;
            return crow::response(400);
        }

        return crow::response(xmrblocks.show_block(block_hash));
    });

    CROW_ROUTE(app, "/tx/<string>")
    ([&](const crow::request& req, string tx_hash) {

        // there is some robot scanning everything
        // on the explorer. I block it with this
        if (!xmreg::does_header_has(req, "Accept", "q=.2, */*; q=.2").empty())
        {
            cout << "Scanner with q=.2, */*; q=.2 blocked!" << endl;
            return crow::response(400);
        }

        return crow::response(xmrblocks.show_tx(tx_hash));
    });

    CROW_ROUTE(app, "/tx/<string>/<uint>")
    ([&](string tx_hash, uint with_ring_signatures) {
        return xmrblocks.show_tx(tx_hash, with_ring_signatures);
    });

    CROW_ROUTE(app, "/myoutputs").methods("GET"_method)
    ([&](const crow::request& req) {

        string tx_hash     = string(req.url_params.get("tx_hash"));
        string xmr_address = string(req.url_params.get("xmr_address"));
        string viewkey     = string(req.url_params.get("viewkey"));

        return xmrblocks.show_my_outputs(tx_hash, xmr_address, viewkey);
    });

    CROW_ROUTE(app, "/search").methods("GET"_method)
    ([&](const crow::request& req) {
        return xmrblocks.search(string(req.url_params.get("value")));
    });

    CROW_ROUTE(app, "/robots.txt")
    ([&]() {
        string text = "User-agent: *\n"
                      "Disallow: ";
        return text;
    });

    CROW_ROUTE(app, "/autorefresh")
    ([&]() {
        uint64_t page_no {0};
        bool refresh_page {true};
        return xmrblocks.index2(page_no, refresh_page);
    });

    // run the crow http server
    app.port(app_port).multithreaded().run();

    return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>724299d1-4b02-11e5-9820-28cfe9171a43<commit_msg>this is my first commit?<commit_after>724d43dc-4b02-11e5-8408-28cfe9171a43<|endoftext|>


<commit_before>752379a3-2749-11e6-ac47-e0f84713e7b8<commit_msg>new flies<commit_after>75333d63-2749-11e6-b252-e0f84713e7b8<|endoftext|>


<commit_before>#define FUSE_USE_VERSION 30
#include <fuse.h>

// POSIX
#include <sys/types.h>
#include <sys/stat.h> // mode info
#include <pwd.h> // user id
#include <grp.h> // group id
#include <unistd.h>

// POSIX++
#include <climits> // PATH_MAX
#include <cstdint>
#include <cassert>
#include <cstring>
#include <ctime>

// STL
#include <map>
#include <set>
#include <string>
#include <system_error>

#include <put/specialized/osdetect.h>
#include <put/specialized/procstat.h>
#include <put/cxxutils/posix_helpers.h>

#if !defined(_XOPEN_SOURCE) || _XOPEN_SOURCE < 600 || \
  defined(__darwin__) || defined(BSD)
# define st_ctim st_ctimespec
# define st_mtim st_mtimespec
# define st_atim st_atimespec
#endif

namespace scfs
{
  inline int return_error(posix::errc val) noexcept
    { return 0 - int(val); }

  enum class Epath
  {
    root,
    directory,
    file,
  };

  struct file_entry_t
  {
    bool operator < (const file_entry_t& other) const noexcept // for locating files by name
      { return name < other.name; }

    std::string name;
    pid_t pid;
    struct stat stat;
  };

  static std::map<uid_t, std::set<file_entry_t>> files;
  static struct timespec inittime;

  void deconstruct_path(const char* path, Epath& type, passwd*& pw_ent, std::string& filename) noexcept
  {
    const char* dir_pos = posix::strchr(path, '/') + 1;
    const char* file_pos = posix::strchr(dir_pos, '/');
    std::string dir;

    if(path[1] == '\0')
    {
      type = Epath::root;
      pw_ent = nullptr;
      filename.clear();
    }
    else
    {
      if(file_pos == NULL)
      {
        dir = dir_pos;
        filename.clear();
        type = Epath::directory;
      }
      else
      {
        dir = std::string(dir_pos, file_pos - dir_pos);
        filename = file_pos + 1;
        type = Epath::file;
      }

      pw_ent = posix::getpwnam(dir.c_str());
    }
  }

  void clean_set(std::set<file_entry_t>& dir_set) noexcept
  {
    process_state_t data;
    auto pos = dir_set.begin();
    while(pos != dir_set.end())
    {
      if(!::procstat(pos->pid, data))
        pos = dir_set.erase(pos);
      else
        ++pos;
    }
  }

  int readdir(const char* path, void* buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info* fileInfo) noexcept
  {
    (void)fileInfo;
    filler(buf, "." , NULL, 0);
    filler(buf, "..", NULL, 0);

    Epath type;
    passwd* pw_ent;
    std::string filename;

    deconstruct_path(path, type, pw_ent, filename);

    switch(type)
    {
      case Epath::root: // root directory (fill with usernames in use)
      {
        auto pos = files.begin();
        while(pos != files.end())
        {
          clean_set(pos->second);

          if(pos->second.empty())
            pos = files.erase(pos);
          else
          {
            struct passwd* p = posix::getpwuid(pos->first);
            if(p != NULL)
              filler(buf, p->pw_name, NULL, offset);
            ++pos;
          }
        }
        break;
      }

      case Epath::directory: // list files in directory (based on username)
      {
        auto pos = files.find(pw_ent->pw_uid);
        if(pos == files.end()) // username has no files
          return return_error(posix::errc::no_such_file_or_directory);

        clean_set(pos->second);

        for(const file_entry_t& entry : pos->second)
          filler(buf, entry.name.c_str(), &entry.stat, offset);

        break;
      }

      case Epath::file: // there must have been a parsing error (impossible situation)
        assert(false);
    }

    return posix::success_response;
  }

  int mknod(const char* path, mode_t mode, dev_t rdev) noexcept
  {
    (void)rdev;
    if(!(mode & S_IFSOCK) || mode & (S_ISUID | S_ISGID)) // if not a socket or execution flag is set
      return return_error(posix::errc::permission_denied);

    Epath type;
    passwd* pw_ent = NULL;
    std::string filename;
    struct stat stat = {};
    struct timespec time;
    clock_gettime(CLOCK_REALTIME, &time);

    deconstruct_path(path, type, pw_ent, filename);

    if(fuse_get_context()->uid && // if NOT root AND
       pw_ent->pw_uid != fuse_get_context()->uid) // UID doesn't match
      return return_error(posix::errc::invalid_argument);

    switch(type)
    {
      case Epath::root: // root directory - cannot make root!
      case Epath::directory: // directory (based on username) - cannot make directory!
        return return_error(posix::errc::permission_denied);

      case Epath::file: // create a node file!
        fuse_context* ctx = fuse_get_context();
        auto& dir = files[pw_ent->pw_uid];
        auto entry = dir.find({ filename, 0, stat });
        if(entry != dir.end())
          dir.erase(entry);

        stat.st_uid = pw_ent->pw_uid;
        stat.st_gid = pw_ent->pw_gid;
        stat.st_mode = mode;
        stat.st_ctim =
        stat.st_mtim =
        stat.st_atim = time;

        dir.insert({ filename, ctx->pid, stat });
        break;
    }
    return posix::success_response;
  }

  int getattr(const char* path, struct stat* statbuf) noexcept
  {
    Epath type;
    passwd* pw_ent = NULL;
    std::string filename;

    deconstruct_path(path, type, pw_ent, filename);
    statbuf->st_size = 0;

    switch(type)
    {
      case Epath::root:      // root directory (always exists)

        statbuf->st_ctim =
        statbuf->st_mtim =
        statbuf->st_atim = inittime;
        statbuf->st_mode = S_IFDIR | // set as directory
                           S_IRUSR | S_IRGRP | S_IROTH | // set readable to everyone
                           S_IXUSR | S_IXGRP | S_IXOTH; // set executable to everyone
        break;

      case Epath::directory: // username (exists if username exists)
        statbuf->st_mode = S_IFDIR | // set as directory
                           S_IRUSR | S_IRGRP | S_IROTH | // set readable to everyone
                           S_IXUSR | S_IXGRP | S_IXOTH; // set executable to everyone
        if(pw_ent == nullptr)
          return return_error(posix::errc::no_such_file_or_directory);
        break;

      case Epath::file:
        auto pos = files.find(pw_ent->pw_uid);
        if(pos == files.end()) // username not registered
          return return_error(posix::errc::no_such_file_or_directory);

        clean_set(pos->second);

        for(const file_entry_t& entry : pos->second) // check every file
        {
          if(entry.name == filename)
          {
            *statbuf = entry.stat;
            return posix::success_response;
          }
        }

        return return_error(posix::errc::no_such_file_or_directory); // no file matched
    }
    return posix::success_response;
  }
}

int main(int argc, char *argv[])
{
  static struct fuse_operations ops;

  clock_gettime(CLOCK_REALTIME, &scfs::inittime);

  ops.readdir = scfs::readdir;
  ops.mknod   = scfs::mknod;
  ops.getattr = scfs::getattr;

  return fuse_main(argc, argv, &ops, NULL);
}
<commit_msg>fix preprocessor logic<commit_after>#define FUSE_USE_VERSION 30
#include <fuse.h>

// POSIX
#include <sys/types.h>
#include <sys/stat.h> // mode info
#include <pwd.h> // user id
#include <grp.h> // group id
#include <unistd.h>

// POSIX++
#include <climits> // PATH_MAX
#include <cstdint>
#include <cassert>
#include <cstring>
#include <ctime>

// STL
#include <map>
#include <set>
#include <string>
#include <system_error>

#include <put/specialized/osdetect.h>
#include <put/specialized/procstat.h>
#include <put/cxxutils/posix_helpers.h>

#if (!defined(_XOPEN_SOURCE) || _XOPEN_SOURCE < 600) && \
    (defined(__darwin__) || defined(BSD))
# define st_ctim st_ctimespec
# define st_mtim st_mtimespec
# define st_atim st_atimespec
#endif

namespace scfs
{
  inline int return_error(posix::errc val) noexcept
    { return 0 - int(val); }

  enum class Epath
  {
    root,
    directory,
    file,
  };

  struct file_entry_t
  {
    bool operator < (const file_entry_t& other) const noexcept // for locating files by name
      { return name < other.name; }

    std::string name;
    pid_t pid;
    struct stat stat;
  };

  static std::map<uid_t, std::set<file_entry_t>> files;
  static struct timespec inittime;

  void deconstruct_path(const char* path, Epath& type, passwd*& pw_ent, std::string& filename) noexcept
  {
    const char* dir_pos = posix::strchr(path, '/') + 1;
    const char* file_pos = posix::strchr(dir_pos, '/');
    std::string dir;

    if(path[1] == '\0')
    {
      type = Epath::root;
      pw_ent = nullptr;
      filename.clear();
    }
    else
    {
      if(file_pos == NULL)
      {
        dir = dir_pos;
        filename.clear();
        type = Epath::directory;
      }
      else
      {
        dir = std::string(dir_pos, file_pos - dir_pos);
        filename = file_pos + 1;
        type = Epath::file;
      }

      pw_ent = posix::getpwnam(dir.c_str());
    }
  }

  void clean_set(std::set<file_entry_t>& dir_set) noexcept
  {
    process_state_t data;
    auto pos = dir_set.begin();
    while(pos != dir_set.end())
    {
      if(!::procstat(pos->pid, data))
        pos = dir_set.erase(pos);
      else
        ++pos;
    }
  }

  int readdir(const char* path, void* buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info* fileInfo) noexcept
  {
    (void)fileInfo;
    filler(buf, "." , NULL, 0);
    filler(buf, "..", NULL, 0);

    Epath type;
    passwd* pw_ent;
    std::string filename;

    deconstruct_path(path, type, pw_ent, filename);

    switch(type)
    {
      case Epath::root: // root directory (fill with usernames in use)
      {
        auto pos = files.begin();
        while(pos != files.end())
        {
          clean_set(pos->second);

          if(pos->second.empty())
            pos = files.erase(pos);
          else
          {
            struct passwd* p = posix::getpwuid(pos->first);
            if(p != NULL)
              filler(buf, p->pw_name, NULL, offset);
            ++pos;
          }
        }
        break;
      }

      case Epath::directory: // list files in directory (based on username)
      {
        auto pos = files.find(pw_ent->pw_uid);
        if(pos == files.end()) // username has no files
          return return_error(posix::errc::no_such_file_or_directory);

        clean_set(pos->second);

        for(const file_entry_t& entry : pos->second)
          filler(buf, entry.name.c_str(), &entry.stat, offset);

        break;
      }

      case Epath::file: // there must have been a parsing error (impossible situation)
        assert(false);
    }

    return posix::success_response;
  }

  int mknod(const char* path, mode_t mode, dev_t rdev) noexcept
  {
    (void)rdev;
    if(!(mode & S_IFSOCK) || mode & (S_ISUID | S_ISGID)) // if not a socket or execution flag is set
      return return_error(posix::errc::permission_denied);

    Epath type;
    passwd* pw_ent = NULL;
    std::string filename;
    struct stat stat = {};
    struct timespec time;
    clock_gettime(CLOCK_REALTIME, &time);

    deconstruct_path(path, type, pw_ent, filename);

    if(fuse_get_context()->uid && // if NOT root AND
       pw_ent->pw_uid != fuse_get_context()->uid) // UID doesn't match
      return return_error(posix::errc::invalid_argument);

    switch(type)
    {
      case Epath::root: // root directory - cannot make root!
      case Epath::directory: // directory (based on username) - cannot make directory!
        return return_error(posix::errc::permission_denied);

      case Epath::file: // create a node file!
        fuse_context* ctx = fuse_get_context();
        auto& dir = files[pw_ent->pw_uid];
        auto entry = dir.find({ filename, 0, stat });
        if(entry != dir.end())
          dir.erase(entry);

        stat.st_uid = pw_ent->pw_uid;
        stat.st_gid = pw_ent->pw_gid;
        stat.st_mode = mode;
        stat.st_ctim =
        stat.st_mtim =
        stat.st_atim = time;

        dir.insert({ filename, ctx->pid, stat });
        break;
    }
    return posix::success_response;
  }

  int getattr(const char* path, struct stat* statbuf) noexcept
  {
    Epath type;
    passwd* pw_ent = NULL;
    std::string filename;

    deconstruct_path(path, type, pw_ent, filename);
    statbuf->st_size = 0;

    switch(type)
    {
      case Epath::root:      // root directory (always exists)

        statbuf->st_ctim =
        statbuf->st_mtim =
        statbuf->st_atim = inittime;
        statbuf->st_mode = S_IFDIR | // set as directory
                           S_IRUSR | S_IRGRP | S_IROTH | // set readable to everyone
                           S_IXUSR | S_IXGRP | S_IXOTH; // set executable to everyone
        break;

      case Epath::directory: // username (exists if username exists)
        statbuf->st_mode = S_IFDIR | // set as directory
                           S_IRUSR | S_IRGRP | S_IROTH | // set readable to everyone
                           S_IXUSR | S_IXGRP | S_IXOTH; // set executable to everyone
        if(pw_ent == nullptr)
          return return_error(posix::errc::no_such_file_or_directory);
        break;

      case Epath::file:
        auto pos = files.find(pw_ent->pw_uid);
        if(pos == files.end()) // username not registered
          return return_error(posix::errc::no_such_file_or_directory);

        clean_set(pos->second);

        for(const file_entry_t& entry : pos->second) // check every file
        {
          if(entry.name == filename)
          {
            *statbuf = entry.stat;
            return posix::success_response;
          }
        }

        return return_error(posix::errc::no_such_file_or_directory); // no file matched
    }
    return posix::success_response;
  }
}

int main(int argc, char *argv[])
{
  static struct fuse_operations ops;

  clock_gettime(CLOCK_REALTIME, &scfs::inittime);

  ops.readdir = scfs::readdir;
  ops.mknod   = scfs::mknod;
  ops.getattr = scfs::getattr;

  return fuse_main(argc, argv, &ops, NULL);
}
<|endoftext|>


<commit_before>#include <vector>
#include <algorithm>
#include <thread>
#include <cstdlib>
#include <ctime>
#include <ncurses.h>
#include <string>

#include "tribe.hpp"
#include "util.hpp"

using namespace std;

int main(int argc, char** argv)
{
    srand(time(NULL));//seeding random

    int tribeChoice = 4;

    int tribeNumber = 10;
    if(tribeNumber > 99)
    {
        return 0;
    }

    int initPopulation = 1000;

    vector<tribe> tribes;
    tribes.resize(tribeNumber);

    for(unsigned i = 0; i < tribes.size(); i++)
    {
        tribes.at(i).setNumber(i);
        for(int j = 0; j < initPopulation; j++)
        {
            tribes.at(i).forceBirth();
        }
    }

    //this is an abortion of ncurses
    initscr();
    keypad(stdscr, TRUE);//reads arrow keys

    unsigned choice = 0;

    //temp
    tribeChoice = 0;
    //temp

    while(tribeChoice == 4)
    {
        move(0,0);
        for(unsigned i = 0; i < tribes.size(); ++i)
        {
            printw("Tribe %d [ ]\n", i);
        }
        move(choice, 9);
        refresh();

        int temp = getch();
        switch(temp)
        {
            case KEY_UP:
                choice--;
                break;
            case KEY_DOWN:
                choice++;
                break;
            case 10:
                tribeChoice = choice;
                break;
        }
        if(choice < 0)
        {
            choice = tribes.size() - 1;
        }
        if(choice > tribes.size() - 1)
        {
            choice = 0;
        }
    }

    //temp
    vector<thread> threads;
    while(true)
    {
        if(tribes.size() == 0)
        {
            break;
        }

        clear();

        for(unsigned i = 0; i < tribes.size(); ++i)//end/win/kill/whatever
        {
            if(tribes.at(i).getTech() >= 1000 || tribes.size() == 1)//current win condition
            {
                clear();
                printw("Tribe %d wins\n",tribes.at(i).getNumber());
                refresh();
                getch();
                endwin();
                return 1;
            }
            else if(tribes.at(i).getTribesmen().size() == 0)//if they're dead
            {
                tribes.erase(tribes.begin() + i);
            }
            /*
            //tribes.at(i).hunt(tribes.at(i).getTribesmen().size());
            tribes.at(i).aiCycle();
            tribes.at(i).stdCycle();
            printw("Tribe %d: %d,%d,%d\n",tribes.at(i).getNumber(),
            tribes.at(i).getTribesmen().size(),tribes.at(i).getFood(),tribes.at(i).getTech());
            */
        }

        /* works fine
        for(unsigned i = 0; i < tribes.size(); ++i)
        {
            //tribes.at(j).hunt(tribes.at(j).getTribesmen().size());
            tribes.at(i).aiCycle();
            tribes.at(i).stdCycle();
            printw("Tribe %d: %d,%d,%d\n",tribes.at(i).getNumber(),
            tribes.at(i).getTribesmen().size(),tribes.at(i).getFood(),tribes.at(i).getTech());
        }
        */

        //initiate multiAIDS
        printw("mark 1\n");
        refresh();
        //getch();
        for(unsigned i = 0; i < tribes.size(); ++i)
        {
            printw("0test #%d\n", i);//fuck i
            /*
            threads.push_back(thread([        &i]{printw("1test #%d\n", i);}));
            threads.at(i).join();
            threads.erase(threads.begin() + i);
            */
            threads.push_back(thread([&tribes,&i]{printw("2test #%d\n", i);//really fuck i
                                                  /*
                                                  tribes.at(i).aiCycle();
                                                  tribes.at(i).stdCycle();
                                                  printw("Tribe %d: %d,%d,%d\n",tribes.at(i).getNumber(),
                                                  tribes.at(i).getTribesmen().size(),tribes.at(i).getFood(),
                                                  tribes.at(i).getTech());
                                                  */
                                                  }));
            //threads.push_back(thread([]{printw("test\n");}));
        }
        printw("mark 2\n");
        refresh();
        //getch();
        for(unsigned i = 0; i < tribes.size(); ++i)
        {
            threads.at(i).join();
        }
        printw("mark 3\n");
        refresh();
        //getch();
        for(unsigned i = 0; i < tribes.size(); ++i)
        {
            threads.erase(threads.begin() + i);
        }
        printw("mark 4\n");
        refresh();
        getch();

        refresh();
    }

    endwin();

    return 0;
}
<commit_msg>about to dick around with const's<commit_after>#include <vector>
#include <algorithm>
#include <thread>
#include <cstdlib>
#include <ctime>
#include <ncurses.h>
#include <string>

#include "tribe.hpp"
#include "util.hpp"

using namespace std;

int main(int argc, char** argv)
{
    srand(time(NULL));//seeding random

    int tribeChoice = 4;

    int tribeNumber = 10;
    if(tribeNumber > 99)
    {
        return 0;
    }

    int initPopulation = 1000;

    vector<tribe> tribes;
    tribes.resize(tribeNumber);

    for(unsigned i = 0; i < tribes.size(); i++)
    {
        tribes.at(i).setNumber(i);
        for(int j = 0; j < initPopulation; j++)
        {
            tribes.at(i).forceBirth();
        }
    }

    //this is an abortion of ncurses
    initscr();
    keypad(stdscr, TRUE);//reads arrow keys

    unsigned choice = 0;

    //temp
    tribeChoice = 0;
    //temp

    while(tribeChoice == 4)
    {
        move(0,0);
        for(unsigned i = 0; i < tribes.size(); ++i)
        {
            printw("Tribe %d [ ]\n", i);
        }
        move(choice, 9);
        refresh();

        int temp = getch();
        switch(temp)
        {
            case KEY_UP:
                choice--;
                break;
            case KEY_DOWN:
                choice++;
                break;
            case 10:
                tribeChoice = choice;
                break;
        }
        if(choice < 0)
        {
            choice = tribes.size() - 1;
        }
        if(choice > tribes.size() - 1)
        {
            choice = 0;
        }
    }

    //temp
    vector<thread> threads;
    while(true)
    {
        if(tribes.size() == 0)
        {
            break;
        }

        clear();

        for(unsigned i = 0; i < tribes.size(); ++i)//end/win/kill/whatever
        {
            if(tribes.at(i).getTech() >= 1000 || tribes.size() == 1)//current win condition
            {
                clear();
                printw("Tribe %d wins\n",tribes.at(i).getNumber());
                refresh();
                getch();
                endwin();
                return 1;
            }
            else if(tribes.at(i).getTribesmen().size() == 0)//if they're dead
            {
                tribes.erase(tribes.begin() + i);
            }
            /*
            //tribes.at(i).hunt(tribes.at(i).getTribesmen().size());
            tribes.at(i).aiCycle();
            tribes.at(i).stdCycle();
            printw("Tribe %d: %d,%d,%d\n",tribes.at(i).getNumber(),
            tribes.at(i).getTribesmen().size(),tribes.at(i).getFood(),tribes.at(i).getTech());
            */
        }

        /* works fine
        for(unsigned i = 0; i < tribes.size(); ++i)
        {
            //tribes.at(j).hunt(tribes.at(j).getTribesmen().size());
            tribes.at(i).aiCycle();
            tribes.at(i).stdCycle();
            printw("Tribe %d: %d,%d,%d\n",tribes.at(i).getNumber(),
            tribes.at(i).getTribesmen().size(),tribes.at(i).getFood(),tribes.at(i).getTech());
        }
        */

        //initiate multiAIDS
        printw("mark 1\n");
        refresh();
        //getch();
        for(unsigned i = 0; i < tribes.size(); ++i)
        {
            printw("0test #%d\n", i);//fuck i
            /*
            threads.push_back(thread([        &i]{printw("1test #%d\n", i);}));
            threads.at(i).join();
            threads.erase(threads.begin() + i);
            */
            threads.push_back(thread([tribes,i]{printw("2test #%d\n", i);//really fuck i
                                                tribes.at(i).aiCycle();
                                                tribes.at(i).stdCycle();
                                                printw("Tribe %d: %d,%d,%d\n",tribes.at(i).getNumber(),
                                                tribes.at(i).getTribesmen().size(),tribes.at(i).getFood(),
                                                tribes.at(i).getTech());
                                                }));
            //threads.push_back(thread([]{printw("test\n");}));
        }
        printw("mark 2\n");
        refresh();
        //getch();
        for(unsigned i = 0; i < tribes.size(); ++i)
        {
            threads.at(i).join();
        }
        printw("mark 3\n");
        refresh();
        //getch();
        for(unsigned i = 0; i < tribes.size(); ++i)
        {
            threads.erase(threads.begin() + i);
        }
        printw("mark 4\n");
        refresh();
        //getch();

        refresh();
    }

    endwin();

    return 0;
}
<|endoftext|>


<commit_before>#include <QtCore/QCoreApplication>
#include <pcl/point_types.h>
#include <pcl/io/pcd_io.h>
#include <pcl/kdtree/kdtree_flann.h>
#include <pcl/features/normal_3d.h>
#include <pcl/surface/gp3.h>
#include <pcl/io/vtk_io.h>

int main(int argc, char *argv[])
{
    //QCoreApplication a(argc, argv);

    // Load input file into a PointCloud<T> with an appropriate type
    pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZRGB>);
    pcl::PCLPointCloud2 cloud_blob;
    pcl::io::loadPCDFile ("pointcloud-ascii-downsampled-inliers.pcd", cloud_blob);
    pcl::fromPCLPointCloud2 (cloud_blob, *cloud);
    //* the data should be available in cloud

    // Normal estimation*
    pcl::NormalEstimation<pcl::PointXYZRGB, pcl::Normal> n;
    pcl::PointCloud<pcl::Normal>::Ptr normals (new pcl::PointCloud<pcl::Normal>);
    pcl::search::KdTree<pcl::PointXYZRGB>::Ptr tree (new pcl::search::KdTree<pcl::PointXYZRGB>);
    tree->setInputCloud (cloud);
    n.setInputCloud (cloud);
    n.setSearchMethod (tree);
    n.setKSearch (20);
    n.compute (*normals);
    //* normals should not contain the point normals + surface curvatures

    // Concatenate the XYZ and normal fields*
    pcl::PointCloud<pcl::PointXYZRGBNormal>::Ptr cloud_with_normals (new pcl::PointCloud<pcl::PointXYZRGBNormal>);
    pcl::concatenateFields (*cloud, *normals, *cloud_with_normals);
    //* cloud_with_normals = cloud + normals

    // Create search tree*
    pcl::search::KdTree<pcl::PointXYZRGBNormal>::Ptr tree2 (new pcl::search::KdTree<pcl::PointXYZRGBNormal>);
    tree2->setInputCloud (cloud_with_normals);

    // Initialize objects
    pcl::GreedyProjectionTriangulation<pcl::PointXYZRGBNormal> gp3;
    pcl::PolygonMesh triangles;

    // Set the maximum distance between connected points (maximum edge length)
    gp3.setSearchRadius (0.125);

    // Set typical values for the parameters
    gp3.setMu (2.5);
    gp3.setMaximumNearestNeighbors (50);
    gp3.setMaximumSurfaceAngle(M_PI/4); // 45 degrees
    gp3.setMinimumAngle(M_PI/18); // 10 degrees
    gp3.setMaximumAngle(2*M_PI/3); // 120 degrees
    gp3.setNormalConsistency(true);

    // Get result
    gp3.setInputCloud (cloud_with_normals);
    gp3.setSearchMethod (tree2);
    gp3.reconstruct (triangles);

    // Additional vertex information
    std::vector<int> parts = gp3.getPartIDs();
    std::vector<int> states = gp3.getPointStates();

    pcl::io::saveVTKFile ("mesh.vtk", triangles);
    // Finish
    //return a.exec();
    return 0;
}
<commit_msg>added typedef's for easy testing<commit_after>#include <pcl/point_types.h>
#include <pcl/io/pcd_io.h>
#include <pcl/kdtree/kdtree_flann.h>
#include <pcl/features/normal_3d.h>
#include <pcl/surface/gp3.h>
#include <pcl/surface/impl/organized_fast_mesh.hpp>
#include <pcl/io/vtk_io.h>

//typedef pcl::PointXYZ PointType;
typedef pcl::Normal Normal;
typedef pcl::PointXYZRGB PointType;
typedef pcl::PointXYZRGBNormal PointTypeN;

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

    // Load input file into a PointCloud<T> with an appropriate type
    pcl::PointCloud<PointType>::Ptr cloud (new pcl::PointCloud<PointType>);
    pcl::PCLPointCloud2 cloud_blob;
    pcl::io::loadPCDFile ("pointcloud-ascii-downsampled-inliers.pcd", cloud_blob);
    //pcl::io::loadPCDFile ("bun0.pcd", cloud_blob);
    pcl::fromPCLPointCloud2 (cloud_blob, *cloud);
    //* the data should be available in cloud
    std::cout << "bun0 loaded " << std::endl;
    std::cout << cloud->size() << std::endl;

    // Normal estimation*
    pcl::NormalEstimation<PointType, Normal> n;
    pcl::PointCloud<Normal>::Ptr normals (new pcl::PointCloud<Normal>);
    pcl::search::KdTree<PointType>::Ptr tree (new pcl::search::KdTree<PointType>);
    tree->setInputCloud (cloud);
    n.setInputCloud (cloud);
    n.setSearchMethod (tree);
    n.setKSearch (20);
    n.compute (*normals);
    //* normals should not contain the point normals + surface curvatures

    // Concatenate the XYZ and normal fields*
    pcl::PointCloud<PointTypeN>::Ptr cloud_with_normals (new pcl::PointCloud<PointTypeN>);
    pcl::concatenateFields (*cloud, *normals, *cloud_with_normals);
    //* cloud_with_normals = cloud + normals

    // Create search tree*
    pcl::search::KdTree<PointTypeN>::Ptr tree2 (new pcl::search::KdTree<PointTypeN>);
    tree2->setInputCloud (cloud_with_normals);

    // Initialize objects
    // pcl::GreedyProjectionTriangulation<pcl::PointXYZRGBNormal> gp3;
    pcl::OrganizedFastMesh<PointTypeN> ofm;
    pcl::PolygonMesh triangles;

    std::cout << cloud_with_normals->size() << std::endl;

    ofm.setSearchMethod(tree2);
    ofm.setInputCloud(cloud_with_normals);
    ofm.reconstruct (triangles);
    // Set the maximum distance between connected points (maximum edge length)
    // gp3.setSearchRadius (0.125);

    // // Set typical values for the parameters
    // gp3.setMu (2.5);
    // gp3.setMaximumNearestNeighbors (50);
    // gp3.setMaximumSurfaceAngle(M_PI/4); // 45 degrees
    // gp3.setMinimumAngle(M_PI/18); // 10 degrees
    // gp3.setMaximumAngle(2*M_PI/3); // 120 degrees
    // gp3.setNormalConsistency(true);

    // // Get result
    // gp3.setInputCloud (cloud_with_normals);
    // gp3.setSearchMethod (tree2);
    // gp3.reconstruct (triangles);

    // // Additional vertex information
    // std::vector<int> parts = gp3.getPartIDs();
    // std::vector<int> states = gp3.getPointStates();

    pcl::io::saveVTKFile ("mesh-ofm.vtk", triangles);
    return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <iterator>
#include <memory>
#include <algorithm>
#include <cstring>
#include <unordered_map>

using namespace std;

vector<string> split(const string& str) {
    string buf; // Have a buffer string
    stringstream ss(str); // Insert the string into a stream
    vector<string> tokens; // Create vector to hold our words

    while (ss >> buf)
        tokens.push_back(buf);

    return tokens;
}

using RoomID = int;

struct RoomObject
{
	vector<string> names;
	string description;
	bool visible;
};

struct Map
{
	static const int max_width = 100, max_height = 100;
	static const int player_start_x = 50, player_start_y = 50;
    enum Location
    {
        UNKNOWN,
        GRAVEYARD,
        GRAVEYARD_GATES,
        KHATHARRS_MOMS_HOUSE,
    };
	Location map_location[max_width][max_height];
	int x, y;
	Map()
	{
        memset(map_location, UNKNOWN, sizeof(map_location));
		x = 50;
		y = 50;
		map_location[50][50] = GRAVEYARD;
		map_location[50][51] = GRAVEYARD_GATES;
		map_location[50][52] = KHATHARRS_MOMS_HOUSE;
	}
};

struct Entity
{
    Entity(string name, int maxHealth) : name(name), health(maxHealth) {}

    void heal(int points)
    {
        health = min(100, health + points);
        cout << name << " healed to " << health << " health" << endl;
    }

    void damage(int points)
    {
        health = max(0, health - points);
        cout << name << " damaged to " << health << "health" << endl;
    }

    int getHealth() const { return health; }

    // Return false if the entity didn't know the command
    virtual bool act(vector<string> commands) = 0;

    string name;
    Map map;

private:
    int health;
};

struct Shogun : public Entity {
  Shogun() : Entity("Shogibear", 100) {}
};

struct Item
{
    virtual void apply(Entity* entity) = 0;
    virtual string identify() const = 0;
};

struct HealthItem : public Item
{
    HealthItem(int healPower) : healPower(healPower) {}

    void apply(Entity* entity) override
    {
        entity->heal(healPower);
    }

    string identify() const override
    {
        stringstream ss;
        ss << "Health Potion (" << healPower << ")";
        return ss.str();
    }

private:
    int healPower;
};
struct BlessedSword : public Item
{
    BlessedSword(int Weapon) : Weapon(Weapon){}
void apply(Entity* entity) override{entity->damage(Weapon);}string identify() const override{stringstream ss; ss << "Hit (" << Weapon << ")";}
private: int Weapon;};//will add this to entity on my next commit. <.<

/*
struct ReallyFastSword : public Item
struct TheFastcall : public Entity
{
    TheFastcall() : Entity("The Fastcall", 22) {}
    virtual bool act(vector<string> commands) override
    {
    }
};
*/

typedef bool (*actionHandler)(vector<string> commands);

struct Player : public Entity
{
    Player(string name, int health) : Entity(name, health) {}

    virtual bool act(vector<string> commands) override
    {
        auto& cmd = commands[0];
        if(cmd == "n") { commands = vector<string>{"go","north"}; }
        if(cmd == "s") { commands = vector<string>{"go","south"}; }
        if(cmd == "e") { commands = vector<string>{"go","east"}; }
        if(cmd == "w") { commands = vector<string>{"go","west"}; }

        if (commands.size() >= 1 && commands[0] == "look")
        {
            look();
            return true;
        }
        else if (commands.size() >= 2 && (commands[0] == "examine" || commands[0] == "x"))
        {
        }
        else if (commands.size() >= 2 && commands[0] == "go")
        {
            if (travel(commands[1]) == true)
            {
                look();
            } else {
                cout << "Can't travel " << commands[1] << endl;
            }
            return true;
        }
        else if (commands.size() >= 1 && commands[0] == "items")
        {
            showItems();
            return true;
        }
        else if (commands.size() >= 2 && commands[0] == "use")
        {
            int index = stoi(commands[1]);
            useItem(index);
            return true;
        }

        return false;
    }

    bool travel(string direction)
    {
		if ((map.x <= 0 && direction == "west") || (map.x >= (map.max_width - 1) && direction == "east"))
			return false;
		if ((map.y <= 0 && direction == "south") || (map.y >= (map.max_width - 1) && direction == "north"))
			return false;
        if(direction=="north"&&map.map_location[map.x][map.y+1]==Map::UNKNOWN)return false;if(direction=="south"&&map.map_location[map.x][map.y-1]==Map::UNKNOWN)return false;if(direction=="east"&&map.map_location[map.x+1][map.y]==Map::UNKNOWN)return false
        ;if(direction=="west"&&map.map_location[map.x-1][map.y]==Map::UNKNOWN)return false;if(direction=="north")map.y++;if(direction=="south")map.y--;if(direction=="east")map.x++;if(direction=="west")map.x--;
        return true;/*
        switch (map.map_location[map.x][map.y])
        {
            case Map::GRAVEYARD:
                if (direction == "north")
                {
					map.y++;
                    return true;
                }
                break;
            case Map::GRAVEYARD_GATES:
                if (direction == "south")
                {
					map.y--;
                    return true;
                }
                if (direction == "north")
                {
                    map.y++;
                    return true;
                }
                break;
        }

        cout << "Can't travel " << direction << endl;
        return false;*/
    }

    void look()
    {
        switch (map.map_location[map.x][map.y])
        {
            case Map::GRAVEYARD:
                cout << "A thick layer of fog covers the graveyard soil. Tombstones jut out here and there and an eerie willow tree looms over your head, obstructing the full moon partially. Off in the distance you see the northern gates -- the only entrance into this forsaken place." << endl;
                break;
            case Map::GRAVEYARD_GATES:
                cout << "For many centuries these gates have stood the test of time. The gateway to the afterlife. Inside the graveyard small hills stretch endlessly, littered with thousands of tombstones. You see a willow tree south of the gates. Outisde, north, you see a very large house." << endl;
                break;
            case Map::KHATHARRS_MOMS_HOUSE:
                cout << "The house is gigantic! What could possibly require such volume, such mass, such density? The house appears to not have any doors, but due to the strain from whatever is present inside, cracks have formed. You see a crack you might just fit into east." << endl;
                break;
        }
    }

    void giveItem(shared_ptr<Item> item)
    {
        inventory.push_back(item);
    }

    void showItems()
    {
        if (inventory.size() == 0)
            cout << "You have no items." << endl;
        int i = 1;
        for (auto item : inventory)
        {
            cout << "  " << i++ << ". " << item->identify() << std::endl;
        }
    }

    void useItem(size_t index)
    {
        if (index > inventory.size())
        {
            cout << "Invalid index" << endl;
            return;
        }

        inventory[index-1]->apply(this);
        inventory.erase(inventory.begin() + index - 1);
    }

private:
    vector<shared_ptr<Item>> inventory;
    unordered_map<string, actionHandler> actions;
};

struct Room {
	string describe() {
    stringstream ss;
		return ss.str(); //description << list entites, list items, list exits
	}
	string description;
	vector<unique_ptr<Entity>> entities;
	vector<RoomObject> objects;
	unordered_map<string, RoomID> exits;
};

class Adventure
{
public:
    void begin()
    {
        string command;
        cout << "Welcome, brave soul. Pray tell, what is thy name?" << endl;
        cout << "> ";
        getline(cin, command);

        Player player(command, 100);
        player.giveItem(make_shared<HealthItem>(20));

        cout << player.name << "! Your presence defiles these sacred grounds. Beware the soil upon which you step, for it will claim you sooner rather than later." << endl;
        player.look();

        while (player.getHealth() > 0)
        {
            cout << "> ";
            getline(cin, command);
            if (player.act(split(command)) == false)
                cout << "Unknown command" << endl;
        }

        cout << "You died. Game over." << endl;
    }
};

int main()
{
    Adventure adventure;
    adventure.begin();
    return 0;
}
<commit_msg>Room::describe()<commit_after>#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <iterator>
#include <memory>
#include <algorithm>
#include <cstring>
#include <unordered_map>

using namespace std;

vector<string> split(const string& str) {
    string buf; // Have a buffer string
    stringstream ss(str); // Insert the string into a stream
    vector<string> tokens; // Create vector to hold our words

    while (ss >> buf)
        tokens.push_back(buf);

    return tokens;
}

using RoomID = int;

struct RoomObject
{
	vector<string> names;
	string description;
	bool visible;
};

struct Map
{
	static const int max_width = 100, max_height = 100;
	static const int player_start_x = 50, player_start_y = 50;
    enum Location
    {
        UNKNOWN,
        GRAVEYARD,
        GRAVEYARD_GATES,
        KHATHARRS_MOMS_HOUSE,
    };
	Location map_location[max_width][max_height];
	int x, y;
	Map()
	{
        memset(map_location, UNKNOWN, sizeof(map_location));
		x = 50;
		y = 50;
		map_location[50][50] = GRAVEYARD;
		map_location[50][51] = GRAVEYARD_GATES;
		map_location[50][52] = KHATHARRS_MOMS_HOUSE;
	}
};

struct Entity
{
    Entity(string name, int maxHealth) : name(name), health(maxHealth) {}

    void heal(int points)
    {
        health = min(100, health + points);
        cout << name << " healed to " << health << " health" << endl;
    }

    void damage(int points)
    {
        health = max(0, health - points);
        cout << name << " damaged to " << health << "health" << endl;
    }

    int getHealth() const { return health; }

    // Return false if the entity didn't know the command
    virtual bool act(vector<string> commands) = 0;

    string name;
    Map map;

private:
    int health;
};

struct Shogun : public Entity {
  Shogun() : Entity("Shogibear", 100) {}
};

struct Item
{
    virtual void apply(Entity* entity) = 0;
    virtual string identify() const = 0;
};

struct HealthItem : public Item
{
    HealthItem(int healPower) : healPower(healPower) {}

    void apply(Entity* entity) override
    {
        entity->heal(healPower);
    }

    string identify() const override
    {
        stringstream ss;
        ss << "Health Potion (" << healPower << ")";
        return ss.str();
    }

private:
    int healPower;
};
struct BlessedSword : public Item
{
    BlessedSword(int Weapon) : Weapon(Weapon){}
void apply(Entity* entity) override{entity->damage(Weapon);}string identify() const override{stringstream ss; ss << "Hit (" << Weapon << ")";}
private: int Weapon;};//will add this to entity on my next commit. <.<

/*
struct ReallyFastSword : public Item
struct TheFastcall : public Entity
{
    TheFastcall() : Entity("The Fastcall", 22) {}
    virtual bool act(vector<string> commands) override
    {
    }
};
*/

typedef bool (*actionHandler)(vector<string> commands);

struct Player : public Entity
{
    Player(string name, int health) : Entity(name, health) {}

    virtual bool act(vector<string> commands) override
    {
        auto& cmd = commands[0];
        if(cmd == "n") { commands = vector<string>{"go","north"}; }
        if(cmd == "s") { commands = vector<string>{"go","south"}; }
        if(cmd == "e") { commands = vector<string>{"go","east"}; }
        if(cmd == "w") { commands = vector<string>{"go","west"}; }

        if (commands.size() >= 1 && commands[0] == "look")
        {
            look();
            return true;
        }
        else if (commands.size() >= 2 && (commands[0] == "examine" || commands[0] == "x"))
        {
        }
        else if (commands.size() >= 2 && commands[0] == "go")
        {
            if (travel(commands[1]) == true)
            {
                look();
            } else {
                cout << "Can't travel " << commands[1] << endl;
            }
            return true;
        }
        else if (commands.size() >= 1 && commands[0] == "items")
        {
            showItems();
            return true;
        }
        else if (commands.size() >= 2 && commands[0] == "use")
        {
            int index = stoi(commands[1]);
            useItem(index);
            return true;
        }

        return false;
    }

    bool travel(string direction)
    {
		if ((map.x <= 0 && direction == "west") || (map.x >= (map.max_width - 1) && direction == "east"))
			return false;
		if ((map.y <= 0 && direction == "south") || (map.y >= (map.max_width - 1) && direction == "north"))
			return false;
        if(direction=="north"&&map.map_location[map.x][map.y+1]==Map::UNKNOWN)return false;if(direction=="south"&&map.map_location[map.x][map.y-1]==Map::UNKNOWN)return false;if(direction=="east"&&map.map_location[map.x+1][map.y]==Map::UNKNOWN)return false
        ;if(direction=="west"&&map.map_location[map.x-1][map.y]==Map::UNKNOWN)return false;if(direction=="north")map.y++;if(direction=="south")map.y--;if(direction=="east")map.x++;if(direction=="west")map.x--;
        return true;/*
        switch (map.map_location[map.x][map.y])
        {
            case Map::GRAVEYARD:
                if (direction == "north")
                {
					map.y++;
                    return true;
                }
                break;
            case Map::GRAVEYARD_GATES:
                if (direction == "south")
                {
					map.y--;
                    return true;
                }
                if (direction == "north")
                {
                    map.y++;
                    return true;
                }
                break;
        }

        cout << "Can't travel " << direction << endl;
        return false;*/
    }

    void look()
    {
        switch (map.map_location[map.x][map.y])
        {
            case Map::GRAVEYARD:
                cout << "A thick layer of fog covers the graveyard soil. Tombstones jut out here and there and an eerie willow tree looms over your head, obstructing the full moon partially. Off in the distance you see the northern gates -- the only entrance into this forsaken place." << endl;
                break;
            case Map::GRAVEYARD_GATES:
                cout << "For many centuries these gates have stood the test of time. The gateway to the afterlife. Inside the graveyard small hills stretch endlessly, littered with thousands of tombstones. You see a willow tree south of the gates. Outisde, north, you see a very large house." << endl;
                break;
            case Map::KHATHARRS_MOMS_HOUSE:
                cout << "The house is gigantic! What could possibly require such volume, such mass, such density? The house appears to not have any doors, but due to the strain from whatever is present inside, cracks have formed. You see a crack you might just fit into east." << endl;
                break;
        }
    }

    void giveItem(shared_ptr<Item> item)
    {
        inventory.push_back(item);
    }

    void showItems()
    {
        if (inventory.size() == 0)
            cout << "You have no items." << endl;
        int i = 1;
        for (auto item : inventory)
        {
            cout << "  " << i++ << ". " << item->identify() << std::endl;
        }
    }

    void useItem(size_t index)
    {
        if (index > inventory.size())
        {
            cout << "Invalid index" << endl;
            return;
        }

        inventory[index-1]->apply(this);
        inventory.erase(inventory.begin() + index - 1);
    }

private:
    vector<shared_ptr<Item>> inventory;
    unordered_map<string, actionHandler> actions;
};

struct Room {
	string describe() {
    stringstream ss;
    ss << description << "\nYou see: ";
    for(auto& ent : entities) { ent->name << ", "; } //clean this up later
    for(auto& obj : objects) { obj.names[0] << ", "; } //clean this up later
		return ss.str(); //exits need listed
	}
	string description;
	vector<unique_ptr<Entity>> entities;
	vector<RoomObject> objects;
	unordered_map<string, RoomID> exits;
};

class Adventure
{
public:
    void begin()
    {
        string command;
        cout << "Welcome, brave soul. Pray tell, what is thy name?" << endl;
        cout << "> ";
        getline(cin, command);

        Player player(command, 100);
        player.giveItem(make_shared<HealthItem>(20));

        cout << player.name << "! Your presence defiles these sacred grounds. Beware the soil upon which you step, for it will claim you sooner rather than later." << endl;
        player.look();

        while (player.getHealth() > 0)
        {
            cout << "> ";
            getline(cin, command);
            if (player.act(split(command)) == false)
                cout << "Unknown command" << endl;
        }

        cout << "You died. Game over." << endl;
    }
};

int main()
{
    Adventure adventure;
    adventure.begin();
    return 0;
}
<|endoftext|>


<commit_before>#include <cstddef>

#include <tuple>

#include <type_traits>

#include <utility>

namespace generic
{

namespace detail
{

namespace many
{

template <::std::size_t I, typename T>
struct many_holder
{
  ::std::conditional_t<::std::is_reference<T>{},
    ::std::add_pointer_t<::std::remove_reference_t<T>>,
    T
  > value;

  template <typename U = T>
  ::std::enable_if_t<!::std::is_reference<U>{}, U&>
  get() noexcept
  {
    return value;
  }

  template <typename U = T>
  ::std::enable_if_t<!::std::is_reference<U>{}, U const&>
  get() const noexcept
  {
    return value;
  }

  template <typename U = T>
  ::std::enable_if_t<::std::is_reference<U>{}, U>
  get() const noexcept
  {
    return *value;
  }

  template <typename A, typename U = T>
  ::std::enable_if_t<!::std::is_reference<U>{}>
  set(A const& u) noexcept(noexcept(::std::declval<U&>() = u))
  {
    value = u;
  }

  template <typename A, typename U = T>
  ::std::enable_if_t<!::std::is_reference<U>{}>
  set(A&& u) noexcept(noexcept(::std::declval<U&>() = ::std::move(u)))
  {
    value = ::std::move(u);
  }

  template <typename A, typename U = T>
  ::std::enable_if_t<::std::is_reference<U>{}>
  set(A&& u) noexcept
  {
    // convert to a reference to handle reference wrappers
    value = &T(u);
  }
};

template <typename, typename ...>
struct many_impl;

template <::std::size_t... Is, typename ...Types>
struct many_impl<::std::index_sequence<Is...>, Types...> :
  many_holder<Is, Types>...
{
};

}

}

template <typename ...Types>
struct many : detail::many::many_impl<
  ::std::make_index_sequence<sizeof...(Types)>,
  Types...
>
{
};

namespace detail
{

namespace many
{

template <typename ...Types, typename ...A, ::std::size_t ...Is>
auto create_many_impl(::std::index_sequence<Is...>, A&& ...a) noexcept(
  noexcept(
    (
      static_cast<
        ::generic::detail::many::many_holder<Is,
          ::std::tuple_element_t<Is, ::generic::many<Types...>>
        >&
      >(::std::declval<::generic::many<Types...>&>()).set(
        ::std::forward<A>(a)
      ),
      ...
    )
  )
)
{
  ::generic::many<Types...> m;

  (
    static_cast<
      ::generic::detail::many::many_holder<Is,
        ::std::tuple_element_t<Is, ::generic::many<Types...>>
      >&
    >(m).set(::std::forward<A>(a)),
    ...
  );

  return m;
}

}

}

template <typename ...Types, typename ...A>
auto create_many(A&& ...a) noexcept(
  noexcept(
    detail::many::create_many_impl<Types...>(
      ::std::index_sequence_for<Types...>{},
      ::std::forward<A>(a)...
    )
  )
)
{
  return detail::many::create_many_impl<Types...>(
    ::std::index_sequence_for<Types...>{},
    ::std::forward<A>(a)...
  );
}

}

namespace std
{

template <typename ...Types>
struct tuple_size<::generic::many<Types...>> :
  ::std::integral_constant<::std::size_t, sizeof...(Types)>
{
};

template <::std::size_t I, class... Types>
struct tuple_element<I, ::generic::many<Types...>>
{
  using type = tuple_element_t<I, ::std::tuple<Types...>>;
};

template<::std::size_t I, typename... Types>
auto& get(::generic::many<Types...>& m) noexcept
{
  return static_cast<
    ::generic::detail::many::many_holder<I,
      ::std::tuple_element_t<I, ::generic::many<Types...>>
    >&
  >(m).get();
}

template<size_t I, typename... Types>
auto& get(::generic::many<Types...> const& m) noexcept
{
  return static_cast<
    ::generic::detail::many::many_holder<I,
      ::std::tuple_element_t<I, ::generic::many<Types...>>
    >const&
  >(m).get();
}

template<::std::size_t I, typename... Types>
auto&& get(::generic::many<Types...>&& m) noexcept
{
  return static_cast<
    ::generic::detail::many::many_holder<I,
      ::std::tuple_element_t<I, ::generic::many<Types...>>
    >&&
  >(m).get();
}

}
<commit_msg>some fixes<commit_after>#include <cstddef>

#include <tuple>

#include <type_traits>

#include <utility>

namespace generic
{

namespace detail
{

namespace many
{

enum TupleValue { Scalar, Reference, Class };

template<std::size_t I,
  class T,
  TupleValue = ::std::is_class<T>{} ?
    TupleValue::Class :
    ::std::is_reference<T>{} ?
      TupleValue::Reference :
      TupleValue::Scalar
>
struct tuple_base {
  T value;

  tuple_base() = default;

  template <typename A>
  constexpr tuple_base(A&& value) : value{::std::forward<A>(value)}
  {
  }
};

template<std::size_t I, class T>
struct tuple_base<I, T, TupleValue::Reference>
{
  ::std::add_pointer_t<::std::remove_reference_t<T>> value;

  tuple_base() = delete;

  constexpr tuple_base(T value) : value{&value}
  {
  }

  tuple_base(tuple_base&&) = default;
  tuple_base(tuple_base const&) = default;
  tuple_base& operator=(tuple_base&&) = default;
  tuple_base& operator=(tuple_base const&) = default;
};

template<std::size_t I, class T>
struct tuple_base<I, T, TupleValue::Class> : T
{
  tuple_base() = default;

  template <typename A>
  constexpr tuple_base(A&& value) : T{::std::forward<A>(value)}
  {
  }
};

template <::std::size_t I, class T>
auto& get(tuple_base<I, T, TupleValue::Scalar>& obj)
{
  return obj.value;
}

template <::std::size_t I, class T>
auto& get(tuple_base<I, T, TupleValue::Scalar> const& obj)
{
  return obj.value;
}

template <::std::size_t I, class T>
auto& get(tuple_base<I, T, TupleValue::Reference> const& obj)
{
  return *obj.value;
}

template <::std::size_t I, class T>
auto& get(tuple_base<I, T, TupleValue::Class>& obj)
{
  return obj;
}

template <::std::size_t I, class T>
auto& get(tuple_base<I, T, TupleValue::Class> const& obj)
{
  return obj;
}

template <typename ...>
struct many_impl;

template <::std::size_t... Is, typename ...Types>
struct many_impl<::std::index_sequence<Is...>, Types...> :
  tuple_base<Is, Types>...
{
  many_impl() = default;
  ~many_impl() = default;
  many_impl(many_impl&&) = default;
  many_impl(many_impl const&) = default;
  many_impl& operator=(many_impl&&) = default;
  many_impl& operator=(many_impl const&) = default;

#if !__cpp_aggregate_bases
  template<typename ...U>
  constexpr many_impl(U&& ...u) :
    tuple_base<Is, Types>{::std::forward<U>(u)}...
  {
  }
#endif
};

}

}

template <typename ...Types>
struct many : detail::many::many_impl<
  ::std::make_index_sequence<sizeof...(Types)>,
  Types...
>
{
  many() = default;
  ~many() = default;
  many(many&&) = default;
  many(many const&) = default;
  many& operator=(many&&) = default;
  many& operator=(many const&) = default;

#if !__cpp_aggregate_bases
  template<class... U>
  constexpr many(U&& ...u) : many::many_impl{::std::forward<U>(u)...}
  {
  }
#endif
};

}

namespace std
{

template <typename ...Types>
struct tuple_size<::generic::many<Types...>> :
  ::std::integral_constant<size_t, sizeof...(Types)>
{
};

template <size_t I, class ...Types>
struct tuple_element<I, ::generic::many<Types...>>
{
  using type = tuple_element_t<I, tuple<Types...>>;
};

template <size_t I, typename ...Types>
auto& get(::generic::many<Types...>& m) noexcept
{
  return ::generic::detail::many::get(m);
}

template <size_t I, typename ...Types>
auto& get(::generic::many<Types...> const& m) noexcept
{
  return ::generic::detail::many::get<I>(m);
}

template<size_t I, typename ...Types>
auto&& get(::generic::many<Types...>&& m) noexcept
{
  // m is now a lvalue
  return ::generic::detail::many::get<I>(m);
}

}
<|endoftext|>


<commit_before>
/**
 * 所有 #include <外部文件> 的头文件 都必须保证 本文件被首先#include
 * 以下项目可以由本文件保证包含：
 * 	<cstdint>
 * 	<cstddef>
 * 	并保证 全局名称空间包含所有stdint。
 * 	CS_DEBUG = 1 时保证 #include <iostream>
 */

#pragma once

/**
 * 平台兼容原则：以不大的代价换取一定的兼容性；以首要目标平台0-overhead为前提。
 */

#ifndef NDEBUG
#	ifndef CS_DEBUG
#   	define CS_DEBUG		2
#	endif
#	ifndef CS_LOG_ON
#		define CS_LOG_ON	1
#	endif
#else
#	undef CS_DEBUG
#	define CS_DEBUG			0
#	undef CS_LOG_ON
#	define CS_LOG_ON		0
#endif

#if ! CS_DEBUG
#ifndef NDEBUG
#	define NDEBUG
#endif
#	define BOOST_DISABLE_ASSERTS
#endif

// Use wchar_t/wstring wcout/wcerr/wcin wfstream or not.
// It's just a standard, not make used in this file.
#ifndef CS_USE_WCS
#	define CS_USE_WCS	0
#endif
// Use wcout/wcerr/wcin or not. This will make use in this file.
#ifndef CS_USE_WIO
#	define CS_USE_WIO	0
#endif

#if defined(CS_USE_WCS) && CS_USE_WCS
#	define CS_STR_LITER(str_liter)		L##str_liter
#else
#	define CS_STR_LITER(str_liter)		#str_liter
#endif

#ifndef __GNUC__
#   define __attribute__(...)
#endif

#ifdef __cplusplus
// avoid from boost if possible.
#	if defined(__GNUC__)	\
		&& (!defined(__GXX_EXPERIMENTAL_CXX0X__) || !__GXX_EXPERIMENTAL_CXX0X__)
#		include <boost/cstdint.hpp>
#	else
#		include <cstdint>
#	endif
#	include <cstddef>
#else
#	include <stdint.h>
#	include <stddef.h>
#endif

#define CS_EXIT_STATUS_FAILED EXIT_FAILURE

#ifdef __cplusplus
#	define CS_PREF_STD(symbol)		::std::symbol
#else
#	define CS_PREF_STD(symbol)		symbol
#endif

#if CS_USE_WIO
#	define CS_STDIN		::std::wcin
#	define CS_STDOUT	::std::wcout
#	define CS_STDERR	::std::wcerr
#else
#	define CS_STDIN		::std::cin
#	define CS_STDOUT	::std::cout
#	define CS_STDERR	::std::cerr
#endif

#ifdef __linux__
#   define CS_OC_BLACK(...) "\033[32;30;5m" << __VA_ARGS__ << "\033[0m"
#   define CS_OC_BLUE(...)  "\033[32;34;5m" << __VA_ARGS__ << "\033[0m"
#   define CS_OC_RED(...)   "\033[32;31;5m" << __VA_ARGS__ << "\033[0m"
#   define CS_OC_GREEN(...) "\033[32;49;5m" << __VA_ARGS__ << "\033[0m"
#else
#   define CS_OC_BLACK(...) __VA_ARGS__
#   define CS_OC_BLUE(...)  __VA_ARGS__
#   define CS_OC_RED(...)   __VA_ARGS__
#   define CS_OC_GREEN(...) __VA_ARGS__
#endif

// line-seperator, should only use for IO..
#ifdef __linux__
#	define CS_LINESEP		'\n'
#	define CS_LINESEP_STR	"\n"
#else
#	ifdef(__WIN32__)
#		define CS_LINESEP		"\r\n"
#		define CS_LINESEP_STR	CS_LINESEP
#	else
#		define CS_LINESEP		::std::endl
#		define CS_LINESEP_STR	::std::endl()
#	endif
#endif

#if CS_DEBUG
#   define CS_DEBUG_OMIT(...)
#   include <iostream>
#   if CS_DEBUG > 1
#		if CS_USE_WCS
#			define CS_OUT(ostream, ...)											\
				do {															\
				ostream << __FILE__ << ":" << __LINE__							\
					<< ":" << __FUNCTION__ << "()" << ":\t"						\
					<< __VA_ARGS__												\
					<< ::std::endl;												\
				} while(false);
#		else
#       	define CS_OUT(ostream, ...)											\
				do {															\
				ostream << CS_OC_BLACK(__FILE__ << ":" << __LINE__)				\
					<< ":" << CS_OC_BLUE(__FUNCTION__ << "()") << ":\t"			\
					<< CS_OC_GREEN(__VA_ARGS__)									\
					<< ::std::endl;												\
				} while(false);
#		endif
#   else
#		define CS_OUT(ostream, ...)	do {ostream << __VA_ARGS__ << ::std::endl;} while(false);
#   endif
#else
#   define CS_DEBUG_OMIT(...)    __VA_ARGS__
#	define CS_OUT(ostream, ...)
#endif

#define CS_SAY(...)		CS_OUT(CS_STDOUT, __VA_ARGS__)

// NOTE: 要自行 #include <iostream>
#define CS_ECHO(...)	CS_STDOUT << __VA_ARGS__ << ::std::endl;
#define CS_ERR(...)		CS_STDERR << __VA_ARGS__ << ::std::endl;

// #define CS_DUMP(...)	CS_OUT(CS_STDOUT, GOL_OC_BLUE(#__VA_ARGS__) << ": " << GOL_OC_GREEN(__VA_ARGS__))

#define CS_DUMP(...)																	\
	CS_OUT(CS_STDOUT, CS_OC_RED(#__VA_ARGS__) << ":[" << CS_OC_GREEN(__VA_ARGS__) << "]")
#define CS_DUMP_N(...) 																	\
	CS_OUT(CS_STDOUT, CS_OC_RED(#__VA_ARGS__) << ":" << ::std::endl << CS_OC_GREEN(__VA_ARGS__))

// #define CS_ERR(msg)
//	CS_STDERR << msg << ::std::endl
// --- 要自行 #include <cstdlib>
#define CS_DIE(msg)																		\
	CS_ERR(msg); 																		\
    ::std::exit(CS_EXIT_STATUS_FAILED)

#ifndef CS_USED
#	ifdef __GNUC__
#		define CS_USED __attribute__((__used__))
#	else
#		define CS_USED
#	endif
#endif

#ifndef CS_ATTR_CONST
#	ifdef __GNUC__
#		define CS_ATTR_CONST __attribute__((const))
#	else
#		define CS_ATTR_CONST
#	endif
#endif

#ifndef CS_MUST_CHECK
#	ifdef __GNUC__
#		define CS_MUST_CHECK __attribute__((warn_unused_result))
#	else
#		define CS_MUST_CHECK
#	endif
#endif

#ifndef CS_DEPRECATED
#	ifdef __GNUC__
#		define CS_DEPRECATED __attribute__((deprecated))
#	else
#		define CS_DEPRECATED
#	endif
#endif

#ifndef CS_FORCE_INLINE
#   ifdef __GNUC__
#       define CS_FORCE_INLINE __attribute__((always_inline))
#   else
#       define CS_FORCE_INLINE inline
#   endif
#endif

#if !defined(CS_LIKELY) && !defined(CS_UNLIKELY)
#	ifdef __GNUC__
#		define CS_LIKELY(...)		__builtin_expect(!!(__VA_ARGS__), 1)
#		define CS_UNLIKELY(...)		__builtin_expect(!!(__VA_ARGS__), 0)
#		define CS_BLIKELY(...)		__builtin_expect((__VA_ARGS__), true)
#		define CS_BUNLIKELY(...)	__builtin_expect((__VA_ARGS__), false)
#	else
#		define CS_LIKELY(expr)		(expr)
#		define CS_UNLIKELY(expr)	(expr)
#		define CS_BLIKELY(expr)		(expr)
#		define CS_BUNLIKELY(expr)	(expr)
#	endif
#endif

#ifndef CS_PREFETCH
#	ifdef __GNUC__
#		define CS_PREFETCH(addr,rw,clean) __builtin_prefetch(addr,rw,clean)
#	else
#		define CS_PREFETCH(addr,rw,clean)
#	endif
#endif

#define CS_RETURN_IF_NORMAL(cond, ...)		\
if (cond)									\
{											\
	return __VA_ARGS__;						\
}
#define CS_RETURN_IF(cond, ...) CS_RETURN_IF_NORMAL(CS_BUNLIKELY(cond), __VA_ARGS__)

#define CS_ABORT_IF_NORMAL(cond)			\
if (cond)									\
{											\
	::std::exit(CS_EXIT_STATUS_FAILED);		\
}
#define CS_ABORT_IF(cond) CS_ABORT_IF_NORMAL(CS_BUNLIKELY(cond))

#define _CS_DIE_IF_NORMAL(cond, info, why)	\
if (cond)									\
{											\
	CS_DIE(__FILE__ << ":" << __LINE__ << "::" << __FUNCTION__ << "() die on " << info << ", results from {" << #why << "}.");  \
}
#define CS_DIE_IF_NORMAL(cond, info) CS_DIE_IF_NORMAL(cond, info, cond)
#define CS_DIE_IF(cond, info) _CS_DIE_IF_NORMAL(CS_BUNLIKELY(cond), info, cond)
<commit_msg>c++11 flag<commit_after>
/**
 * 所有 #include <外部文件> 的头文件 都必须保证 本文件被首先#include
 * 以下项目可以由本文件保证包含：
 * 	<cstdint>
 * 	<cstddef>
 * 	并保证 全局名称空间包含所有stdint。
 * 	CS_DEBUG = 1 时保证 #include <iostream>
 */

#pragma once

/**
 * 平台兼容原则：以不大的代价换取一定的兼容性；以首要目标平台0-overhead为前提。
 */

#ifndef NDEBUG
#	ifndef CS_DEBUG
#   	define CS_DEBUG		2
#	endif
#	ifndef CS_LOG_ON
#		define CS_LOG_ON	1
#	endif
#else
#	undef CS_DEBUG
#	define CS_DEBUG			0
#	undef CS_LOG_ON
#	define CS_LOG_ON		0
#endif

#if ! CS_DEBUG
#ifndef NDEBUG
#	define NDEBUG
#endif
#	define BOOST_DISABLE_ASSERTS
#endif

#if defined(__cplusplus) && __cplusplus >= 201103L
#   define CS_CPP11 1
#else
#   define CS_CPP11 0

// Use wchar_t/wstring wcout/wcerr/wcin wfstream or not.
// It's just a standard, not make used in this file.
#ifndef CS_USE_WCS
#	define CS_USE_WCS	0
#endif
// Use wcout/wcerr/wcin or not. This will make use in this file.
#ifndef CS_USE_WIO
#	define CS_USE_WIO	0
#endif

#if defined(CS_USE_WCS) && CS_USE_WCS
#	define CS_STR_LITER(str_liter)		L##str_liter
#else
#	define CS_STR_LITER(str_liter)		#str_liter
#endif

#ifndef __GNUC__
#   define __attribute__(...)
#endif

#ifdef __cplusplus
// avoid from boost if possible.
#	if defined(__GNUC__)	\
		&& (!defined(__GXX_EXPERIMENTAL_CXX0X__) || !__GXX_EXPERIMENTAL_CXX0X__)
#		include <boost/cstdint.hpp>
#	else
#		include <cstdint>
#	endif
#	include <cstddef>
#else
#	include <stdint.h>
#	include <stddef.h>
#endif

#define CS_EXIT_STATUS_FAILED EXIT_FAILURE

#ifdef __cplusplus
#	define CS_PREF_STD(symbol)		::std::symbol
#else
#	define CS_PREF_STD(symbol)		symbol
#endif

#if CS_USE_WIO
#	define CS_STDIN		::std::wcin
#	define CS_STDOUT	::std::wcout
#	define CS_STDERR	::std::wcerr
#else
#	define CS_STDIN		::std::cin
#	define CS_STDOUT	::std::cout
#	define CS_STDERR	::std::cerr
#endif

#ifdef __linux__
#   define CS_OC_BLACK(...) "\033[32;30;5m" << __VA_ARGS__ << "\033[0m"
#   define CS_OC_BLUE(...)  "\033[32;34;5m" << __VA_ARGS__ << "\033[0m"
#   define CS_OC_RED(...)   "\033[32;31;5m" << __VA_ARGS__ << "\033[0m"
#   define CS_OC_GREEN(...) "\033[32;49;5m" << __VA_ARGS__ << "\033[0m"
#else
#   define CS_OC_BLACK(...) __VA_ARGS__
#   define CS_OC_BLUE(...)  __VA_ARGS__
#   define CS_OC_RED(...)   __VA_ARGS__
#   define CS_OC_GREEN(...) __VA_ARGS__
#endif

// line-seperator, should only use for IO..
#ifdef __linux__
#	define CS_LINESEP		'\n'
#	define CS_LINESEP_STR	"\n"
#else
#	ifdef(__WIN32__)
#		define CS_LINESEP		"\r\n"
#		define CS_LINESEP_STR	CS_LINESEP
#	else
#		define CS_LINESEP		::std::endl
#		define CS_LINESEP_STR	::std::endl()
#	endif
#endif

#if CS_DEBUG
#   define CS_DEBUG_OMIT(...)
#   include <iostream>
#   if CS_DEBUG > 1
#		if CS_USE_WCS
#			define CS_OUT(ostream, ...)											\
				do {															\
				ostream << __FILE__ << ":" << __LINE__							\
					<< ":" << __FUNCTION__ << "()" << ":\t"						\
					<< __VA_ARGS__												\
					<< ::std::endl;												\
				} while(false);
#		else
#       	define CS_OUT(ostream, ...)											\
				do {															\
				ostream << CS_OC_BLACK(__FILE__ << ":" << __LINE__)				\
					<< ":" << CS_OC_BLUE(__FUNCTION__ << "()") << ":\t"			\
					<< CS_OC_GREEN(__VA_ARGS__)									\
					<< ::std::endl;												\
				} while(false);
#		endif
#   else
#		define CS_OUT(ostream, ...)	do {ostream << __VA_ARGS__ << ::std::endl;} while(false);
#   endif
#else
#   define CS_DEBUG_OMIT(...)    __VA_ARGS__
#	define CS_OUT(ostream, ...)
#endif

#define CS_SAY(...)		CS_OUT(CS_STDOUT, __VA_ARGS__)

// NOTE: 要自行 #include <iostream>
#define CS_ECHO(...)	CS_STDOUT << __VA_ARGS__ << ::std::endl;
#define CS_ERR(...)		CS_STDERR << __VA_ARGS__ << ::std::endl;

// #define CS_DUMP(...)	CS_OUT(CS_STDOUT, GOL_OC_BLUE(#__VA_ARGS__) << ": " << GOL_OC_GREEN(__VA_ARGS__))

#define CS_DUMP(...)																	\
	CS_OUT(CS_STDOUT, CS_OC_RED(#__VA_ARGS__) << ":[" << CS_OC_GREEN(__VA_ARGS__) << "]")
#define CS_DUMP_N(...) 																	\
	CS_OUT(CS_STDOUT, CS_OC_RED(#__VA_ARGS__) << ":" << ::std::endl << CS_OC_GREEN(__VA_ARGS__))

// #define CS_ERR(msg)
//	CS_STDERR << msg << ::std::endl
// --- 要自行 #include <cstdlib>
#define CS_DIE(msg)																		\
	CS_ERR(msg); 																		\
    ::std::exit(CS_EXIT_STATUS_FAILED)

#ifndef CS_USED
#	ifdef __GNUC__
#		define CS_USED __attribute__((__used__))
#	else
#		define CS_USED
#	endif
#endif

#ifndef CS_ATTR_CONST
#	ifdef __GNUC__
#		define CS_ATTR_CONST __attribute__((const))
#	else
#		define CS_ATTR_CONST
#	endif
#endif

#ifndef CS_MUST_CHECK
#	ifdef __GNUC__
#		define CS_MUST_CHECK __attribute__((warn_unused_result))
#	else
#		define CS_MUST_CHECK
#	endif
#endif

#ifndef CS_DEPRECATED
#	ifdef __GNUC__
#		define CS_DEPRECATED __attribute__((deprecated))
#	else
#		define CS_DEPRECATED
#	endif
#endif

#ifndef CS_FORCE_INLINE
#   ifdef __GNUC__
#       define CS_FORCE_INLINE __attribute__((always_inline))
#   else
#       define CS_FORCE_INLINE inline
#   endif
#endif

#if !defined(CS_LIKELY) && !defined(CS_UNLIKELY)
#	ifdef __GNUC__
#		define CS_LIKELY(...)		__builtin_expect(!!(__VA_ARGS__), 1)
#		define CS_UNLIKELY(...)		__builtin_expect(!!(__VA_ARGS__), 0)
#		define CS_BLIKELY(...)		__builtin_expect((__VA_ARGS__), true)
#		define CS_BUNLIKELY(...)	__builtin_expect((__VA_ARGS__), false)
#	else
#		define CS_LIKELY(expr)		(expr)
#		define CS_UNLIKELY(expr)	(expr)
#		define CS_BLIKELY(expr)		(expr)
#		define CS_BUNLIKELY(expr)	(expr)
#	endif
#endif

#ifndef CS_PREFETCH
#	ifdef __GNUC__
#		define CS_PREFETCH(addr,rw,clean) __builtin_prefetch(addr,rw,clean)
#	else
#		define CS_PREFETCH(addr,rw,clean)
#	endif
#endif

#define CS_RETURN_IF_NORMAL(cond, ...)		\
if (cond)									\
{											\
	return __VA_ARGS__;						\
}
#define CS_RETURN_IF(cond, ...) CS_RETURN_IF_NORMAL(CS_BUNLIKELY(cond), __VA_ARGS__)

#define CS_ABORT_IF_NORMAL(cond)			\
if (cond)									\
{											\
	::std::exit(CS_EXIT_STATUS_FAILED);		\
}
#define CS_ABORT_IF(cond) CS_ABORT_IF_NORMAL(CS_BUNLIKELY(cond))

#define _CS_DIE_IF_NORMAL(cond, info, why)	\
if (cond)									\
{											\
	CS_DIE(__FILE__ << ":" << __LINE__ << "::" << __FUNCTION__ << "() die on " << info << ", results from {" << #why << "}.");  \
}
#define CS_DIE_IF_NORMAL(cond, info) CS_DIE_IF_NORMAL(cond, info, cond)
#define CS_DIE_IF(cond, info) _CS_DIE_IF_NORMAL(CS_BUNLIKELY(cond), info, cond)
<|endoftext|>


<commit_before><commit_msg>add an include<commit_after><|endoftext|>


<commit_before><commit_msg>修正ccontrol和基于其的控件无法保存enabled属性的bug<commit_after><|endoftext|>


<commit_before><commit_msg>Thirdy party library list in the about window now uses bullets.<commit_after><|endoftext|>