<commit_before>22cedb26-ad58-11e7-b864-ac87a332f658<commit_msg>add file<commit_after>2337a907-ad58-11e7-bc13-ac87a332f658<|endoftext|>


<commit_before>09a83987-2748-11e6-a21f-e0f84713e7b8<commit_msg>Now it no longer crashes if X<commit_after>09c903c7-2748-11e6-8a4e-e0f84713e7b8<|endoftext|>


<commit_before>#include <vector>
#include <string>
#include <iostream>
#include <fstream>
#include "sudoku.h"

template <typename T>
struct Option
{
    int const key;
    std::string const label;
    T const value;
};

template <typename T>
T get_selection(std::vector<Option<T> > v)
{
    for ( ; ; )
    {
        for (auto it = v.begin(); it != v.end(); ++it)
        {
            std::cout << it->key << ": " << it->label << std::endl;
        }
        int selected;
        std::cin >> selected;
        for (auto it = v.begin(); it != v.end(); ++it)
        {
            if (it->key == selected)
            {
                return it->value;
            }
        }
        std::cout << std::endl;
        std::cout << "Invalid option: " << selected << std::endl;
        std::cout << std::endl;
    }
}

bool handler_write(Sudoku& sudoku_instance);
bool handler_erase(Sudoku& sudoku_instance);
bool handler_give_hint(Sudoku& sudoku_instance);
bool handler_check_complete(Sudoku& sudoku_instance);
bool handler_show_solution(Sudoku& sudoku_instance);
bool handler_quit(Sudoku& sudoku_instance);

int main()
{
    std::cout << (
        "+------------------+\n"
        "| Sudoku Game Menu |\n"
        "+------------------+\n"
    ) << std::endl;

    std::vector<Option<bool> > const intro_options = {
        {1, "Game Start", true},
        {0, "Quit", false},
    };

    std::vector<Option<bool (*)(Sudoku&)> > const loop_options = {
        {1, "Write", handler_write},
        {2, "Erase", handler_erase},
        {3, "Hint", handler_give_hint},
        {4, "Complete?", handler_check_complete},
        {5, "Solution", handler_show_solution},
        {0, "Quit", handler_quit},
    };

    bool game_start = get_selection(intro_options);

    if (game_start)
    {
        std::ifstream sudoku_file("Text.txt");
        Sudoku sudoku_instance = sudoku_file;
        sudoku_file.close();

        bool continue_loop = true;
        while (continue_loop)
        {
            std::cout << std::endl;
            sudoku_instance.show_game();
            auto handler = get_selection(loop_options);
            std::cout << std::endl;
            continue_loop = handler(sudoku_instance);
        }
    }

    return 0;
}

bool handler_write(Sudoku& sudoku_instance)
{
    int row;
    int col;
    int value;

    std::cout << "Row(0-based): ";
    std::cin >> row;

    std::cout << "Column(0-based): ";
    std::cin >> col;

    std::cout << "Value: ";
    std::cin >> value;

    sudoku_instance.write_game_board(row, col, value);

    return true;
}

bool handler_erase(Sudoku& sudoku_instance)
{
    int row;
    int col;

    std::cout << "Row(0-based): ";
    std::cin >> row;

    std::cout << "Column(0-based): ";
    std::cin >> col;

    sudoku_instance.erase_game_board(row, col);

    return true;
}

bool handler_give_hint(Sudoku& sudoku_instance)
{
    sudoku_instance.hint();
    return true;
}

bool handler_check_complete(Sudoku& sudoku_instance)
{
    std::cout << (
        sudoku_instance.is_complete()
        ? "Yes."
        : "No."
    ) << std::endl;

    return true;
}

bool handler_show_solution(Sudoku& sudoku_instance)
{
    sudoku_instance.show_answer();
    std::cout << "BYE BYE" << std::endl;

    return false;
}

bool handler_quit(Sudoku&)
{
    return false;
}
<commit_msg>Improve `get_selection`<commit_after>#include <vector>
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include "sudoku.h"

template <typename T>
struct Option
{
    int const key;
    std::string const label;
    T const value;
};

template <typename T>
T get_selection(std::vector<Option<T> > v)
{
    for ( ; ; )
    {
        for (auto it = v.begin(); it != v.end(); ++it)
        {
            std::cout << it->key << ": " << it->label << std::endl;
        }

        std::string line;
        std::getline(std::cin, line);

        int selected;
        std::istringstream line_stream(line);

        line_stream >> selected;

        if (!line_stream.fail())
        {
            line_stream >> std::ws;
            if (line_stream.eof())
            {
                for (auto it = v.begin(); it != v.end(); ++it)
                {
                    if (it->key == selected)
                    {
                        return it->value;
                    }
                }
            }
        }

        std::cout << std::endl;
        std::cout << "Invalid option: \"" << line << "\"" << std::endl;
        std::cout << std::endl;
    }
}

bool handler_write(Sudoku& sudoku_instance);
bool handler_erase(Sudoku& sudoku_instance);
bool handler_give_hint(Sudoku& sudoku_instance);
bool handler_check_complete(Sudoku& sudoku_instance);
bool handler_show_solution(Sudoku& sudoku_instance);
bool handler_quit(Sudoku& sudoku_instance);

int main()
{
    std::cout << (
        "+------------------+\n"
        "| Sudoku Game Menu |\n"
        "+------------------+\n"
    ) << std::endl;

    std::vector<Option<bool> > const intro_options = {
        {1, "Game Start", true},
        {0, "Quit", false},
    };

    std::vector<Option<bool (*)(Sudoku&)> > const loop_options = {
        {1, "Write", handler_write},
        {2, "Erase", handler_erase},
        {3, "Hint", handler_give_hint},
        {4, "Complete?", handler_check_complete},
        {5, "Solution", handler_show_solution},
        {0, "Quit", handler_quit},
    };

    bool game_start = get_selection(intro_options);

    if (game_start)
    {
        std::ifstream sudoku_file("Text.txt");
        Sudoku sudoku_instance = sudoku_file;
        sudoku_file.close();

        bool continue_loop = true;
        while (continue_loop)
        {
            std::cout << std::endl;
            sudoku_instance.show_game();
            auto handler = get_selection(loop_options);
            std::cout << std::endl;
            continue_loop = handler(sudoku_instance);
        }
    }

    return 0;
}

bool handler_write(Sudoku& sudoku_instance)
{
    int row;
    int col;
    int value;

    std::cout << "Row(0-based): ";
    std::cin >> row;

    std::cout << "Column(0-based): ";
    std::cin >> col;

    std::cout << "Value: ";
    std::cin >> value;

    sudoku_instance.write_game_board(row, col, value);

    return true;
}

bool handler_erase(Sudoku& sudoku_instance)
{
    int row;
    int col;

    std::cout << "Row(0-based): ";
    std::cin >> row;

    std::cout << "Column(0-based): ";
    std::cin >> col;

    sudoku_instance.erase_game_board(row, col);

    return true;
}

bool handler_give_hint(Sudoku& sudoku_instance)
{
    sudoku_instance.hint();
    return true;
}

bool handler_check_complete(Sudoku& sudoku_instance)
{
    std::cout << (
        sudoku_instance.is_complete()
        ? "Yes."
        : "No."
    ) << std::endl;

    return true;
}

bool handler_show_solution(Sudoku& sudoku_instance)
{
    sudoku_instance.show_answer();
    std::cout << "BYE BYE" << std::endl;

    return false;
}

bool handler_quit(Sudoku&)
{
    return false;
}
<|endoftext|>


<commit_before>73d1cebd-4b02-11e5-b082-28cfe9171a43<commit_msg>I am finally done<commit_after>73de372e-4b02-11e5-bf15-28cfe9171a43<|endoftext|>


<commit_before>c59f17a8-2747-11e6-a19a-e0f84713e7b8<commit_msg>Adding stuff<commit_after>c5b611a8-2747-11e6-a1d9-e0f84713e7b8<|endoftext|>


<commit_before>#include <iostream>
#include <ctime>
#include <fstream>
#include <chrono>
#include <thread>

std::string getCurrentTimeStamp(){
  std::chrono::time_point<std::chrono::system_clock> theTime;
  theTime = std::chrono::system_clock::now();
  std::time_t the_time = std::chrono::system_clock::to_time_t(theTime);

  return std::ctime(&the_time);
}

int main(){

  std::string timeStamp = getCurrentTimeStamp();
  timeStamp.erase(timeStamp.size() - 2);
  std::string fileNameA = timeStamp + "a.log";
  std::string fileNameB = timeStamp + "b.log";

  std::cout << "Logging to files: " << fileNameA << " and " << fileNameB << std::endl;

  std::ofstream fileA;
  std::ofstream fileB;

  int index = 0;
  while(true){
    //If index is even write to file A else write to file B
    if(index % 2 == 0){
      fileA.open(fileNameA);
      fileA << getCurrentTimeStamp();
      fileA.close();
    }
    else{
      fileB.open(fileNameB);
      fileB << getCurrentTimeStamp();
      fileB.close();
    }

    std::this_thread::sleep_for(std::chrono::milliseconds(1000));

    ++index;
  }
  return 0;
}
<commit_msg>Added Unix Timestamp to print to file for ease of calculation in the future. Also added the start time as a unix timestamp the the top of the file for the same reason as before<commit_after>#include <iostream>
#include <ctime>
#include <fstream>
#include <chrono>
#include <thread>

std::string getCurrentTimeStamp(){
  std::chrono::time_point<std::chrono::system_clock> theTime;
  theTime = std::chrono::system_clock::now();
  std::time_t the_time = std::chrono::system_clock::to_time_t(theTime);

  return std::ctime(&the_time);
}

unsigned int unixTimestamp(){
  return (unsigned int)time(NULL);
}

int main(){

  std::string timeStamp = getCurrentTimeStamp();
  unsigned int startUnixTimestamp = unixTimestamp();
  timeStamp.erase(timeStamp.size() - 2);
  std::string fileNameA = timeStamp + "a.log";
  std::string fileNameB = timeStamp + "b.log";

  std::cout << "Logging to files: " << fileNameA << " and " << fileNameB << std::endl;

  std::ofstream fileA;
  std::ofstream fileB;

  int index = 0;
  while(true){
    //If index is even write to file A else write to file B
    if(index % 2 == 0){
      fileA.open(fileNameA);
      fileA << startUnixTimestamp << std::endl;
      fileA << unixTimestamp();
      fileA.close();
    }
    else{
      fileB.open(fileNameB);
      fileB << startUnixTimestamp << std::endl;
      fileB << unixTimestamp();
      fileB.close();
    }

    ++index;
  }
  return 0;
}
<|endoftext|>


<commit_before>e24d437d-2747-11e6-b33e-e0f84713e7b8<commit_msg>Added that feature we discussed on... Was it monday?<commit_after>e25f4eab-2747-11e6-ba9a-e0f84713e7b8<|endoftext|>


<commit_before>// small-radiosity by Magnus Burenius
#include <algorithm>
#include <functional>
#include <numeric>
#include <random>
#include <valarray>
#include <fstream>
#include <iostream>
#include <sstream>
using namespace std;
// Fast settings:
const auto S            = 20;		    // Number of patches per rect is S*S.			// SCENE
const auto PHOTONS      = 10000;	    // 300000;//30000;	// Number of particles used for each color component	// COMPUTE RADIOSITY
const auto WIDTH        = 250.0;		// Width of image		// RENDERING
const auto HEIGHT       = 250.0;		// Height of image		// RENDERING
const auto DRAW_SAMPLES = 20;		    // Number of gaussian samples used for drawing.	// RENDERING
const auto DRAW_STD     = 0.5 / S;	    // STD of gaussian filter						// RENDERING (this could be a hidden parameter)
// Slow settings:
//const auto S				= 64;//30;	// Number of patches per rect is S*S.
//const auto WIDTH			= 4096.0;	// Width of image
//const auto HEIGHT			= 4096.0;	// Height of image
//const auto PHOTONS		= 100000000;// Number of particles used for each color component
//const auto DRAW_SAMPLES	= 100;		// Number of gaussian samples used for drawing.
//const auto DRAW_STD		= 0.5/S;	// STD of gaussian filter
auto g = bind(      normal_distribution<double>(), mt19937());
auto u = bind(uniform_real_distribution<double>(), mt19937());
// Definition of vector type:
using vec = valarray<double>;
double dot(const vec& a, const vec& b) { return (a * b).sum(); }
vec normalized(const vec& v) { return v / sqrt( dot(v,v) ); }
// Used to describe the geometrical properties of a rectangular surface:
struct Rect
{
    vec p;		// A corner in the rectangle.
    vec x;		// Vector going from p to the right nearby corner.
    vec y;		// Vector going from p to the top nearby corner.
    vec n;		// Normal of the plane. The cross product of x and y.
    vec xn;     // normalized(x)
    vec yn;		// normalized(y)
    vec nn;		// normalized(n)
    double a;	// Area of rectangle. Given by length of x cross y.
    Rect(vec P, vec X, vec Y) : p{P}, x{X}, y{Y},
        n{vec{x[1]*y[2]-x[2]*y[1], x[2]*y[0]-x[0]*y[2], x[0]*y[1]-x[1]*y[0]}},
        xn{normalized(x)}, yn{normalized(y)}, nn{normalized(n)}, a{sqrt(dot(n, n))} {}
};
const auto L = 555.0; // Length of Cornell Box side.
struct Scene // Define the Cornell box:
{
    static const auto NUM_RECTANGLES = 15;
    static const auto NUM_PATCHES = NUM_RECTANGLES * S * S;

