<commit_before>#pragma once

#include "../condition_manager.hpp"
#include "../types.hpp"
#include "event_queue.hpp"
#include "modifier_flag_manager.hpp"

namespace krbn {
namespace manipulator {
namespace manipulators {
class base {
protected:
  base(void) : valid_(true) {
  }

public:
  virtual ~base(void) {
  }

  virtual bool already_manipulated(const event_queue::entry& front_input_event) = 0;

  virtual manipulate_result manipulate(event_queue::entry& front_input_event,
                                       const event_queue::queue& input_event_queue,
                                       std::shared_ptr<event_queue::queue> output_event_queue,
                                       absolute_time_point now) = 0;

  virtual bool active(void) const = 0;

  virtual bool needs_virtual_hid_pointing(void) const = 0;

  virtual void handle_device_keys_and_pointing_buttons_are_released_event(const event_queue::entry& front_input_event,
                                                                          event_queue::queue& output_event_queue) = 0;

  virtual void handle_device_ungrabbed_event(device_id device_id,
                                             const event_queue::queue& output_event_queue,
                                             absolute_time_point time_stamp) = 0;

  virtual void handle_pointing_device_event_from_event_tap(const event_queue::entry& front_input_event,
                                                           event_queue::queue& output_event_queue) = 0;

  bool get_valid(void) const {
    return valid_;
  }
  virtual void set_valid(bool value) {
    valid_ = value;
  }

  void push_back_condition(std::shared_ptr<manipulator::conditions::base> condition) {
    condition_manager_.push_back_condition(condition);
  }

  static void post_lazy_modifier_key_events(const std::unordered_set<modifier_flag>& modifiers,
                                            event_type event_type,
                                            device_id device_id,
                                            const event_queue::event_time_stamp& event_time_stamp,
                                            absolute_time_duration& time_stamp_delay,
                                            const event_queue::event& original_event,
                                            event_queue::queue& output_event_queue) {
    for (const auto& m : modifiers) {
      momentary_switch_event e(m);
      if (e.valid()) {
        auto t = event_time_stamp;
        t.set_time_stamp(t.get_time_stamp() + time_stamp_delay++);

        event_queue::entry event(device_id,
                                 t,
                                 event_queue::event(e),
                                 event_type,
                                 original_event,
                                 event_queue::state::manipulated,
                                 true);
        output_event_queue.push_back_entry(event);
      }
    }
  }

protected:
  bool valid_;
  condition_manager condition_manager_;
};
} // namespace manipulators
} // namespace manipulator
} // namespace krbn
<commit_msg>Add manipulators::base::post_lazy_modifier_key_event<commit_after>#pragma once

#include "../condition_manager.hpp"
#include "../types.hpp"
#include "event_queue.hpp"
#include "modifier_flag_manager.hpp"

namespace krbn {
namespace manipulator {
namespace manipulators {
class base {
protected:
  base(void) : valid_(true) {
  }

public:
  virtual ~base(void) {
  }

  virtual bool already_manipulated(const event_queue::entry& front_input_event) = 0;

  virtual manipulate_result manipulate(event_queue::entry& front_input_event,
                                       const event_queue::queue& input_event_queue,
                                       std::shared_ptr<event_queue::queue> output_event_queue,
                                       absolute_time_point now) = 0;

  virtual bool active(void) const = 0;

  virtual bool needs_virtual_hid_pointing(void) const = 0;

  virtual void handle_device_keys_and_pointing_buttons_are_released_event(const event_queue::entry& front_input_event,
                                                                          event_queue::queue& output_event_queue) = 0;

  virtual void handle_device_ungrabbed_event(device_id device_id,
                                             const event_queue::queue& output_event_queue,
                                             absolute_time_point time_stamp) = 0;

  virtual void handle_pointing_device_event_from_event_tap(const event_queue::entry& front_input_event,
                                                           event_queue::queue& output_event_queue) = 0;

  bool get_valid(void) const {
    return valid_;
  }
  virtual void set_valid(bool value) {
    valid_ = value;
  }

  void push_back_condition(std::shared_ptr<manipulator::conditions::base> condition) {
    condition_manager_.push_back_condition(condition);
  }

  static void post_lazy_modifier_key_events(const std::unordered_set<modifier_flag>& modifiers,
                                            event_type event_type,
                                            device_id device_id,
                                            const event_queue::event_time_stamp& event_time_stamp,
                                            absolute_time_duration& time_stamp_delay,
                                            const event_queue::event& original_event,
                                            event_queue::queue& output_event_queue) {
    for (const auto& m : modifiers) {
      post_lazy_modifier_key_event(m,
                                   event_type,
                                   device_id,
                                   event_time_stamp,
                                   time_stamp_delay,
                                   original_event,
                                   output_event_queue);
    }
  }

  static void post_lazy_modifier_key_event(modifier_flag modifier_flag,
                                           event_type event_type,
                                           device_id device_id,
                                           const event_queue::event_time_stamp& event_time_stamp,
                                           absolute_time_duration& time_stamp_delay,
                                           const event_queue::event& original_event,
                                           event_queue::queue& output_event_queue) {
    momentary_switch_event e(modifier_flag);
    if (e.valid()) {
      auto t = event_time_stamp;
      t.set_time_stamp(t.get_time_stamp() + time_stamp_delay++);

      event_queue::entry event(device_id,
                               t,
                               event_queue::event(e),
                               event_type,
                               original_event,
                               event_queue::state::manipulated,
                               true);
      output_event_queue.push_back_entry(event);
    }
  }

protected:
  bool valid_;
  condition_manager condition_manager_;
};
} // namespace manipulators
} // namespace manipulator
} // namespace krbn
<|endoftext|>


<commit_before>acd264de-2747-11e6-a475-e0f84713e7b8<commit_msg>updated some files<commit_after>acdb1661-2747-11e6-9026-e0f84713e7b8<|endoftext|>


<commit_before>#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <fstream>
#include <stdexcept>
#include "source.hpp"
#include "lexer.hpp"
#include "parser.hpp"
#include "pprint/c_pprint.hpp"

static const char PROGNAME[] = "bfc";
static const char FILETYPE[] = "bf";
static const size_t FILETYPE_LEN = 2;
// TODO: add version number (requires configure setup)

using namespace bfc;

static void
print_usage(FILE *out)
{
  fprintf(out, "usage: %s <source-file>\n", PROGNAME);
}

static void
print_filename_error(FILE *out)
{
  fprintf(out, "file must be of type %s\n", FILETYPE);
}

static int
handle_filepath(const char *filepath)
{
  size_t len = strlen(filepath);
  if (filepath[len - FILETYPE_LEN - 1] != '.'){
    print_filename_error(stderr);
    return -1;
  }

  for (size_t i = FILETYPE_LEN ; i > 0; --i){
    if (filepath[len - i] != FILETYPE[FILETYPE_LEN - i]){
      print_filename_error(stderr);
      return -1;
    }
  }

  parser<stream_source> parser{
    lexer<stream_source>{stream_source{new std::fstream{filepath}}}};
  try
  {
    ast_node astNode= parser.parse();
  }
  catch (std::runtime_error& e)
  {
    printf("%s", e.what());
    return -2;
  }
  pprint::c_pprint printer{};
  std::ofstream output{std::string{filepath} + ".c"};
  printer.emit(output, astNode);

  return 0;
}

int
main(int argc, const char *const *argv)
{
  if (argc != 2) {
    print_usage(stderr);
    exit(EXIT_FAILURE);
  }

  handle_filepath(argv[1]);

  return 0;
}
<commit_msg>I messed up the try catch too<commit_after>#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <fstream>
#include <stdexcept>
#include "source.hpp"
#include "lexer.hpp"
#include "parser.hpp"
#include "pprint/c_pprint.hpp"

static const char PROGNAME[] = "bfc";
static const char FILETYPE[] = "bf";
static const size_t FILETYPE_LEN = 2;
// TODO: add version number (requires configure setup)

using namespace bfc;

static void
print_usage(FILE *out)
{
  fprintf(out, "usage: %s <source-file>\n", PROGNAME);
}

static void
print_filename_error(FILE *out)
{
  fprintf(out, "file must be of type %s\n", FILETYPE);
}

static int
handle_filepath(const char *filepath)
{
  size_t len = strlen(filepath);
  if (filepath[len - FILETYPE_LEN - 1] != '.'){
    print_filename_error(stderr);
    return -1;
  }

  for (size_t i = FILETYPE_LEN ; i > 0; --i){
    if (filepath[len - i] != FILETYPE[FILETYPE_LEN - i]){
      print_filename_error(stderr);
      return -1;
    }
  }

  parser<stream_source> parser{
    lexer<stream_source>{stream_source{new std::fstream{filepath}}}};
  try
  {
    ast_node astNode = parser.parse();
    pprint::c_pprint printer{};
    std::ofstream output{std::string{filepath} + ".c"};
    printer.emit(output, astNode);
  }
  catch (std::runtime_error& e)
  {
    printf("%s", e.what());
    return -2;
  }

  return 0;
}

int
main(int argc, const char *const *argv)
{
  if (argc != 2) {
    print_usage(stderr);
    exit(EXIT_FAILURE);
  }

  handle_filepath(argv[1]);

  return 0;
}
<|endoftext|>


<commit_before>#include <stdint.h>
#ifdef __cplusplus
	#include <cstdlib>
#else
	#include <stdlib.h>
#endif
#ifdef __APPLE__
#include <SDL/SDL.h>
#else
#include <SDL.h>
#endif

uint8_t sawtooth = 0;

void audioCallback(void* udata, uint8_t* stream, int len) {
	for (; len; len--) {
		*stream++ = sawtooth++ >> 5;
	}
}

int main(int argc, char** argv) {
	// initialize SDL video and audio
	if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) < 0) {
		printf("Unable to init SDL: %s\n", SDL_GetError());
		return 1;
	}

	// make sure SDL cleans up before exit
	atexit(SDL_Quit);

	// init audio
	SDL_AudioSpec audioSpec;
	audioSpec.freq     = 44100;
	audioSpec.format   = AUDIO_S16;
	audioSpec.channels = 1;
	audioSpec.samples  = 512;
	audioSpec.callback = audioCallback;

	if (SDL_OpenAudio(&audioSpec, NULL) < 0) {
		fprintf(stderr, "Couldn't open audio: %s\n", SDL_GetError());
		return(-1);
	};

	// start audio
	SDL_PauseAudio(0);

	// create a new window
	SDL_Surface* screen = SDL_SetVideoMode(640, 480, 16, SDL_HWSURFACE | SDL_DOUBLEBUF);
	if (!screen) {
		printf("Unable to set 640x480 video: %s\n", SDL_GetError());
		return 1;
	}

	// load image
	SDL_Surface* bmp = SDL_LoadBMP("mario.bmp");
	if (!bmp) {
		printf("Unable to load bitmap: %s\n", SDL_GetError());
		return 1;
	}

	// centre the bitmap on screen
	SDL_Rect dstrect;
	dstrect.x = (screen->w - bmp->w) / 2;
	dstrect.y = (screen->h - bmp->h) / 2;

	// program main loop
	bool done = false;
	while (!done) {

		//-------------------------
		// message processing loop
		SDL_Event event;
		while (SDL_PollEvent(&event)) {
			// check for messages
			switch (event.type) {
			case SDL_QUIT:
				// exit if the window is closed
				done = true;
				break;

				// check for keypresses
			case SDL_KEYDOWN:
				// exit if ESCAPE is pressed
				if (event.key.keysym.sym == SDLK_ESCAPE) done = true;
				break;
			}
		}

		SDL_FillRect(screen, 0, SDL_MapRGB(screen->format, 0xCC, 0xEE, 0xDD)); // clear screen
		SDL_SetColorKey(bmp, SDL_SRCCOLORKEY, SDL_MapRGB(bmp->format, 255, 0, 0));
        /* On blitte l'image maintenant transparente sur le fond : */
		SDL_BlitSurface(bmp, NULL, screen, &dstrect); // draw bitmap
		SDL_Flip(screen); // update the screen

		SDL_Delay(100);
	}

	SDL_CloseAudio(); // close audio
	SDL_FreeSurface(bmp); // free loaded bitmap
	printf("Exited cleanly\n");
	return 0;
}
<commit_msg>cleanup comments<commit_after>#include <stdint.h>
#ifdef __cplusplus
	#include <cstdlib>
#else
	#include <stdlib.h>
#endif
#ifdef __APPLE__
#include <SDL/SDL.h>
#else
#include <SDL.h>
#endif

uint8_t sawtooth = 0;

void audioCallback(void* udata, uint8_t* stream, int len) {
	for (; len; len--) {
		*stream++ = sawtooth++ >> 5;
	}
}

int main(int argc, char** argv) {
	// initialize SDL video and audio
	if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) < 0) {
		printf("Unable to init SDL: %s\n", SDL_GetError());
		return 1;
	}

	// make sure SDL cleans up before exit
	atexit(SDL_Quit);

	// init audio
	SDL_AudioSpec audioSpec;
	audioSpec.freq     = 44100;
	audioSpec.format   = AUDIO_S16;
	audioSpec.channels = 1;
	audioSpec.samples  = 512;
	audioSpec.callback = audioCallback;

	if (SDL_OpenAudio(&audioSpec, NULL) < 0) {
		fprintf(stderr, "Couldn't open audio: %s\n", SDL_GetError());
		return(-1);
	};

	// start audio
	SDL_PauseAudio(0);

	// create a new window
	SDL_Surface* screen = SDL_SetVideoMode(640, 480, 16, SDL_HWSURFACE | SDL_DOUBLEBUF);
	if (!screen) {
		printf("Unable to set 640x480 video: %s\n", SDL_GetError());
		return 1;
	}

	// load image
	SDL_Surface* bmp = SDL_LoadBMP("mario.bmp");
	if (!bmp) {
		printf("Unable to load bitmap: %s\n", SDL_GetError());
		return 1;
	}

	// centre the bitmap on screen
	SDL_Rect dstrect;
	dstrect.x = (screen->w - bmp->w) / 2;
	dstrect.y = (screen->h - bmp->h) / 2;

	// program main loop
	bool done = false;
	while (!done) {

		//-------------------------
		// message processing loop
		SDL_Event event;
		while (SDL_PollEvent(&event)) {
			// check for messages
			switch (event.type) {
			case SDL_QUIT:
				// exit if the window is closed
				done = true;
				break;

				// check for keypresses
			case SDL_KEYDOWN:
				// exit if ESCAPE is pressed
				if (event.key.keysym.sym == SDLK_ESCAPE) done = true;
				break;
			}
		}

		SDL_FillRect(screen, 0, SDL_MapRGB(screen->format, 0xCC, 0xEE, 0xDD)); // clear screen
		SDL_SetColorKey(bmp, SDL_SRCCOLORKEY, SDL_MapRGB(bmp->format, 255, 0, 0)); // set transparency
		SDL_BlitSurface(bmp, NULL, screen, &dstrect); // draw bitmap
		SDL_Flip(screen); // update the screen

		SDL_Delay(100);
	}

	SDL_CloseAudio(); // close audio
	SDL_FreeSurface(bmp); // free loaded bitmap
	printf("Exited cleanly\n");
	return 0;
}
<|endoftext|>


<commit_before>08a799a8-2748-11e6-b330-e0f84713e7b8<commit_msg>Put the thingie in the thingie<commit_after>08b7ae26-2748-11e6-98a7-e0f84713e7b8<|endoftext|>


<commit_before>/*
 ---------------------------------------------------------------------------
This is free and unencumbered software released into the public domain.

Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.

In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.

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

For more information, please refer to <http://unlicense.org>
---------------------------------------------------------------------------
*/
/*
Made By: Patrick J. Rye
Purpose: A game I made as an attempt to teach myself c++, just super basic, but going to try to keep improving it as my knowledge increases.
Current Revision: 1.3b
Change Log---------------------------------------------------------------------------------------------------------------------------------------------------
Date	Revision	Changed By			Changes
------  ---------   ------------		---------------------------------------------------------------------------------------------------------------------
=============================================================================================================================================================
-------------------------------------------------------------------------------------------------------------------------------------------------------------
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~MOVED FROM ALPHA TO BETA~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-------------------------------------------------------------------------------------------------------------------------------------------------------------
=============================================================================================================================================================
2/24/15	1.0b		Patrick Rye			-Moved from V5.0-alpha to V1.0-beta
										-Fixed level up so it happens when you get to a new level.
										-Allowed exit on map.
										-Fixed opening text to reflect recent changes in the game.
										-Grammar and spelling fixes (yay, made it several revisions without having to do this. :) ).
=============================================================================================================================================================
2/24/15	1.1b		Patrick Rye			-Attempted to allow movement on map through arrow keys.
											-Could not get this to work and broke everything. Rolling back to previous version.
											-Keeping this attempt in the record and will try to implement it again later.
=============================================================================================================================================================
2/25/15	1.2b		Patrick Rye			-Grammar and spelling fixes. ((╯°□°)╯︵ ┻━┻)
										-Cleaned up code some more.
										-Changed some if statements to case switches.
										-Added breaks to case switches.
=============================================================================================================================================================
2/26/15	1.3b		Patrick Rye			-Moved player movement to the room.h
=============================================================================================================================================================
*/

/*********************************************************************************************************/
#include <iostream>
#include <string>
#include <math.h>
#include <cstdlib>
#include <cmath>
#include <locale>
#include <cstdio>
#include <ctime>
/*********************************************************************************************************/
#include "casechanger.h" //Functions that hold change the case of chars and strings.
#include "rooms.h" //Functions that deal with generating a dungeon.
#include "battle.h" //Functions that deal with battling, levelling up and making a player.
/*********************************************************************************************************/
using namespace std;
/*********************************************************************************************************/
//Make all the global variables that I need.
int intMainLevel;
/*********************************************************************************************************/

int main()
{

	char chrPlayerMade = 'F';
	char charPlayerDirection;
	char charBattleEnding;
	char charExitFind;

	cout<<"Welcome to the World of Attacker"<<endl<<"Your objective is to go through 10 randomly generated dungeons."<<endl;
	cout<<"You are looking for the stairs down ( > ). While you are represented by †"<<endl;
	cout<<"Every step brings you closer to your goal, but there might be a monster there as well."<<endl;
	cout<<"Each level is harder than the last, do you have what it takes to win?"<<endl;
	cout<<"Good luck!"<<endl<<endl<<endl<<endl;

	do {chrPlayerMade = PlayerInitialize();}while (chrPlayerMade != 'T'); //Repeat initialization until player is made.
	//cout << string(50, '\n');
	for(intMainLevel = 1; intMainLevel <= 10; intMainLevel++)
	{
		//Do level up if not first level.
		if( intMainLevel != 1) { LevelUpFunction();}
		charExitFind = 'F';
		cout<<endl;
		Dungeon d;//Generates dungeon.

		do
		{
			cout << string(50, '\n');
			d.showDungeon();
			cout<<"Level "<<intMainLevel<<" of 10."<<endl;
			cout<<"Please enter a direction you would like to go ( N , E , S , W )."<<endl<<"Enter X to exit."<<endl;
			cout<<"> ";
			cin>>charPlayerDirection;
			charPlayerDirection = CharConvertToUpper(charPlayerDirection);
			charExitFind = d.PlayerMovement(charPlayerDirection);
			if (charExitFind == 'E') {return 0;} //If we get an error exit program.
			if(rand() % 101 <= 10) //Random chance to encounter monster.
			{
				cout << string(50, '\n');
				charBattleEnding = startbattle(intMainLevel); //Starts battle.
				if(charBattleEnding == 'F') {return 0;} //Player lost battle.
			}
		}while (charExitFind != 'T'); //Repeat until player finds exit.
	}
	cout << string(50, '\n');
	cout<<"You win!!";
	system("PAUSE");
	return 0;
//End of main
}
<commit_msg>Update to V2.0b<commit_after>/*
 ---------------------------------------------------------------------------
This is free and unencumbered software released into the public domain.

Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.

In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.

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

For more information, please refer to <http://unlicense.org>
---------------------------------------------------------------------------
*/
/*
Made By: Patrick J. Rye
Purpose: A game I made as an attempt to teach myself c++, just super basic, but going to try to keep improving it as my knowledge increases.
Current Revision: 2.0b
Change Log---------------------------------------------------------------------------------------------------------------------------------------------------
Date	Revision	Changed By			Changes
------  ---------   ------------		---------------------------------------------------------------------------------------------------------------------
=============================================================================================================================================================
-------------------------------------------------------------------------------------------------------------------------------------------------------------
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~MOVED FROM ALPHA TO BETA~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-------------------------------------------------------------------------------------------------------------------------------------------------------------
=============================================================================================================================================================
2/24/15	1.0b		Patrick Rye			-Moved from V5.0-alpha to V1.0-beta
										-Fixed level up so it happens when you get to a new level.
										-Allowed exit on map.
										-Fixed opening text to reflect recent changes in the game.
										-Grammar and spelling fixes (yay, made it several revisions without having to do this. :) ).
=============================================================================================================================================================
2/24/15	1.1b		Patrick Rye			-Attempted to allow movement on map through arrow keys.
											-Could not get this to work and broke everything. Rolling back to previous version.
											-Keeping this attempt in the record and will try to implement it again later.
=============================================================================================================================================================
2/25/15	1.2b		Patrick Rye			-Grammar and spelling fixes. ((╯°□°)╯︵ ┻━┻)
										-Cleaned up code some more.
										-Changed some if statements to case switches.
										-Added breaks to case switches.
=============================================================================================================================================================
2/26/15	1.3b		Patrick Rye			-Moved player movement to the room.h
=============================================================================================================================================================
2/27/15	2.0b		Patrick Rye			-Added a save function, for testing purposes.
										-Added load function.
										-Added function to see if file exists.
=============================================================================================================================================================
*/

/*********************************************************************************************************/
#include <iostream>
#include <fstream>
#include <string>
#include <math.h>
#include <cstdlib>
#include <cmath>
#include <locale>
#include <cstdio>
#include <ctime>
/*********************************************************************************************************/
#include "casechanger.h" //Functions that hold change the case of chars and strings.
#include "rooms.h" //Functions that deal with generating a dungeon.
#include "battle.h" //Functions that deal with battling, levelling up and making a player.
/*********************************************************************************************************/
using namespace std;
Dungeon d;
/*********************************************************************************************************/
//Make all the global variables that I need.
int intMainLevel;
int intLevelStart;
/*********************************************************************************************************/