    Rect rectangles[NUM_RECTANGLES] = {
        Rect{ vec{ 0, 0, 0 }, vec{  0, 0, L }, vec{ L, 0, 0 } },    // Floor
        Rect{ vec{ 0, L, 0 }, vec{  L, 0, 0 }, vec{ 0, 0, L } },    // Ceiling
        Rect{ vec{ L, 0, L }, vec{ -L, 0, 0 }, vec{ 0, L, 0 } },	    // Back wall
        Rect{ vec{ 0, 0, 0 }, vec{  0, L, 0 }, vec{ 0, 0, L } },    // Right wall
        Rect{ vec{ L, 0, 0 }, vec{  0, 0, L }, vec{ 0, L, 0 } },    // Left wall
        // Tall block:
        Rect{ vec{ 314, 330, 454 }, vec{  158, 0,  -49 }, vec{ -49,   0, -158 } },
        Rect{ vec{ 314,   0, 454 }, vec{  158, 0,  -49 }, vec{   0, 330,    0 } },
        Rect{ vec{ 423,   0, 247 }, vec{ -158, 0,   49 }, vec{   0, 330,    0 } },
        Rect{ vec{ 265,   0, 296 }, vec{   49, 0,  158 }, vec{   0, 330,    0 } },
        Rect{ vec{ 472,   0, 405 }, vec{  -49, 0, -158 }, vec{   0, 330,    0 } },
        // Short block:
        Rect{ vec{  81, 165, 223 }, vec{  158, 0,   49 }, vec{  49,   0, -158 } },
        Rect{ vec{  81,   0, 223 }, vec{  158, 0,   49 }, vec{   0, 165,    0 } },
        Rect{ vec{ 288,   0, 114 }, vec{ -158, 0,  -49 }, vec{   0, 165,    0 } },
        Rect{ vec{ 130,   0,  65 }, vec{  -49, 0,  158 }, vec{   0, 165,    0 } },
        Rect{ vec{ 239,   0, 272 }, vec{   49, 0, -158 }, vec{   0, 165,    0 } } };

    // The color quantities for each patch:
    // TODO: rename?
    valarray<vec> R{ .75 * vec{ 1, 1, 1 }, NUM_PATCHES }; // Reflectance for each patch
    valarray<vec> B{ vec{ 0, 0, 0 }, NUM_PATCHES };       // Radiosity for each patch

    vec lightPos   =    L * vec{ .5, .8, .5 };
    vec lightPower = 1e11 * vec{  1,  1,  1 };

    Scene()
    {
        fill(&R[3 * S * S], &R[4 * S * S], vec{ .25, .75, .25 }); // Color right wall
        fill(&R[4 * S * S], &R[5 * S * S], vec{ .75, .25, .25 }); // Color left wall
    }
};
// Information about an intersection between a ray and a Rect:
struct Intersection
{
    double distance;
    double u; // 0-1 coordinate of the intersection within the rectangle.
    double v; // 0-1 coordinate of the intersection within the rectangle.
    vec position;
    int rectangleIndex;
    Intersection() : distance{numeric_limits<double>::max()} {}
    operator bool() const { return distance < numeric_limits<double>::max(); }
};
// Compute the first intersection along a ray:
Intersection ComputeIntersection(const Scene& scene, vec start, vec dir)
{
    const auto e = 0.0001;
    start += e * dir;
    dir = normalized(dir);
    auto firstIntersection = Intersection();
    for (auto r = 0; r < Scene::NUM_RECTANGLES; ++r)
    {
        const auto& rectangle = scene.rectangles[r];
        auto i = Intersection();
        i.distance = dot(rectangle.p - start, rectangle.n) / dot(dir, rectangle.n);
        if (i.distance < 0 || firstIntersection.distance < i.distance)
            continue;
        i.rectangleIndex = r;
        i.position = start + i.distance * dir;
        const auto p = i.position - rectangle.p;
        i.u = dot(p, rectangle.x) / dot(rectangle.x, rectangle.x);
        i.v = dot(p, rectangle.y) / dot(rectangle.y, rectangle.y);
        if (0 - e < i.u && i.u < 1 + e && 0 - e < i.v && i.v < 1 + e)
            firstIntersection = i;
    }
    return firstIntersection;
}
// Get patch index of an intersection, with an optional u and v offset:
int Patch(const Intersection& i, double du = 0, double dv = 0)
{
    const auto ui = max(min(int((i.u + du) * S), S - 1), 0);
    const auto vi = max(min(int((i.v + dv) * S), S - 1), 0);
    return ui + vi * S + i.rectangleIndex * S * S;
}
// Get an "interpolated" value for the radiosity using gaussian samples:
vec Radiosity(const Scene& scene, const Intersection& i)
{
    auto r = vec{0, 0, 0};
    if (!i)
        return r;
    //return B[Patch(i)]; // No interpolation
    // Gaussian filter:
    for (auto s = 0; s < DRAW_SAMPLES; ++s)
        r += scene.B[Patch(i, DRAW_STD * g(), DRAW_STD * g())];
    return r / double(DRAW_SAMPLES);
}
// Third component is assumed to be in the direction of the normal:
vec RandomDiffuseReflectionDir()
{
    const auto a = u();
    return sqrt(a) * normalized(vec{g(), g(), 0}) + sqrt(1 - a) * vec{0, 0, 1};
}
// Compute the radiosity of the scene by bouncing around photons.
void ComputeRadiosity(Scene& scene)
{
    for (auto c = 0; c < 3; ++c)
    {
        for (auto p = 0; p < PHOTONS; ++p)
        {
            auto ray_dir = normalized(vec{g(), g(), g()});
            auto ray_start = scene.lightPos;
            auto i = ComputeIntersection(scene, ray_start, ray_dir);
            while (i && u() < scene.R[Patch(i)][c])
            {
                const auto& r = scene.rectangles[i.rectangleIndex];
                scene.B[Patch(i)][c] += scene.lightPower[c] / PHOTONS * S * S / r.a;
                const auto d = RandomDiffuseReflectionDir();
                ray_dir = r.xn * d[0] + r.yn * d[1] + r.nn * d[2];
                ray_start = i.position;
                i = ComputeIntersection(scene, ray_start, ray_dir);
            }
        }
    }
}
// Do gamma correction and truncation of color:
int ScreenColor(double c)
{
    return min(int(pow(c, 1 / 2.2)), 255);
}
// Render the image to a ppm-file:
void Render(const Scene& scene, vec cameraPos, double focalLength, const char* filename)
{
    ofstream file(filename);
    file << "P3\n" << int(WIDTH) << " " << int(HEIGHT) << "\n255\n";
    for (auto y = 0.0; y < HEIGHT; ++y)
    {
        for (auto x = 0.0; x < WIDTH; ++x)
        {
            const auto pixelDir = vec{WIDTH / 2 - x, HEIGHT / 2 - y, focalLength};
            const auto color = Radiosity(scene, ComputeIntersection(scene, cameraPos, pixelDir));
            for (auto c = 0; c < 3; ++c)
                file << ScreenColor(color[c]) << " ";
        }
    }
}
int RectToPatch(int r, int i, int j)
{
    return i + j * S + r * S * S;
}
void SaveLightmaps(const Scene& scene, const char* fileNameStart)
{
    for (auto r = 0; r < Scene::NUM_RECTANGLES; ++r)
    {
        auto ss = stringstream();
        ss << fileNameStart << r << ".ppm";
        auto file = ofstream(ss.str());
        file << "P3" << endl << S << " " << S << endl << 255 << endl;
        for (auto y = 0; y < S; ++y)
        {
            for (auto x = 0; x < S; ++x)
            {
                const auto color = scene.B[RectToPatch(r, x, y)];
                for (auto c = 0; c < 3; ++c)
                    file << ScreenColor(color[c]) << " ";
            }
        }
    }
}
// Here we go:
int main()
{
    auto scene = Scene();
    cout << "Computing radiosity." << endl;
    ComputeRadiosity(scene);
    cout << "Saving lightmaps to files." << endl;
    SaveLightmaps(scene, "lightmap");
    cout << "Rendering image to file." << endl;
    const auto focalLength = 1.4 * WIDTH;
    const auto cameraPos = L * vec{.5, .5, -1.4};
    Render(scene, cameraPos, focalLength, "image.ppm");
}

//void LoadLightmaps()
//{
//	for(size_t q=0; q<Q;++q)
//	{
//		stringstream ss;
//		ss << "lightmaps30/lightmap" << q << ".ppm";
//		ifstream f( ss.str() );
//		string temp;
//		size_t w,h,color;
//		f >> temp >> w >> h >> color;
//		for( size_t y=0; y<S; ++y )
//		{
//			for( size_t x=0; x<S; ++x )
//			{
//				vec color = vec{0,0,0);
//				for( int c=0; c<3; ++c )
//					f >> color[c];
//				B[QuadToPatch(q,x,y)] = 700.*color; // N.B. truncated over 255
//			}
//		}
//	}
//}

//void LoadLightmaps()
//{
//	for(size_t q=0; q<Q;++q)
//	{
//		stringstream ss;
//		ss << "lightmap" << q << ".ppm";
//		ifstream f( ss.str() );
//		string temp;
//		size_t w,h,color;
//		f >> temp >> w >> h >> color;
//		for( size_t y=0; y<S; ++y )
//		{
//			for( size_t x=0; x<S; ++x )
//			{
//				vec color = vec{0,0,0);
//				for( int c=0; c<3; ++c )
//					f >> color[c];
//				radiosity[QuadToPatch(q,x,y)] = color; // N.B. truncated over 255
//			}
//		}
//	}
//}
<commit_msg>Refactor: add helper functions and constants<commit_after>// small-radiosity by Magnus Burenius
#include <algorithm>
#include <functional>
#include <numeric>
#include <random>
#include <valarray>
#include <fstream>
#include <iostream>
#include <sstream>
using namespace std;
// Fast settings:
const auto S            = 20;		    // Number of patches per rect is S*S.			// SCENE
const auto PHOTONS      = 10000;	    // 300000;//30000;	// Number of particles used for each color component	// COMPUTE RADIOSITY
const auto DRAW_SAMPLES = 20;		    // Number of gaussian samples used for drawing.	// RENDERING
const auto WIDTH        = 250.0;		// Width of image		// RENDERING
const auto HEIGHT       = 250.0;		// Height of image		// RENDERING
// Slow settings:
//const auto S            = 64;//30;    // Number of patches per rect is S*S.
//const auto PHOTONS      = 100000000;  // Number of particles used for each color component
//const auto DRAW_SAMPLES = 100;        // Number of gaussian samples used for drawing.
//const auto WIDTH        = 4096.0;     // Width of image
//const auto HEIGHT       = 4096.0;     // Height of image
auto g = bind(      normal_distribution<double>(), mt19937());
auto u = bind(uniform_real_distribution<double>(), mt19937());
// Definition of vector type:
using vec = valarray<double>;
double dot(vec a, vec b)
{
    return (a * b).sum();
}
vec normalized(vec v)
{
    return v / sqrt(dot(v, v));
}
vec crossProduct(vec x, vec y)
{
    return vec{x[1]*y[2]-x[2]*y[1], x[2]*y[0]-x[0]*y[2], x[0]*y[1]-x[1]*y[0]};
}
// Used to describe the geometrical properties of a rectangular surface:
struct Rect
{
    vec p;      // A corner in the rectangle.
    vec x;      // Vector going from p to the right nearby corner.
    vec y;      // Vector going from p to the top nearby corner.
    vec n;      // Normal of the plane. The cross product of x and y.
    vec xn;     // normalized(x).
    vec yn;     // normalized(y).
    vec nn;     // normalized(n).
    double a;   // Area of rectangle. Given by length of x cross y.
    Rect(vec P, vec X, vec Y) : p{P}, x{X}, y{Y}, n{crossProduct(x, y)},
        xn{normalized(x)}, yn{normalized(y)}, nn{normalized(n)}, a{sqrt(dot(n, n))} {}
};
const auto L = 555.0; // Length of Cornell Box side.
struct Scene // Define the Cornell box:
{
    static const auto NUM_RECTANGLES = 15;
    static const auto NUM_PATCHES = NUM_RECTANGLES * S * S;

    Rect rectangles[NUM_RECTANGLES] = {
        Rect{ vec{ 0, 0, 0 }, vec{  0, 0, L }, vec{ L, 0, 0 } },    // Floor
        Rect{ vec{ 0, L, 0 }, vec{  L, 0, 0 }, vec{ 0, 0, L } },    // Ceiling
        Rect{ vec{ L, 0, L }, vec{ -L, 0, 0 }, vec{ 0, L, 0 } },	    // Back wall
        Rect{ vec{ 0, 0, 0 }, vec{  0, L, 0 }, vec{ 0, 0, L } },    // Right wall
        Rect{ vec{ L, 0, 0 }, vec{  0, 0, L }, vec{ 0, L, 0 } },    // Left wall
        // Tall block:
        Rect{ vec{ 314, 330, 454 }, vec{  158, 0,  -49 }, vec{ -49,   0, -158 } },
        Rect{ vec{ 314,   0, 454 }, vec{  158, 0,  -49 }, vec{   0, 330,    0 } },
        Rect{ vec{ 423,   0, 247 }, vec{ -158, 0,   49 }, vec{   0, 330,    0 } },
        Rect{ vec{ 265,   0, 296 }, vec{   49, 0,  158 }, vec{   0, 330,    0 } },
        Rect{ vec{ 472,   0, 405 }, vec{  -49, 0, -158 }, vec{   0, 330,    0 } },
        // Short block:
        Rect{ vec{  81, 165, 223 }, vec{  158, 0,   49 }, vec{  49,   0, -158 } },
        Rect{ vec{  81,   0, 223 }, vec{  158, 0,   49 }, vec{   0, 165,    0 } },
        Rect{ vec{ 288,   0, 114 }, vec{ -158, 0,  -49 }, vec{   0, 165,    0 } },
        Rect{ vec{ 130,   0,  65 }, vec{  -49, 0,  158 }, vec{   0, 165,    0 } },
        Rect{ vec{ 239,   0, 272 }, vec{   49, 0, -158 }, vec{   0, 165,    0 } } };