bool saveexists()
{
  ifstream ifile("save.bif");
  return ifile;
}

char savefunction()
{
	/*
	Testing a possible save function.
	2 Return values possible.
	T = True, save succeeded.
	F = False, save failed.
	*/
	int intCheckSum = 0;
	int arrbattlesave[7];
	int arrmainsave[1] = {intMainLevel};
	int arrroomsave[80][20];
	for (int i = 0; i < 6; i++) {arrbattlesave[i] = savebattle(i);}
	for (int y = 0; y < 20; y++) {for (int x = 0; x < 80; x++) {arrroomsave[x][y] = d.getCell(x,y);}}
	ofstream savefile;
	savefile.open ("save.bif");
	for (int i = 0; i < 7; i++) {savefile << arrbattlesave[i] << "\n";}
	//savefile << "\n";
	for (int i = 0; i < 1; i++) {savefile << arrmainsave[i] << "\n";}
	//savefile << "\n";
	for (int y = 0; y < 20; y++)
	{
		for (int x = 0; x < 80; x++) {savefile << arrroomsave[x][y] << "\n";}
		//savefile << " ";
	}
	savefile.close();
	//Save will now attempt to "load" the save it just made and compare it to the data available.
	//Checks to see if save is correct or not.
	ifstream loadfile("save.bif");
	int arrloadnumbers[1608];
	int x;
	for(int i = 0; i < 1608; i++) {loadfile>>arrloadnumbers[i];}
	loadfile.close();
	for (int i = 0; i < 8; i++)
	{
		if(i<7) {if (arrloadnumbers[i]==arrbattlesave[i]){intCheckSum++;}}
		else if (i == 7) {if (arrloadnumbers[i]==intMainLevel) {intCheckSum++;}}
	}
	int num = 7;
	for (int y = 0; y < 20; y++)
	{
		for (int x = 0; x < 80; x++)
		{
			num ++;
			if (arrloadnumbers[num]==d.getCell(x,y)) {intCheckSum++;}
		}
	}
	cout<<endl<<endl<<intCheckSum;
	if(intCheckSum >= 1608) {return 'T';}
	else {return 'F';}
}

bool loadfunction()
{
	ifstream loadfile("save.bif");
	int arrloadnumbers[1608];
	int x;
	for(int i = 0; i < 1608; i++) {loadfile>>arrloadnumbers[i];}
	loadfile.close();
	for (int i = 0; i < 8; i++)
	{
		if(i<7) {x = loadbattle(i,arrloadnumbers[i]);/*cout<<arrloadnumbers[i]<<endl;*/}
		else if (i == 7) {intLevelStart = arrloadnumbers[i];/*cout<<intLevelStart<<endl;*/}
	}
	int num = 7;
	for (int y = 0; y < 20; y++)
	{
		for (int x = 0; x < 80; x++)
		{
			num ++;
			d.setCell(x,y,arrloadnumbers[num]);
			//cout<<arrloadnumbers[num];
		}
	}
	//d.showDungeon();
	return true;
}

int main()
{

	cout << string(48, '\n');
	char chrPlayerMade = 'F';
	char charPlayerDirection;
	char charBattleEnding;
	char charExitFind;
	bool blLoadSuccess = false;
	bool blOldSave = false;
	char chrSaveSuccess = 'N'; //N means that save has not been run.
	intLevelStart = 1;
	if (saveexists())
	{
		blLoadSuccess = loadfunction();
		if (blLoadSuccess)
		{
			chrPlayerMade = 'T';
			blOldSave = true;
		}
		else {cout<<"There is a save present, but game is unable to load it."<<endl<<"Save is possibly corrupted."<<endl<<endl<<endl;}
	}

	if(!blOldSave) //If it is not an old save show welcome message.
	{
		NewGame:
		cout<<"Welcome to the World of Attacker"<<endl<<"Your objective is to go through 10 randomly generated dungeons."<<endl;
		cout<<"You are looking for the stairs down ( > ). While you are represented by †"<<endl;
		cout<<"Every step brings you closer to your goal, but there might be a monster there as well."<<endl;
		cout<<"Each level is harder than the last, do you have what it takes to win?"<<endl;
		cout<<"Good luck!"<<endl<<endl<<endl<<endl;
		while (chrPlayerMade != 'T') {chrPlayerMade = PlayerInitialize();}; //Repeat initialization until player is made.
	}

	for(intMainLevel = intLevelStart; intMainLevel <= 10; intMainLevel++)
	{
		//Do level up if new level.
		if (intMainLevel > intLevelStart) {LevelUpFunction();}
		charExitFind = 'F';
		cout<<endl;
		if (blOldSave && intMainLevel == intLevelStart) {d.playerfind(); d.showDungeon();} //If Old save and the level of that save, just load old dungeon.
		else {Dungeon d;/*Generates dungeon.*/} //If it is not old game OR a different level of old game, make new dungeon.

		do
		{
			cout << string(50, '\n');
			d.showDungeon();
			cout<<"Level "<<intMainLevel<<" of 10."<<endl;
			cout<<"Please enter a direction you would like to go ( N , E , S , W )."<<endl<<"Enter X to exit, or P to save."<<endl;
			cout<<"> ";
			cin>>charPlayerDirection;
			charPlayerDirection = CharConvertToUpper(charPlayerDirection);
			charExitFind = d.PlayerMovement(charPlayerDirection);
			if (charExitFind == 'E') {return 0;} //If we get an error exit program.
			if (charExitFind == 'S') {chrSaveSuccess = savefunction();} //Save the game.
			switch (chrSaveSuccess)
			{
				case 'T' :
					cout<<endl<<"Save succeeded."<<endl;
					system("pause");
					chrSaveSuccess = 'N';
					break;
				case 'F' :
					cout<<endl<<"Save failed!"<<endl;
					system("pause");
					chrSaveSuccess = 'N';
					break;
			}
			if(rand() % 101 <= 10) //Random chance to encounter monster.
			{
				cout << string(50, '\n');
				charBattleEnding = startbattle(intMainLevel); //Starts battle.
				if(charBattleEnding == 'F') {return 0;} //Player lost battle.
			}
		}while (charExitFind != 'T'); //Repeat until player finds exit.
	}
	cout << string(50, '\n');
	cout<<"You win!!";
	system("pause");
	return 0;
//End of main
}
<|endoftext|>


<commit_before>6ed3c4a6-4b02-11e5-8852-28cfe9171a43<commit_msg>more bug fix<commit_after>6ee2be97-4b02-11e5-8e22-28cfe9171a43<|endoftext|>


<commit_before>/**
 * This is free and unencumbered software released into the public domain.
**/

#include "Sha256.h"
#include "JsonRpc.h"
#include "Settings.h"
#include "Util.h"
#include "Transaction.h"
#include "Radix.h"
#include "Block.h"
#include "Miner.h"

#include <cassert>
#include <algorithm>
#include <cstdio>
#include <iostream>
#include <string>
#include <ctype.h>
#include <climits>
#include <chrono>
#include <thread>
#include <atomic>
#include <sstream>

using namespace std;

std::unique_ptr<Block> createBlockTemplate( JsonRpc& rpc )
{
   // Get block template
   Json::Value params;
   params[0u]["capabilities"] = Json::arrayValue;
   auto blockTemplate = rpc.call( "getblocktemplate", params );

   if( blockTemplate.isMember("coinbasetxn") )
      throw std::runtime_error( "Coinbase txn already exists" );

   // Get coinbase destination
   params.clear();
   params[0u] = "Mining Coinbase";
   auto coinbaseAddress = rpc.call( "getaccountaddress", params ).asString();
   // Convert address to pubkey hash
   auto coinbasePubKeyHash = Radix::base58DecodeCheck( coinbaseAddress );
   // Remove leading version byte
   coinbasePubKeyHash.erase( coinbasePubKeyHash.begin() );

   auto coinbaseValue = blockTemplate["coinbasevalue"].asInt64();

   // Create coinbase transaction
   auto coinbaseTxn = Transaction::createCoinbase( blockTemplate["height"].asInt(),
                                                   coinbaseValue,
                                                   coinbasePubKeyHash );

   // Create block
   std::unique_ptr<Block> block( new Block );
   block->header.version = blockTemplate["version"].asInt();
   block->header.time = blockTemplate["curtime"].asInt();
   block->header.bits = stoi( blockTemplate["bits"].asString(), nullptr, 16 );
   auto prevBlockHash = hexStringToBinary( blockTemplate["previousblockhash"].asString() );
   std::reverse( prevBlockHash.begin(), prevBlockHash.end() );
   block->setPrevBlockHash( prevBlockHash );
   // Add all the transactions
   block->appendTransaction( std::move(coinbaseTxn) );
   auto txnArray = blockTemplate["transactions"];
   assert( txnArray.isArray() );
   for( unsigned i = 0; i < txnArray.size(); ++i )
   {
      auto txnData = txnArray[i]["data"].asString();
      auto txn = Transaction::deserialize( txnData );
      block->appendTransaction( std::move(txn) );
   }
   block->updateHeader();

   return block;
}

Json::Value submitBlock( JsonRpc& rpc, const Block& block )
{
   std::ostringstream stream;
   block.serialize( stream );

   Json::Value params;
   params[0] = stream.str();
   return rpc.call( "submitblock", params );
}

int main( int argc, char** argv )
{
   try
   {
      Settings::init( argc, argv );

      JsonRpc rpc( Settings::RpcHost(), Settings::RpcPort(),
                   Settings::RpcUser(), Settings::RpcPassword() );

      auto miner = Miner::createInstance( Settings::minerType() );
      if( miner == nullptr )
      {
         throw runtime_error( "Miner implementation doesn't exist" );
      }

      auto block = createBlockTemplate( rpc );

      if( miner->mine(*block) == Miner::SolutionFound )
      {
         std::cout << "Solution found: " << std::endl
                   << "\tHeader: " << block->headerData() << std::endl
                   << "\tHash:   " << Sha256::doubleHash( &block->header, sizeof(block->header) ) << std::endl;

         auto result = submitBlock( rpc, *block );
         if( !result.isNull() )
         {
            std::cout << "Solution rejected! (" << result.asString() << ")" << std::endl;
         }
         else
         {
            std::cout << "Solution accepted!" << std::endl;
         }
      }
      else
      {
         std::cout << "No solution found" << std::endl;
      }

      return EXIT_SUCCESS;
   }
   catch( std::exception& e )
   {
      cerr << "ERROR: " << e.what() << endl;
      return EXIT_FAILURE;
   }
}
<commit_msg>Reorganize main to do continuous mining<commit_after>/**
 * This is free and unencumbered software released into the public domain.
**/

#include "Sha256.h"
#include "JsonRpc.h"
#include "Settings.h"
#include "Util.h"
#include "Transaction.h"
#include "Radix.h"
#include "Block.h"
#include "Miner.h"

#include <cassert>
#include <algorithm>
#include <cstdio>
#include <iostream>
#include <string>
#include <ctype.h>
#include <climits>
#include <chrono>
#include <thread>
#include <atomic>
#include <sstream>

using namespace std;

std::unique_ptr<Block> createBlockTemplate( JsonRpc& rpc, const ByteArray& coinbasePubKeyHash )
{
   // Get block template
   Json::Value params;
   params[0u]["capabilities"] = Json::arrayValue;
   auto blockTemplate = rpc.call( "getblocktemplate", params );

   if( blockTemplate.isMember("coinbasetxn") )
      throw std::runtime_error( "Coinbase txn already exists" );

   auto coinbaseValue = blockTemplate["coinbasevalue"].asInt64();

   // Create coinbase transaction
   auto coinbaseTxn = Transaction::createCoinbase( blockTemplate["height"].asInt(),
                                                   coinbaseValue,
                                                   coinbasePubKeyHash );

   // Create block
   std::unique_ptr<Block> block( new Block );
   block->header.version = blockTemplate["version"].asInt();
   block->header.time = blockTemplate["curtime"].asInt();
   block->header.bits = stoi( blockTemplate["bits"].asString(), nullptr, 16 );
   auto prevBlockHash = hexStringToBinary( blockTemplate["previousblockhash"].asString() );
   std::reverse( prevBlockHash.begin(), prevBlockHash.end() );
   block->setPrevBlockHash( prevBlockHash );
   // Add all the transactions
   block->appendTransaction( std::move(coinbaseTxn) );
   auto txnArray = blockTemplate["transactions"];
   assert( txnArray.isArray() );
   for( unsigned i = 0; i < txnArray.size(); ++i )
   {
      auto txnData = txnArray[i]["data"].asString();
      auto txn = Transaction::deserialize( txnData );
      block->appendTransaction( std::move(txn) );
   }
   block->updateHeader();

   return block;
}

Json::Value submitBlock( JsonRpc& rpc, const Block& block )
{
   std::ostringstream stream;
   block.serialize( stream );

   Json::Value params;
   params[0] = stream.str();
   return rpc.call( "submitblock", params );
}

Miner::Result mineSingleBlock( JsonRpc& rpc, Miner& miner, const ByteArray& coinbasePubKeyHash )
{
   auto block = createBlockTemplate( rpc, coinbasePubKeyHash );

   auto result = miner.mine( *block );
   if( result == Miner::SolutionFound )
   {
      std::cout << "Solution found: " << std::endl
         << "\tHeader: " << block->headerData() << std::endl
         << "\tHash:   " << Sha256::doubleHash( &block->header, sizeof(block->header) ) << std::endl;

      auto response = submitBlock( rpc, *block );
      if( !response.isNull() )
      {
         std::cout << "Solution rejected! (" << response.asString() << ")" << std::endl;
         return Miner::NoSolutionFound;
      }
      else
      {
         std::cout << "Solution accepted!" << std::endl;
      }
   }
   else
   {
      std::cout << "No solution found" << std::endl;
      // TODO: fiddle with extranonce and continue
   }

   return result;
}

void doMining( JsonRpc& rpc, Miner& miner )
{
   // Get coinbase destination
   Json::Value params;
   params[0] = "Mining Coinbase";
   auto coinbaseAddress = rpc.call( "getaccountaddress", params ).asString();
   // Convert address to pubkey hash
   auto coinbasePubKeyHash = Radix::base58DecodeCheck( coinbaseAddress );
   // Remove leading version byte
   coinbasePubKeyHash.erase( coinbasePubKeyHash.begin() );

   auto result = Miner::SolutionFound;
   while( result == Miner::SolutionFound )
   {
      result = mineSingleBlock( rpc, miner, coinbasePubKeyHash );
   }
}

int main( int argc, char** argv )
{
   try
   {
      Settings::init( argc, argv );

      JsonRpc rpc( Settings::RpcHost(), Settings::RpcPort(),
                   Settings::RpcUser(), Settings::RpcPassword() );

      auto miner = Miner::createInstance( Settings::minerType() );
      if( miner == nullptr )
      {
         throw runtime_error( "Miner implementation doesn't exist" );
      }

      doMining( rpc, *miner );

      return EXIT_SUCCESS;
   }
   catch( std::exception& e )
   {
      cerr << "ERROR: " << e.what() << endl;
      return EXIT_FAILURE;
   }
}
<|endoftext|>


<commit_before>/** Copyright (c) 2013, Sean Kasun */
#include <QtWidgets/QApplication>
#include <QTranslator>
#include <QLocale>

#include "./minutor.h"

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

  QString locale = QLocale::system().name();

  QTranslator translator;
  translator.load(QString("minutor_")+locale);
  app.installTranslator(&translator);

  app.setApplicationName("Minutor");
  app.setApplicationVersion("2.1.2");
  app.setOrganizationName("seancode");

  Minutor minutor;

  // Process the cmdline arguments:
  QStringList args = app.arguments();
  int numArgs = args.size();
  bool regionChecker = false;
  bool chunkChecker = false;
  for (int i = 0; i < numArgs; i++) {
    if (args[i].length() > 2) {
      // convert long variants to lower case
      args[i] = args[i].toLower();
    }
    if ((args[i] == "-w" || args[i] == "--world") && i + 1 < numArgs) {
      minutor.loadWorld(args[i + 1]);
      i += 1;
      continue;
    }
    if (args[i] == "--regionchecker") {
      regionChecker = true;
      continue;
    }
    if (args[i] == "--chunkchecker") {
      chunkChecker = true;
      continue;
    }
    if ((args[i] == "-s" || args[i] == "--savepng") && i + 1 < numArgs) {
      minutor.savePNG(args[i + 1], true, regionChecker, chunkChecker);
      i += 1;
      continue;
    }
    if ((args[i] == "-j" || args[i] == "--jump") && i + 2 < numArgs) {
      minutor.jumpToXZ(args[i + 1].toInt(), args[i + 2].toInt());
      i += 2;
      continue;
    }
    if ((args[i] == "-y" || args[i] == "--depth") && i + 1 < numArgs) {
      minutor.setDepth(args[i + 1].toInt());
      i += 1;
      continue;
    }

    // menu View->
    if (args[i] == "-L" || args[i] == "--lighting") {
      minutor.setViewLighting(true);
      continue;
    }
    if (args[i] == "-M" || args[i] == "--mobspawning") {
      minutor.setViewMobspawning(true);
      continue;
    }
    if (args[i] == "-D" || args[i] == "--depthshading") {
      minutor.setViewDepthshading(true);
      continue;
    }
    if (args[i] == "-B" || args[i] == "--biomecolors") {
      minutor.setViewBiomeColors(true);
      continue;
    }
  }

  minutor.show();
  return app.exec();
}
<commit_msg>add command line support  for export region range<commit_after>/** Copyright (c) 2013, Sean Kasun */
#include <QtWidgets/QApplication>
#include <QTranslator>
#include <QLocale>

#include "./minutor.h"

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

  QString locale = QLocale::system().name();

  QTranslator translator;
  translator.load(QString("minutor_")+locale);
  app.installTranslator(&translator);

  app.setApplicationName("Minutor");
  app.setApplicationVersion("2.1.3");
  app.setOrganizationName("seancode");

  Minutor minutor;

  // Process the cmdline arguments:
  QStringList args = app.arguments();
  int numArgs = args.size();
  int ex_top    = 0;
  int ex_left   = 0;
  int ex_bottom = 0;
  int ex_right  = 0;
  bool regionChecker = false;
  bool chunkChecker = false;
  for (int i = 0; i < numArgs; i++) {
    if (args[i].length() > 2) {
      // convert long variants to lower case
      args[i] = args[i].toLower();
    }
    if ((args[i] == "-w" || args[i] == "--world") && i + 1 < numArgs) {
      minutor.loadWorld(args[i + 1]);
      i += 1;
      continue;
    }
    if (args[i] == "--regionchecker") {
      regionChecker = true;
      continue;
    }
    if (args[i] == "--chunkchecker") {
      chunkChecker = true;
      continue;
    }
    if ((args[i] == "-r" || args[i] == "--exportrange") && i + 4 < numArgs) {
      ex_top    = args[i + 1].toInt();
      ex_left   = args[i + 2].toInt();
      ex_bottom = args[i + 3].toInt();
      ex_right  = args[i + 4].toInt();
      i += 4;
      continue;
    }
    if ((args[i] == "-s" || args[i] == "--savepng") && i + 1 < numArgs) {
      minutor.savePNG(args[i + 1], true, regionChecker, chunkChecker,
                      ex_top, ex_left, ex_bottom, ex_right);
      i += 1;
      continue;
    }
    if ((args[i] == "-j" || args[i] == "--jump") && i + 2 < numArgs) {
      minutor.jumpToXZ(args[i + 1].toInt(), args[i + 2].toInt());
      i += 2;
      continue;
    }
    if ((args[i] == "-y" || args[i] == "--depth") && i + 1 < numArgs) {
      minutor.setDepth(args[i + 1].toInt());
      i += 1;
      continue;
    }

    // menu View->
    if (args[i] == "-L" || args[i] == "--lighting") {
      minutor.setViewLighting(true);
      continue;
    }
    if (args[i] == "-M" || args[i] == "--mobspawning") {
      minutor.setViewMobspawning(true);
      continue;
    }
    if (args[i] == "-D" || args[i] == "--depthshading") {
      minutor.setViewDepthshading(true);
      continue;
    }
    if (args[i] == "-B" || args[i] == "--biomecolors") {
      minutor.setViewBiomeColors(true);
      continue;
    }
  }

  minutor.show();
  return app.exec();
}
<|endoftext|>


<commit_before>#include <random>
#include <Common.h>
#include <secp256k1.h>
#include "RLP.h"
#include "Trie.h"
#include "VirtualMachine.h"
using namespace std;
using namespace eth;

std::string randomWord()
{
	static std::mt19937_64 s_eng(0);
	std::string ret(uniform_int_distribution<int>(4, 10)(s_eng), ' ');
	char const n[] = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890";
	uniform_int_distribution<int> d(0, sizeof(n) - 2);
	for (char& c: ret)
		c = n[d(s_eng)];
	return ret;
}