    // The color quantities for each patch:
    // TODO: rename?
    valarray<vec> R{ .75 * vec{ 1, 1, 1 }, NUM_PATCHES }; // Reflectance for each patch
    valarray<vec> B{       vec{ 0, 0, 0 }, NUM_PATCHES }; // Radiosity for each patch

    vec lightPos   =    L * vec{ .5, .8, .5 };
    vec lightPower = 1e11 * vec{  1,  1,  1 };

    Scene()
    {
        fill(&R[3 * S * S], &R[4 * S * S], vec{ .25, .75, .25 }); // Color right wall
        fill(&R[4 * S * S], &R[5 * S * S], vec{ .75, .25, .25 }); // Color left wall
    }
};
// Information about an intersection between a ray and a Rect:
struct Intersection
{
    double distance;
    double u; // 0-1 coordinate of the intersection within the rectangle.
    double v; // 0-1 coordinate of the intersection within the rectangle.
    vec position;
    int rectangleIndex;
    Intersection() : distance{numeric_limits<double>::max()} {}
    operator bool() const { return distance < numeric_limits<double>::max(); }
};
// Compute the first intersection along a ray:
Intersection ComputeIntersection(const Scene& scene, vec start, vec dir)
{
    const auto e = 0.0001;
    start += e * dir;
    dir = normalized(dir);
    auto firstIntersection = Intersection();
    for (auto r = 0; r < Scene::NUM_RECTANGLES; ++r)
    {
        const auto& rectangle = scene.rectangles[r];
        auto i = Intersection();
        i.distance = dot(rectangle.p - start, rectangle.nn) / dot(dir, rectangle.nn);
        if (i.distance < 0 || firstIntersection.distance < i.distance)
            continue;
        i.rectangleIndex = r;
        i.position = start + i.distance * dir;
        const auto p = i.position - rectangle.p;
        i.u = dot(p, rectangle.x) / dot(rectangle.x, rectangle.x);
        i.v = dot(p, rectangle.y) / dot(rectangle.y, rectangle.y);
        if (0 - e < i.u && i.u < 1 + e && 0 - e < i.v && i.v < 1 + e)
            firstIntersection = i;
    }
    return firstIntersection;
}
int RectToPatch(int rect_index, int rect_patch_u, int rect_path_v)
{
    return rect_patch_u + rect_path_v * S + rect_index * S * S;
}
// Get patch index of an intersection, with an optional u and v offset:
int Patch(const Intersection& i, double du = 0, double dv = 0)
{
    const auto rect_path_u = max(min(int((i.u + du) * S), S - 1), 0);
    const auto rect_path_v = max(min(int((i.v + dv) * S), S - 1), 0);
    return RectToPatch(i.rectangleIndex, rect_path_u, rect_path_v);
}
// Get an "interpolated" value for the radiosity using gaussian samples:
vec Radiosity(const Scene& scene, const Intersection& i)
{
    auto r = vec{0, 0, 0};
    if (!i)
        return r;
    //return B[Patch(i)]; // No interpolation
    // Gaussian filter:
    const auto DRAW_STD = 0.5 / S; // STD of gaussian filter.
    for (auto s = 0; s < DRAW_SAMPLES; ++s)
        r += scene.B[Patch(i, DRAW_STD * g(), DRAW_STD * g())];
    return r / double(DRAW_SAMPLES);
}
vec RandomDiffuseReflectionDirection(vec tangent1, vec tangent2, vec normal)
{
    const auto a = u();
    const auto dir = sqrt(a) * normalized(vec{g(), g(), 0}) + vec{0, 0, sqrt(1 - a)};
    return tangent1 * dir[0] + tangent2 * dir[1] + normal * dir[2];
}
vec RandomDirection()
{
    return normalized(vec{ g(), g(), g() });
}
bool PhotonIsAbsorbed(double reflectance)
{
    return u() > reflectance;
}
const auto NUM_COLOR_CHANNELS = 3;
// Compute the radiosity of the scene by bouncing around photons.
void ComputeRadiosity(Scene& scene)
{
    for (auto c = 0; c < NUM_COLOR_CHANNELS; ++c)
    {
        for (auto p = 0; p < PHOTONS; ++p)
        {
            auto ray_dir = RandomDirection();
            auto ray_start = scene.lightPos;
            auto i = ComputeIntersection(scene, ray_start, ray_dir);
            while (i && !PhotonIsAbsorbed(scene.R[Patch(i)][c]))
            {
                const auto& r = scene.rectangles[i.rectangleIndex];
                scene.B[Patch(i)][c] += scene.lightPower[c] / PHOTONS * S * S / r.a;
                ray_dir = RandomDiffuseReflectionDirection(r.xn, r.yn, r.nn);
                ray_start = i.position;
                i = ComputeIntersection(scene, ray_start, ray_dir);
            }
        }
    }
}
// Do gamma correction and truncation of color:
int ScreenColor(double c)
{
    return min(int(pow(c, 1 / 2.2)), 255);
}
// Render the image to a ppm-file:
void Render(const Scene& scene, vec cameraPos, double focalLength, const char* filename)
{
    ofstream file(filename);
    file << "P3\n" << int(WIDTH) << " " << int(HEIGHT) << "\n255\n";
    for (auto y = 0.0; y < HEIGHT; ++y)
    {
        for (auto x = 0.0; x < WIDTH; ++x)
        {
            const auto rayDir = vec{WIDTH / 2 - x, HEIGHT / 2 - y, focalLength};
            const auto color = Radiosity(scene, ComputeIntersection(scene, cameraPos, rayDir));
            for (auto c = 0; c < NUM_COLOR_CHANNELS; ++c)
                file << ScreenColor(color[c]) << " ";
        }
    }
}
void SaveLightmaps(const Scene& scene, const char* fileNameStart)
{
    for (auto r = 0; r < Scene::NUM_RECTANGLES; ++r)
    {
        auto ss = stringstream();
        ss << fileNameStart << r << ".ppm";
        auto file = ofstream(ss.str());
        file << "P3" << endl << S << " " << S << endl << 255 << endl;
        for (auto y = 0; y < S; ++y)
        {
            for (auto x = 0; x < S; ++x)
            {
                const auto color = scene.B[RectToPatch(r, x, y)];
                for (auto c = 0; c < NUM_COLOR_CHANNELS; ++c)
                    file << ScreenColor(color[c]) << " ";
            }
        }
    }
}
// Here we go:
int main()
{
    auto scene = Scene();
    cout << "Computing radiosity." << endl;
    ComputeRadiosity(scene);
    cout << "Saving lightmaps to files." << endl;
    SaveLightmaps(scene, "lightmap");
    cout << "Rendering image to file." << endl;
    const auto focalLength = 1.4 * WIDTH;
    const auto cameraPos = L * vec{.5, .5, -1.4};
    Render(scene, cameraPos, focalLength, "image.ppm");
}

//void LoadLightmaps()
//{
//	for(size_t q=0; q<Q;++q)
//	{
//		stringstream ss;
//		ss << "lightmaps30/lightmap" << q << ".ppm";
//		ifstream f( ss.str() );
//		string temp;
//		size_t w,h,color;
//		f >> temp >> w >> h >> color;
//		for( size_t y=0; y<S; ++y )
//		{
//			for( size_t x=0; x<S; ++x )
//			{
//				vec color = vec{0,0,0);
//				for( int c=0; c<3; ++c )
//					f >> color[c];
//				B[QuadToPatch(q,x,y)] = 700.*color; // N.B. truncated over 255
//			}
//		}
//	}
//}

//void LoadLightmaps()
//{
//	for(size_t q=0; q<Q;++q)
//	{
//		stringstream ss;
//		ss << "lightmap" << q << ".ppm";
//		ifstream f( ss.str() );
//		string temp;
//		size_t w,h,color;
//		f >> temp >> w >> h >> color;
//		for( size_t y=0; y<S; ++y )
//		{
//			for( size_t x=0; x<S; ++x )
//			{
//				vec color = vec{0,0,0);
//				for( int c=0; c<3; ++c )
//					f >> color[c];
//				radiosity[QuadToPatch(q,x,y)] = color; // N.B. truncated over 255
//			}
//		}
//	}
//}
<|endoftext|>


<commit_before>9c4f044f-2747-11e6-a142-e0f84713e7b8<commit_msg>Initial commit.13<commit_after>9c579399-2747-11e6-96e2-e0f84713e7b8<|endoftext|>


<commit_before>ed443ac2-2747-11e6-b3f0-e0f84713e7b8<commit_msg>almost working<commit_after>ed5816e8-2747-11e6-a569-e0f84713e7b8<|endoftext|>


<commit_before>6fe01b91-4b02-11e5-b644-28cfe9171a43<commit_msg>OKAY this time it should work<commit_after>6fedb7a3-4b02-11e5-ab9b-28cfe9171a43<|endoftext|>


<commit_before>7b1951d9-2749-11e6-a078-e0f84713e7b8<commit_msg>almost working<commit_after>7b27fc94-2749-11e6-a4d7-e0f84713e7b8<|endoftext|>


<commit_before>d0cb6fd1-2747-11e6-9a22-e0f84713e7b8<commit_msg>lets try again<commit_after>d0d79200-2747-11e6-b44e-e0f84713e7b8<|endoftext|>


<commit_before>cdac6ffa-4b02-11e5-9314-28cfe9171a43<commit_msg>My Backup<commit_after>cdb7dfd4-4b02-11e5-8d79-28cfe9171a43<|endoftext|>


<commit_before>faa8cf40-2747-11e6-a85d-e0f84713e7b8<commit_msg>Bug fixes and performance improvements<commit_after>fab1e5b0-2747-11e6-8cbd-e0f84713e7b8<|endoftext|>


<commit_before>// ReSharper disable CppUnusedIncludeDirective
#undef NDEBUG
#include "src/Exception.hpp"
#include "src/ExpressionTree.hpp"
#include "src/ExpressionStack.hpp"
#include "src/SparseMatrix.hpp"
#include "src/BFS.hpp"
#include "src/BinaryTree.hpp"

#include <iostream>
#include <cmath>
#include <cassert>
#include <sstream>
#include <stdexcept>

int main()
{
#ifdef Use_Wcout

	try {
#ifdef _WIN32
		std::wcout.imbue(std::locale("chs"));
#else //_WIN32
		std::wcout.imbue(std::locale("zh_CN.UTF-8"));
#endif //_WIN32
	}
	catch (std::runtime_error) {
		setlocale(LC_ALL, "chs");
		std::ios_base::sync_with_stdio(false);
	}
#endif //Use_Wcout

#ifdef SparseMatrix_enabled
	//++Start SparseMatrix2 test
	{
		//auto mat0 = SparseMatrix2<int, 2, 3>({ { 1,1,0,4 },{ 0,0,4,4 } }); //将会触发编译器报错：Col size doesn't match

		auto mat = SparseMatrix2<int, 2, 3>({ { 1,1,0 },{0,0,4 } });

		auto mat2 = SparseMatrix2<int, 3, 1>();
		mat2.set<0, 0>(4);
		mat2.set<1, 0>(1);
		mat2.set<2, 0>(2);

		auto mat3 = mat * mat2;
		auto mat4 = mat3.Rev();

		assert((mat3.get<0, 0>() == 14));
		assert((mat3.get<1, 0>() == 28));
		assert((mat4.get<0, 0>() == 14));
		assert((mat4.get<0, 1>() == 28));
		//assert((mat4.get<0, 2>() == 28)); //将会触发编译器报错：Matrix bound check failed

		auto mat5 = SparseMatrix2<int, 2, 3>();
		mat5.set<0, 0>(1);
		mat5.set<0, 1>(1);
		mat5.set<1, 2>(2);

		assert((mat5.get(1, 1) == 0));
		assert((mat5.get<1, 1>() == 0));

		try{
			mat5.get(3, 5);
			throw std::runtime_error("Exception Expected");
		}catch(std::out_of_range e){
			assert(std::string(e.what()) == "Matrix bound check failed");
		}

		auto mat6 = mat - mat5;
		assert((mat6.get<1, 2>() == 2));
		std::stringstream ss;
		ss << mat;
		assert(ss.str() == "1 1 0\n0 0 4\n");

	}
#ifdef Use_Wcout
	std::wcout << L"SparseMatrix2 测试完成" << std::endl;
#else //Use_Wcout
	std::cout << "SparseMatrix2 test complete" << std::endl;
#endif //Use_Wcout
	//++End SparseMatrix2 test
#endif

#ifndef BFS_disabled
	//++Start BFS test
	{
		auto map =
R"(
0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0
)";
		auto x = BFS(0, 0, 4, 4, 5, 5, map);

		auto t = BFS_pretty_text(x);
		std::stringstream ss1, ss2;
		ss1 << '\n' << t;
		auto anstext =
R"(
(0,0)
(1,0)
(2,0)
(2,1)
(2,2)
(2,3)
(2,4)
(3,4)
(4,4)
)";
		ss2 << anstext;
		assert(ss1.str() == ss2.str());

		auto w = BFS_pretty_graph(x, 5, 5, map);
		std::stringstream ss3, ss4;
		ss3 << '\n' << w;
		auto ans =