int main()
{
	secp256k1_start();

	bytes pubkey(65);
	int pubkeylen = 65;
	{
		cout << "SEC: " << asHex(sha256("123", false)) << endl;
		int ret = secp256k1_ecdsa_pubkey_create(pubkey.data(), &pubkeylen, (byte const*)sha256("123", false).data(), 1);
		pubkey.resize(pubkeylen);
		cout << "PUB: " << ret << " " << pubkeylen << " " << asHex(pubkey) << endl;
	}

	bytes tx = fromUserHex("88005401010101010101010101010101010101010101011f0de0b6b3a76400001ce8d4a5100080181c373130a009ba1f10285d4e659568bfcfec85067855c5a3c150100815dad4ef98fd37cf0593828c89db94bd6c64e210a32ef8956eaa81ea9307194996a3b879441f5d");
	cout << "TX: " << RLP(tx) << endl;

	Transaction t(tx);
	std::string sig64 = toBigEndianString(t.vrs.r) + toBigEndianString(t.vrs.s);
	cout << "SIG: " << sig64.size() << " " << asHex(sig64) << " " << t.vrs.v << endl;

	auto msg = t.rlp(false);
	cout << "TX w/o SIG: " << RLP(msg) << endl;
	cout << "RLP(TX w/o SIG): " << asHex(t.rlpString(false)) << endl;
	std::string hmsg = sha256(t.rlpString(false), false);
	cout << "SHA256(RLP(TX w/o SIG)): 0x" << asHex(hmsg) << endl;

	{
		bytes sig(64);
		u256 nonce = 0;
		int v = 0;
		int ret = secp256k1_ecdsa_sign_compact((byte const*)hmsg.data(), hmsg.size(), sig.data(), (byte const*)sha256("123", false).data(), (byte const*)&nonce, &v);
		cout << "MYSIG: " << dec << ret << " " << sig.size() << " " << asHex(sig) << " " << v << endl;

		ret = secp256k1_ecdsa_recover_compact((byte const*)hmsg.data(), hmsg.size(), (byte const*)sig.data(), pubkey.data(), &pubkeylen, 1, (int)t.vrs.v);
		pubkey.resize(pubkeylen);
		cout << "MYREC: " << dec << ret << " " << pubkeylen << " " << asHex(pubkey) << endl;
	}

	{
		pubkey.resize(65);
		int ret = secp256k1_ecdsa_recover_compact((byte const*)hmsg.data(), hmsg.size(), (byte const*)sig64.data(), pubkey.data(), &pubkeylen, 1, (int)t.vrs.v);
		pubkey.resize(pubkeylen);
		cout << "REC: " << dec << ret << " " << pubkeylen << " " << asHex(pubkey) << endl;
		cout << hex << sha256(pubkey) << endl;

		pubkey.resize(65);
		ret = secp256k1_ecdsa_recover_compact((byte const*)hmsg.data(), hmsg.size(), (byte const*)sig64.data(), pubkey.data(), &pubkeylen, 0, (int)t.vrs.v);
		pubkey.resize(pubkeylen);
		cout << "REC+: " << dec << ret << " " << pubkeylen << " " << asHex(pubkey) << endl;
		cout << hex << sha256(pubkey) << endl;
	}

	{
		Trie t;
		t.insert("dog", "puppy");
		assert(t.sha256() == hash256({{"dog", "puppy"}}));
		assert(t.at("dog") == "puppy");
		t.insert("doe", "reindeer");
		assert(t.sha256() == hash256({{"dog", "puppy"}, {"doe", "reindeer"}}));
		assert(t.at("doe") == "reindeer");
		assert(t.at("dog") == "puppy");
		t.insert("dogglesworth", "cat");
		assert(t.sha256() == hash256({{"doe", "reindeer"}, {"dog", "puppy"}, {"dogglesworth", "cat"}}));
		assert(t.at("doe") == "reindeer");
		assert(t.at("dog") == "puppy");
		assert(t.at("dogglesworth") == "cat");
		t.remove("dogglesworth");
		t.remove("doe");
		assert(t.at("doe").empty());
		assert(t.at("dogglesworth").empty());
		assert(t.at("dog") == "puppy");
		assert(t.sha256() == hash256({{"dog", "puppy"}}));
		t.insert("horse", "stallion");
		t.insert("do", "verb");
		t.insert("doge", "coin");
		assert(t.sha256() == hash256({{"dog", "puppy"}, {"horse", "stallion"}, {"do", "verb"}, {"doge", "coin"}}));
		assert(t.at("doge") == "coin");
		assert(t.at("do") == "verb");
		assert(t.at("horse") == "stallion");
		assert(t.at("dog") == "puppy");
		t.remove("horse");
		t.remove("do");
		t.remove("doge");
		assert(t.sha256() == hash256({{"dog", "puppy"}}));
		assert(t.at("dog") == "puppy");
		t.remove("dog");

		for (int a = 0; a < 20; ++a)
		{
			StringMap m;
			for (int i = 0; i < 20; ++i)
			{
				auto k = randomWord();
				auto v = toString(i);
				m.insert(make_pair(k, v));
				t.insert(k, v);
				assert(hash256(m) == t.sha256());
			}
			while (!m.empty())
			{
				auto k = m.begin()->first;
				t.remove(k);
				m.erase(k);
				assert(hash256(m) == t.sha256());
			}
		}
	}

	// int of value 15
	assert(RLP("\x0f") == 15);
	assert(rlp(15) == "\x0f");

	// 3-character string
	assert(RLP("\x43""dog") == "dog");
	assert(rlp("dog") == "\x43""dog");

	// 2-item list
	RLP twoItemList("\x82\x0f\x43""dog");
	assert(twoItemList.itemCount() == 2);
	assert(twoItemList[0] == 15);
	assert(twoItemList[1] == "dog");
	assert(rlpList(15, "dog") == "\x82\x0f\x43""dog");

	// 1-byte (8-bit) int
	assert(RLP("\x18\x45") == 69);
	assert(rlp(69) == "\x18\x45");

	// 2-byte (16-bit) int
	assert(RLP("\x19\x01\x01") == 257);
	assert(rlp(257) == "\x19\x01\x01");

	// 32-byte (256-bit) int
	assert(RLP("\x37\x10\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f") == bigint("0x100102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f"));
	assert(rlp(bigint("0x100102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f")) == "\x37\x10\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f");

	// 33-byte (264-bit) int
	assert(RLP("\x38\x21\x20\x10\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f") == bigint("0x20100102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F"));
	assert(rlp(bigint("0x20100102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F")) == "\x38\x21\x20\x10\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f");

	// 56-character string.
	assert(RLP("\x78\x38""Lorem ipsum dolor sit amet, consectetur adipisicing elit") == "Lorem ipsum dolor sit amet, consectetur adipisicing elit");
	assert(rlp("Lorem ipsum dolor sit amet, consectetur adipisicing elit") == "\x78\x38""Lorem ipsum dolor sit amet, consectetur adipisicing elit");

	/*
	 * Hex-prefix Notation. First nibble has flags: oddness = 2^0 & termination = 2^1
	 * [0,0,1,2,3,4,5]   0x10012345
	 * [0,1,2,3,4,5]     0x00012345
	 * [1,2,3,4,5]       0x112345
	 * [0,0,1,2,3,4]     0x00001234
	 * [0,1,2,3,4]       0x101234
	 * [1,2,3,4]         0x001234
	 * [0,0,1,2,3,4,5,T] 0x30012345
	 * [0,0,1,2,3,4,T]   0x20001234
	 * [0,1,2,3,4,5,T]   0x20012345
	 * [1,2,3,4,5,T]     0x312345
	 * [1,2,3,4,T]       0x201234
	 */
	assert(asHex(hexPrefixEncode({0, 0, 1, 2, 3, 4, 5}, false)) == "10012345");
	assert(asHex(hexPrefixEncode({0, 1, 2, 3, 4, 5}, false)) == "00012345");
	assert(asHex(hexPrefixEncode({1, 2, 3, 4, 5}, false)) == "112345");
	assert(asHex(hexPrefixEncode({0, 0, 1, 2, 3, 4}, false)) == "00001234");
	assert(asHex(hexPrefixEncode({0, 1, 2, 3, 4}, false)) == "101234");
	assert(asHex(hexPrefixEncode({1, 2, 3, 4}, false)) == "001234");
	assert(asHex(hexPrefixEncode({0, 0, 1, 2, 3, 4, 5}, true)) == "30012345");
	assert(asHex(hexPrefixEncode({0, 0, 1, 2, 3, 4}, true)) == "20001234");
	assert(asHex(hexPrefixEncode({0, 1, 2, 3, 4, 5}, true)) == "20012345");
	assert(asHex(hexPrefixEncode({1, 2, 3, 4, 5}, true)) == "312345");
	assert(asHex(hexPrefixEncode({1, 2, 3, 4}, true)) == "201234");

	return 0;
}

<commit_msg>Signatures working.<commit_after>#include <random>
#include <Common.h>
#include <secp256k1.h>
#include "RLP.h"
#include "Trie.h"
#include "VirtualMachine.h"
using namespace std;
using namespace eth;

int main()
{
	bytes tx = fromUserHex("88005401010101010101010101010101010101010101011f0de0b6b3a76400001ce8d4a5100080181c373130a009ba1f10285d4e659568bfcfec85067855c5a3c150100815dad4ef98fd37cf0593828c89db94bd6c64e210a32ef8956eaa81ea9307194996a3b879441f5d");
	cout << "TX: " << RLP(tx) << endl;

	Transaction t(tx);
	cout << "SENDER: " << hex << t.sender() << endl;

	bytes sig64 = toBigEndian(t.vrs.r) + toBigEndian(t.vrs.s);
	cout << "SIG: " << sig64.size() << " " << asHex(sig64) << " " << t.vrs.v << endl;

	auto msg = t.rlp(false);
	cout << "TX w/o SIG: " << RLP(msg) << endl;
	cout << "RLP(TX w/o SIG): " << asHex(t.rlpString(false)) << endl;
	std::string hmsg = sha256(t.rlpString(false), false);
	cout << "SHA256(RLP(TX w/o SIG)): 0x" << asHex(hmsg) << endl;

	bytes privkey = sha256Bytes("123");

	secp256k1_start();

	{
		bytes pubkey(65);
		int pubkeylen = 65;

		int ret = secp256k1_ecdsa_seckey_verify(privkey.data());
		cout << "SEC: " << dec << ret << " " << asHex(privkey) << endl;

		ret = secp256k1_ecdsa_pubkey_create(pubkey.data(), &pubkeylen, privkey.data(), 1);
		pubkey.resize(pubkeylen);
		int good = secp256k1_ecdsa_pubkey_verify(pubkey.data(), pubkey.size());
		cout << "PUB: " << dec << ret << " " << pubkeylen << " " << asHex(pubkey) << (good ? " GOOD" : " BAD") << endl;
	}

	// Test roundtrip...
	{
		bytes sig(64);
		u256 nonce = 0;
		int v = 0;
		int ret = secp256k1_ecdsa_sign_compact((byte const*)hmsg.data(), hmsg.size(), sig.data(), privkey.data(), (byte const*)&nonce, &v);
		cout << "MYSIG: " << dec << ret << " " << sig.size() << " " << asHex(sig) << " " << v << endl;

		bytes pubkey(65);
		int pubkeylen = 65;
		ret = secp256k1_ecdsa_recover_compact((byte const*)hmsg.data(), hmsg.size(), (byte const*)sig.data(), pubkey.data(), &pubkeylen, 0, v);
		pubkey.resize(pubkeylen);
		cout << "MYREC: " << dec << ret << " " << pubkeylen << " " << asHex(pubkey) << endl;
	}

	{
		bytes pubkey(65);
		int pubkeylen = 65;
		int ret = secp256k1_ecdsa_recover_compact((byte const*)hmsg.data(), hmsg.size(), (byte const*)sig64.data(), pubkey.data(), &pubkeylen, 0, (int)t.vrs.v - 27);
		pubkey.resize(pubkeylen);
		cout << "RECPUB: " << dec << ret << " " << pubkeylen << " " << asHex(pubkey) << endl;
		cout << "SENDER: " << hex << low160(eth::sha256(bytesConstRef(&pubkey).cropped(1))) << endl;
	}

	{
		Trie t;
		t.insert("dog", "puppy");
		assert(t.sha256() == hash256({{"dog", "puppy"}}));
		assert(t.at("dog") == "puppy");
		t.insert("doe", "reindeer");
		assert(t.sha256() == hash256({{"dog", "puppy"}, {"doe", "reindeer"}}));
		assert(t.at("doe") == "reindeer");
		assert(t.at("dog") == "puppy");
		t.insert("dogglesworth", "cat");
		assert(t.sha256() == hash256({{"doe", "reindeer"}, {"dog", "puppy"}, {"dogglesworth", "cat"}}));
		assert(t.at("doe") == "reindeer");
		assert(t.at("dog") == "puppy");
		assert(t.at("dogglesworth") == "cat");
		t.remove("dogglesworth");
		t.remove("doe");
		assert(t.at("doe").empty());
		assert(t.at("dogglesworth").empty());
		assert(t.at("dog") == "puppy");
		assert(t.sha256() == hash256({{"dog", "puppy"}}));
		t.insert("horse", "stallion");
		t.insert("do", "verb");
		t.insert("doge", "coin");
		assert(t.sha256() == hash256({{"dog", "puppy"}, {"horse", "stallion"}, {"do", "verb"}, {"doge", "coin"}}));
		assert(t.at("doge") == "coin");
		assert(t.at("do") == "verb");
		assert(t.at("horse") == "stallion");
		assert(t.at("dog") == "puppy");
		t.remove("horse");
		t.remove("do");
		t.remove("doge");
		assert(t.sha256() == hash256({{"dog", "puppy"}}));
		assert(t.at("dog") == "puppy");
		t.remove("dog");

		for (int a = 0; a < 20; ++a)
		{
			StringMap m;
			for (int i = 0; i < 20; ++i)
			{
				auto k = randomWord();
				auto v = toString(i);
				m.insert(make_pair(k, v));
				t.insert(k, v);
				assert(hash256(m) == t.sha256());
			}
			while (!m.empty())
			{
				auto k = m.begin()->first;
				t.remove(k);
				m.erase(k);
				assert(hash256(m) == t.sha256());
			}
		}
	}

	// int of value 15
	assert(RLP("\x0f") == 15);
	assert(rlp(15) == "\x0f");

	// 3-character string
	assert(RLP("\x43""dog") == "dog");
	assert(rlp("dog") == "\x43""dog");

	// 2-item list
	RLP twoItemList("\x82\x0f\x43""dog");
	assert(twoItemList.itemCount() == 2);
	assert(twoItemList[0] == 15);
	assert(twoItemList[1] == "dog");
	assert(rlpList(15, "dog") == "\x82\x0f\x43""dog");

	// 1-byte (8-bit) int
	assert(RLP("\x18\x45") == 69);
	assert(rlp(69) == "\x18\x45");

	// 2-byte (16-bit) int
	assert(RLP("\x19\x01\x01") == 257);
	assert(rlp(257) == "\x19\x01\x01");

	// 32-byte (256-bit) int
	assert(RLP("\x37\x10\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f") == bigint("0x100102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f"));
	assert(rlp(bigint("0x100102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f")) == "\x37\x10\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f");

	// 33-byte (264-bit) int
	assert(RLP("\x38\x21\x20\x10\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f") == bigint("0x20100102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F"));
	assert(rlp(bigint("0x20100102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F")) == "\x38\x21\x20\x10\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f");

	// 56-character string.
	assert(RLP("\x78\x38""Lorem ipsum dolor sit amet, consectetur adipisicing elit") == "Lorem ipsum dolor sit amet, consectetur adipisicing elit");
	assert(rlp("Lorem ipsum dolor sit amet, consectetur adipisicing elit") == "\x78\x38""Lorem ipsum dolor sit amet, consectetur adipisicing elit");

	/*
	 * Hex-prefix Notation. First nibble has flags: oddness = 2^0 & termination = 2^1
	 * [0,0,1,2,3,4,5]   0x10012345
	 * [0,1,2,3,4,5]     0x00012345
	 * [1,2,3,4,5]       0x112345
	 * [0,0,1,2,3,4]     0x00001234
	 * [0,1,2,3,4]       0x101234
	 * [1,2,3,4]         0x001234
	 * [0,0,1,2,3,4,5,T] 0x30012345
	 * [0,0,1,2,3,4,T]   0x20001234
	 * [0,1,2,3,4,5,T]   0x20012345
	 * [1,2,3,4,5,T]     0x312345
	 * [1,2,3,4,T]       0x201234
	 */
	assert(asHex(hexPrefixEncode({0, 0, 1, 2, 3, 4, 5}, false)) == "10012345");
	assert(asHex(hexPrefixEncode({0, 1, 2, 3, 4, 5}, false)) == "00012345");
	assert(asHex(hexPrefixEncode({1, 2, 3, 4, 5}, false)) == "112345");
	assert(asHex(hexPrefixEncode({0, 0, 1, 2, 3, 4}, false)) == "00001234");
	assert(asHex(hexPrefixEncode({0, 1, 2, 3, 4}, false)) == "101234");
	assert(asHex(hexPrefixEncode({1, 2, 3, 4}, false)) == "001234");
	assert(asHex(hexPrefixEncode({0, 0, 1, 2, 3, 4, 5}, true)) == "30012345");
	assert(asHex(hexPrefixEncode({0, 0, 1, 2, 3, 4}, true)) == "20001234");
	assert(asHex(hexPrefixEncode({0, 1, 2, 3, 4, 5}, true)) == "20012345");
	assert(asHex(hexPrefixEncode({1, 2, 3, 4, 5}, true)) == "312345");
	assert(asHex(hexPrefixEncode({1, 2, 3, 4}, true)) == "201234");

	return 0;
}

<|endoftext|>


<commit_before>/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */
// vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4:
#ident "$Id$"
/*
COPYING CONDITIONS NOTICE:

  This program is free software; you can redistribute it and/or modify
  it under the terms of version 2 of the GNU General Public License as
  published by the Free Software Foundation, and provided that the
  following conditions are met:

      * Redistributions of source code must retain this COPYING
        CONDITIONS NOTICE, the COPYRIGHT NOTICE (below), the
        DISCLAIMER (below), the UNIVERSITY PATENT NOTICE (below), the
        PATENT MARKING NOTICE (below), and the PATENT RIGHTS
        GRANT (below).

      * Redistributions in binary form must reproduce this COPYING
        CONDITIONS NOTICE, the COPYRIGHT NOTICE (below), the
        DISCLAIMER (below), the UNIVERSITY PATENT NOTICE (below), the
        PATENT MARKING NOTICE (below), and the PATENT RIGHTS
        GRANT (below) in the documentation and/or other materials
        provided with the distribution.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  02110-1301, USA.

COPYRIGHT NOTICE:

  TokuDB, Tokutek Fractal Tree Indexing Library.
  Copyright (C) 2007-2013 Tokutek, Inc.

DISCLAIMER:

  This program is distributed in the hope that it will be useful, but
  WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  General Public License for more details.

UNIVERSITY PATENT NOTICE:

  The technology is licensed by the Massachusetts Institute of
  Technology, Rutgers State University of New Jersey, and the Research
  Foundation of State University of New York at Stony Brook under
  United States of America Serial No. 11/760379 and to the patents
  and/or patent applications resulting from it.

PATENT MARKING NOTICE:

  This software is covered by US Patent No. 8,185,551.

PATENT RIGHTS GRANT:

  "THIS IMPLEMENTATION" means the copyrightable works distributed by
  Tokutek as part of the Fractal Tree project.

  "PATENT CLAIMS" means the claims of patents that are owned or
  licensable by Tokutek, both currently or in the future; and that in
  the absence of this license would be infringed by THIS
  IMPLEMENTATION or by using or running THIS IMPLEMENTATION.

  "PATENT CHALLENGE" shall mean a challenge to the validity,
  patentability, enforceability and/or non-infringement of any of the
  PATENT CLAIMS or otherwise opposing any of the PATENT CLAIMS.

  Tokutek hereby grants to you, for the term and geographical scope of
  the PATENT CLAIMS, a non-exclusive, no-charge, royalty-free,
  irrevocable (except as stated in this section) patent license to
  make, have made, use, offer to sell, sell, import, transfer, and
  otherwise run, modify, and propagate the contents of THIS
  IMPLEMENTATION, where such license applies only to the PATENT
  CLAIMS.  This grant does not include claims that would be infringed
  only as a consequence of further modifications of THIS
  IMPLEMENTATION.  If you or your agent or licensee institute or order
  or agree to the institution of patent litigation against any entity
  (including a cross-claim or counterclaim in a lawsuit) alleging that
  THIS IMPLEMENTATION constitutes direct or contributory patent
  infringement, or inducement of patent infringement, then any rights
  granted to you under this License shall terminate as of the date
  such litigation is filed.  If you or your agent or exclusive
  licensee institute or order or agree to the institution of a PATENT
  CHALLENGE, then Tokutek may terminate any rights granted to you
  under this License.
*/

#ident "Copyright (c) 2007-2013 Tokutek Inc.  All rights reserved."
#ident "The technology is licensed by the Massachusetts Institute of Technology, Rutgers State University of New Jersey, and the Research Foundation of State University of New York at Stony Brook under United States of America Serial No. 11/760379 and to the patents and/or patent applications resulting from it."

#include "test.h"

static DB_TXN *txn1, *txn2, *txn3;

struct iterate_extra {
    iterate_extra() : n(0) {
        visited_txn[0] = false;
        visited_txn[1] = false;
        visited_txn[2] = false;
    }
    int n;
    bool visited_txn[3];
};

static int iterate_callback(uint64_t txnid, uint64_t client_id,
                            iterate_row_locks_callback iterate_locks,
                            void *locks_extra, void *extra) {
    iterate_extra *info = reinterpret_cast<iterate_extra *>(extra);
    DB *db;
    DBT left_key, right_key;
    int r = iterate_locks(&db, &left_key, &right_key, locks_extra);
    invariant(r == DB_NOTFOUND);
    if (txnid == txn1->id64(txn1)) {
        assert(!info->visited_txn[0]);
        invariant(client_id == 0);
        info->visited_txn[0] = true;
    } else if (txnid == txn2->id64(txn2)) {
        assert(!info->visited_txn[1]);
        invariant(client_id == 1);
        info->visited_txn[1] = true;
    } else if (txnid == txn3->id64(txn3)) {
        assert(!info->visited_txn[2]);
        invariant(client_id == 2);
        info->visited_txn[2] = true;
    }
    info->n++;
    return 0;
}