R"(
FW
DW W
RRRRD
 WWWD
   WF
)";
		ss4 << ans;
		assert(ss3.str() == ss4.str());

		auto map2 =
R"(
0 1 0
0 1 0
)";
		auto x2 = BFS(0, 0, 2, 1, 3, 2, map2);
		assert(x2.size() == 0);
	}
#ifdef Use_Wcout
	std::wcout << L"BFS 测试完成" << std::endl;
#else //Use_Wcout
	std::cout << "BFS test complete" << std::endl;
#endif //Use_Wcout
	//++End BFS test
#endif

#ifndef ExpressionStack_disabled
	//++Start ExpressionStack test
	{
		auto str = "1+2*3";
		auto ans = ExpressionStack::Eval(str);
		assert(ans == 7.0);

		auto str1 = "2-3*4-5/6";
		auto ans1 = ExpressionStack::Eval(str1);
		assert(fabs(ans1 - (2 - 3 * 4 - 5.0 / 6)) < 0.01);

		auto str2 = "(1-2)*3";
		auto ans2 = ExpressionStack::Eval(str2);
		assert(ans2 == -3.0);

		auto str3 = "1+2+(40*34-22)*2";
		auto ans3 = ExpressionStack::Eval(str3);
		assert(ans3 == 2679.0);

		auto str4 = "2-3*4-5/6+7*(8-(9*10+1)/2+20+2*10)-20+12";
		auto ans4 = ExpressionStack::Eval(str4);
		assert(fabs(ans4 - (2 - 3 * 4 - 5.0 / 6 + 7 * (8 - (9 * 10 + 1.0) / 2 + 20 + 2 * 10) - 20 + 12)) < 0.01);
		try {
			ExpressionStack::Eval("3+4)4");
			throw std::runtime_error("Exception Expected");
		}
		catch (Exception& e) {
			assert(std::wstring(e.Error) == L"错误的优先级");
		}

		try {
			ExpressionStack::Eval("*5-4");
			throw std::runtime_error("Exception Expected");
		}
		catch (Exception& e) {
			assert(std::wstring(e.Error) == L"错误的操作符");
		}
	}
#ifdef Use_Wcout
	std::wcout << L"ExpressionStack 测试完成" << std::endl;
#else //Use_Wcout
	std::cout << "ExpressionStack test complete" << std::endl;
#endif //Use_Wcout
	//++End ExpressionStack test
#endif

#ifndef ExpressionTree_disabled
	//++Start ExpressionTree test
	{
		auto str = "1+2+   (40*34-22)*2";
		auto exp = GetExp(str);
		assert(exp->Eval() == 2679.0);

		auto str1 = "2-3*4-5/6";
		auto exp1 = GetExp(str1);
		assert(fabs(exp1->Eval() - (2 - 3 * 4 - 5.0 / 6)) < 0.01);

		auto str2 = "2-3*4-5/6 + 7*(8-   (9*10+1)/2 +20+2*10    ) -20 +12";
		auto exp2 = GetExp(str2);
		assert(fabs(exp2->Eval() - (2 - 3 * 4 - 5.0 / 6 + 7 * (8 - (9 * 10 + 1.0) / 2 + 20 + 2 * 10) - 20 + 12)) < 0.01);

		try{
			auto str3 = "2-(3";
			GetExp(str3);
			throw std::runtime_error("Exception Expected");
		}catch(Exception e){
			assert(std::wstring(e.Error) == L"此处需要右括号");
		}

		try{
			auto str3 = "2-*3";
			GetExp(str3);
			throw std::runtime_error("Exception Expected");
		}catch(Exception e){
			assert(std::wstring(e.Error) == L"此处需要表达式");
		}

		try{
			auto brokenExp = BinaryExpression(static_cast<BinaryOperator>(1),std::make_unique<NumberExpression>(1),std::make_unique<NumberExpression>(1));
			brokenExp.Eval();
			throw std::runtime_error("Exception Expected");
		}catch(Exception e){
			assert(std::wstring(e.Error) == L"错误的操作符");
		}
	}
#ifdef Use_Wcout
	std::wcout << L"ExpressionTree 测试完成" << std::endl;
#else //Use_Wcout
	std::cout << "ExpressionTree test complete" << std::endl;
#endif //Use_Wcout
	//++End ExpressionTree test
#endif

#ifndef BinaryTree_disabled
	//++Start BinaryTree test
	{
/*
      1
     / \
    2   3
   / \
  4	  5

*/
		auto tree = MakeTree(MakeTree(MakeTree(std::make_unique<int>(4)), MakeTree(std::make_unique<int>(5)), std::make_unique<int>(2)), MakeTree(std::make_unique<int>(3)), std::make_unique<int>(1));
		auto tree2 = MakeTree(MakeTree(MakeTree(4), MakeTree(5), 2), MakeTree(3), 1);
		auto ans =
R"(
1 2 4 5 3
4 2 5 1 3
4 5 2 3 1
)";
		auto ans2 =
R"(
1 2 4 5 3
4 2 5 1 3
1 1 1 1 1
)";
		std::stringstream ss2, ss1, ssa(ans), ssa2(ans2);

		ss1 << std::endl;
		VisitTreeRecurse<Order::PreOrder>(tree, [&ss1](std::unique_ptr<int>& i) {ss1 << *i << " "; });
		ss1 << std::endl;
		VisitTreeRecurse<Order::InOrder>(tree, [&ss1](std::unique_ptr<int>& i) {ss1 << *i << " "; });
		ss1 << std::endl;
		VisitTreeRecurse<Order::PostOrder>(tree, [&ss1](std::unique_ptr<int>& i) {ss1 << *i << " "; });
		ss1 << std::endl;
		assert(ssa.str() == ss1.str());

		ss2 << std::endl;
		VisitTreeRecurse<Order::PreOrder>(tree2, [&ss2](int i) {ss2 << i << " "; });
		ss2 << std::endl;
		VisitTreeRecurse<Order::InOrder>(tree2, [&ss2](int& i) {ss2 << i << " "; i = 1;});
		ss2 << std::endl;
		VisitTreeRecurse<Order::PostOrder>(tree2, [&ss2](int i) {ss2 << i << " "; });
		ss2 << std::endl;
		assert(ssa2.str() == ss2.str());
	}
#ifdef Use_Wcout
	std::wcout << L"BinaryTree 测试完成" << std::endl;
#else //Use_Wcout
	std::cout << "BinaryTree test complete" << std::endl;
#endif //Use_Wcout
	//++End BinaryTree test
#endif
	return 0;
}
<commit_msg>UPDATE test case for lambda deduction<commit_after>// ReSharper disable CppUnusedIncludeDirective
#undef NDEBUG
#include "src/Exception.hpp"
#include "src/ExpressionTree.hpp"
#include "src/ExpressionStack.hpp"
#include "src/SparseMatrix.hpp"
#include "src/BFS.hpp"
#include "src/BinaryTree.hpp"

#include <iostream>
#include <cmath>
#include <cassert>
#include <sstream>
#include <stdexcept>

int main()
{
#ifdef Use_Wcout

	try {
#ifdef _WIN32
		std::wcout.imbue(std::locale("chs"));
#else //_WIN32
		std::wcout.imbue(std::locale("zh_CN.UTF-8"));
#endif //_WIN32
	}
	catch (std::runtime_error) {
		setlocale(LC_ALL, "chs");
		std::ios_base::sync_with_stdio(false);
	}
#endif //Use_Wcout

#ifdef SparseMatrix_enabled
	//++Start SparseMatrix2 test
	{
		//auto mat0 = SparseMatrix2<int, 2, 3>({ { 1,1,0,4 },{ 0,0,4,4 } }); //将会触发编译器报错：Col size doesn't match

		auto mat = SparseMatrix2<int, 2, 3>({ { 1,1,0 },{0,0,4 } });

		auto mat2 = SparseMatrix2<int, 3, 1>();
		mat2.set<0, 0>(4);
		mat2.set<1, 0>(1);
		mat2.set<2, 0>(2);

		auto mat3 = mat * mat2;
		auto mat4 = mat3.Rev();

		assert((mat3.get<0, 0>() == 14));
		assert((mat3.get<1, 0>() == 28));
		assert((mat4.get<0, 0>() == 14));
		assert((mat4.get<0, 1>() == 28));
		//assert((mat4.get<0, 2>() == 28)); //将会触发编译器报错：Matrix bound check failed

		auto mat5 = SparseMatrix2<int, 2, 3>();
		mat5.set<0, 0>(1);
		mat5.set<0, 1>(1);
		mat5.set<1, 2>(2);

		assert((mat5.get(1, 1) == 0));
		assert((mat5.get<1, 1>() == 0));

		try{
			mat5.get(3, 5);
			throw std::runtime_error("Exception Expected");
		}catch(std::out_of_range e){
			assert(std::string(e.what()) == "Matrix bound check failed");
		}

		auto mat6 = mat - mat5;
		assert((mat6.get<1, 2>() == 2));
		std::stringstream ss;
		ss << mat;
		assert(ss.str() == "1 1 0\n0 0 4\n");

	}
#ifdef Use_Wcout
	std::wcout << L"SparseMatrix2 测试完成" << std::endl;
#else //Use_Wcout
	std::cout << "SparseMatrix2 test complete" << std::endl;
#endif //Use_Wcout
	//++End SparseMatrix2 test
#endif

#ifndef BFS_disabled
	//++Start BFS test
	{
		auto map =
R"(
0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0
)";
		auto x = BFS(0, 0, 4, 4, 5, 5, map);

		auto t = BFS_pretty_text(x);
		std::stringstream ss1, ss2;
		ss1 << '\n' << t;
		auto anstext =
R"(
(0,0)
(1,0)
(2,0)
(2,1)
(2,2)
(2,3)
(2,4)
(3,4)
(4,4)
)";
		ss2 << anstext;
		assert(ss1.str() == ss2.str());

		auto w = BFS_pretty_graph(x, 5, 5, map);
		std::stringstream ss3, ss4;
		ss3 << '\n' << w;
		auto ans =
R"(
FW
DW W
RRRRD
 WWWD
   WF
)";
		ss4 << ans;
		assert(ss3.str() == ss4.str());

		auto map2 =
R"(
0 1 0
0 1 0
)";
		auto x2 = BFS(0, 0, 2, 1, 3, 2, map2);
		assert(x2.size() == 0);
	}
#ifdef Use_Wcout
	std::wcout << L"BFS 测试完成" << std::endl;
#else //Use_Wcout
	std::cout << "BFS test complete" << std::endl;
#endif //Use_Wcout
	//++End BFS test
#endif

#ifndef ExpressionStack_disabled
	//++Start ExpressionStack test
	{
		auto str = "1+2*3";
		auto ans = ExpressionStack::Eval(str);
		assert(ans == 7.0);

		auto str1 = "2-3*4-5/6";
		auto ans1 = ExpressionStack::Eval(str1);
		assert(fabs(ans1 - (2 - 3 * 4 - 5.0 / 6)) < 0.01);

		auto str2 = "(1-2)*3";
		auto ans2 = ExpressionStack::Eval(str2);
		assert(ans2 == -3.0);

		auto str3 = "1+2+(40*34-22)*2";
		auto ans3 = ExpressionStack::Eval(str3);
		assert(ans3 == 2679.0);

		auto str4 = "2-3*4-5/6+7*(8-(9*10+1)/2+20+2*10)-20+12";
		auto ans4 = ExpressionStack::Eval(str4);
		assert(fabs(ans4 - (2 - 3 * 4 - 5.0 / 6 + 7 * (8 - (9 * 10 + 1.0) / 2 + 20 + 2 * 10) - 20 + 12)) < 0.01);
		try {
			ExpressionStack::Eval("3+4)4");
			throw std::runtime_error("Exception Expected");
		}
		catch (Exception& e) {
			assert(std::wstring(e.Error) == L"错误的优先级");
		}

		try {
			ExpressionStack::Eval("*5-4");
			throw std::runtime_error("Exception Expected");
		}
		catch (Exception& e) {
			assert(std::wstring(e.Error) == L"错误的操作符");
		}
	}
#ifdef Use_Wcout
	std::wcout << L"ExpressionStack 测试完成" << std::endl;
#else //Use_Wcout
	std::cout << "ExpressionStack test complete" << std::endl;
#endif //Use_Wcout
	//++End ExpressionStack test
#endif

#ifndef ExpressionTree_disabled
	//++Start ExpressionTree test
	{
		auto str = "1+2+   (40*34-22)*2";
		auto exp = GetExp(str);
		assert(exp->Eval() == 2679.0);

		auto str1 = "2-3*4-5/6";
		auto exp1 = GetExp(str1);
		assert(fabs(exp1->Eval() - (2 - 3 * 4 - 5.0 / 6)) < 0.01);

		auto str2 = "2-3*4-5/6 + 7*(8-   (9*10+1)/2 +20+2*10    ) -20 +12";
		auto exp2 = GetExp(str2);
		assert(fabs(exp2->Eval() - (2 - 3 * 4 - 5.0 / 6 + 7 * (8 - (9 * 10 + 1.0) / 2 + 20 + 2 * 10) - 20 + 12)) < 0.01);

		try{
			auto str3 = "2-(3";
			GetExp(str3);
			throw std::runtime_error("Exception Expected");
		}catch(Exception e){
			assert(std::wstring(e.Error) == L"此处需要右括号");
		}

		try{
			auto str3 = "2-*3";
			GetExp(str3);
			throw std::runtime_error("Exception Expected");
		}catch(Exception e){
			assert(std::wstring(e.Error) == L"此处需要表达式");
		}

		try{
			auto brokenExp = BinaryExpression(static_cast<BinaryOperator>(1),std::make_unique<NumberExpression>(1),std::make_unique<NumberExpression>(1));
			brokenExp.Eval();
			throw std::runtime_error("Exception Expected");
		}catch(Exception e){
			assert(std::wstring(e.Error) == L"错误的操作符");
		}
	}
#ifdef Use_Wcout
	std::wcout << L"ExpressionTree 测试完成" << std::endl;
#else //Use_Wcout
	std::cout << "ExpressionTree test complete" << std::endl;
#endif //Use_Wcout
	//++End ExpressionTree test
#endif

#ifndef BinaryTree_disabled
	//++Start BinaryTree test
	{
/*
      1
     / \
    2   3
   / \
  4	  5

*/
		auto tree = MakeTree(MakeTree(MakeTree(std::make_unique<int>(4)), MakeTree(std::make_unique<int>(5)), std::make_unique<int>(2)), MakeTree(std::make_unique<int>(3)), std::make_unique<int>(1));
		auto tree2 = MakeTree(MakeTree(MakeTree(4), MakeTree(5), 2), MakeTree(3), 1);
		auto ans =
R"(
1 2 4 5 3
4 2 5 1 3
4 5 2 3 1
)";
		auto ans2 =
R"(
1 2 4 5 3
4 2 5 1 3
1 1 1 1 1
)";
		std::stringstream ss2, ss1, ssa(ans), ssa2(ans2);

		ss1 << std::endl;
		VisitTreeRecurse<Order::PreOrder>(tree, [&ss1](auto& i) {ss1 << *i << " "; });
		ss1 << std::endl;
		VisitTreeRecurse<Order::InOrder>(tree, [&ss1](std::unique_ptr<int>& i) {ss1 << *i << " "; });
		ss1 << std::endl;
		VisitTreeRecurse<Order::PostOrder>(tree, [&ss1](auto& i) {ss1 << *i << " "; });
		ss1 << std::endl;
		assert(ssa.str() == ss1.str());

		ss2 << std::endl;
		VisitTreeRecurse<Order::PreOrder>(tree2, [&ss2](int i) {ss2 << i << " "; });
		ss2 << std::endl;
		VisitTreeRecurse<Order::InOrder>(tree2, [&ss2](auto& i) {ss2 << i << " "; i = 1;});
		ss2 << std::endl;
		VisitTreeRecurse<Order::PostOrder>(tree2, [&ss2](auto i) {ss2 << i << " "; });
		ss2 << std::endl;
		assert(ssa2.str() == ss2.str());
	}
#ifdef Use_Wcout
	std::wcout << L"BinaryTree 测试完成" << std::endl;
#else //Use_Wcout
	std::cout << "BinaryTree test complete" << std::endl;
#endif //Use_Wcout
	//++End BinaryTree test
#endif
	return 0;
}
<|endoftext|>


<commit_before>2a0f3fc5-2748-11e6-b348-e0f84713e7b8<commit_msg>GOD DAMNED IT!<commit_after>2a1aab87-2748-11e6-96f5-e0f84713e7b8<|endoftext|>


<commit_before>// Стрелки <Лево / Право> - смена сцены ========================================

#include <iostream>
#include <SFML/Graphics.hpp>
#include "data/scene.cpp"

using namespace std;

int main() {
    sf::RenderWindow app(sf::VideoMode(SCREEN_WIDTH, SCREEN_HEIGHT), "KeyboardNinja");

    app.setFramerateLimit(60);

    //Инициализация сцены
    scene_main_menu = new kb::SceneMainMenu;
    scene_main_menu->init(&app);

    scene_game = new kb::SceneGame;
    scene_game->init(&app);

    scene_game = new kb::SceneTableLead;
    scene_table_lead->init(&app);

    scene_game = new kb::SceneInputLead;
    scene_input_lead->init(&app);

    scene = scene_main_menu;

    while (app.isOpen())
    {
        //Обработчик событий
        sf::Event event;
        while (app.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
                app.close();
        }

        //Очистка экрана
        app.clear();

        //Вывод текущей сцены
        scene->draw();

        scene->step();

        //Отображение выведенного изображения
        app.display();

        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space)) app.close();
    }

    return 0;
}
<commit_msg>Fix bug<commit_after>// Стрелки <Лево / Право> - смена сцены ========================================

#include <iostream>
#include <SFML/Graphics.hpp>
#include "data/scene.cpp"

using namespace std;

int main() {
    sf::RenderWindow app(sf::VideoMode(SCREEN_WIDTH, SCREEN_HEIGHT), "KeyboardNinja");

    app.setFramerateLimit(60);

    //Инициализация сцены
    scene_main_menu = new kb::SceneMainMenu;
    scene_main_menu->init(&app);

    scene_game = new kb::SceneGame;
    scene_game->init(&app);

    scene_table_lead = new kb::SceneTableLead;
    scene_table_lead->init(&app);

    scene_input_lead = new kb::SceneInputLead;
    scene_input_lead->init(&app);

    scene = scene_main_menu;

    while (app.isOpen())
    {
        //Обработчик событий
        sf::Event event;
        while (app.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
                app.close();
        }

        //Очистка экрана
        app.clear();

        //Вывод текущей сцены
        scene->draw();

        scene->step();

        //Отображение выведенного изображения
        app.display();

        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space)) app.close();
    }

    return 0;
}
<|endoftext|>


<commit_before>#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/resource.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <unistd.h>

#include <iostream>

int main(int /* argc */, char* argv[])
{
	timeval start;
	gettimeofday(&start, nullptr);

	switch (fork())
	{
		case -1: // Error
			std::cerr << "Error on fork()\n";
			return -1;
		case 0: // Child process
			if (-1 == execvp(argv[1], &argv[1]))
			{
				std::cerr << "Error on exec()\n";
				return -1;
			}
			std::cout << "test";
			break;
		default: // Parent process
		{
			int status;
			if (wait(&status) <= 0)
			{
				std::cerr << "Error on wait()\n";
			}

			rusage ts;
			timeval end;
			timeval wallclock;

			gettimeofday(&end, nullptr);
			timersub(&end, &start, &wallclock);

			if (-1 != getrusage(RUSAGE_CHILDREN, &ts))
			{
				char tmbuf[64];
				timeval tv;
				timeradd(&ts.ru_utime, &ts.ru_stime, &tv);
				strftime(tmbuf, 64, "%s", localtime(&tv.tv_sec));
				printf("CPU time: %s.%06ld seconds\n", tmbuf, tv.tv_usec);
				strftime(tmbuf, sizeof tmbuf, "%s", localtime(&wallclock.tv_sec));
				printf("Wall-clock time: %s.%06ld seconds\n", tmbuf, wallclock.tv_usec);
				printf("Voluntary context switches: %ld\n", ts.ru_nvcsw);
				printf("Involuntary context switches: %ld\n", ts.ru_nivcsw);
				printf("Page reclaims (soft page faults): %ld\n", ts.ru_minflt);
				printf("Page faults (hard page faults): %ld\n", ts.ru_majflt);
			}

			if (WIFEXITED(status))
			{
				return WEXITSTATUS(status);
			}
		} break;
	}
}
<commit_msg>cmd abstraction<commit_after>#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/resource.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <unistd.h>

#include <iostream>
#include <string>
#include <tuple>
#include <vector>