int test_main(int UU(argc), char *const UU(argv[])) {
    int r;
    const int env_flags = DB_INIT_MPOOL | DB_CREATE | DB_THREAD |
        DB_INIT_LOCK | DB_INIT_LOG | DB_INIT_TXN | DB_PRIVATE;

    toku_os_recursive_delete(TOKU_TEST_FILENAME);
    r = toku_os_mkdir(TOKU_TEST_FILENAME, 0755); CKERR(r);

    DB_ENV *env;
    r = db_env_create(&env, 0); CKERR(r);
    r = env->iterate_live_transactions(env, iterate_callback, NULL);
    assert(r == EINVAL);
    r = env->open(env, TOKU_TEST_FILENAME, env_flags, 0755); CKERR(r);

    r = env->txn_begin(env, NULL, &txn1, 0); CKERR(r);
    txn1->set_client_id(txn1, 0);
    r = env->txn_begin(env, NULL, &txn2, 0); CKERR(r);
    txn2->set_client_id(txn2, 1);
    r = env->txn_begin(env, NULL, &txn3, 0); CKERR(r);
    txn3->set_client_id(txn3, 2);

    {
        iterate_extra e;
        r = env->iterate_live_transactions(env, iterate_callback, &e); CKERR(r);
        assert(e.visited_txn[0]);
        assert(e.visited_txn[1]);
        assert(e.visited_txn[2]);
        assert(e.n == 3);
    }

    r = txn1->commit(txn1, 0); CKERR(r);
    r = txn2->abort(txn2); CKERR(r);
    {
        iterate_extra e;
        r = env->iterate_live_transactions(env, iterate_callback, &e); CKERR(r);
        assert(!e.visited_txn[0]);
        assert(!e.visited_txn[1]);
        assert(e.visited_txn[2]);
        assert(e.n == 1);
    }

    r = txn3->commit(txn3, 0); CKERR(r);
    {
        iterate_extra e;
        r = env->iterate_live_transactions(env, iterate_callback, &e); CKERR(r);
        assert(!e.visited_txn[0]);
        assert(!e.visited_txn[1]);
        assert(!e.visited_txn[2]);
        assert(e.n == 0);
    }

    r = env->close(env, 0); CKERR(r);
    return 0;
}
<commit_msg>fixes #71 fix a test bug by caching the txnid instead of trying to use a txn object after it commits or aborts<commit_after>/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */
// vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4:
#ident "$Id$"
/*
COPYING CONDITIONS NOTICE:

  This program is free software; you can redistribute it and/or modify
  it under the terms of version 2 of the GNU General Public License as
  published by the Free Software Foundation, and provided that the
  following conditions are met:

      * Redistributions of source code must retain this COPYING
        CONDITIONS NOTICE, the COPYRIGHT NOTICE (below), the
        DISCLAIMER (below), the UNIVERSITY PATENT NOTICE (below), the
        PATENT MARKING NOTICE (below), and the PATENT RIGHTS
        GRANT (below).

      * Redistributions in binary form must reproduce this COPYING
        CONDITIONS NOTICE, the COPYRIGHT NOTICE (below), the
        DISCLAIMER (below), the UNIVERSITY PATENT NOTICE (below), the
        PATENT MARKING NOTICE (below), and the PATENT RIGHTS
        GRANT (below) in the documentation and/or other materials
        provided with the distribution.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  02110-1301, USA.

COPYRIGHT NOTICE:

  TokuDB, Tokutek Fractal Tree Indexing Library.
  Copyright (C) 2007-2013 Tokutek, Inc.

DISCLAIMER:

  This program is distributed in the hope that it will be useful, but
  WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  General Public License for more details.

UNIVERSITY PATENT NOTICE:

  The technology is licensed by the Massachusetts Institute of
  Technology, Rutgers State University of New Jersey, and the Research
  Foundation of State University of New York at Stony Brook under
  United States of America Serial No. 11/760379 and to the patents
  and/or patent applications resulting from it.

PATENT MARKING NOTICE:

  This software is covered by US Patent No. 8,185,551.

PATENT RIGHTS GRANT:

  "THIS IMPLEMENTATION" means the copyrightable works distributed by
  Tokutek as part of the Fractal Tree project.

  "PATENT CLAIMS" means the claims of patents that are owned or
  licensable by Tokutek, both currently or in the future; and that in
  the absence of this license would be infringed by THIS
  IMPLEMENTATION or by using or running THIS IMPLEMENTATION.

  "PATENT CHALLENGE" shall mean a challenge to the validity,
  patentability, enforceability and/or non-infringement of any of the
  PATENT CLAIMS or otherwise opposing any of the PATENT CLAIMS.

  Tokutek hereby grants to you, for the term and geographical scope of
  the PATENT CLAIMS, a non-exclusive, no-charge, royalty-free,
  irrevocable (except as stated in this section) patent license to
  make, have made, use, offer to sell, sell, import, transfer, and
  otherwise run, modify, and propagate the contents of THIS
  IMPLEMENTATION, where such license applies only to the PATENT
  CLAIMS.  This grant does not include claims that would be infringed
  only as a consequence of further modifications of THIS
  IMPLEMENTATION.  If you or your agent or licensee institute or order
  or agree to the institution of patent litigation against any entity
  (including a cross-claim or counterclaim in a lawsuit) alleging that
  THIS IMPLEMENTATION constitutes direct or contributory patent
  infringement, or inducement of patent infringement, then any rights
  granted to you under this License shall terminate as of the date
  such litigation is filed.  If you or your agent or exclusive
  licensee institute or order or agree to the institution of a PATENT
  CHALLENGE, then Tokutek may terminate any rights granted to you
  under this License.
*/

#ident "Copyright (c) 2007-2013 Tokutek Inc.  All rights reserved."
#ident "The technology is licensed by the Massachusetts Institute of Technology, Rutgers State University of New Jersey, and the Research Foundation of State University of New York at Stony Brook under United States of America Serial No. 11/760379 and to the patents and/or patent applications resulting from it."

#include "test.h"

static DB_TXN *txn1, *txn2, *txn3;
static uint64_t txnid1, txnid2, txnid3;

struct iterate_extra {
    iterate_extra() : n(0) {
        visited_txn[0] = false;
        visited_txn[1] = false;
        visited_txn[2] = false;
    }
    int n;
    bool visited_txn[3];
};

static int iterate_callback(uint64_t txnid, uint64_t client_id,
                            iterate_row_locks_callback iterate_locks,
                            void *locks_extra, void *extra) {
    iterate_extra *info = reinterpret_cast<iterate_extra *>(extra);
    DB *db;
    DBT left_key, right_key;
    int r = iterate_locks(&db, &left_key, &right_key, locks_extra);
    invariant(r == DB_NOTFOUND);
    if (txnid == txnid1) {
        assert(!info->visited_txn[0]);
        invariant(client_id == 0);
        info->visited_txn[0] = true;
    } else if (txnid == txnid2) {
        assert(!info->visited_txn[1]);
        invariant(client_id == 1);
        info->visited_txn[1] = true;
    } else if (txnid == txnid3) {
        assert(!info->visited_txn[2]);
        invariant(client_id == 2);
        info->visited_txn[2] = true;
    }
    info->n++;
    return 0;
}

int test_main(int UU(argc), char *const UU(argv[])) {
    int r;
    const int env_flags = DB_INIT_MPOOL | DB_CREATE | DB_THREAD |
        DB_INIT_LOCK | DB_INIT_LOG | DB_INIT_TXN | DB_PRIVATE;

    toku_os_recursive_delete(TOKU_TEST_FILENAME);
    r = toku_os_mkdir(TOKU_TEST_FILENAME, 0755); CKERR(r);

    DB_ENV *env;
    r = db_env_create(&env, 0); CKERR(r);
    r = env->iterate_live_transactions(env, iterate_callback, NULL);
    assert(r == EINVAL);
    r = env->open(env, TOKU_TEST_FILENAME, env_flags, 0755); CKERR(r);

    r = env->txn_begin(env, NULL, &txn1, 0); CKERR(r);
    txn1->set_client_id(txn1, 0);
    txnid1 = txn1->id64(txn1);
    r = env->txn_begin(env, NULL, &txn2, 0); CKERR(r);
    txn2->set_client_id(txn2, 1);
    txnid2 = txn2->id64(txn2);
    r = env->txn_begin(env, NULL, &txn3, 0); CKERR(r);
    txn3->set_client_id(txn3, 2);
    txnid3 = txn3->id64(txn3);

    {
        iterate_extra e;
        r = env->iterate_live_transactions(env, iterate_callback, &e); CKERR(r);
        assert(e.visited_txn[0]);
        assert(e.visited_txn[1]);
        assert(e.visited_txn[2]);
        assert(e.n == 3);
    }

    r = txn1->commit(txn1, 0); CKERR(r);
    r = txn2->abort(txn2); CKERR(r);
    {
        iterate_extra e;
        r = env->iterate_live_transactions(env, iterate_callback, &e); CKERR(r);
        assert(!e.visited_txn[0]);
        assert(!e.visited_txn[1]);
        assert(e.visited_txn[2]);
        assert(e.n == 1);
    }

    r = txn3->commit(txn3, 0); CKERR(r);
    {
        iterate_extra e;
        r = env->iterate_live_transactions(env, iterate_callback, &e); CKERR(r);
        assert(!e.visited_txn[0]);
        assert(!e.visited_txn[1]);
        assert(!e.visited_txn[2]);
        assert(e.n == 0);
    }

    r = env->close(env, 0); CKERR(r);
    return 0;
}
<|endoftext|>


<commit_before>#include "extlineeditmainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    CExtLineEditMainWindow w;
    w.show();

    return a.exec();
}
<commit_msg>Just starts the demo<commit_after>#include "demo.h"
//#include "extstackedwidgetmainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    CDemo w;
    w.show();

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


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/usr/diag/prdf/plat/mem/prdfMemTdQueue.H $                 */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2017                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

/** @file  prdfMemTdQueue.H
 *  @brief Support code for a Targeted Diagnostics weighted event queue.
 */

#ifndef __prdfMemTdQueue_H
#define __prdfMemTdQueue_H

// Framework includes
#include <iipServiceDataCollector.h>

// Platform includes
#include <prdfMemRank.H>

// Other includes
#include <algorithm>
#include <vector>

namespace PRDF
{

//------------------------------------------------------------------------------
//                               TdEntry class
//------------------------------------------------------------------------------

/** @brief Abstract class for a Targeted Diagnostics event. */
class TdEntry
{
  public: // enums, constants

    /**
     * @brief This enum will be used to indicate type of TD event requested to
     *        be handled.
     * @note  The order of the enums values is important because it is used for
     *        sorting the TdQueue by event type priority.
     */
    enum TdType
    {
        VCM_EVENT = 0,       ///< A Verify Chip Mark event.
        TPS_EVENT,           ///< A Two-Phase Scrub event.
        INVALID_EVENT = 0xf, ///< Used to denote that no event is in progress
    };

    /**
     * @brief This enum will indicate which VCM or TPS phase we are currently on
     */
    enum Phase
    {
        TD_PHASE_0,
        TD_PHASE_1,
        TD_PHASE_2,
    };

  public: // functions

    /** @brief Default destructor */
    virtual ~TdEntry() = default;

    /**
     * @brief  Each entry will have a set of steps that need to be performed.
     *         This function tells the procedure to move onto the next step.
     * @param  io_sc  The step code data struct.
     * @param  o_done True if the procedure is complete or has aborted, false
     *                otherwise.
     * @return Non-SUCCESS if an internal function fails, SUCCESS otherwise.
     */
    virtual uint32_t nextStep( STEP_CODE_DATA_STRUCT & io_sc,
                               bool & o_done ) = 0;

    /** @return Each event type will have a unique key identifier used for each
     *          procedure. The value is arbitrary. The only requirement is that
     *          it is unique to the hardware it is targeting. For example, VCM
     *          events will use only the master rank, where TPS events will use
     *          both the master and slave rank. */
    virtual uint32_t getKey() const = 0;

    /** @brief '==' operator */
    bool operator==( const TdEntry & i_e ) const
    {
        return ( this->iv_tdType == i_e.iv_tdType &&
                 this->getKey()  == i_e.getKey()     );
    }

    /**
     * @brief '<' operator
     * @note This only compares iv_tdType because the TdQueue only sorts by type
     */
    bool operator<( const TdEntry & i_e ) const
    {
        return this->iv_tdType < i_e.iv_tdType;
    }