<<<<<<< HEAD
int main(int /* argc */, char* argv[])
{
	timeval start;
	gettimeofday(&start, nullptr);

	switch (fork())
=======
using process_info = std::tuple<pid_t, timeval>;

process_info launch_cmd(std::vector<std::string> args)
{
	pid_t child_pid = fork();
	timeval t;
	gettimeofday(&t, nullptr);
	switch (child_pid)
>>>>>>> 9f950e0... cmd abstraction
	{
		case -1: // Error
			std::cerr << "Error on fork()\n";
			return process_info(child_pid, t);

		case 0: // Child process
		{
			const char *file = args[0].c_str();
			char * * argv = new char *[args.size()+1];
			std::vector<std::string>::size_type i;

			for (i = 0; i < args.size(); ++i) {
				argv[i] = const_cast<char*>(args[i].c_str());
			}

			argv[i] = nullptr;

			if (-1 == execvp(file, argv))
			{
				std::cerr << "Error on exec()\n";
				return process_info(-1, t);
			}
			return process_info(-1, t);
		} break;
		default: // Parent process
		{
			return process_info(child_pid, t);
		}
	}
}

int main(int /* argc */, char* /* argv */[])
{
	timeval start;
	gettimeofday(&start, nullptr);

	std::vector<std::string> args = {"ls", "-lahF"};
	launch_cmd(args);
}

/*
int status;
			if (wait(&status) <= 0)
			{
				std::cerr << "Error on wait()\n";
			}

			rusage ts;
			timeval end;
			timeval wallclock;

			gettimeofday(&end, nullptr);
			timersub(&end, &start, &wallclock);

			if (-1 != getrusage(RUSAGE_CHILDREN, &ts))
			{
				char tmbuf[64];
				timeval tv;
				timeradd(&ts.ru_utime, &ts.ru_stime, &tv);
				strftime(tmbuf, 64, "%s", localtime(&tv.tv_sec));
				printf("CPU time: %s.%06ld seconds\n", tmbuf, tv.tv_usec);
				strftime(tmbuf, sizeof tmbuf, "%s", localtime(&wallclock.tv_sec));
				printf("Wall-clock time: %s.%06ld seconds\n", tmbuf, wallclock.tv_usec);
				printf("Voluntary context switches: %ld\n", ts.ru_nvcsw);
				printf("Involuntary context switches: %ld\n", ts.ru_nivcsw);
				printf("Page reclaims (soft page faults): %ld\n", ts.ru_minflt);
				printf("Page faults (hard page faults): %ld\n", ts.ru_majflt);
			}

			if (WIFEXITED(status))
			{
				return WEXITSTATUS(status);
			}
		} break;
*/
<|endoftext|>


<commit_before>#include "mainwindow.h"
#include <QApplication>
#include <QtGlobal>
#include <iostream>

void customLogHandler(QtMsgType type, const QMessageLogContext &context,
		      const QString &msg)
{
// now output to debugger console
#ifdef Q_OS_WIN
//OutputDebugString(msg.toStdWString().c_str());
#else
	std::cerr << msg.toStdString() << std::endl;
#endif
}

int main(int argc, char *argv[])
{
	// The version that Ubuntu uses for QT isn't hiqh enough to support this, so neither of these will work.
	// commenting both of them out will work
	//QApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
	//QApplication::setAttribute(Qt::AA_DisableHighDpiScaling);

	qInstallMessageHandler(&customLogHandler);

	QApplication a(argc, argv);
	MainWindow w;
	w.show();

	return a.exec();
}
<commit_msg>attemping a v5.8 install<commit_after>#include "mainwindow.h"
#include <QApplication>
#include <QtGlobal>
#include <iostream>

void customLogHandler(QtMsgType type, const QMessageLogContext &context,
		      const QString &msg)
{
// now output to debugger console
#ifdef Q_OS_WIN
//OutputDebugString(msg.toStdWString().c_str());
#else
	std::cerr << msg.toStdString() << std::endl;
#endif
}

int main(int argc, char *argv[])
{
	QApplication::setAttribute(Qt::AA_DisableHighDpiScaling);

	qInstallMessageHandler(&customLogHandler);

	QApplication a(argc, argv);
	MainWindow w;
	w.show();

	return a.exec();
}
<|endoftext|>


<commit_before>6175e540-2749-11e6-920b-e0f84713e7b8<commit_msg>Long commit messages are not required<commit_after>6180c8b5-2749-11e6-b269-e0f84713e7b8<|endoftext|>


<commit_before>/*
 * Copyright 2014 Cloudius Systems
 */

#include "database.hh"
#include "core/app-template.hh"
#include "core/distributed.hh"
#include "thrift/server.hh"
#include "transport/server.hh"
#include "http/httpd.hh"
#include "api/api.hh"
#include "db/config.hh"
#include "message/messaging_service.hh"
#include "service/storage_service.hh"
#include "dns.hh"
#include <cstdio>

namespace bpo = boost::program_options;

static future<>
read_config(bpo::variables_map& opts, db::config& cfg) {
    if (opts.count("options-file") == 0) {
        return make_ready_future<>();
    }
    return cfg.read_from_file(opts["options-file"].as<sstring>());
}

int main(int ac, char** av) {
    std::setvbuf(stdout, nullptr, _IOLBF, 1000);
    app_template app;
    auto opt_add = app.add_options();

    auto cfg = make_lw_shared<db::config>();
    cfg->add_options(opt_add)
        ("api-port", bpo::value<uint16_t>()->default_value(10000), "Http Rest API port")
        ("api-dir", bpo::value<sstring>()->default_value("swagger-ui/dist/"),
                "The directory location of the API GUI")
        // TODO : default, always read?
        ("options-file", bpo::value<sstring>(), "cassandra.yaml file to read options from")
        ;

    distributed<database> db;
    distributed<cql3::query_processor> qp;
    distributed<service::storage_proxy> proxy;
    api::http_context ctx(db);

    return app.run(ac, av, [&] {
        auto&& opts = app.configuration();

        return read_config(opts, *cfg).then([&cfg, &db, &qp, &proxy, &ctx, &opts]() {
            uint16_t thrift_port = cfg->rpc_port();
            uint16_t cql_port = cfg->native_transport_port();
            uint16_t api_port = opts["api-port"].as<uint16_t>();
            ctx.api_dir = opts["api-dir"].as<sstring>();
            sstring listen_address = cfg->listen_address();
            sstring rpc_address = cfg->rpc_address();
            auto seed_provider= cfg->seed_provider();
            using namespace locator;
            return i_endpoint_snitch::create_snitch(cfg->endpoint_snitch()).then(
                    [&db, cfg] () {
                return service::init_storage_service().then([&db, cfg] {
                    return db.start(std::move(*cfg)).then([&db] {
                        engine().at_exit([&db] {
                            return db.stop().then([] {
                                return i_endpoint_snitch::stop_snitch();
                            });
                        });
                        return db.invoke_on_all(&database::init_from_data_directory);
                    });
                });
            }).then([listen_address, seed_provider] {
                return net::init_messaging_service(listen_address, seed_provider);
            }).then([&proxy, &db] {
                return proxy.start(std::ref(db)).then([&proxy] {
                    engine().at_exit([&proxy] { return proxy.stop(); });
                });
            }).then([&db, &proxy, &qp] {
                return qp.start(std::ref(proxy), std::ref(db)).then([&qp] {
                    engine().at_exit([&qp] { return qp.stop(); });
                });
            }).then([rpc_address] {
                return dns::gethostbyname(rpc_address);
            }).then([&db, &proxy, &qp, cql_port, thrift_port] (dns::hostent e) {
                auto rpc_address = e.addresses[0].in.s_addr;
                auto cserver = new distributed<cql_server>;
                cserver->start(std::ref(proxy), std::ref(qp)).then([server = std::move(cserver), cql_port, rpc_address] () mutable {
                    server->invoke_on_all(&cql_server::listen, ipv4_addr{rpc_address, cql_port});
                }).then([cql_port] {
                    std::cout << "CQL server listening on port " << cql_port << " ...\n";
                });
                auto tserver = new distributed<thrift_server>;
                tserver->start(std::ref(db)).then([server = std::move(tserver), thrift_port, rpc_address] () mutable {
                    server->invoke_on_all(&thrift_server::listen, ipv4_addr{rpc_address, thrift_port});
                }).then([thrift_port] {
                    std::cout << "Thrift server listening on port " << thrift_port << " ...\n";
                });
            }).then([&db, api_port, &ctx]{
                ctx.http_server.start().then([api_port, &ctx] {
                    return set_server(ctx);
                }).then([&ctx, api_port] {
                    ctx.http_server.listen(api_port);
                }).then([api_port] {
                    std::cout << "Seastar HTTP server listening on port " << api_port << " ...\n";
                });
            }).or_terminate();
        });
    });
}
<commit_msg>main: init from data directory later<commit_after>/*
 * Copyright 2014 Cloudius Systems
 */

#include "database.hh"
#include "core/app-template.hh"
#include "core/distributed.hh"
#include "thrift/server.hh"
#include "transport/server.hh"
#include "http/httpd.hh"
#include "api/api.hh"
#include "db/config.hh"
#include "message/messaging_service.hh"
#include "service/storage_service.hh"
#include "dns.hh"
#include <cstdio>

namespace bpo = boost::program_options;

static future<>
read_config(bpo::variables_map& opts, db::config& cfg) {
    if (opts.count("options-file") == 0) {
        return make_ready_future<>();
    }
    return cfg.read_from_file(opts["options-file"].as<sstring>());
}

int main(int ac, char** av) {
    std::setvbuf(stdout, nullptr, _IOLBF, 1000);
    app_template app;
    auto opt_add = app.add_options();

    auto cfg = make_lw_shared<db::config>();
    cfg->add_options(opt_add)
        ("api-port", bpo::value<uint16_t>()->default_value(10000), "Http Rest API port")
        ("api-dir", bpo::value<sstring>()->default_value("swagger-ui/dist/"),
                "The directory location of the API GUI")
        // TODO : default, always read?
        ("options-file", bpo::value<sstring>(), "cassandra.yaml file to read options from")
        ;

    distributed<database> db;
    distributed<cql3::query_processor> qp;
    distributed<service::storage_proxy> proxy;
    api::http_context ctx(db);

    return app.run(ac, av, [&] {
        auto&& opts = app.configuration();

        return read_config(opts, *cfg).then([&cfg, &db, &qp, &proxy, &ctx, &opts]() {
            uint16_t thrift_port = cfg->rpc_port();
            uint16_t cql_port = cfg->native_transport_port();
            uint16_t api_port = opts["api-port"].as<uint16_t>();
            ctx.api_dir = opts["api-dir"].as<sstring>();
            sstring listen_address = cfg->listen_address();
            sstring rpc_address = cfg->rpc_address();
            auto seed_provider= cfg->seed_provider();
            using namespace locator;
            return i_endpoint_snitch::create_snitch(cfg->endpoint_snitch()).then(
                    [&db, cfg] () {
                return service::init_storage_service().then([&db, cfg] {
                    return db.start(std::move(*cfg)).then([&db] {
                        engine().at_exit([&db] {
                            return db.stop().then([] {
                                return i_endpoint_snitch::stop_snitch();
                            });
                        });
                    });
                });
            }).then([listen_address, seed_provider] {
                return net::init_messaging_service(listen_address, seed_provider);
            }).then([&proxy, &db] {
                return proxy.start(std::ref(db)).then([&proxy] {
                    engine().at_exit([&proxy] { return proxy.stop(); });
                });
            }).then([&db, &proxy, &qp] {
                return qp.start(std::ref(proxy), std::ref(db)).then([&qp] {
                    engine().at_exit([&qp] { return qp.stop(); });
                });
            }).then([&db] {
                return db.invoke_on_all([&proxy] (database& db) {
                    return db.init_from_data_directory();
                });
            }).then([rpc_address] {
                return dns::gethostbyname(rpc_address);
            }).then([&db, &proxy, &qp, cql_port, thrift_port] (dns::hostent e) {
                auto rpc_address = e.addresses[0].in.s_addr;
                auto cserver = new distributed<cql_server>;
                cserver->start(std::ref(proxy), std::ref(qp)).then([server = std::move(cserver), cql_port, rpc_address] () mutable {
                    server->invoke_on_all(&cql_server::listen, ipv4_addr{rpc_address, cql_port});
                }).then([cql_port] {
                    std::cout << "CQL server listening on port " << cql_port << " ...\n";
                });
                auto tserver = new distributed<thrift_server>;
                tserver->start(std::ref(db)).then([server = std::move(tserver), thrift_port, rpc_address] () mutable {
                    server->invoke_on_all(&thrift_server::listen, ipv4_addr{rpc_address, thrift_port});
                }).then([thrift_port] {
                    std::cout << "Thrift server listening on port " << thrift_port << " ...\n";
                });
            }).then([&db, api_port, &ctx]{
                ctx.http_server.start().then([api_port, &ctx] {
                    return set_server(ctx);
                }).then([&ctx, api_port] {
                    ctx.http_server.listen(api_port);
                }).then([api_port] {
                    std::cout << "Seastar HTTP server listening on port " << api_port << " ...\n";
                });
            }).or_terminate();
        });
    });
}
<|endoftext|>


<commit_before>/*
 * Copyright 2011 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "Test.h"
#include "SkAAClip.h"
#include "SkPath.h"
#include "SkRandom.h"

static const SkRegion::Op gRgnOps[] = {
    SkRegion::kDifference_Op,
    SkRegion::kIntersect_Op,
    SkRegion::kUnion_Op,
    SkRegion::kXOR_Op,
    SkRegion::kReverseDifference_Op,
    SkRegion::kReplace_Op
};

static const char* gRgnOpNames[] = {
    "DIFF", "INTERSECT", "UNION", "XOR", "REVERSE_DIFF", "REPLACE"
};

static void imoveTo(SkPath& path, int x, int y) {
    path.moveTo(SkIntToScalar(x), SkIntToScalar(y));
}

static void icubicTo(SkPath& path, int x0, int y0, int x1, int y1, int x2, int y2) {
    path.cubicTo(SkIntToScalar(x0), SkIntToScalar(y0),
                 SkIntToScalar(x1), SkIntToScalar(y1),
                 SkIntToScalar(x2), SkIntToScalar(y2));
}

static void test_path_bounds(skiatest::Reporter* reporter) {
    SkPath path;
    SkAAClip clip;
    const int height = 40;
    const SkScalar sheight = SkIntToScalar(height);

    path.addOval(SkRect::MakeWH(sheight, sheight));
    REPORTER_ASSERT(reporter, sheight == path.getBounds().height());
    clip.setPath(path, NULL, true);
    REPORTER_ASSERT(reporter, height == clip.getBounds().height());

    // this is the trimmed height of this cubic (with aa). The critical thing
    // for this test is that it is less than height, which represents just
    // the bounds of the path's control-points.
    //
    // This used to fail until we tracked the MinY in the BuilderBlitter.
    //
    const int teardrop_height = 12;
    path.reset();
    imoveTo(path, 0, 20);
    icubicTo(path, 40, 40, 40, 0, 0, 20);
    REPORTER_ASSERT(reporter, sheight == path.getBounds().height());
    clip.setPath(path, NULL, true);
    REPORTER_ASSERT(reporter, teardrop_height == clip.getBounds().height());
}

static void test_empty(skiatest::Reporter* reporter) {
    SkAAClip clip0, clip1;

    REPORTER_ASSERT(reporter, clip0.isEmpty());
    REPORTER_ASSERT(reporter, clip0.getBounds().isEmpty());
    REPORTER_ASSERT(reporter, clip1 == clip0);

    clip0.translate(10, 10);    // should have no effect on empty
    REPORTER_ASSERT(reporter, clip0.isEmpty());
    REPORTER_ASSERT(reporter, clip0.getBounds().isEmpty());
    REPORTER_ASSERT(reporter, clip1 == clip0);

    SkIRect r = { 10, 10, 40, 50 };
    clip0.setRect(r);
    REPORTER_ASSERT(reporter, !clip0.isEmpty());
    REPORTER_ASSERT(reporter, !clip0.getBounds().isEmpty());
    REPORTER_ASSERT(reporter, clip0 != clip1);
    REPORTER_ASSERT(reporter, clip0.getBounds() == r);

    clip0.setEmpty();
    REPORTER_ASSERT(reporter, clip0.isEmpty());
    REPORTER_ASSERT(reporter, clip0.getBounds().isEmpty());
    REPORTER_ASSERT(reporter, clip1 == clip0);

    SkMask mask;
    mask.fImage = NULL;
    clip0.copyToMask(&mask);
    REPORTER_ASSERT(reporter, NULL == mask.fImage);
    REPORTER_ASSERT(reporter, mask.fBounds.isEmpty());
}

static void rand_irect(SkIRect* r, int N, SkRandom& rand) {
    r->setXYWH(0, 0, rand.nextU() % N, rand.nextU() % N);
    int dx = rand.nextU() % (2*N);
    int dy = rand.nextU() % (2*N);
    // use int dx,dy to make the subtract be signed
    r->offset(N - dx, N - dy);
}

static void test_irect(skiatest::Reporter* reporter) {
    SkRandom rand;

    for (int i = 0; i < 10000; i++) {
        SkAAClip clip0, clip1;
        SkRegion rgn0, rgn1;
        SkIRect r0, r1;

        rand_irect(&r0, 10, rand);
        rand_irect(&r1, 10, rand);
        clip0.setRect(r0);
        clip1.setRect(r1);
        rgn0.setRect(r0);
        rgn1.setRect(r1);
        for (size_t j = 0; j < SK_ARRAY_COUNT(gRgnOps); ++j) {
            SkRegion::Op op = gRgnOps[j];
            SkAAClip clip2;
            SkRegion rgn2;
            bool nonEmptyAA = clip2.op(clip0, clip1, op);
            bool nonEmptyBW = rgn2.op(rgn0, rgn1, op);
            if (nonEmptyAA != nonEmptyBW || clip2.getBounds() != rgn2.getBounds()) {
                SkDebugf("[%d %d %d %d] %s [%d %d %d %d] = BW:[%d %d %d %d] AA:[%d %d %d %d]\n",
                         r0.fLeft, r0.fTop, r0.right(), r0.bottom(),
                         gRgnOpNames[j],
                         r1.fLeft, r1.fTop, r1.right(), r1.bottom(),
                         rgn2.getBounds().fLeft, rgn2.getBounds().fTop,
                         rgn2.getBounds().right(), rgn2.getBounds().bottom(),
                         clip2.getBounds().fLeft, clip2.getBounds().fTop,
                         clip2.getBounds().right(), clip2.getBounds().bottom());
            }
            REPORTER_ASSERT(reporter, nonEmptyAA == nonEmptyBW);
            REPORTER_ASSERT(reporter, clip2.getBounds() == rgn2.getBounds());
        }
    }
}

static void TestAAClip(skiatest::Reporter* reporter) {
    test_empty(reporter);
    test_path_bounds(reporter);
    test_irect(reporter);
}

#include "TestClassDef.h"
DEFINE_TESTCLASS("AAClip", AAClipTestClass, TestAAClip)
<commit_msg>add test that aaclip.setRegion creates the same mask as the region ... in prep for optimizatin work on setRegion.<commit_after>/*
 * Copyright 2011 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "Test.h"
#include "SkAAClip.h"
#include "SkCanvas.h"
#include "SkMask.h"
#include "SkPath.h"
#include "SkRandom.h"

static bool operator==(const SkMask& a, const SkMask& b) {
    if (a.fFormat != b.fFormat || a.fBounds != b.fBounds) {
        return false;
    }
    if (!a.fImage && !b.fImage) {
        return true;
    }
    if (!a.fImage || !b.fImage) {
        return false;
    }

    size_t wbytes = a.fBounds.width();
    switch (a.fFormat) {
        case SkMask::kBW_Format:
            wbytes = (wbytes + 7) >> 3;
            break;
        case SkMask::kA8_Format:
        case SkMask::k3D_Format:
            break;
        case SkMask::kLCD16_Format:
            wbytes <<= 1;
            break;
        case SkMask::kLCD32_Format:
        case SkMask::kARGB32_Format:
            wbytes <<= 2;
            break;
        default:
            SkASSERT(!"unknown mask format");
            return false;
    }

    const int h = a.fBounds.height();
    const char* aptr = (const char*)a.fImage;
    const char* bptr = (const char*)b.fImage;
    for (int y = 0; y < h; ++y) {
        if (memcmp(aptr, bptr, wbytes)) {
            return false;
        }
        aptr += wbytes;
        bptr += wbytes;
    }
    return true;
}

static void copyToMask(const SkRegion& rgn, SkMask* mask) {
    if (rgn.isEmpty()) {
        mask->fImage = NULL;
        mask->fBounds.setEmpty();
        mask->fRowBytes = 0;
        return;
    }

    mask->fBounds = rgn.getBounds();
    mask->fRowBytes = mask->fBounds.width();
    mask->fFormat = SkMask::kA8_Format;
    mask->fImage = SkMask::AllocImage(mask->computeImageSize());
    sk_bzero(mask->fImage, mask->computeImageSize());

    SkBitmap bitmap;
    bitmap.setConfig(SkBitmap::kA8_Config, mask->fBounds.width(),
                     mask->fBounds.height(), mask->fRowBytes);
    bitmap.setPixels(mask->fImage);

    // canvas expects its coordinate system to always be 0,0 in the top/left
    // so we translate the rgn to match that before drawing into the mask.
    //
    SkRegion tmpRgn(rgn);
    tmpRgn.translate(-rgn.getBounds().fLeft, -rgn.getBounds().fTop);

    SkCanvas canvas(bitmap);
    canvas.clipRegion(tmpRgn);
    canvas.drawColor(SK_ColorBLACK);
}

static SkIRect rand_rect(SkRandom& rand, int n) {
    int x = rand.nextS() % n;
    int y = rand.nextS() % n;
    int w = rand.nextU() % n;
    int h = rand.nextU() % n;
    return SkIRect::MakeXYWH(x, y, w, h);
}

static void make_rand_rgn(SkRegion* rgn, SkRandom& rand) {
    int count = rand.nextU() % 20;
    for (int i = 0; i < count; ++i) {
        rgn->op(rand_rect(rand, 100), SkRegion::kXOR_Op);
    }
}

// aaclip.setRegion should create idential masks to the region
static void test_rgn(skiatest::Reporter* reporter) {
    SkRandom rand;
    for (int i = 0; i < 1000; i++) {
        SkRegion rgn;
        make_rand_rgn(&rgn, rand);
        SkMask mask0;
        copyToMask(rgn, &mask0);
        SkAAClip aaclip;
        aaclip.setRegion(rgn);
        SkMask mask1;
        aaclip.copyToMask(&mask1);

        REPORTER_ASSERT(reporter, mask0 == mask1);

        SkMask::FreeImage(mask0.fImage);
        SkMask::FreeImage(mask1.fImage);
    }
}

static const SkRegion::Op gRgnOps[] = {
    SkRegion::kDifference_Op,
    SkRegion::kIntersect_Op,
    SkRegion::kUnion_Op,
    SkRegion::kXOR_Op,
    SkRegion::kReverseDifference_Op,
    SkRegion::kReplace_Op
};

static const char* gRgnOpNames[] = {
    "DIFF", "INTERSECT", "UNION", "XOR", "REVERSE_DIFF", "REPLACE"
};

static void imoveTo(SkPath& path, int x, int y) {
    path.moveTo(SkIntToScalar(x), SkIntToScalar(y));
}

static void icubicTo(SkPath& path, int x0, int y0, int x1, int y1, int x2, int y2) {
    path.cubicTo(SkIntToScalar(x0), SkIntToScalar(y0),
                 SkIntToScalar(x1), SkIntToScalar(y1),
                 SkIntToScalar(x2), SkIntToScalar(y2));
}

static void test_path_bounds(skiatest::Reporter* reporter) {
    SkPath path;
    SkAAClip clip;
    const int height = 40;
    const SkScalar sheight = SkIntToScalar(height);

    path.addOval(SkRect::MakeWH(sheight, sheight));
    REPORTER_ASSERT(reporter, sheight == path.getBounds().height());
    clip.setPath(path, NULL, true);
    REPORTER_ASSERT(reporter, height == clip.getBounds().height());

    // this is the trimmed height of this cubic (with aa). The critical thing
    // for this test is that it is less than height, which represents just
    // the bounds of the path's control-points.
    //
    // This used to fail until we tracked the MinY in the BuilderBlitter.
    //
    const int teardrop_height = 12;
    path.reset();
    imoveTo(path, 0, 20);
    icubicTo(path, 40, 40, 40, 0, 0, 20);
    REPORTER_ASSERT(reporter, sheight == path.getBounds().height());
    clip.setPath(path, NULL, true);
    REPORTER_ASSERT(reporter, teardrop_height == clip.getBounds().height());
}

static void test_empty(skiatest::Reporter* reporter) {
    SkAAClip clip0, clip1;

    REPORTER_ASSERT(reporter, clip0.isEmpty());
    REPORTER_ASSERT(reporter, clip0.getBounds().isEmpty());
    REPORTER_ASSERT(reporter, clip1 == clip0);

    clip0.translate(10, 10);    // should have no effect on empty
    REPORTER_ASSERT(reporter, clip0.isEmpty());
    REPORTER_ASSERT(reporter, clip0.getBounds().isEmpty());
    REPORTER_ASSERT(reporter, clip1 == clip0);

    SkIRect r = { 10, 10, 40, 50 };
    clip0.setRect(r);
    REPORTER_ASSERT(reporter, !clip0.isEmpty());
    REPORTER_ASSERT(reporter, !clip0.getBounds().isEmpty());
    REPORTER_ASSERT(reporter, clip0 != clip1);
    REPORTER_ASSERT(reporter, clip0.getBounds() == r);

    clip0.setEmpty();
    REPORTER_ASSERT(reporter, clip0.isEmpty());
    REPORTER_ASSERT(reporter, clip0.getBounds().isEmpty());
    REPORTER_ASSERT(reporter, clip1 == clip0);

    SkMask mask;
    mask.fImage = NULL;
    clip0.copyToMask(&mask);
    REPORTER_ASSERT(reporter, NULL == mask.fImage);
    REPORTER_ASSERT(reporter, mask.fBounds.isEmpty());
}

static void rand_irect(SkIRect* r, int N, SkRandom& rand) {
    r->setXYWH(0, 0, rand.nextU() % N, rand.nextU() % N);
    int dx = rand.nextU() % (2*N);
    int dy = rand.nextU() % (2*N);
    // use int dx,dy to make the subtract be signed
    r->offset(N - dx, N - dy);
}

static void test_irect(skiatest::Reporter* reporter) {
    SkRandom rand;

    for (int i = 0; i < 10000; i++) {
        SkAAClip clip0, clip1;
        SkRegion rgn0, rgn1;
        SkIRect r0, r1;

        rand_irect(&r0, 10, rand);
        rand_irect(&r1, 10, rand);
        clip0.setRect(r0);
        clip1.setRect(r1);
        rgn0.setRect(r0);
        rgn1.setRect(r1);
        for (size_t j = 0; j < SK_ARRAY_COUNT(gRgnOps); ++j) {
            SkRegion::Op op = gRgnOps[j];
            SkAAClip clip2;
            SkRegion rgn2;
            bool nonEmptyAA = clip2.op(clip0, clip1, op);
            bool nonEmptyBW = rgn2.op(rgn0, rgn1, op);
            if (nonEmptyAA != nonEmptyBW || clip2.getBounds() != rgn2.getBounds()) {
                SkDebugf("[%d %d %d %d] %s [%d %d %d %d] = BW:[%d %d %d %d] AA:[%d %d %d %d]\n",
                         r0.fLeft, r0.fTop, r0.right(), r0.bottom(),
                         gRgnOpNames[j],
                         r1.fLeft, r1.fTop, r1.right(), r1.bottom(),
                         rgn2.getBounds().fLeft, rgn2.getBounds().fTop,
                         rgn2.getBounds().right(), rgn2.getBounds().bottom(),
                         clip2.getBounds().fLeft, clip2.getBounds().fTop,
                         clip2.getBounds().right(), clip2.getBounds().bottom());
            }
            REPORTER_ASSERT(reporter, nonEmptyAA == nonEmptyBW);
            REPORTER_ASSERT(reporter, clip2.getBounds() == rgn2.getBounds());
        }
    }
}

static void TestAAClip(skiatest::Reporter* reporter) {
    test_empty(reporter);
    test_path_bounds(reporter);
    test_irect(reporter);
    test_rgn(reporter);
}

#include "TestClassDef.h"
DEFINE_TESTCLASS("AAClip", AAClipTestClass, TestAAClip)
<|endoftext|>


<commit_before>be1d1991-ad5c-11e7-8a55-ac87a332f658<commit_msg>Deal with it<commit_after>bef5c7b8-ad5c-11e7-bccd-ac87a332f658<|endoftext|>


<commit_before>#include <cstdlib>

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

#include "fasta_parser.h"
#include "sa_is.h"
#include "search.h"

struct suffix {
  unsigned int index;
  std::string suffix_string;
};

bool compare(suffix i, suffix j) {
  return i.suffix_string < j.suffix_string ;
}

// Creates a sufix array for the given string using a simple and slow method
void suffix_array(std::string str, std::vector<int> &sa) {
  std::vector<suffix> suffixes;

  for (unsigned int i = 0; i < str.size(); ++i) {
    suffix *s = new suffix;
    s->index = i;
    s->suffix_string = str.substr(i);
    suffixes.push_back(*s);
    delete s;
  }

  std::sort(suffixes.begin(), suffixes.end(), compare);
  for (unsigned int i = 0; i < suffixes.size(); ++i) {
    sa.push_back(suffixes[i].index);
  }
}

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

  if(argc != 5) {
    std::cerr << "Usage: " << argv[1] << " <file containing reference string>" << std::endl;
		std::cerr << "Usage: " << argv[2] << " <file containing query string>" << std::endl;
		std::cerr << "Usage: " << argv[3] << " <index level of sparseSA, K-SA>" << std::endl;
		std::cerr << "Usage: " << argv[4] << " <size of minimal match>" << std::endl;

    exit(-1);
  }

  std::ifstream ref_file(argv[1]);
	std::ifstream query_file(argv[2]);

  if(!ref_file.is_open()) {
    std::cerr << "There was a problem openning the file \"" << argv[1] << "\"!\nAborting." << std::endl;
    exit(-2);
  }

  if(!query_file.is_open()) {
    std::cerr << "There was a problem openning the file \"" << argv[2] << "\"!\nAborting." << std::endl;
    exit(-2);
  }

  // Read in reference string (fasta format)
	std::string ref_string;
	std::vector<string> refdescr;
	std::vector<long> startpos;
	fasta_parser(argv[1], ref_string, refdescr, startpos);

  // Read in query string (fasta format)
	std::string query_string;
	std::vector<string> querydescr;
	std::vector<long> q_startpos;
  fasta_parser(argv[2], query_string, querydescr, q_startpos);

  int K = atoi(argv[3]);
  int L = atoi(argv[4]);
  int N = ref_string.length();

  std::vector<int> sa;
  sa.reserve(N);
  bool *types = new bool[N];

  suffix_array(ref_string, sa);
  type_array(ref_string.c_str(), types, N, sizeof(char));
  /*
  for (unsigned int i = 0; i < sa.size() - 1; ++i) {
    std::cout << "[" << i << "]\t" << sa[i] << (types[sa[i]] ? "\tS\t" : "\tL\t")
    << ref_string.substr(sa[i]) << std::endl;
  }
  */
  int *SA = new int[N];
  int *sparseSA = new int[N / K + 1];
  int *sparseISA = new int[N / K + 1];
  int *sparseLCP = new int[N / K + 1];

  // Creates Suffix Array using SA_IS algorithm
  sa_is(ref_string.c_str(), SA, N, 256, sizeof(char));

  // Generate Sparse Suffix Array
  for (int i = 0; i < N / K; ++i) {
    sparseSA[i] = SA[i * K];
  }

  // Generate ISA
  for(long i = 0; i < N/K; i++) {
    sparseISA[sparseSA[i]/K] = i;
  }

  // Generate LCP
  int h = 0;
  for(int i = 0; i < N/K ; i+=K) {
    int m = sparseISA[i];
    if(m==0) {
      sparseLCP[m] = 0;
    }
    else {
      int j = sparseSA[m-1];
      while(i+h < N && j+h < N && ref_string[i+h] == ref_string[j+h]) {
        h++;
      }
      sparseLCP[m] = h;
    }
    h = std::max(0, h - K);
  }

  printf("\nSparse SA: ");
  for (int i = 0; i < N/K; ++i)
    printf("%d ", sparseSA[i]);

  printf("\nSparse ISA: ");
  for (int i = 0; i < N/K; ++i)
    printf("%d ", sparseISA[i]);

  printf("\nSparse LCP: ");
  for (int i = 0; i < N/K; ++i)
    printf("%d ", sparseLCP[i]);
  printf("\n");

  // Search for MEMs:
  printf("\tRef.\tQuery\tLength\n");
  int p0 = 0;
  MEM(p0, ref_string, sparseISA, sparseLCP, sparseSA, query_string, K, N, L);

  return 0;
}

<commit_msg>solved core dump<commit_after>#include <cstdlib>

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

#include "fasta_parser.h"
#include "sa_is.h"
#include "search.h"

struct suffix {
  unsigned int index;
  std::string suffix_string;
};

bool compare(suffix i, suffix j) {
  return i.suffix_string < j.suffix_string ;
}

// Creates a sufix array for the given string using a simple and slow method
void suffix_array(std::string str, std::vector<int> &sa) {
  std::vector<suffix> suffixes;

  for (unsigned int i = 0; i < str.size(); ++i) {
    suffix *s = new suffix;
    s->index = i;
    s->suffix_string = str.substr(i);
    suffixes.push_back(*s);
    delete s;
  }

  std::sort(suffixes.begin(), suffixes.end(), compare);
  for (unsigned int i = 0; i < suffixes.size(); ++i) {
    sa.push_back(suffixes[i].index);
  }
}

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

  if(argc != 5) {
    std::cerr << "Usage: " << argv[1] << " <file containing reference string>" << std::endl;
		std::cerr << "Usage: " << argv[2] << " <file containing query string>" << std::endl;
		std::cerr << "Usage: " << argv[3] << " <index level of sparseSA, K-SA>" << std::endl;
		std::cerr << "Usage: " << argv[4] << " <size of minimal match>" << std::endl;

    exit(-1);
  }

  std::ifstream ref_file(argv[1]);
	std::ifstream query_file(argv[2]);

  if(!ref_file.is_open()) {
    std::cerr << "There was a problem openning the file \"" << argv[1] << "\"!\nAborting." << std::endl;
    exit(-2);
  }

  if(!query_file.is_open()) {
    std::cerr << "There was a problem openning the file \"" << argv[2] << "\"!\nAborting." << std::endl;
    exit(-2);
  }

  // Read in reference string (fasta format)
	std::string ref_string;
	std::vector<string> refdescr;
	std::vector<long> startpos;
	fasta_parser(argv[1], ref_string, refdescr, startpos);

  // Read in query string (fasta format)
	std::string query_string;
	std::vector<string> querydescr;
	std::vector<long> q_startpos;
  fasta_parser(argv[2], query_string, querydescr, q_startpos);

  int K = atoi(argv[3]);
  int L = atoi(argv[4]);
  int N = ref_string.length();

  std::vector<int> sa;
  sa.reserve(N);
  bool *types = new bool[N];

  suffix_array(ref_string, sa);
  type_array(ref_string.c_str(), types, N, sizeof(char));

  for (unsigned int i = 0; i < sa.size() ; ++i) {
    std::cout << "[" << i << "]\t" << sa[i] << (types[sa[i]] ? "\tS\t" : "\tL\t")
    << ref_string.substr(sa[i]) << std::endl;
  }

  int *SA = new int[N];
  int *sparseSA = new int[N / K];
  int *sparseISA = new int[N / K];
  int *sparseLCP = new int[N / K];

  // Creates Suffix Array using SA_IS algorithm
  sa_is(ref_string.c_str(), SA, N, 256, sizeof(char));

  // Generate Sparse Suffix Array
  for (int i = 0; i < N / K; ++i) {
    sparseSA[i] = SA[i * K];
  }

  // Generate ISA
  for(long i = 0; i < N/K; i++) {
    sparseISA[sparseSA[i]/K] = i;
  }

  // Generate LCP
  int h = 0;
  for(int i = 0; i < N/K ; i+=K) {
    int m = sparseISA[i];
    if(m==0) {
      sparseLCP[m] = 0;
    }
    else {
      int j = sparseSA[m-1];
      while(i+h < N && j+h < N && ref_string[i+h] == ref_string[j+h]) {
        h++;
      }
      sparseLCP[m] = h;
    }
    h = std::max(0, h - K);
  }

  printf("\nSparse SA: ");
  for (int i = 0; i < N/K; ++i)
    printf("%d ", sparseSA[i]);

  printf("\nSparse ISA: ");
  for (int i = 0; i < N/K; ++i)
    printf("%d ", sparseISA[i]);

  printf("\nSparse LCP: ");
  for (int i = 0; i < N/K; ++i)
    printf("%d ", sparseLCP[i]);
  printf("\n");

  // Search for MEMs:
  printf("\tRef.\tQuery\tLength\n");
  int p0 = 0;
  MEM(p0, ref_string, sparseISA, sparseLCP, sparseSA, query_string, K, N, L);

  return 0;
}