    /** @return The event type */
    TdType getType() const { return iv_tdType; }

    /** @return The rank in which this event occurred */
    MemRank getRank() const { return iv_rank; }

    /** @return The event phase */
    Phase getPhase() const { return iv_phase; }

  protected: // functions

    /**
     * @brief Constructor
     * @param i_tdType  See TdType enum
     * @param i_chip    MCA or MBA chip
     * @param i_rank    Target rank
     */
    TdEntry( TdType i_tdType, ExtensibleChip * i_chip, MemRank i_rank ) :
        iv_tdType(i_tdType), iv_chip(i_chip), iv_rank(i_rank)
    {}

  protected: // instance variables

    const TdType iv_tdType;      ///< The event type (see enum TdType).
    Phase iv_phase = TD_PHASE_0; ///< The event phase (see enum Phase).

    // These are not used for comparisons, but used by all procedures and also
    // used for displaying FFDC in the TD controller.
    ExtensibleChip * const iv_chip; ///< The chip in which this event occurred.
    const MemRank          iv_rank; ///< The rank in which this event occurred.

};

//------------------------------------------------------------------------------
//                               TdQueue class
//------------------------------------------------------------------------------

/**
 * @brief This is a weighted queue for all Targeted Diagnostics events.
 * @note  Events with a higher priority will be moved ahead of lower priority
 *        events.
 */
class TdQueue
{
  public: // typedefs

    typedef          std::vector< TdEntry * >           Queue;
    typedef typename std::vector< TdEntry * >::iterator QueueItr;

  public: // functions

    /** @brief Destructor. */
    ~TdQueue() { for ( auto & a : iv_queue ) delete a; }

    /** @return TRUE if the queue is empty, FALSE otherwise. */
    bool empty() const { return iv_queue.empty(); }

    /**
     * @brief  Sorts the queue by priority order then returns the first entry.
     * @return The first entry in the queue.
     * @note   This is intended to be called only once for each time the TD
     *         controller needs to find the next TD procedure to do. If it is
     *         called multiple times, it is possible the list is reordered such
     *         that a new entry is moved to the front of the queue and is
     *         mistakenly removed via pop() before the TD controller is able to
     *         execute the request.
     */
    TdEntry * getNextEntry()
    {
        PRDF_ASSERT( !iv_queue.empty() );

        // TODO: RTC 66487 This function currently has the complexity of
        //       O(n lg n) because of the sorting. It is possible to optimize
        //       this to O(n) if we use push_heap()/pop_heap(). However, there
        //       is a problem were push_heap() could possibly reorder the queue
        //       while a TD procedure is in progress, which is undesirable.

        std::sort( iv_queue.begin(), iv_queue.end(),
                   [](TdEntry * a, TdEntry * b) { return *a < *b; } );

        return iv_queue.front();
    }

    /**
     * @brief Add new TD entry at the end of the queue.
     * @param i_e A TD entry.
     * @note  Only adds the entry to the queue if the entry does not already
     *        exist in the queue.
     */
    void push( TdEntry * i_e )
    {
        QueueItr it = std::find_if( iv_queue.begin(), iv_queue.end(),
                                    [=](TdEntry * a){return *i_e == *a;} );
        if ( iv_queue.end() == it )
        {
            iv_queue.push_back( i_e );
        }
        else
        {
            // The event is already in the queue. So free up the memory.
            delete i_e;
        }
    }

    /**
     * @brief Removes the entry at the beginning of the queue.
     */
    // TODO: RTC 66487 This function currently has a complexity of 0(n). It
    //       is preferred to have 0(1), which could be accomplished with by
    //       using a deque or list. Unfortunately, Hostboot currently does not
    //       support std::deque or std::list::sort(). Therefore, we must use a
    //       vector at this time.
    void pop()
    {
        PRDF_ASSERT( !iv_queue.empty() );

        delete *(iv_queue.begin());
        iv_queue.erase(iv_queue.begin());
    }

    /**
     * @return A constant reference to the queue.
     * @note   The only purpose for this is for FFDC.
     */
    const Queue & getQueue() const { return iv_queue; }

  private: // instance variables

    /** Stores all ranks that are marked for targeted diagnostics. */
    Queue iv_queue;
};

} // end namespace PRDF

#endif // __prdfMemTdQueue_H

<commit_msg>PRD: Add iv_chip to TdEntry equality operator<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/usr/diag/prdf/plat/mem/prdfMemTdQueue.H $                 */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2017                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

/** @file  prdfMemTdQueue.H
 *  @brief Support code for a Targeted Diagnostics weighted event queue.
 */

#ifndef __prdfMemTdQueue_H
#define __prdfMemTdQueue_H

// Framework includes
#include <iipServiceDataCollector.h>

// Platform includes
#include <prdfMemRank.H>

// Other includes
#include <algorithm>
#include <vector>

namespace PRDF
{

//------------------------------------------------------------------------------
//                               TdEntry class
//------------------------------------------------------------------------------

/** @brief Abstract class for a Targeted Diagnostics event. */
class TdEntry
{
  public: // enums, constants

    /**
     * @brief This enum will be used to indicate type of TD event requested to
     *        be handled.
     * @note  The order of the enums values is important because it is used for
     *        sorting the TdQueue by event type priority.
     */
    enum TdType
    {
        VCM_EVENT = 0,       ///< A Verify Chip Mark event.
        TPS_EVENT,           ///< A Two-Phase Scrub event.
        INVALID_EVENT = 0xf, ///< Used to denote that no event is in progress
    };

    /**
     * @brief This enum will indicate which VCM or TPS phase we are currently on
     */
    enum Phase
    {
        TD_PHASE_0,
        TD_PHASE_1,
        TD_PHASE_2,
    };

  public: // functions

    /** @brief Default destructor */
    virtual ~TdEntry() = default;

    /**
     * @brief  Each entry will have a set of steps that need to be performed.
     *         This function tells the procedure to move onto the next step.
     * @param  io_sc  The step code data struct.
     * @param  o_done True if the procedure is complete or has aborted, false
     *                otherwise.
     * @return Non-SUCCESS if an internal function fails, SUCCESS otherwise.
     */
    virtual uint32_t nextStep( STEP_CODE_DATA_STRUCT & io_sc,
                               bool & o_done ) = 0;

    /** @return Each event type will have a unique key identifier used for each
     *          procedure. The value is arbitrary. The only requirement is that
     *          it is unique to the hardware it is targeting. For example, VCM
     *          events will use only the master rank, where TPS events will use
     *          both the master and slave rank. */
    virtual uint32_t getKey() const = 0;

    /** @brief '==' operator */
    bool operator==( const TdEntry & i_e ) const
    {
        return ( this->iv_tdType == i_e.iv_tdType &&
                 this->getKey()  == i_e.getKey()  &&
                 this->iv_chip   == i_e.iv_chip );
    }

    /**
     * @brief '<' operator
     * @note This only compares iv_tdType because the TdQueue only sorts by type
     */
    bool operator<( const TdEntry & i_e ) const
    {
        return this->iv_tdType < i_e.iv_tdType;
    }

    /** @return The event type */
    TdType getType() const { return iv_tdType; }

    /** @return The rank in which this event occurred */
    MemRank getRank() const { return iv_rank; }

    /** @return The event phase */
    Phase getPhase() const { return iv_phase; }

  protected: // functions

    /**
     * @brief Constructor
     * @param i_tdType  See TdType enum
     * @param i_chip    MCA or MBA chip
     * @param i_rank    Target rank
     */
    TdEntry( TdType i_tdType, ExtensibleChip * i_chip, MemRank i_rank ) :
        iv_tdType(i_tdType), iv_chip(i_chip), iv_rank(i_rank)
    {}

  protected: // instance variables

    const TdType iv_tdType;         ///< The event type (see enum TdType).
    Phase iv_phase = TD_PHASE_0;    ///< The event phase (see enum Phase).
    ExtensibleChip * const iv_chip; ///< The chip in which this event occurred.

    // These are not used for comparisons, but used by all procedures and also
    // used for displaying FFDC in the TD controller.
    const MemRank          iv_rank; ///< The rank in which this event occurred.

};

//------------------------------------------------------------------------------
//                               TdQueue class
//------------------------------------------------------------------------------

/**
 * @brief This is a weighted queue for all Targeted Diagnostics events.
 * @note  Events with a higher priority will be moved ahead of lower priority
 *        events.
 */
class TdQueue
{
  public: // typedefs

    typedef          std::vector< TdEntry * >           Queue;
    typedef typename std::vector< TdEntry * >::iterator QueueItr;

  public: // functions

    /** @brief Destructor. */
    ~TdQueue() { for ( auto & a : iv_queue ) delete a; }

    /** @return TRUE if the queue is empty, FALSE otherwise. */
    bool empty() const { return iv_queue.empty(); }

    /**
     * @brief  Sorts the queue by priority order then returns the first entry.
     * @return The first entry in the queue.
     * @note   This is intended to be called only once for each time the TD
     *         controller needs to find the next TD procedure to do. If it is
     *         called multiple times, it is possible the list is reordered such
     *         that a new entry is moved to the front of the queue and is
     *         mistakenly removed via pop() before the TD controller is able to
     *         execute the request.
     */
    TdEntry * getNextEntry()
    {
        PRDF_ASSERT( !iv_queue.empty() );

        // TODO: RTC 66487 This function currently has the complexity of
        //       O(n lg n) because of the sorting. It is possible to optimize
        //       this to O(n) if we use push_heap()/pop_heap(). However, there
        //       is a problem were push_heap() could possibly reorder the queue
        //       while a TD procedure is in progress, which is undesirable.

        std::sort( iv_queue.begin(), iv_queue.end(),
                   [](TdEntry * a, TdEntry * b) { return *a < *b; } );

        return iv_queue.front();
    }

    /**
     * @brief Add new TD entry at the end of the queue.
     * @param i_e A TD entry.
     * @note  Only adds the entry to the queue if the entry does not already
     *        exist in the queue.
     */
    void push( TdEntry * i_e )
    {
        QueueItr it = std::find_if( iv_queue.begin(), iv_queue.end(),
                                    [=](TdEntry * a){return *i_e == *a;} );
        if ( iv_queue.end() == it )
        {
            iv_queue.push_back( i_e );
        }
        else
        {
            // The event is already in the queue. So free up the memory.
            delete i_e;
        }
    }

    /**
     * @brief Removes the entry at the beginning of the queue.
     */
    // TODO: RTC 66487 This function currently has a complexity of 0(n). It
    //       is preferred to have 0(1), which could be accomplished with by
    //       using a deque or list. Unfortunately, Hostboot currently does not
    //       support std::deque or std::list::sort(). Therefore, we must use a
    //       vector at this time.
    void pop()
    {
        PRDF_ASSERT( !iv_queue.empty() );

        delete *(iv_queue.begin());
        iv_queue.erase(iv_queue.begin());
    }

    /**
     * @return A constant reference to the queue.
     * @note   The only purpose for this is for FFDC.
     */
    const Queue & getQueue() const { return iv_queue; }

  private: // instance variables

    /** Stores all ranks that are marked for targeted diagnostics. */
    Queue iv_queue;
};

} // end namespace PRDF

#endif // __prdfMemTdQueue_H

<|endoftext|>