<|endoftext|>


<commit_before>df597fb3-2747-11e6-8be8-e0f84713e7b8<commit_msg>I hope I am done<commit_after>df691d40-2747-11e6-a3d9-e0f84713e7b8<|endoftext|>


<commit_before>

#include <iostream>

#include "tmx.h"

#define DEPTH_SCALE 5

#define printf_depth( depth, format, ... ) \
	printf("%*s " format "\n", ((depth)*DEPTH_SCALE), "", __VA_ARGS__)

void printProperties(int depth, const TmxParser::TmxPropertyMap_t& map)
{
	printf_depth(depth, "%s", "<properties>");
	for (auto it = map.begin(); it != map.end(); ++it)
	{
		printf_depth(depth+1, "%s=%s", it->first.c_str(), it->second.c_str());
	}
}

void printImageData(int depth, const TmxParser::TmxImage& tmximage)
{
	printf_depth(depth, "%s", "<image>");

	depth = depth +1;
	printf_depth(depth, "Source: %s", tmximage.source.c_str());
	printf_depth(depth, "Format: %s", tmximage.format.c_str());
	printf_depth(depth, "Width: %u", tmximage.width);
	printf_depth(depth, "Height: %u", tmximage.height);
	printf_depth(depth, "TransparentColor: %s", tmximage.transparentColor.c_str());
}

void printTileDefinition(int depth, const TmxParser::TmxTileDefinitionCollection_t& collection)
{
	for (auto it = collection.begin(); it != collection.end(); ++it)
	{
		printf_depth(depth, "%s", "<tile>");
		printf_depth(depth+1, "Id: %u", it->id);
		printProperties(depth+1, it->propertyMap);
	}
}

void printTilesets(int depth, const TmxParser::TmxTilesetCollection_t& collection)
{
	for (auto it = collection.begin(); it != collection.end(); ++it)
	{
		printf_depth(depth, "%s", "<tileset>");

		depth = depth + 1;

		printf_depth(depth, "Name: %s", (*it).name.c_str());
		printf_depth(depth, "FirstGid: %u", (*it).firstgid);
		printf_depth(depth, "Width: %u", (*it).tileWidth);
		printf_depth(depth, "Height: %u", (*it).tileHeight);
		printf_depth(depth, "MarginImage: %u", (*it).tileMarginInImage);
		printf_depth(depth, "SpaceImage: %u", (*it).tileSpacingInImage);
		printImageData(depth, (*it).image);
		printTileDefinition(depth, (*it)._tiles);
	}
}

void printLayers(int depth, const TmxParser::TmxLayerCollection_t& collection)
{
	for (auto it = collection.begin(); it != collection.end(); ++it)
	{
		printf_depth(depth, "%s", "<layer>");

		depth = depth + 1;

		printf_depth(depth, "Name: %s", it->name.c_str());
		printf_depth(depth, "Width: %u", (*it).width);
		printf_depth(depth, "Height: %u", (*it).height);
		printf_depth(depth, "Opacity: %f", (*it).opacity);
		printf_depth(depth, "Visible: %u", (*it).visible);
		printProperties(depth+1, it->propertyMap);
	}
}

void printTmxMapData(const TmxParser::TmxMap* map)
{
	int depth = 0;

	printf_depth(0, "%s", "<map>");
	depth = 1;
	printf_depth(depth, "Version: %s", map->version.c_str());
	printf_depth(depth, "Orientation: %s", map->orientation.c_str());
	printf_depth(depth, "Width: %u", map->width);
	printf_depth(depth, "Height: %u", map->height);
	printf_depth(depth, "TileWidth: %u", map->tileWidth);
	printf_depth(depth, "TileHeight: %u", map->tileHeight);
	printf_depth(depth, "BackgroundColor: %s", map->backgroundColor.c_str());
	printProperties(depth+1, map->propertyMap);
	printTilesets(depth+1, map->tilesetCollection);
	printLayers(depth+1, map->layerCollection);
}

int main()
{
	std::cout << "Hello World" << std::endl;

	TmxParser::Tmx tmx;
	std::unique_ptr<TmxParser::TmxMap> map = tmx.parseFromFile("example.tmx");

	printTmxMapData(map.get());

	return 0;
}

<commit_msg>- fixed all functions depth wise - printing entire map with all xml encoding for data nodes<commit_after>

#include <iostream>

#include "tmx.h"

#define DEPTH_SCALE 5

#define printf_depth( depth, format, ... ) \
	printf("%*s " format "\n", ((depth)*DEPTH_SCALE), "", __VA_ARGS__)

void printProperties(int depth, const TmxParser::TmxPropertyMap_t& map)
{
	printf_depth(depth, "%s", "<properties>");
	for (auto it = map.begin(); it != map.end(); ++it)
	{
		printf_depth(depth+1, "%s=%s", it->first.c_str(), it->second.c_str());
	}
}

void printImageData(int depth, const TmxParser::TmxImage& tmximage)
{
	printf_depth(depth, "%s", "<image>");

	depth = depth +1;
	printf_depth(depth, "Source: %s", tmximage.source.c_str());
	printf_depth(depth, "Format: %s", tmximage.format.c_str());
	printf_depth(depth, "Width: %u", tmximage.width);
	printf_depth(depth, "Height: %u", tmximage.height);
	printf_depth(depth, "TransparentColor: %s", tmximage.transparentColor.c_str());
}

void printTileDefinition(int depth, const TmxParser::TmxTileDefinitionCollection_t& collection)
{
	for (auto it = collection.begin(); it != collection.end(); ++it)
	{
		printf_depth(depth, "%s", "<tile>");
		printf_depth(depth+1, "Id: %u", it->id);
		printProperties(depth+1, it->propertyMap);
	}
}

void printTilesets(int depth, const TmxParser::TmxTilesetCollection_t& collection)
{
	for (auto it = collection.begin(); it != collection.end(); ++it)
	{
		printf_depth(depth, "%s", "<tileset>");

		int nextdepth = depth + 1;

		printf_depth(nextdepth, "Name: %s", (*it).name.c_str());
		printf_depth(nextdepth, "FirstGid: %u", (*it).firstgid);
		printf_depth(nextdepth, "Width: %u", (*it).tileWidth);
		printf_depth(nextdepth, "Height: %u", (*it).tileHeight);
		printf_depth(nextdepth, "MarginImage: %u", (*it).tileMarginInImage);
		printf_depth(nextdepth, "SpaceImage: %u", (*it).tileSpacingInImage);
		printImageData(nextdepth, (*it).image);
		printTileDefinition(nextdepth, (*it)._tiles);
	}
}

void printLayerTiles(int depth, const TmxParser::TmxLayerTileCollection_t& collection)
{
	for (auto it = collection.begin(); it != collection.end(); ++it)
	{
		printf_depth(depth, "%s", "<tile>");

		int nextdepth = depth + 1;

		printf_depth(nextdepth, "Gid: %u", it->gid);
	}
}

void printLayers(int depth, const TmxParser::TmxLayerCollection_t& collection)
{
	for (auto it = collection.begin(); it != collection.end(); ++it)
	{
		printf_depth(depth, "%s", "<layer>");

		int nextdepth = depth + 1;

		printf_depth(nextdepth, "Name: %s", it->name.c_str());
		printf_depth(nextdepth, "Width: %u", (*it).width);
		printf_depth(nextdepth, "Height: %u", (*it).height);
		printf_depth(nextdepth, "Opacity: %f", (*it).opacity);
		printf_depth(nextdepth, "Visible: %u", (*it).visible);
		printProperties(nextdepth+1, it->propertyMap);
		printLayerTiles(nextdepth+1, it->tiles);
	}
}

void printTmxMapData(const TmxParser::TmxMap* map)
{
	int depth = 0;

	printf_depth(0, "%s", "<map>");
	depth = 1;
	printf_depth(depth, "Version: %s", map->version.c_str());
	printf_depth(depth, "Orientation: %s", map->orientation.c_str());
	printf_depth(depth, "Width: %u", map->width);
	printf_depth(depth, "Height: %u", map->height);
	printf_depth(depth, "TileWidth: %u", map->tileWidth);
	printf_depth(depth, "TileHeight: %u", map->tileHeight);
	printf_depth(depth, "BackgroundColor: %s", map->backgroundColor.c_str());
	printProperties(depth+1, map->propertyMap);
	printTilesets(depth+1, map->tilesetCollection);
	printLayers(depth+1, map->layerCollection);
}

int main()
{
	std::cout << "Hello World" << std::endl;

	TmxParser::Tmx tmx;
	std::unique_ptr<TmxParser::TmxMap> map = tmx.parseFromFile("example.tmx");

	printTmxMapData(map.get());

	return 0;
}

<|endoftext|>


<commit_before>794a5c30-ad58-11e7-904c-ac87a332f658<commit_msg>more fixes<commit_after>79ae4ce1-ad58-11e7-bd49-ac87a332f658<|endoftext|>


<commit_before>a22690f3-4b02-11e5-ae16-28cfe9171a43<commit_msg>Did ANOTHER thing<commit_after>a233784f-4b02-11e5-888f-28cfe9171a43<|endoftext|>


<commit_before>b3619dba-2747-11e6-9748-e0f84713e7b8<commit_msg>Typical bobby<commit_after>b379f5a3-2747-11e6-af72-e0f84713e7b8<|endoftext|>


<commit_before>d469ae70-4b02-11e5-9c3d-28cfe9171a43<commit_msg>this is my first commit?<commit_after>d4764ee6-4b02-11e5-8baa-28cfe9171a43<|endoftext|>