<commit_before>#include "player.h"

Player::Player()
{

}

Player::Player(Level* lev)
{
	moveVector = sf::Vector2f(0,0);
	position = lev->getPlayerStart();
//	std::cout << "pos: " << position.x << "," << position.y << "\n";
//	initPlayer();
	movementSpeed = 8;
	level = lev;
	collectedScrews = 0;
//	orientation = DIRECTION_LEFT;
//	s = SoundHandler::getSoundHandler();
//	shooting = false;
//	reload_time = 40;
//	shoot_threshold = 0;
//	leben = 100.0f;
	roboto_bold.loadFromFile("assets/Roboto-Bold.ttf");
	tex_player.loadFromFile("assets/robot_ani.png");
	ani = new Animation();
	ani->setSpriteSheet(tex_player);
	ani->addFrame(sf::IntRect(0, 0, 80, 80));
	ani->addFrame(sf::IntRect(80, 0, 80, 80));
	animatedSprite = new AnimatedSprite(sf::seconds(0.2), true, false);
}

void Player::move()
{

	sf::Vector2f mV = moveVector*movementSpeed;

	//std::cout << "move\n" << mV.x << "  " <<mV.y<<"\n";

	// Bounding box of the player(after the move)
	sf::FloatRect* player_box = new sf::FloatRect(position + mV,sf::Vector2f(ROBOTSIZE,ROBOTSIZE));

	//check if hit exit
	if(level->isExit(position + mV,player_box))
	{
		resetLevel(new Level(level->getNextLevel()));
		std::cout << "Exit\n";
	}

	//check for wall Collisions
	mV = level->wallCollision(position,player_box,mV);

	// Update the player location
	sf::Vector2f new_location(position + mV);
	//std::cout << "pos: " << position.x << "," << position.y << "\n";

	//std::cout << "move\n" << mV.x << "  " <<mV.y<<"\n";

	// Check if new position is inside the game area
	if(new_location.x >= 0
		&& new_location.x + ROBOTSIZE <= level->getBounds().x
		&& new_location.y >= 0
		&& new_location.y + ROBOTSIZE <= level->getBounds().y)
	{
	//	std::cout<< collision << "\n";
		position = new_location; // Update location
	}
	collectedScrews += level->screwCollision(position,player_box);

	animatedSprite->update(sf::seconds(0.02));
	animatedSprite->setPosition(position);
}

void Player::setMovementDirection(int direction)
{

	switch(direction)
	{
		case DIRECTION_LEFT:
		moveVector = sf::Vector2f(-1,0);
		break;

		case DIRECTION_LEFT_UP:
		moveVector = sf::Vector2f(-1,-1);
		break;

		case DIRECTION_LEFT_DOWN:
		moveVector = sf::Vector2f(-1,1);
		break;

		case DIRECTION_RIGHT:
		moveVector = sf::Vector2f(1,0);
		break;

		case DIRECTION_RIGHT_UP:
		moveVector = sf::Vector2f(1,-1);
		break;

		case DIRECTION_RIGHT_DOWN:
		moveVector = sf::Vector2f(1,1);
		break;

		case DIRECTION_UP:
		moveVector = sf::Vector2f(0,-1);
		break;

		case DIRECTION_DOWN:
		moveVector = sf::Vector2f(0,1);
		break;

		default:
		//moveVector = sf::Vector2f(0,0);
		break;
	}
}

sf::Vector2f Player::getPosition()
{
	return position;
}

void Player::onDeath()
{

}
void Player::resetLevel(Level* level)
{
	*this->level = *level;
	position = level->getPlayerStart();
}

void Player::draw(sf::RenderTarget& target,sf::RenderStates states)const
{
	/*sf::Sprite sprite_playeVr;
	sprite_player.setTexture(tex_player);
	sprite_player.setPosition(position);

	target.draw(sprite_player);*/

	sf::Time t = sf::seconds(0.2);
	animatedSprite->play(*ani);
	target.draw(*animatedSprite);

	//draw stats
	std::stringstream str;
	str << collectedScrews << " Schrauben gesammelt\n";

	sf::Text stats;
	stats.setFont(roboto_bold);
	stats.setString(str.str());
	stats.setCharacterSize(30);
	stats.setPosition(position - sf::Vector2f(600,350));
	target.draw(stats);
}
<commit_msg>bugfix<commit_after>#include "player.h"

Player::Player()
{

}

Player::Player(Level* lev)
{
	moveVector = sf::Vector2f(0,0);
	position = lev->getPlayerStart();
//	std::cout << "pos: " << position.x << "," << position.y << "\n";
//	initPlayer();
	movementSpeed = 8;
	level = lev;
	collectedScrews = 0;
//	orientation = DIRECTION_LEFT;
//	s = SoundHandler::getSoundHandler();
//	shooting = false;
//	reload_time = 40;
//	shoot_threshold = 0;
//	leben = 100.0f;
	roboto_bold.loadFromFile("assets/Roboto-Bold.ttf");
	tex_player.loadFromFile("assets/robot_ani.png");
	ani = new Animation();
	ani->setSpriteSheet(tex_player);
	ani->addFrame(sf::IntRect(0, 0, 80, 80));
	ani->addFrame(sf::IntRect(80, 0, 80, 80));
	animatedSprite = new AnimatedSprite(sf::seconds(0.2), true, false);
}

void Player::move()
{

	sf::Vector2f mV = moveVector*movementSpeed;

	//std::cout << "move\n" << mV.x << "  " <<mV.y<<"\n";

	// Bounding box of the player(after the move)
	sf::FloatRect* player_box = new sf::FloatRect(position + mV,sf::Vector2f(ROBOTSIZE,ROBOTSIZE));

	//check if hit exit
	if(level->isExit(position + mV,player_box))
	{
		resetLevel(new Level(level->getNextLevel()));
		std::cout << "Exit\n";
	}

	//check for wall Collisions
	mV = level->wallCollision(position,player_box,mV);

	// Update the player location
	sf::Vector2f new_location(position + mV);
	//std::cout << "pos: " << position.x << "," << position.y << "\n";

	//std::cout << "move\n" << mV.x << "  " <<mV.y<<"\n";

	// Check if new position is inside the game area
	if(new_location.x >= 0
		&& new_location.x + ROBOTSIZE <= level->getBounds().x
		&& new_location.y >= 0
		&& new_location.y + ROBOTSIZE <= level->getBounds().y)
	{
	//	std::cout<< collision << "\n";
		position = new_location; // Update location
	}
	collectedScrews += level->screwCollision(position,player_box);

	animatedSprite->update(sf::seconds(0.02));
	animatedSprite->setPosition(position);
}

void Player::setMovementDirection(int direction)
{

	switch(direction)
	{
		case DIRECTION_LEFT:
		moveVector = sf::Vector2f(-1,0);
		break;

		case DIRECTION_LEFT_UP:
		moveVector = sf::Vector2f(-1,-1);
		break;

		case DIRECTION_LEFT_DOWN:
		moveVector = sf::Vector2f(-1,1);
		break;

		case DIRECTION_RIGHT:
		moveVector = sf::Vector2f(1,0);
		break;

		case DIRECTION_RIGHT_UP:
		moveVector = sf::Vector2f(1,-1);
		break;

		case DIRECTION_RIGHT_DOWN:
		moveVector = sf::Vector2f(1,1);
		break;

		case DIRECTION_UP:
		moveVector = sf::Vector2f(0,-1);
		break;

		case DIRECTION_DOWN:
		moveVector = sf::Vector2f(0,1);
		break;

		default:
		moveVector = sf::Vector2f(0,0);
		break;
	}
}

sf::Vector2f Player::getPosition()
{
	return position;
}

void Player::onDeath()
{

}
void Player::resetLevel(Level* level)
{
	*this->level = *level;
	position = level->getPlayerStart();
}

void Player::draw(sf::RenderTarget& target,sf::RenderStates states)const
{
	/*sf::Sprite sprite_playeVr;
	sprite_player.setTexture(tex_player);
	sprite_player.setPosition(position);

	target.draw(sprite_player);*/

	sf::Time t = sf::seconds(0.2);
	animatedSprite->play(*ani);
	target.draw(*animatedSprite);

	//draw stats
	std::stringstream str;
	str << collectedScrews << " Schrauben gesammelt\n";

	sf::Text stats;
	stats.setFont(roboto_bold);
	stats.setString(str.str());
	stats.setCharacterSize(30);
	stats.setPosition(position - sf::Vector2f(600,350));
	target.draw(stats);
}
<|endoftext|>


<commit_before>// Copyright (c) 2011-2015 Zeex
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
//    this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
//    this list of conditions and the following disclaimer in the documentation
//    and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

#include <functional>
#include <sstream>
#include <string>
#include <subhook.h>
#ifdef _WIN32
  #include <windows.h>
#else
  #include <stdio.h>
#endif
#include "amxerror.h"
#include "amxpathfinder.h"
#include "crashdetecthandler.h"
#include "fileutils.h"
#include "logprintf.h"
#include "natives.h"
#include "os.h"
#include "plugincommon.h"
#include "pluginversion.h"
#include "stringutils.h"

namespace {

subhook::Hook amx_exec_hook;

// Path to the last loaded AMX file. This is used to make a connection between
// *.amx files and their corresponding AMX instances.
std::string last_amx_path;

// Stores paths to loaded AMX files and is able to find a path by a pointer to
// an AMX instance.
AMXPathFinder amx_path_finder;

#ifdef _WIN32
  subhook::Hook create_file_hook;

  HANDLE
  WINAPI
  CreateFileHookA(
      _In_ LPCSTR lpFileName,
      _In_ DWORD dwDesiredAccess,
      _In_ DWORD dwShareMode,
      _In_opt_ LPSECURITY_ATTRIBUTES lpSecurityAttributes,
      _In_ DWORD dwCreationDisposition,
      _In_ DWORD dwFlagsAndAttributes,
      _In_opt_ HANDLE hTemplateFile)
  {
    subhook::ScopedHookRemove _(&create_file_hook);

    std::string file_ext(fileutils::GetExtenstion(lpFileName));
    if (stringutils::ToLower(file_ext) == "amx") {
      last_amx_path = lpFileName;
    }

    return CreateFileA(
      lpFileName,
      dwDesiredAccess,
      dwShareMode,
      lpSecurityAttributes,
      dwCreationDisposition,
      dwFlagsAndAttributes,
      hTemplateFile);
  }
#else
  subhook::Hook fopen_hook;

  FILE *FopenHook(const char *filename, const char *mode) {
    subhook::ScopedHookRemove _(&fopen_hook);

    std::string file_ext(fileutils::GetExtenstion(filename));
    if (stringutils::ToLower(file_ext) == "amx") {
      last_amx_path = filename;
    }

    return fopen(filename, mode);
  }
#endif

int AMXAPI AmxDebug(AMX *amx) {
  return CrashDetectHandler::GetHandler(amx)->HandleAMXDebug();
}

int AMXAPI AmxCallback(AMX *amx, cell index, cell *result, cell *params) {
  CrashDetectHandler *handler = CrashDetectHandler::GetHandler(amx);
  return handler->HandleAMXCallback(index, result, params);
}

int AMXAPI AmxExec(AMX *amx, cell *retval, int index) {
  if (amx->flags & AMX_FLAG_BROWSE) {
    return amx_Exec(amx, retval, index);
  }
  return CrashDetectHandler::GetHandler(amx)->HandleAMXExec(retval, index);
}

void AMXAPI AmxExecError(AMX *amx, cell index, cell *retval, int error) {
  CrashDetectHandler *handler = CrashDetectHandler::GetHandler(amx);
  handler->HandleAMXExecError(index, retval, error);
}

} // anonymous namespace

PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() {
  return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES;
}

PLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData) {
  void **exports = reinterpret_cast<void**>(ppData[PLUGIN_DATA_AMX_EXPORTS]);
  ::logprintf = (logprintf_t)ppData[PLUGIN_DATA_LOGPRINTF];

  void *amx_Exec_ptr = exports[PLUGIN_AMX_EXPORT_Exec];
  void *amx_Exec_sub = subhook::Hook::ReadDst(amx_Exec_ptr);

  if (amx_Exec_sub == 0) {
    amx_exec_hook.Install(amx_Exec_ptr, (void*)AmxExec);
  } else {
    std::string module =
      fileutils::GetFileName(os::GetModuleName(amx_Exec_sub));
    if (!module.empty()) {
      logprintf("  CrashDetect must be loaded before '%s'", module.c_str());
    }
    return false;
  }

  #if _WIN32
    create_file_hook.Install((void*)CreateFileA, (void*)CreateFileHookA);
  #else
    fopen_hook.Install((void*)fopen, (void*)FopenHook);
  #endif

  amx_path_finder.AddSearchPath("gamemodes");
  amx_path_finder.AddSearchPath("filterscripts");

  const char *amx_path_var = getenv("AMX_PATH");
  if (amx_path_var != 0) {
    stringutils::SplitString(
      amx_path_var,
      fileutils::kNativePathListSepChar,
      std::bind1st(std::mem_fun(&AMXPathFinder::AddSearchPath),
                   &amx_path_finder));
  }

  os::SetCrashHandler(CrashDetectHandler::OnCrash);
  os::SetInterruptHandler(CrashDetectHandler::OnInterrupt);

  logprintf("  CrashDetect plugin " PROJECT_VERSION_STRING);
  return true;
}

PLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx) {
  if (last_amx_path.length() != 0) {
    amx_path_finder.AddKnownFile(amx, last_amx_path);
  }

  CrashDetectHandler *handler = CrashDetectHandler::CreateHandler(amx);
  handler->set_amx_path_finder(&amx_path_finder);
  handler->Load();

  amx_SetDebugHook(amx, AmxDebug);
  amx_SetCallback(amx, AmxCallback);
  amx_SetExecErrorHandler(amx, AmxExecError);

  RegisterNatives(amx);
  return AMX_ERR_NONE;
}

PLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx) {
  CrashDetectHandler::GetHandler(amx)->Unload();
  CrashDetectHandler::DestroyHandler(amx);
  return AMX_ERR_NONE;
}
<commit_msg>Add null handler check in amx_Exec() hook<commit_after>// Copyright (c) 2011-2015 Zeex
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
//    this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
//    this list of conditions and the following disclaimer in the documentation
//    and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

#include <functional>
#include <sstream>
#include <string>
#include <subhook.h>
#ifdef _WIN32
  #include <windows.h>
#else
  #include <stdio.h>
#endif
#include "amxerror.h"
#include "amxpathfinder.h"
#include "crashdetecthandler.h"
#include "fileutils.h"
#include "logprintf.h"
#include "natives.h"
#include "os.h"
#include "plugincommon.h"
#include "pluginversion.h"
#include "stringutils.h"

namespace {

subhook::Hook amx_exec_hook;

// Path to the last loaded AMX file. This is used to make a connection between
// *.amx files and their corresponding AMX instances.
std::string last_amx_path;

// Stores paths to loaded AMX files and is able to find a path by a pointer to
// an AMX instance.
AMXPathFinder amx_path_finder;

#ifdef _WIN32
  subhook::Hook create_file_hook;

  HANDLE
  WINAPI
  CreateFileHookA(
      _In_ LPCSTR lpFileName,
      _In_ DWORD dwDesiredAccess,
      _In_ DWORD dwShareMode,
      _In_opt_ LPSECURITY_ATTRIBUTES lpSecurityAttributes,
      _In_ DWORD dwCreationDisposition,
      _In_ DWORD dwFlagsAndAttributes,
      _In_opt_ HANDLE hTemplateFile)
  {
    subhook::ScopedHookRemove _(&create_file_hook);

    std::string file_ext(fileutils::GetExtenstion(lpFileName));
    if (stringutils::ToLower(file_ext) == "amx") {
      last_amx_path = lpFileName;
    }

    return CreateFileA(
      lpFileName,
      dwDesiredAccess,
      dwShareMode,
      lpSecurityAttributes,
      dwCreationDisposition,
      dwFlagsAndAttributes,
      hTemplateFile);
  }
#else
  subhook::Hook fopen_hook;

  FILE *FopenHook(const char *filename, const char *mode) {
    subhook::ScopedHookRemove _(&fopen_hook);

    std::string file_ext(fileutils::GetExtenstion(filename));
    if (stringutils::ToLower(file_ext) == "amx") {
      last_amx_path = filename;
    }

    return fopen(filename, mode);
  }
#endif

int AMXAPI AmxDebug(AMX *amx) {
  return CrashDetectHandler::GetHandler(amx)->HandleAMXDebug();
}

int AMXAPI AmxCallback(AMX *amx, cell index, cell *result, cell *params) {
  CrashDetectHandler *handler = CrashDetectHandler::GetHandler(amx);
  return handler->HandleAMXCallback(index, result, params);
}

int AMXAPI AmxExec(AMX *amx, cell *retval, int index) {
  if (amx->flags & AMX_FLAG_BROWSE) {
    return amx_Exec(amx, retval, index);
  }
  CrashDetectHandler *handler = CrashDetectHandler::GetHandler(amx);
  if (handler == 0) {
    return amx_Exec(amx, retval, index);
  }
  return handler->HandleAMXExec(retval, index);
}

void AMXAPI AmxExecError(AMX *amx, cell index, cell *retval, int error) {
  CrashDetectHandler *handler = CrashDetectHandler::GetHandler(amx);
  handler->HandleAMXExecError(index, retval, error);
}

} // anonymous namespace

PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() {
  return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES;
}

PLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData) {
  void **exports = reinterpret_cast<void**>(ppData[PLUGIN_DATA_AMX_EXPORTS]);
  ::logprintf = (logprintf_t)ppData[PLUGIN_DATA_LOGPRINTF];

  void *amx_Exec_ptr = exports[PLUGIN_AMX_EXPORT_Exec];
  void *amx_Exec_sub = subhook::Hook::ReadDst(amx_Exec_ptr);

  if (amx_Exec_sub == 0) {
    amx_exec_hook.Install(amx_Exec_ptr, (void*)AmxExec);
  } else {
    std::string module =
      fileutils::GetFileName(os::GetModuleName(amx_Exec_sub));
    if (!module.empty()) {
      logprintf("  CrashDetect must be loaded before '%s'", module.c_str());
    }
    return false;
  }

  #if _WIN32
    create_file_hook.Install((void*)CreateFileA, (void*)CreateFileHookA);
  #else
    fopen_hook.Install((void*)fopen, (void*)FopenHook);
  #endif

  amx_path_finder.AddSearchPath("gamemodes");
  amx_path_finder.AddSearchPath("filterscripts");

  const char *amx_path_var = getenv("AMX_PATH");
  if (amx_path_var != 0) {
    stringutils::SplitString(
      amx_path_var,
      fileutils::kNativePathListSepChar,
      std::bind1st(std::mem_fun(&AMXPathFinder::AddSearchPath),
                   &amx_path_finder));
  }

  os::SetCrashHandler(CrashDetectHandler::OnCrash);
  os::SetInterruptHandler(CrashDetectHandler::OnInterrupt);

  logprintf("  CrashDetect plugin " PROJECT_VERSION_STRING);
  return true;
}

PLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx) {
  if (last_amx_path.length() != 0) {
    amx_path_finder.AddKnownFile(amx, last_amx_path);
  }

  CrashDetectHandler *handler = CrashDetectHandler::CreateHandler(amx);
  handler->set_amx_path_finder(&amx_path_finder);
  handler->Load();

  amx_SetDebugHook(amx, AmxDebug);
  amx_SetCallback(amx, AmxCallback);
  amx_SetExecErrorHandler(amx, AmxExecError);

  RegisterNatives(amx);
  return AMX_ERR_NONE;
}

PLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx) {
  CrashDetectHandler::GetHandler(amx)->Unload();
  CrashDetectHandler::DestroyHandler(amx);
  return AMX_ERR_NONE;
}
<|endoftext|>


<commit_before>#include <uv.h>
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#include <strsafe.h>

#include "pm.h"
#include "constants.h"

#define MAX_THREAD_WINDOW_NAME 64

HWND handle;
DWORD threadId;
HANDLE threadHandle;

HANDLE notifyEvent;

char *notify_msg;

bool isRunning = false;

DWORD WINAPI ListenerThread( LPVOID lpParam );

void NotifyAsync(uv_work_t* req);
void NotifyFinished(uv_work_t* req);

void NotifyAsync(uv_work_t* req)
{
    WaitForSingleObject(notifyEvent, INFINITE);
}

void NotifyFinished(uv_work_t* req)
{
    if (isRunning)
    {
        Notify(notify_msg);
    }

    uv_queue_work(uv_default_loop(), req, NotifyAsync, (uv_after_work_cb)NotifyFinished);
}

static long FAR PASCAL WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    if(message == WM_POWERBROADCAST)
    {
		// printf("%d\n", wParam);
		if (wParam == PBT_APMRESUMESUSPEND)
		{
			// printf("wake\n");

            notify_msg = (char *)WAKE_NOTIFY;
            SetEvent(notifyEvent);
		}

		if (wParam == PBT_APMRESUMEAUTOMATIC)
		{
			// printf("waking\n");
            // strcpy(notify_msg, "waking");
            // SetEvent(notifyEvent);
		}

		if (wParam == PBT_APMSUSPEND)
		{
			// printf("sleeping\n");

            notify_msg = (char *)SLEEP_NOTIFY;
            SetEvent(notifyEvent);
		}

		if (wParam == PBT_APMPOWERSTATUSCHANGE)
		{
			// printf("PBT_APMPOWERSTATUSCHANGE\n");
            // SetEvent(notifyEvent);
		}

        //Do something
        return TRUE;
    }
    else
        return DefWindowProc(hWnd, message, wParam, lParam);
}

DWORD WINAPI ListenerThread( LPVOID lpParam )
{
    char className[MAX_THREAD_WINDOW_NAME];
    _snprintf(className, MAX_THREAD_WINDOW_NAME, "ListnerThreadPmNotify_%d", GetCurrentThreadId());

    WNDCLASS wc = {0};

    // Set up and register window class
    wc.lpfnWndProc = (WNDPROC)WindowProc;
    wc.lpszClassName = className;
    RegisterClass(&wc);
    HWND hWin = CreateWindow(className, className, 0, 0, 0, 0, 0, NULL, NULL, NULL, 0);

    BOOL bRet;
    MSG msg;
    while( (bRet = GetMessage( &msg, hWin, 0, 0 )) != 0)
    {
        if (bRet == -1)
        {
            // handle the error and possibly exit
        }
        else
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
    }

    return 0;
}

void Start()
{
    isRunning = true;
}

void Stop()
{
    isRunning = false;
}

void InitPM()
{
    notifyEvent = CreateEvent(NULL, false /* auto-reset event */, false /* non-signalled state */, "");

    threadHandle = CreateThread(
        NULL,                   // default security attributes
        0,                      // use default stack size
        ListenerThread,         // thread function name
        NULL,                   // argument to thread function
        0,                      // use default creation flags
        &threadId);

    uv_work_t* req = new uv_work_t();
    uv_queue_work(uv_default_loop(), req, NotifyAsync, (uv_after_work_cb)NotifyFinished);

    Start();
}<commit_msg>Remove compiler warnings<commit_after>#include <uv.h>
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#include <strsafe.h>

#include "pm.h"
#include "constants.h"

#define MAX_THREAD_WINDOW_NAME 64

HWND handle;
DWORD threadId;
HANDLE threadHandle;

HANDLE notifyEvent;

char *notify_msg;

bool isRunning = false;

DWORD WINAPI ListenerThread( LPVOID lpParam );

void NotifyAsync(uv_work_t* req);
void NotifyFinished(uv_work_t* req);

void NotifyAsync(uv_work_t* req)
{
    WaitForSingleObject(notifyEvent, INFINITE);
}

void NotifyFinished(uv_work_t* req)
{
    if (isRunning)
    {
        Notify(notify_msg);
    }

    uv_queue_work(uv_default_loop(), req, NotifyAsync, (uv_after_work_cb)NotifyFinished);
}

static LRESULT FAR PASCAL WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    if(message == WM_POWERBROADCAST)
    {
		// printf("%d\n", wParam);
		if (wParam == PBT_APMRESUMESUSPEND)
		{
			// printf("wake\n");

            notify_msg = (char *)WAKE_NOTIFY;
            SetEvent(notifyEvent);
		}

		if (wParam == PBT_APMRESUMEAUTOMATIC)
		{
			// printf("waking\n");
            // strcpy(notify_msg, "waking");
            // SetEvent(notifyEvent);
		}

		if (wParam == PBT_APMSUSPEND)
		{
			// printf("sleeping\n");

            notify_msg = (char *)SLEEP_NOTIFY;
            SetEvent(notifyEvent);
		}

		if (wParam == PBT_APMPOWERSTATUSCHANGE)
		{
			// printf("PBT_APMPOWERSTATUSCHANGE\n");
            // SetEvent(notifyEvent);
		}

        //Do something
        return TRUE;
    }
    else
        return DefWindowProc(hWnd, message, wParam, lParam);
}

DWORD WINAPI ListenerThread( LPVOID lpParam )
{
    char className[MAX_THREAD_WINDOW_NAME];
    _snprintf_s(className, MAX_THREAD_WINDOW_NAME, "ListnerThreadPmNotify_%d", GetCurrentThreadId());

    WNDCLASS wc = {0};

    // Set up and register window class
    wc.lpfnWndProc = (WNDPROC)WindowProc;
    wc.lpszClassName = className;
    RegisterClass(&wc);
    HWND hWin = CreateWindow(className, className, 0, 0, 0, 0, 0, NULL, NULL, NULL, 0);

    BOOL bRet;
    MSG msg;
    while( (bRet = GetMessage( &msg, hWin, 0, 0 )) != 0)
    {
        if (bRet == -1)
        {
            // handle the error and possibly exit
        }
        else
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
    }

    return 0;
}

void Start()
{
    isRunning = true;
}

void Stop()
{
    isRunning = false;
}

void InitPM()
{
    notifyEvent = CreateEvent(NULL, false /* auto-reset event */, false /* non-signalled state */, "");

    threadHandle = CreateThread(
        NULL,                   // default security attributes
        0,                      // use default stack size
        ListenerThread,         // thread function name
        NULL,                   // argument to thread function
        0,                      // use default creation flags
        &threadId);

    uv_work_t* req = new uv_work_t();
    uv_queue_work(uv_default_loop(), req, NotifyAsync, (uv_after_work_cb)NotifyFinished);

    Start();
}<|endoftext|>


<commit_before>#include <bitcoin/poller.hpp>

#include <bitcoin/utility/logger.hpp>

namespace libbitcoin {

using std::placeholders::_1;
using std::placeholders::_2;

poller::poller(async_service& service, blockchain& chain)
  : strand_(service.get_service()), chain_(chain)
{
}

void poller::query(channel_ptr node)
{
    fetch_block_locator(chain_,
        std::bind(&poller::initial_ask_blocks,
            this, _1, _2, node));
}

void poller::monitor(channel_ptr node)
{
    node->subscribe_inventory(
        strand_.wrap(std::bind(&poller::receive_inv,
            this, _1, _2, node)));
    node->subscribe_block(
        std::bind(&poller::receive_block,
            this, _1, _2, node));
}

void poller::initial_ask_blocks(const std::error_code& ec,
    const message::block_locator& locator, channel_ptr node)
{
    if (ec)
    {
        log_error(log_domain::poller)
            << "Fetching initial block locator: " << ec.message();
        return;
    }
    strand_.dispatch(std::bind(&poller::ask_blocks,
        this, ec, locator, null_hash, node));
}

void handle_send_packet(const std::error_code& ec)
{
    if (ec)
        log_error(log_domain::poller)
            << "Send problem: " << ec.message();
}

void poller::receive_inv(const std::error_code& ec,
    const message::inventory& packet, channel_ptr node)
{
    if (ec)
    {
        log_error(log_domain::poller)
            << "Received bad inventory: " << ec.message();
        return;
    }
    // Filter out only block inventories
    message::get_data getdata;
    for (const message::inventory_vector& ivv: packet.inventories)
    {
        if (ivv.type != message::inventory_type::block)
            continue;
        // Already got this block
        if (ivv.hash == last_block_hash_)
            continue;
        getdata.inventories.push_back(ivv);
    }
    if (!getdata.inventories.empty())
    {
        last_block_hash_ = getdata.inventories.back().hash;
        node->send(getdata, handle_send_packet);
    }
    node->subscribe_inventory(
        strand_.wrap(std::bind(&poller::receive_inv,
            this, _1, _2, node)));
}

void poller::receive_block(const std::error_code& ec,
    const message::block& blk, channel_ptr node)
{
    if (ec)
    {
        log_error(log_domain::poller)
            << "Received bad block: " << ec.message();
        return;
    }
    chain_.store(blk,
        std::bind(&poller::handle_store,
            this, _1, _2, hash_block_header(blk), node));
    node->subscribe_block(
        std::bind(&poller::receive_block,
            this, _1, _2, node));
}

void poller::handle_store(const std::error_code& ec, block_info info,
    const hash_digest& block_hash, channel_ptr node)
{
    // We need orphan blocks so we can do the next getblocks round
    if (ec && info.status != block_status::orphan)
    {
        log_error(log_domain::poller)
            << "Storing block " << pretty_hex(block_hash)
            << ": " << ec.message();
        return;
    }
    switch (info.status)
    {
        case block_status::orphan:
            // TODO: Make more efficient by storing block hash
            // and next time do not download orphan block again.
            // Remember to remove from list once block is no longer orphan
            fetch_block_locator(chain_,
                strand_.wrap(std::bind(&poller::ask_blocks,
                    this, _1, _2, block_hash, node)));
            break;

        case block_status::rejected:
            log_error(log_domain::poller)
                << "Rejected block " << pretty_hex(block_hash);
            break;

        case block_status::confirmed:
            log_info(log_domain::poller)
                << "Block #" << info.depth << " " << pretty_hex(block_hash);
            break;
    }
}

void poller::ask_blocks(const std::error_code& ec,
    const message::block_locator& locator,
    const hash_digest& hash_stop, channel_ptr node)
{
    if (ec)
    {
        log_error(log_domain::poller)
            << "Ask for blocks: " << ec.message();
        return;
    }
    if (last_hash_end_ == locator.front())
    {
        log_debug(log_domain::poller) << "Skipping duplicate ask blocks: "
            << pretty_hex(locator.front());
        return;
    }
    message::get_blocks packet;
    packet.start_hashes = locator;
    packet.hash_stop = hash_stop;
    node->send(packet, std::bind(&handle_send_packet, _1));
    last_hash_end_ = locator.front();
}

} // namespace libbitcoin

<commit_msg>unitialised variable.<commit_after>#include <bitcoin/poller.hpp>

#include <bitcoin/utility/logger.hpp>

namespace libbitcoin {

using std::placeholders::_1;
using std::placeholders::_2;

poller::poller(async_service& service, blockchain& chain)
  : strand_(service.get_service()), chain_(chain), last_hash_end_(null_hash)
{
}

void poller::query(channel_ptr node)
{
    fetch_block_locator(chain_,
        std::bind(&poller::initial_ask_blocks,
            this, _1, _2, node));
}

void poller::monitor(channel_ptr node)
{
    node->subscribe_inventory(
        strand_.wrap(std::bind(&poller::receive_inv,
            this, _1, _2, node)));
    node->subscribe_block(
        std::bind(&poller::receive_block,
            this, _1, _2, node));
}

void poller::initial_ask_blocks(const std::error_code& ec,
    const message::block_locator& locator, channel_ptr node)
{
    if (ec)
    {
        log_error(log_domain::poller)
            << "Fetching initial block locator: " << ec.message();
        return;
    }
    strand_.dispatch(std::bind(&poller::ask_blocks,
        this, ec, locator, null_hash, node));
}

void handle_send_packet(const std::error_code& ec)
{
    if (ec)
        log_error(log_domain::poller)
            << "Send problem: " << ec.message();
}

void poller::receive_inv(const std::error_code& ec,
    const message::inventory& packet, channel_ptr node)
{
    if (ec)
    {
        log_error(log_domain::poller)
            << "Received bad inventory: " << ec.message();
        return;
    }
    // Filter out only block inventories
    message::get_data getdata;
    for (const message::inventory_vector& ivv: packet.inventories)
    {
        if (ivv.type != message::inventory_type::block)
            continue;
        // Already got this block
        if (ivv.hash == last_block_hash_)
            continue;
        getdata.inventories.push_back(ivv);
    }
    if (!getdata.inventories.empty())
    {
        last_block_hash_ = getdata.inventories.back().hash;
        node->send(getdata, handle_send_packet);
    }
    node->subscribe_inventory(
        strand_.wrap(std::bind(&poller::receive_inv,
            this, _1, _2, node)));
}

void poller::receive_block(const std::error_code& ec,
    const message::block& blk, channel_ptr node)
{
    if (ec)
    {
        log_error(log_domain::poller)
            << "Received bad block: " << ec.message();
        return;
    }
    chain_.store(blk,
        std::bind(&poller::handle_store,
            this, _1, _2, hash_block_header(blk), node));
    node->subscribe_block(
        std::bind(&poller::receive_block,
            this, _1, _2, node));
}

void poller::handle_store(const std::error_code& ec, block_info info,
    const hash_digest& block_hash, channel_ptr node)
{
    // We need orphan blocks so we can do the next getblocks round
    if (ec && info.status != block_status::orphan)
    {
        log_error(log_domain::poller)
            << "Storing block " << pretty_hex(block_hash)
            << ": " << ec.message();
        return;
    }
    switch (info.status)
    {
        case block_status::orphan:
            // TODO: Make more efficient by storing block hash
            // and next time do not download orphan block again.
            // Remember to remove from list once block is no longer orphan
            fetch_block_locator(chain_,
                strand_.wrap(std::bind(&poller::ask_blocks,
                    this, _1, _2, block_hash, node)));
            break;

        case block_status::rejected:
            log_error(log_domain::poller)
                << "Rejected block " << pretty_hex(block_hash);
            break;

        case block_status::confirmed:
            log_info(log_domain::poller)
                << "Block #" << info.depth << " " << pretty_hex(block_hash);
            break;
    }
}

void poller::ask_blocks(const std::error_code& ec,
    const message::block_locator& locator,
    const hash_digest& hash_stop, channel_ptr node)
{
    if (ec)
    {
        log_error(log_domain::poller)
            << "Ask for blocks: " << ec.message();
        return;
    }
    if (last_hash_end_ == locator.front())
    {
        log_debug(log_domain::poller) << "Skipping duplicate ask blocks: "
            << pretty_hex(locator.front());
        return;
    }
    message::get_blocks packet;
    packet.start_hashes = locator;
    packet.hash_stop = hash_stop;
    node->send(packet, std::bind(&handle_send_packet, _1));
    last_hash_end_ = locator.front();
}

} // namespace libbitcoin

<|endoftext|>


<commit_before>/* -*- Mode: C++; indent-tabs-mode: nil; c-basic-offset: 4; tab-width: 4 -*- */

#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/functional.h>
#include <vector>

PYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr<T>)

#include "client.h"

using namespace echolib;
namespace py = pybind11;

typedef function<void(string)> MessageCallback;

class PySubscriber : public Subscriber, public std::enable_shared_from_this<PySubscriber> {
  public:
    PySubscriber(SharedClient client, const string &alias, const string &type, function<void(MessageReader)> callback) : Subscriber(client, alias, type), callback(callback) {

    }

    virtual void on_message(SharedMessage message) {
        MessageReader reader(message);
        py::gil_scoped_acquire gil; // acquire GIL lock
        callback(reader);
    }

  private:

    function<void(MessageReader)> callback;

};

class PyWatcher : public Watcher {
  public:
    using Watcher::Watcher;

    virtual void on_event(SharedDictionary command) {
        PYBIND11_OVERLOAD_PURE(
            void,
            Subscriber,
            on_event,
            command
        );
    }
};

PYBIND11_PLUGIN(pyecho) {

    py::init_threading();
    py::module m("pyecho", "Echo IPC library");

    py::class_<Client, std::shared_ptr<Client> >(m, "Client")
    .def(py::init<string>())
    .def("disconnect", &Client::disconnect, "Disconnect the client")
    .def("wait", [](Client& c, long timeout) {
        py::gil_scoped_release gil; // release GIL lock
        return c.wait(timeout);
    }, "Wait for more messages")
    .def("isConnected", &Client::is_connected, "Check if the client is connected");

    py::class_<PySubscriber, std::shared_ptr<PySubscriber> >(m, "Subscriber")
    .def(py::init<SharedClient, string, string, function<void(MessageReader)> >())
    .def("subscribe", [](PySubscriber &a) {
        py::gil_scoped_release gil; // release GIL lock
        return a.subscribe();
    }, "Start receiving")
    .def("unsubscribe", [](PySubscriber &a) {
        py::gil_scoped_release gil; // release GIL lock
        return a.unsubscribe();
    }, "Stop receiving");

    py::class_<PyWatcher, std::shared_ptr<PyWatcher> >(m, "Watcher")
    .def(py::init<SharedClient, string>())
    .def("subscribe", [](PyWatcher &a) {
        py::gil_scoped_release gil; // release GIL lock
        return a.watch();
    }, "Start receiving")
    .def("unsubscribe", [](PyWatcher &a) {
        py::gil_scoped_release gil; // release GIL lock
        return a.unwatch();
    }, "Stop watching");

    py::class_<Publisher, std::shared_ptr<Publisher> >(m, "Publisher")
    .def(py::init<SharedClient, string, string>())
    .def("send", [](Publisher &p, uchar* data, int size) {
        py::gil_scoped_release gil; // release GIL lock
        return p.send_message(data, size);
    } , "Send a raw buffer")
    .def("send", [](Publisher &p, MessageWriter& message) {
        py::gil_scoped_release gil; // release GIL lock
        return p.send_message(message);
    }, "Send a writer");

    py::class_<BufferedMessage, std::shared_ptr<Message> >(m, "BufferedMessage")
    .def(py::init<int, uchar*, int, bool>())
    .def(py::init<int, MessageWriter>())
    .def("getChannel", &BufferedMessage::get_channel, "Get channel");

    py::class_<MessageReader>(m, "MessageReader")
    .def("readInt", &MessageReader::read_integer, "Read an integer")
    .def("readLong", &MessageReader::read_long, "Read a long")
    .def("readChar", &MessageReader::read_char, "Read a char")
    .def("readFloat", &MessageReader::read_float, "Read a float")
    .def("readDouble", &MessageReader::read_double, "Read a double")
    .def("readString", &MessageReader::read_string, "Read a string");

    py::class_<MessageWriter>(m, "MessageWriter")
    .def(py::init<ssize_t>(), py::arg("size") = 0)
    .def("writeInt", &MessageWriter::write_integer, "Write an integer")
    .def("writeLong", &MessageWriter::write_long, "Write a long")
    .def("writeChar", &MessageWriter::write_char, "Write a char")
    .def("writeFloat", &MessageWriter::write_float, "Write a float")
    .def("writeDouble", &MessageWriter::write_double, "Write a double")
    .def("writeString", &MessageWriter::write_string, "Write a string");

    return m.ptr();

}
<commit_msg>Updating python bindings.<commit_after>/* -*- Mode: C++; indent-tabs-mode: nil; c-basic-offset: 4; tab-width: 4 -*- */

#define WITH_THREAD

#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/functional.h>
#include <vector>

PYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr<T>)

#include "client.h"

using namespace echolib;
namespace py = pybind11;

typedef function<void(string)> MessageCallback;

class PySubscriber : public Subscriber, public std::enable_shared_from_this<PySubscriber> {
  public:
    PySubscriber(SharedClient client, const string &alias, const string &type, function<void(MessageReader)> callback) : Subscriber(client, alias, type), callback(callback) {

    }

    virtual void on_message(SharedMessage message) {
        MessageReader reader(message);
        py::gil_scoped_acquire gil; // acquire GIL lock
        callback(reader);
    }

    using Subscriber::subscribe;
    using Subscriber::unsubscribe;

  private:

    function<void(MessageReader)> callback;

};

class PyWatcher : public Watcher {
  public:
    using Watcher::Watcher;

    void on_event(SharedDictionary command) override {
        PYBIND11_OVERLOAD_PURE(
            void,
            Watcher,
            on_event,
            command
        );
    }
};

PYBIND11_PLUGIN(pyecho) {

    py::module m("pyecho", "Echo IPC library Python bindings");

    py::class_<Client, std::shared_ptr<Client> >(m, "Client")
    .def(py::init<string>())
    .def("disconnect", &Client::disconnect, "Disconnect the client")
    .def("wait", [](Client& c, long timeout) {
        py::gil_scoped_release gil; // release GIL lock
        return c.wait(timeout);
    }, "Wait for more messages")
    .def("isConnected", &Client::is_connected, "Check if the client is connected");

    py::class_<Subscriber, PySubscriber, std::shared_ptr<Subscriber> >(m, "Subscriber")
    .def(py::init<SharedClient, string, string, function<void(MessageReader)> >())
    .def("subscribe", [](PySubscriber &a) {
        py::gil_scoped_release gil; // release GIL lock
        return a.subscribe();
    }, "Start receiving")
    .def("unsubscribe", [](PySubscriber &a) {
        py::gil_scoped_release gil; // release GIL lock
        return a.unsubscribe();
    }, "Stop receiving");

    py::class_<Watcher, PyWatcher, std::shared_ptr<Watcher> >(m, "Watcher")
    .def(py::init<SharedClient, string>())
    .def("subscribe", [](PyWatcher &a) {
        py::gil_scoped_release gil; // release GIL lock
        return a.watch();
    }, "Start receiving")
    .def("unsubscribe", [](PyWatcher &a) {
        py::gil_scoped_release gil; // release GIL lock
        return a.unwatch();
    }, "Stop watching");

    py::class_<Publisher, std::shared_ptr<Publisher> >(m, "Publisher")
    .def(py::init<SharedClient, string, string>())
    .def("send", [](Publisher &p, uchar* data, int size) {
        py::gil_scoped_release gil; // release GIL lock
        return p.send_message(data, size);
    } , "Send a raw buffer")
    .def("send", [](Publisher &p, MessageWriter& message) {
        py::gil_scoped_release gil; // release GIL lock
        return p.send_message(message);
    }, "Send a writer");

    py::class_<BufferedMessage, std::shared_ptr<BufferedMessage> >(m, "BufferedMessage")
    .def(py::init<int, uchar*, int, bool>())
    .def(py::init<int, MessageWriter>())
    .def("getChannel", &BufferedMessage::get_channel, "Get channel");

    py::class_<MessageReader>(m, "MessageReader")
    .def("readInt", &MessageReader::read_integer, "Read an integer")
    .def("readLong", &MessageReader::read_long, "Read a long")
    .def("readChar", &MessageReader::read_char, "Read a char")
    .def("readFloat", &MessageReader::read_float, "Read a float")
    .def("readDouble", &MessageReader::read_double, "Read a double")
    .def("readString", &MessageReader::read_string, "Read a string");

    py::class_<MessageWriter>(m, "MessageWriter")
    .def(py::init<ssize_t>(), py::arg("size") = 0)
    .def("writeInt", &MessageWriter::write_integer, "Write an integer")
    .def("writeLong", &MessageWriter::write_long, "Write a long")
    .def("writeChar", &MessageWriter::write_char, "Write a char")
    .def("writeFloat", &MessageWriter::write_float, "Write a float")
    .def("writeDouble", &MessageWriter::write_double, "Write a double")
    .def("writeString", &MessageWriter::write_string, "Write a string");

    return m.ptr();

}
<|endoftext|>


<commit_before>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2006-2007 Torsten Rahn <tackat@kde.org>
// Copyright 2007      Inge Wallin  <ingwa@kde.org>
//

#include <QtGui/QApplication>
#include <QtCore/QFile>
#include <QtCore/QDir>
#include <QtCore/QLocale>
#include <QtCore/QSettings>
#include <QtCore/QTranslator>

#include "QtMainWindow.h"

#include "MarbleDirs.h"
#include "MarbleDebug.h"
#include "MarbleTest.h"

#ifdef STATIC_BUILD
 #include <QtCore/QtPlugin>
 Q_IMPORT_PLUGIN(qjpeg)
 Q_IMPORT_PLUGIN(qsvg)
#endif

#ifdef Q_OS_MACX
//for getting app bundle path
#include <ApplicationServices/ApplicationServices.h>
#endif

using namespace Marble;

int main(int argc, char *argv[])
{
    // The GraphicsSystem needs to be set before the instantiation of the
    // QApplication. Therefore we need to parse the current setting
    // in this unusual place :-/
    QSettings * graphicsSettings = new QSettings("kde.org", "Marble Desktop Globe");
    QString graphicsString = graphicsSettings->value("View/graphicsSystem", "native").toString();
    delete graphicsSettings;
    QApplication::setGraphicsSystem( graphicsString );

    QApplication app(argc, argv);
    // Widget translation

    QString      lang = QLocale::system().name().section('_', 0, 0);
    QTranslator  translator;
    translator.load( "marble-" + lang, MarbleDirs::path(QString("lang") ) );
    app.installTranslator(&translator);

    // For non static builds on mac and win
    // we need to be sure we can find the qt image
    // plugins. In mac be sure to look in the
    // application bundle...

#ifdef Q_WS_WIN
    QApplication::addLibraryPath( QApplication::applicationDirPath()
        + QDir::separator() + "plugins" );
#endif
#ifdef Q_OS_MACX
    QApplication::instance()->setAttribute(Qt::AA_DontShowIconsInMenus);
    qDebug("Adding qt image plugins to plugin search path...");
    CFURLRef myBundleRef = CFBundleCopyBundleURL(CFBundleGetMainBundle());
    CFStringRef myMacPath = CFURLCopyFileSystemPath(myBundleRef, kCFURLPOSIXPathStyle);
    const char *mypPathPtr = CFStringGetCStringPtr(myMacPath,CFStringGetSystemEncoding());
    CFRelease(myBundleRef);
    CFRelease(myMacPath);
    QString myPath(mypPathPtr);
    // if we are not in a bundle assume that the app is built
    // as a non bundle app and that image plugins will be
    // in system Qt frameworks. If the app is a bundle
    // lets try to set the qt plugin search path...
    if (myPath.contains(".app"))
    {
      myPath += "/Contents/plugins";
      QApplication::addLibraryPath( myPath );
      qDebug( "Added %s to plugin search path", qPrintable( myPath ) );
    }
#endif

    QString marbleDataPath;
    int dataPathIndex=0;
    MarbleGlobal::Profiles profiles = MarbleGlobal::detectProfiles();

    QStringList args = QApplication::arguments();

    for ( int i = 1; i < args.count(); ++i ) {
        const QString arg = args.at(i);

        if ( arg == "--debug-info" )
        {
            MarbleDebug::enable = true;
        }
        else if ( arg.startsWith( "--marbledatapath=", Qt::CaseInsensitive ) )
        {
            marbleDataPath = args.at(i).mid(17);
        }
        else if ( arg.compare( "--marbledatapath", Qt::CaseInsensitive ) == 0 ) {
            dataPathIndex = i + 1;
            marbleDataPath = args.value( dataPathIndex );
            ++i;
        }
        else if ( arg == "--smallscreen" ) {
            profiles |= MarbleGlobal::SmallScreen;
        }
        else if ( arg == "--nosmallscreen" ) {
            profiles &= ~MarbleGlobal::SmallScreen;
        }
        else if ( arg == "--highresolution" ) {
            profiles |= MarbleGlobal::HighResolution;
        }
        else if ( arg == "--nohighresolution" ) {
            profiles &= ~MarbleGlobal::HighResolution;
        }
    }
    MarbleGlobal::getInstance()->setProfiles( profiles );

    MainWindow *window = new MainWindow( marbleDataPath );
    window->setAttribute( Qt::WA_DeleteOnClose, true );

    MarbleTest *marbleTest = new MarbleTest( window->marbleWidget() );

//    window->marbleWidget()->rotateTo( 0, 0, -90 );
//    window->show();

    for ( int i = 1; i < args.count(); ++i ) {
        const QString arg = args.at(i);
        if ( arg == "--timedemo" )
        {
            window->resize(900, 640);
            marbleTest->timeDemo();
            return 0;
        }
        else if( arg == "--gpsdemo" ) {
            window->resize( 900, 640 );
            marbleTest->gpsDemo();
            return 0;
        }
        else if( arg == "--fps" ) {
            window->marbleControl()->marbleWidget()->setShowFrameRate( true );
        }
        else if( arg == "--enableCurrentLocation" )
        {
            window->marbleControl()->setCurrentLocationTabShown(true);
        }
        else if( arg == "--enableFileView" )
        {
            window->marbleControl()->setFileViewTabShown(true);
        }
        else if ( arg == "--tile-id" )
        {
	    window->marbleControl()->marbleWidget()->setShowTileId(true);
        }
        else if ( i != dataPathIndex && QFile::exists( arg ) )
            ( window->marbleControl() )->addGeoDataFile( arg );
    }

    delete marbleTest;

    return app.exec();
}
<commit_msg>Initialize measurement system in the qt application. Fixes wrong distance unit being shown in the mapscale float item and the toolbar. Note that you need to remove a previous View/distanceUnit config entry for this to take effect.<commit_after>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2006-2007 Torsten Rahn <tackat@kde.org>
// Copyright 2007      Inge Wallin  <ingwa@kde.org>
//

#include <QtGui/QApplication>
#include <QtCore/QFile>
#include <QtCore/QDir>
#include <QtCore/QLocale>
#include <QtCore/QSettings>
#include <QtCore/QTranslator>

#include "QtMainWindow.h"

#include "MarbleDirs.h"
#include "MarbleDebug.h"
#include "MarbleTest.h"
#include "MarbleLocale.h"

#ifdef STATIC_BUILD
 #include <QtCore/QtPlugin>
 Q_IMPORT_PLUGIN(qjpeg)
 Q_IMPORT_PLUGIN(qsvg)
#endif

#ifdef Q_OS_MACX
//for getting app bundle path
#include <ApplicationServices/ApplicationServices.h>
#endif

using namespace Marble;

int main(int argc, char *argv[])
{
    // The GraphicsSystem needs to be set before the instantiation of the
    // QApplication. Therefore we need to parse the current setting
    // in this unusual place :-/
    QSettings * graphicsSettings = new QSettings("kde.org", "Marble Desktop Globe");
    QString graphicsString = graphicsSettings->value("View/graphicsSystem", "native").toString();
    delete graphicsSettings;
    QApplication::setGraphicsSystem( graphicsString );

    QApplication app(argc, argv);
    // Widget translation

    QString      lang = QLocale::system().name().section('_', 0, 0);
    QTranslator  translator;
    translator.load( "marble-" + lang, MarbleDirs::path(QString("lang") ) );
    app.installTranslator(&translator);

    // For non static builds on mac and win
    // we need to be sure we can find the qt image
    // plugins. In mac be sure to look in the
    // application bundle...

#ifdef Q_WS_WIN
    QApplication::addLibraryPath( QApplication::applicationDirPath()
        + QDir::separator() + "plugins" );
#endif
#ifdef Q_OS_MACX
    QApplication::instance()->setAttribute(Qt::AA_DontShowIconsInMenus);
    qDebug("Adding qt image plugins to plugin search path...");
    CFURLRef myBundleRef = CFBundleCopyBundleURL(CFBundleGetMainBundle());
    CFStringRef myMacPath = CFURLCopyFileSystemPath(myBundleRef, kCFURLPOSIXPathStyle);
    const char *mypPathPtr = CFStringGetCStringPtr(myMacPath,CFStringGetSystemEncoding());
    CFRelease(myBundleRef);
    CFRelease(myMacPath);
    QString myPath(mypPathPtr);
    // if we are not in a bundle assume that the app is built
    // as a non bundle app and that image plugins will be
    // in system Qt frameworks. If the app is a bundle
    // lets try to set the qt plugin search path...
    if (myPath.contains(".app"))
    {
      myPath += "/Contents/plugins";
      QApplication::addLibraryPath( myPath );
      qDebug( "Added %s to plugin search path", qPrintable( myPath ) );
    }
#endif

    QString marbleDataPath;
    int dataPathIndex=0;
    MarbleGlobal::Profiles profiles = MarbleGlobal::detectProfiles();

    QStringList args = QApplication::arguments();

    for ( int i = 1; i < args.count(); ++i ) {
        const QString arg = args.at(i);

        if ( arg == "--debug-info" )
        {
            MarbleDebug::enable = true;
        }
        else if ( arg.startsWith( "--marbledatapath=", Qt::CaseInsensitive ) )
        {
            marbleDataPath = args.at(i).mid(17);
        }
        else if ( arg.compare( "--marbledatapath", Qt::CaseInsensitive ) == 0 ) {
            dataPathIndex = i + 1;
            marbleDataPath = args.value( dataPathIndex );
            ++i;
        }
        else if ( arg == "--smallscreen" ) {
            profiles |= MarbleGlobal::SmallScreen;
        }
        else if ( arg == "--nosmallscreen" ) {
            profiles &= ~MarbleGlobal::SmallScreen;
        }
        else if ( arg == "--highresolution" ) {
            profiles |= MarbleGlobal::HighResolution;
        }
        else if ( arg == "--nohighresolution" ) {
            profiles &= ~MarbleGlobal::HighResolution;
        }
    }
    MarbleGlobal::getInstance()->setProfiles( profiles );

    QLocale::MeasurementSystem const measurement = QLocale::system().measurementSystem();
    Marble::MeasureSystem const marbleMeasurement = measurement == QLocale::ImperialSystem ? Marble::Imperial : Marble::Metric;
    MarbleGlobal::getInstance()->locale()->setMeasureSystem( marbleMeasurement );

    MainWindow *window = new MainWindow( marbleDataPath );
    window->setAttribute( Qt::WA_DeleteOnClose, true );

    MarbleTest *marbleTest = new MarbleTest( window->marbleWidget() );

//    window->marbleWidget()->rotateTo( 0, 0, -90 );
//    window->show();

    for ( int i = 1; i < args.count(); ++i ) {
        const QString arg = args.at(i);
        if ( arg == "--timedemo" )
        {
            window->resize(900, 640);
            marbleTest->timeDemo();
            return 0;
        }
        else if( arg == "--gpsdemo" ) {
            window->resize( 900, 640 );
            marbleTest->gpsDemo();
            return 0;
        }
        else if( arg == "--fps" ) {
            window->marbleControl()->marbleWidget()->setShowFrameRate( true );
        }
        else if( arg == "--enableCurrentLocation" )
        {
            window->marbleControl()->setCurrentLocationTabShown(true);
        }
        else if( arg == "--enableFileView" )
        {
            window->marbleControl()->setFileViewTabShown(true);
        }
        else if ( arg == "--tile-id" )
        {
	    window->marbleControl()->marbleWidget()->setShowTileId(true);
        }
        else if ( i != dataPathIndex && QFile::exists( arg ) )
            ( window->marbleControl() )->addGeoDataFile( arg );
    }

    delete marbleTest;

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


<commit_before>/*!
 * \file report.cxx
 * \brief Program entry and command line parsing for MP3Report.
 *
 * Copyright (c) 2013 Falko Schmidt <kaethorn@gmail.com>
 *
 * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
 * or copy at http://opensource.org/licenses/MIT)
 */

#include <boost/program_options.hpp>
namespace po = boost::program_options;

#include <iostream>
#include <iterator>
#include <map>
using namespace std;

#include "report_config.hxx"
#include "reporter.hxx"

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

  string reportType, directory, outputPath;

  po::options_description desc("Allowed options");
  desc.add_options()
    ("help,h", "Produce this help message")
    ("version,v", "Print version string")
    ("report-type,r", po::value<string>(&reportType)->default_value("plain"),
     "Report type (html_list, html_collapsible, csv, plain)")
    ("output-path,o", po::value<string>(&outputPath),
     "File to write the report to (fallback: stdout)")
    ("directory", po::value<string>(&directory)->required(), "Working directory")
  ;

  po::positional_options_description p;
  p.add("directory", -1);

  po::variables_map vm;

  po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm);

  if (vm.count("help")) {
    cout << desc << endl;
    return 0;
  }
  if (vm.count("version")) {
    cout << argv[0] << " version " << MP3REPORT_VERSION_MAJOR << "." << MP3REPORT_VERSION_MINOR << endl;
    return 0;
  }

  try {
    po::notify(vm);
  } catch ( const boost::program_options::error& e ) {
    cerr << e.what() << endl;
    return 1;
  }

  if (vm["report-type"].as<string>() != "html_list" &&
      vm["report-type"].as<string>() != "html_collapsible" &&
      vm["report-type"].as<string>() != "csv" &&
      vm["report-type"].as<string>() != "plain") {
    cerr << "invalid report type (should be one of html_list, html_collapsible, csv or plain)" << endl;
    return 1;
  }

  Reporter reporter(&directory, &reportType, &outputPath);
  reporter.run();
  return 0;
}
<commit_msg>use basename for argv[0] in version output.<commit_after>/*!
 * \file report.cxx
 * \brief Program entry and command line parsing for MP3Report.
 *
 * Copyright (c) 2013 Falko Schmidt <kaethorn@gmail.com>
 *
 * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
 * or copy at http://opensource.org/licenses/MIT)
 */

#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>
namespace po = boost::program_options;

#include <iostream>
#include <iterator>
#include <map>
using namespace std;

#include "report_config.hxx"
#include "reporter.hxx"

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

  string reportType, directory, outputPath;

  po::options_description desc("Allowed options");
  desc.add_options()
    ("help,h", "Produce this help message")
    ("version,v", "Print version string")
    ("report-type,r", po::value<string>(&reportType)->default_value("plain"),
     "Report type (html_list, html_collapsible, csv, plain)")
    ("output-path,o", po::value<string>(&outputPath),
     "File to write the report to (fallback: stdout)")
    ("directory", po::value<string>(&directory)->required(), "Working directory")
  ;

  po::positional_options_description p;
  p.add("directory", -1);

  po::variables_map vm;

  po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm);

  if (vm.count("help")) {
    cout << desc << endl;
    return 0;
  }
  if (vm.count("version")) {
    cout << boost::filesystem::basename(argv[0]) << " version " <<
      MP3REPORT_VERSION_MAJOR << "." << MP3REPORT_VERSION_MINOR << endl;
    return 0;
  }

  try {
    po::notify(vm);
  } catch ( const boost::program_options::error& e ) {
    cerr << e.what() << endl;
    return 1;
  }

  if (vm["report-type"].as<string>() != "html_list" &&
      vm["report-type"].as<string>() != "html_collapsible" &&
      vm["report-type"].as<string>() != "csv" &&
      vm["report-type"].as<string>() != "plain") {
    cerr << "invalid report type (should be one of html_list, html_collapsible, csv or plain)" << endl;
    return 1;
  }

  Reporter reporter(&directory, &reportType, &outputPath);
  reporter.run();
  return 0;
}
<|endoftext|>


<commit_before>// Copyright (c) 2009-2012 Bitcoin Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "net.h"
#include "bitcoinrpc.h"
#include "alert.h"
#include "wallet.h"
#include "db.h"
#include "walletdb.h"

using namespace json_spirit;
using namespace std;
extern std::string NeuralRequest(std::string MyNeuralRequest);
extern bool RequestSupermajorityNeuralData();
std::string GetCurrentNeuralNetworkSupermajorityHash(double& out_popularity);
extern void GatherNeuralHashes();
extern bool AsyncNeuralRequest(std::string command_name,std::string cpid,int NodeLimit);

Value getconnectioncount(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 0)
        throw runtime_error(
            "getconnectioncount\n"
            "Returns the number of connections to other nodes.");

    LOCK(cs_vNodes);
    return (int)vNodes.size();
}

std::string NeuralRequest(std::string MyNeuralRequest)
{
    // Find a Neural Network Node that is free
    LOCK(cs_vNodes);
    BOOST_FOREACH(CNode* pNode, vNodes)
    {
        if (Contains(pNode->strSubVer,"1999"))
        {
            //printf("Node is a neural participant \r\n");
            std::string reqid = "reqid";
            pNode->PushMessage("neural", MyNeuralRequest, reqid);
            if (fDebug3) printf(" PUSH ");
        }
    }
    return "";
}

void GatherNeuralHashes()
{
    // Find a Neural Network Node that is free
    LOCK(cs_vNodes);
    BOOST_FOREACH(CNode* pNode, vNodes)
    {
        if (Contains(pNode->strSubVer,"1999"))
        {
            std::string reqid = "reqid";
            std::string command_name="neural_hash";
            pNode->PushMessage("neural", command_name, reqid);
            if (fDebug10) printf(" Pushed ");
        }
    }
}

bool RequestSupermajorityNeuralData()
{
    LOCK(cs_vNodes);
    double dCurrentPopularity = 0;
    std::string sCurrentNeuralSupermajorityHash = GetCurrentNeuralNetworkSupermajorityHash(dCurrentPopularity);
    std::string reqid = DefaultWalletAddress();

    BOOST_FOREACH(CNode* pNode, vNodes)
    {
        if (!pNode->NeuralHash.empty() && !sCurrentNeuralSupermajorityHash.empty() && pNode->NeuralHash == sCurrentNeuralSupermajorityHash)
        {
            std::string command_name="neural_data";
            pNode->PushMessage("neural", command_name, reqid);
            return true;
        }
    }
    return false;
}

Value addnode(const Array& params, bool fHelp)
{
    string strCommand;
    if (params.size() == 2)
        strCommand = params[1].get_str();
    if (fHelp || params.size() != 2 ||
        (strCommand != "onetry" && strCommand != "add" && strCommand != "remove"))
        throw runtime_error(
            "addnode <node> <add|remove|onetry>\n"
            "Attempts add or remove <node> from the addnode list or try a connection to <node> once.");

    string strNode = params[0].get_str();

    if (strCommand == "onetry")
    {
        CAddress addr;
        ConnectNode(addr, strNode.c_str());
        return Value::null;
    }

    LOCK(cs_vAddedNodes);
    vector<string>::iterator it = vAddedNodes.begin();
    for(; it != vAddedNodes.end(); it++)
        if (strNode == *it)
            break;

    if (strCommand == "add")
    {
        if (it != vAddedNodes.end())
            throw JSONRPCError(-23, "Error: Node already added");
        vAddedNodes.push_back(strNode);
    }
    else if(strCommand == "remove")
    {
        if (it == vAddedNodes.end())
            throw JSONRPCError(-24, "Error: Node has not been added.");
        vAddedNodes.erase(it);
    }

    return Value::null;
}

Value getaddednodeinfo(const Array& params, bool fHelp)
{
    if (fHelp || params.size() < 1 || params.size() > 2)
        throw runtime_error(
            "getaddednodeinfo <dns> [node]\n"
            "Returns information about the given added node, or all added nodes\n"
            "(note that onetry addnodes are not listed here)\n"
            "If dns is false, only a list of added nodes will be provided,\n"
            "otherwise connected information will also be available.");

    bool fDns = params[0].get_bool();

    list<string> laddedNodes(0);
    if (params.size() == 1)
    {
        LOCK(cs_vAddedNodes);
        BOOST_FOREACH(string& strAddNode, vAddedNodes)
            laddedNodes.push_back(strAddNode);
    }
    else
    {
        string strNode = params[1].get_str();
        LOCK(cs_vAddedNodes);
        BOOST_FOREACH(string& strAddNode, vAddedNodes)
            if (strAddNode == strNode)
            {
                laddedNodes.push_back(strAddNode);
                break;
            }
        if (laddedNodes.size() == 0)
            throw JSONRPCError(-24, "Error: Node has not been added.");
    }

    if (!fDns)
    {
        Object ret;
        BOOST_FOREACH(string& strAddNode, laddedNodes)
            ret.push_back(Pair("addednode", strAddNode));
        return ret;
    }

    Array ret;

    list<pair<string, vector<CService> > > laddedAddreses(0);
    BOOST_FOREACH(string& strAddNode, laddedNodes)
    {
        vector<CService> vservNode(0);
        if(Lookup(strAddNode.c_str(), vservNode, GetDefaultPort(), fNameLookup, 0))
            laddedAddreses.push_back(make_pair(strAddNode, vservNode));
        else
        {
            Object obj;
            obj.push_back(Pair("addednode", strAddNode));
            obj.push_back(Pair("connected", false));
            Array addresses;
            obj.push_back(Pair("addresses", addresses));
        }
    }

    LOCK(cs_vNodes);
    for (list<pair<string, vector<CService> > >::iterator it = laddedAddreses.begin(); it != laddedAddreses.end(); it++)
    {
        Object obj;
        obj.push_back(Pair("addednode", it->first));

        Array addresses;
        bool fConnected = false;
        BOOST_FOREACH(CService& addrNode, it->second)
        {
            bool fFound = false;
            Object node;
            node.push_back(Pair("address", addrNode.ToString()));
            BOOST_FOREACH(CNode* pnode, vNodes)
                if (pnode->addr == addrNode)
                {
                    fFound = true;
                    fConnected = true;
                    node.push_back(Pair("connected", pnode->fInbound ? "inbound" : "outbound"));
                    break;
                }
            if (!fFound)
                node.push_back(Pair("connected", "false"));
            addresses.push_back(node);
        }
        obj.push_back(Pair("connected", fConnected));
        obj.push_back(Pair("addresses", addresses));
        ret.push_back(obj);
    }

    return ret;
}

bool AsyncNeuralRequest(std::string command_name,std::string cpid,int NodeLimit)
{
    // Find a Neural Network Node that is free
    LOCK(cs_vNodes);
    int iContactCount = 0;
    msNeuralResponse="";
    BOOST_FOREACH(CNode* pNode, vNodes)
    {
        if (Contains(pNode->strSubVer,"1999"))
        {
            std::string reqid = cpid;
            pNode->PushMessage("neural", command_name, reqid);
            //if (fDebug3) printf("Requested command %s \r\n",command_name.c_str());
            iContactCount++;
            if (iContactCount >= NodeLimit) return true;
        }
    }
    if (iContactCount==0)
    {
        printf("No neural network nodes online.");
        return false;
    }
    return true;
}

Value ping(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 0)
        throw runtime_error(
            "ping\n"
            "Requests that a ping be sent to all other nodes, to measure ping time.\n"
            "Results provided in getpeerinfo, pingtime and pingwait fields are decimal seconds.\n"
            "Ping command is handled in queue with all other commands, so it measures processing backlog, not just network ping.");

    // Request that each node send a ping during next message processing pass
    LOCK(cs_vNodes);
    BOOST_FOREACH(CNode* pNode, vNodes) {
        pNode->fPingQueued = true;
    }

    return Value::null;
}

static void CopyNodeStats(std::vector<CNodeStats>& vstats)
{
    vstats.clear();

    LOCK(cs_vNodes);
    vstats.reserve(vNodes.size());
    BOOST_FOREACH(CNode* pnode, vNodes) {
        CNodeStats stats;
        pnode->copyStats(stats);
        vstats.push_back(stats);
    }
}

Value getpeerinfo(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 0)
        throw runtime_error(
            "getpeerinfo\n"
            "Returns data about each connected network node.");

    vector<CNodeStats> vstats;
    CopyNodeStats(vstats);

    Array ret;
    GatherNeuralHashes();

    BOOST_FOREACH(const CNodeStats& stats, vstats) {
        Object obj;

        obj.push_back(Pair("addr", stats.addrName));

          if (!(stats.addrLocal.empty()))
            obj.push_back(Pair("addrlocal", stats.addrLocal));

        obj.push_back(Pair("services", strprintf("%08" PRIx64, stats.nServices)));
        obj.push_back(Pair("lastsend", stats.nLastSend));
        obj.push_back(Pair("lastrecv", stats.nLastRecv));
        obj.push_back(Pair("conntime", stats.nTimeConnected));
        obj.push_back(Pair("pingtime", stats.dPingTime));
        if (stats.dPingWait > 0.0)
            obj.push_back(Pair("pingwait", stats.dPingWait));
        obj.push_back(Pair("version", stats.nVersion));
        obj.push_back(Pair("subver", stats.strSubVer));
        obj.push_back(Pair("inbound", stats.fInbound));
        obj.push_back(Pair("startingheight", stats.nStartingHeight));
        obj.push_back(Pair("nTrust", stats.nTrust));
        obj.push_back(Pair("banscore", stats.nMisbehavior));
        bool bNeural = false;
        bNeural = Contains(stats.strSubVer, "1999");
        obj.push_back(Pair("Neural Network", bNeural));
        if (bNeural)
        {
            obj.push_back(Pair("Neural Hash", stats.NeuralHash));
            obj.push_back(Pair("Neural Participant", IsNeuralNodeParticipant(stats.sGRCAddress, GetAdjustedTime())));

        }
        ret.push_back(obj);
    }

    return ret;
}

Value getnettotals(const Array& params, bool fHelp)
{
    if (fHelp || params.size() > 0)
        throw runtime_error(
            "getnettotals\n"
            "Returns information about network traffic, including bytes in, bytes out,\n"
            "and current time.");

    Object obj;
    obj.push_back(Pair("totalbytesrecv", CNode::GetTotalBytesRecv()));
    obj.push_back(Pair("totalbytessent", CNode::GetTotalBytesSent()));
    obj.push_back(Pair("timemillis", GetTimeMillis()));
    return obj;
}

// ppcoin: send alert.
// There is a known deadlock situation with ThreadMessageHandler
// ThreadMessageHandler: holds cs_vSend and acquiring cs_main in SendMessages()
// ThreadRPCServer: holds cs_main and acquiring cs_vSend in alert.RelayTo()/PushMessage()/BeginMessage()
Value sendalert(const Array& params, bool fHelp)
{
    if (fHelp || params.size() < 6)
        throw runtime_error(
            "sendalert <message> <privatekey> <minver> <maxver> <priority> <id> [cancelupto]\n"
            "<message> is the alert text message\n"
            "<privatekey> is hex string of alert master private key\n"
            "<minver> is the minimum applicable internal client version\n"
            "<maxver> is the maximum applicable internal client version\n"
            "<priority> is integer priority number\n"
            "<id> is the alert id\n"
            "[cancelupto] cancels all alert id's up to this number\n"
            "Returns true or false.");

    CAlert alert;
    CKey key;

    alert.strStatusBar = params[0].get_str();
    alert.nMinVer = params[2].get_int();
    alert.nMaxVer = params[3].get_int();
    alert.nPriority = params[4].get_int();
    alert.nID = params[5].get_int();
    if (params.size() > 6)
        alert.nCancel = params[6].get_int();
    alert.nVersion = PROTOCOL_VERSION;
    alert.nRelayUntil = GetAdjustedTime() + 365*24*60*60;
    alert.nExpiration = GetAdjustedTime() + 365*24*60*60;

    CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
    sMsg << (CUnsignedAlert)alert;
    alert.vchMsg = vector<unsigned char>(sMsg.begin(), sMsg.end());

    vector<unsigned char> vchPrivKey = ParseHex(params[1].get_str());
    key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash
    if (!key.Sign(Hash(alert.vchMsg.begin(), alert.vchMsg.end()), alert.vchSig))
        throw runtime_error(
            "Unable to sign alert, check private key?\n");
    if(!alert.ProcessAlert())
        throw runtime_error(
            "Failed to process alert.\n");
    // Relay alert
    {
        LOCK(cs_vNodes);
        BOOST_FOREACH(CNode* pnode, vNodes)
            alert.RelayTo(pnode);
    }

    Object result;
    result.push_back(Pair("strStatusBar", alert.strStatusBar));
    result.push_back(Pair("nVersion", alert.nVersion));
    result.push_back(Pair("nMinVer", alert.nMinVer));
    result.push_back(Pair("nMaxVer", alert.nMaxVer));
    result.push_back(Pair("nPriority", alert.nPriority));
    result.push_back(Pair("nID", alert.nID));
    if (alert.nCancel > 0)
        result.push_back(Pair("nCancel", alert.nCancel));
    return result;
}
<commit_msg>boost_foreach change in rpcnet.cpp<commit_after>// Copyright (c) 2009-2012 Bitcoin Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "net.h"
#include "bitcoinrpc.h"
#include "alert.h"
#include "wallet.h"
#include "db.h"
#include "walletdb.h"

using namespace json_spirit;
using namespace std;
extern std::string NeuralRequest(std::string MyNeuralRequest);
extern bool RequestSupermajorityNeuralData();
std::string GetCurrentNeuralNetworkSupermajorityHash(double& out_popularity);
extern void GatherNeuralHashes();
extern bool AsyncNeuralRequest(std::string command_name,std::string cpid,int NodeLimit);

Value getconnectioncount(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 0)
        throw runtime_error(
            "getconnectioncount\n"
            "Returns the number of connections to other nodes.");

    LOCK(cs_vNodes);
    return (int)vNodes.size();
}

std::string NeuralRequest(std::string MyNeuralRequest)
{
    // Find a Neural Network Node that is free
    LOCK(cs_vNodes);
    for (auto const& pNode : vNodes)
    {
        if (Contains(pNode->strSubVer,"1999"))
        {
            //printf("Node is a neural participant \r\n");
            std::string reqid = "reqid";
            pNode->PushMessage("neural", MyNeuralRequest, reqid);
            if (fDebug3) printf(" PUSH ");
        }
    }
    return "";
}

void GatherNeuralHashes()
{
    // Find a Neural Network Node that is free
    LOCK(cs_vNodes);
    for (auto const& pNode : vNodes)
    {
        if (Contains(pNode->strSubVer,"1999"))
        {
            std::string reqid = "reqid";
            std::string command_name="neural_hash";
            pNode->PushMessage("neural", command_name, reqid);
            if (fDebug10) printf(" Pushed ");
        }
    }
}

bool RequestSupermajorityNeuralData()
{
    LOCK(cs_vNodes);
    double dCurrentPopularity = 0;
    std::string sCurrentNeuralSupermajorityHash = GetCurrentNeuralNetworkSupermajorityHash(dCurrentPopularity);
    std::string reqid = DefaultWalletAddress();

    for (auto const& pNode : vNodes)
    {
        if (!pNode->NeuralHash.empty() && !sCurrentNeuralSupermajorityHash.empty() && pNode->NeuralHash == sCurrentNeuralSupermajorityHash)
        {
            std::string command_name="neural_data";
            pNode->PushMessage("neural", command_name, reqid);
            return true;
        }
    }
    return false;
}

Value addnode(const Array& params, bool fHelp)
{
    string strCommand;
    if (params.size() == 2)
        strCommand = params[1].get_str();
    if (fHelp || params.size() != 2 ||
        (strCommand != "onetry" && strCommand != "add" && strCommand != "remove"))
        throw runtime_error(
            "addnode <node> <add|remove|onetry>\n"
            "Attempts add or remove <node> from the addnode list or try a connection to <node> once.");

    string strNode = params[0].get_str();

    if (strCommand == "onetry")
    {
        CAddress addr;
        ConnectNode(addr, strNode.c_str());
        return Value::null;
    }

    LOCK(cs_vAddedNodes);
    vector<string>::iterator it = vAddedNodes.begin();
    for(; it != vAddedNodes.end(); it++)
        if (strNode == *it)
            break;

    if (strCommand == "add")
    {
        if (it != vAddedNodes.end())
            throw JSONRPCError(-23, "Error: Node already added");
        vAddedNodes.push_back(strNode);
    }
    else if(strCommand == "remove")
    {
        if (it == vAddedNodes.end())
            throw JSONRPCError(-24, "Error: Node has not been added.");
        vAddedNodes.erase(it);
    }

    return Value::null;
}

Value getaddednodeinfo(const Array& params, bool fHelp)
{
    if (fHelp || params.size() < 1 || params.size() > 2)
        throw runtime_error(
            "getaddednodeinfo <dns> [node]\n"
            "Returns information about the given added node, or all added nodes\n"
            "(note that onetry addnodes are not listed here)\n"
            "If dns is false, only a list of added nodes will be provided,\n"
            "otherwise connected information will also be available.");

    bool fDns = params[0].get_bool();

    list<string> laddedNodes(0);
    if (params.size() == 1)
    {
        LOCK(cs_vAddedNodes);
        for (auto const& strAddNode : vAddedNodes)
            laddedNodes.push_back(strAddNode);
    }
    else
    {
        string strNode = params[1].get_str();
        LOCK(cs_vAddedNodes);
        for (auto const& strAddNode : vAddedNodes)
            if (strAddNode == strNode)
            {
                laddedNodes.push_back(strAddNode);
                break;
            }
        if (laddedNodes.size() == 0)
            throw JSONRPCError(-24, "Error: Node has not been added.");
    }

    if (!fDns)
    {
        Object ret;
        for (auto const& strAddNode : laddedNodes)
            ret.push_back(Pair("addednode", strAddNode));
        return ret;
    }

    Array ret;

    list<pair<string, vector<CService> > > laddedAddreses(0);
    for (auto const& strAddNode : laddedNodes)
    {
        vector<CService> vservNode(0);
        if(Lookup(strAddNode.c_str(), vservNode, GetDefaultPort(), fNameLookup, 0))
            laddedAddreses.push_back(make_pair(strAddNode, vservNode));
        else
        {
            Object obj;
            obj.push_back(Pair("addednode", strAddNode));
            obj.push_back(Pair("connected", false));
            Array addresses;
            obj.push_back(Pair("addresses", addresses));
        }
    }

    LOCK(cs_vNodes);
    for (list<pair<string, vector<CService> > >::iterator it = laddedAddreses.begin(); it != laddedAddreses.end(); it++)
    {
        Object obj;
        obj.push_back(Pair("addednode", it->first));

        Array addresses;
        bool fConnected = false;
        for (auto const& addrNode : it->second)
        {
            bool fFound = false;
            Object node;
            node.push_back(Pair("address", addrNode.ToString()));
            for (auto const& pnode : vNodes)
                if (pnode->addr == addrNode)
                {
                    fFound = true;
                    fConnected = true;
                    node.push_back(Pair("connected", pnode->fInbound ? "inbound" : "outbound"));
                    break;
                }
            if (!fFound)
                node.push_back(Pair("connected", "false"));
            addresses.push_back(node);
        }
        obj.push_back(Pair("connected", fConnected));
        obj.push_back(Pair("addresses", addresses));
        ret.push_back(obj);
    }

    return ret;
}

bool AsyncNeuralRequest(std::string command_name,std::string cpid,int NodeLimit)
{
    // Find a Neural Network Node that is free
    LOCK(cs_vNodes);
    int iContactCount = 0;
    msNeuralResponse="";
    for (auto const& pNode : vNodes)
    {
        if (Contains(pNode->strSubVer,"1999"))
        {
            std::string reqid = cpid;
            pNode->PushMessage("neural", command_name, reqid);
            //if (fDebug3) printf("Requested command %s \r\n",command_name.c_str());
            iContactCount++;
            if (iContactCount >= NodeLimit) return true;
        }
    }
    if (iContactCount==0)
    {
        printf("No neural network nodes online.");
        return false;
    }
    return true;
}

Value ping(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 0)
        throw runtime_error(
            "ping\n"
            "Requests that a ping be sent to all other nodes, to measure ping time.\n"
            "Results provided in getpeerinfo, pingtime and pingwait fields are decimal seconds.\n"
            "Ping command is handled in queue with all other commands, so it measures processing backlog, not just network ping.");

    // Request that each node send a ping during next message processing pass
    LOCK(cs_vNodes);
    for (auto const& pNode : vNodes) {
        pNode->fPingQueued = true;
    }

    return Value::null;
}

static void CopyNodeStats(std::vector<CNodeStats>& vstats)
{
    vstats.clear();

    LOCK(cs_vNodes);
    vstats.reserve(vNodes.size());
    for (auto const& pnode : vNodes) {
        CNodeStats stats;
        pnode->copyStats(stats);
        vstats.push_back(stats);
    }
}

Value getpeerinfo(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 0)
        throw runtime_error(
            "getpeerinfo\n"
            "Returns data about each connected network node.");

    vector<CNodeStats> vstats;
    CopyNodeStats(vstats);

    Array ret;
    GatherNeuralHashes();

    for (auto const& stats : vstats) {
        Object obj;

        obj.push_back(Pair("addr", stats.addrName));

          if (!(stats.addrLocal.empty()))
            obj.push_back(Pair("addrlocal", stats.addrLocal));

        obj.push_back(Pair("services", strprintf("%08" PRIx64, stats.nServices)));
        obj.push_back(Pair("lastsend", stats.nLastSend));
        obj.push_back(Pair("lastrecv", stats.nLastRecv));
        obj.push_back(Pair("conntime", stats.nTimeConnected));
        obj.push_back(Pair("pingtime", stats.dPingTime));
        if (stats.dPingWait > 0.0)
            obj.push_back(Pair("pingwait", stats.dPingWait));
        obj.push_back(Pair("version", stats.nVersion));
        obj.push_back(Pair("subver", stats.strSubVer));
        obj.push_back(Pair("inbound", stats.fInbound));
        obj.push_back(Pair("startingheight", stats.nStartingHeight));
        obj.push_back(Pair("nTrust", stats.nTrust));
        obj.push_back(Pair("banscore", stats.nMisbehavior));
        bool bNeural = false;
        bNeural = Contains(stats.strSubVer, "1999");
        obj.push_back(Pair("Neural Network", bNeural));
        if (bNeural)
        {
            obj.push_back(Pair("Neural Hash", stats.NeuralHash));
            obj.push_back(Pair("Neural Participant", IsNeuralNodeParticipant(stats.sGRCAddress, GetAdjustedTime())));

        }
        ret.push_back(obj);
    }

    return ret;
}

Value getnettotals(const Array& params, bool fHelp)
{
    if (fHelp || params.size() > 0)
        throw runtime_error(
            "getnettotals\n"
            "Returns information about network traffic, including bytes in, bytes out,\n"
            "and current time.");

    Object obj;
    obj.push_back(Pair("totalbytesrecv", CNode::GetTotalBytesRecv()));
    obj.push_back(Pair("totalbytessent", CNode::GetTotalBytesSent()));
    obj.push_back(Pair("timemillis", GetTimeMillis()));
    return obj;
}

// ppcoin: send alert.
// There is a known deadlock situation with ThreadMessageHandler
// ThreadMessageHandler: holds cs_vSend and acquiring cs_main in SendMessages()
// ThreadRPCServer: holds cs_main and acquiring cs_vSend in alert.RelayTo()/PushMessage()/BeginMessage()
Value sendalert(const Array& params, bool fHelp)
{
    if (fHelp || params.size() < 6)
        throw runtime_error(
            "sendalert <message> <privatekey> <minver> <maxver> <priority> <id> [cancelupto]\n"
            "<message> is the alert text message\n"
            "<privatekey> is hex string of alert master private key\n"
            "<minver> is the minimum applicable internal client version\n"
            "<maxver> is the maximum applicable internal client version\n"
            "<priority> is integer priority number\n"
            "<id> is the alert id\n"
            "[cancelupto] cancels all alert id's up to this number\n"
            "Returns true or false.");

    CAlert alert;
    CKey key;

    alert.strStatusBar = params[0].get_str();
    alert.nMinVer = params[2].get_int();
    alert.nMaxVer = params[3].get_int();
    alert.nPriority = params[4].get_int();
    alert.nID = params[5].get_int();
    if (params.size() > 6)
        alert.nCancel = params[6].get_int();
    alert.nVersion = PROTOCOL_VERSION;
    alert.nRelayUntil = GetAdjustedTime() + 365*24*60*60;
    alert.nExpiration = GetAdjustedTime() + 365*24*60*60;

    CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
    sMsg << (CUnsignedAlert)alert;
    alert.vchMsg = vector<unsigned char>(sMsg.begin(), sMsg.end());

    vector<unsigned char> vchPrivKey = ParseHex(params[1].get_str());
    key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash
    if (!key.Sign(Hash(alert.vchMsg.begin(), alert.vchMsg.end()), alert.vchSig))
        throw runtime_error(
            "Unable to sign alert, check private key?\n");
    if(!alert.ProcessAlert())
        throw runtime_error(
            "Failed to process alert.\n");
    // Relay alert
    {
        LOCK(cs_vNodes);
        for (auto const& pnode : vNodes)
            alert.RelayTo(pnode);
    }

    Object result;
    result.push_back(Pair("strStatusBar", alert.strStatusBar));
    result.push_back(Pair("nVersion", alert.nVersion));
    result.push_back(Pair("nMinVer", alert.nMinVer));
    result.push_back(Pair("nMaxVer", alert.nMaxVer));
    result.push_back(Pair("nPriority", alert.nPriority));
    result.push_back(Pair("nID", alert.nID));
    if (alert.nCancel > 0)
        result.push_back(Pair("nCancel", alert.nCancel));
    return result;
}
<|endoftext|>


<commit_before>#include "scanner.hh"
#include <cctype>

using namespace std;

/*
    Spidermonkey's tokenize function has the following control flow structure:

    retry:
    switch (c) {
      case ...:
        goto badchar
      badchar:
      default:
    }
    out:
    error:
*/
boost::optional<boost::variant<Token, Decimal> >
Scanner::getToken() {
    for (;;) {
      Token token;

      if (tokStream.eof()) {
	return boost::optional<boost::variant<Token, Decimal> >();
      }
      int c = tokStream.get();
      auto initialKind = FirstCharKind(firstCharKinds[c]);
      // Cases:
      // 1. Single character token
      if (initialKind <= OneChar_Max) {
	return boost::optional<boost::variant<Token, Decimal> >(Token());
      }
      // 2. Whitespace
      if (isspace(tokStream.get())) continue;

      // 3. Identifier
      for (;;) {
	c = tokStream.get();

      }
      // 4. Decimal
      if (isASCIIDecimal(c)) {
	while (isASCIIDecimal(c)) {
	  c = tokStream.get();
	  if (c == '.') {
	    do {
	      c = tokStream.get();
	    } while (isASCIIDecimal(c));
	  }
	  if (c == 'e' || c == 'E') {
	    c = tokStream.get();
	    if (c == '+' || c == '-')
	      c = tokStream.get();
	    if (!isASCIIDecimal(c)) {
	      std::cerr << "error: malformed decimal" << std::endl;
	      return boost::optional<boost::variant<Token, Decimal> >();
	    }
	    do {
	      c = tokStream.get();
	    } while (isASCIIDecimal(c));
	  }
	}

      }
      // 5. String or Template String
      // 6. EOL
      // 7. Hex, octal, binary
      // 8. Operators
      switch (c) {
      case '.':
	c = tokStream.get();
	if (isASCIIDecimal(c)) {
	  return boost::optional<boost::variant<Token, Decimal> >(Decimal(tokStream.tellg()));
	}
	if (c == '.' && tokStream.get() == '.') {
	  token.type = TOK_TRIPLEDOT;
	  return boost::optional<boost::variant<Token, Decimal> >(token);
	}
      case '=':
	c = tokStream.get();
	if (c == '=') {
	  if (tokStream.get() == '=') token.type = TOK_STRICTEQ;
	  else token.type = TOK_EQ;
	} else if (c == '>') {
	  token.type = TOK_ARROW;
	} else {
	  token.type = TOK_ASSIGN;
	}
	return boost::optional<boost::variant<Token, Decimal> >(token);
      }
    }
}
<commit_msg>scaffolding<commit_after>#include "scanner.hh"
#include <cctype>

using namespace std;

/*
    Spidermonkey's tokenize function has the following control flow structure:

    retry:
    switch (c) {
      case ...:
        goto badchar
      badchar:
      default:
    }
    out:
    error:
*/
boost::optional<boost::variant<Token, Decimal> >
Scanner::getToken() {
    for (;;) {
      Token token;

      if (tokStream.eof()) {
	return boost::optional<boost::variant<Token, Decimal> >();
      }
      int c = tokStream.get();
      auto initialKind = FirstCharKind(firstCharKinds[c]);
      // Cases:
      // 1. Single character token
      if (initialKind <= OneChar_Max) {
	return boost::optional<boost::variant<Token, Decimal> >(Token());
      }
      // 2. Whitespace
      if (isspace(tokStream.get())) continue;

      // 3. Identifier
      for (;;) {
	c = tokStream.get();

      }
      // 4. Decimal
      if (isASCIIDecimal(c)) {
	while (isASCIIDecimal(c)) {
	  c = tokStream.get();
	  if (c == '.') {
	    do {
	      c = tokStream.get();
	    } while (isASCIIDecimal(c));
	  }
	  if (c == 'e' || c == 'E') {
	    c = tokStream.get();
	    if (c == '+' || c == '-')
	      c = tokStream.get();
	    if (!isASCIIDecimal(c)) {
	      std::cerr << "error: malformed decimal" << std::endl;
	      return boost::optional<boost::variant<Token, Decimal> >();
	    }
	    do {
	      c = tokStream.get();
	    } while (isASCIIDecimal(c));
	  }
	}

      }
      // 5. String or Template String
      if (initialKind == String) {

      }
      // 6. EOL
      // 7. Hex, octal, binary
      if (initialKind == BasePrefix) {
	c = tokStream.get();
	if (c == 'x' || c == 'X') {

	} else if (c == 'b' || c == 'B') {

	} else if (c == 'o' || c == 'O') {

	} else if (isASCIIDecimal(c)) {

	} else {
	}
      }
      // 8. Operators
      switch (c) {
      case '.':
	c = tokStream.get();
	if (isASCIIDecimal(c)) {
	  return boost::optional<boost::variant<Token, Decimal> >(Decimal(tokStream.tellg()));
	}
	if (c == '.' && tokStream.get() == '.') {
	  token.type = TOK_TRIPLEDOT;
	  return boost::optional<boost::variant<Token, Decimal> >(token);
	}
      case '=':
	c = tokStream.get();
	if (c == '=') {
	  if (tokStream.get() == '=') token.type = TOK_STRICTEQ;
	  else token.type = TOK_EQ;
	} else if (c == '>') {
	  token.type = TOK_ARROW;
	} else {
	  token.type = TOK_ASSIGN;
	}
	return boost::optional<boost::variant<Token, Decimal> >(token);
      }
    }
}
<|endoftext|>


<commit_before>#include <algorithm>

#include "base/common.h"
#include "base/task.h"

static double english_frequencies[26] = {
    0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015,
    0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749,
    0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758,
    0.00978, 0.02360, 0.00150, 0.01974, 0.00074};

double ScoreData(const std::vector<uint8_t>& input) {
  double frequences[256] = {0.0};
  for (uint8_t element : input) {
    frequences[element] += 1;
  }
  for (double& f : frequences) {
    f /= input.size();
  }

  double score = 0.0;
  for (int i = 0; i < 256; ++i) {
    if ('A' <= i && i <= 'Z') {
      score += std::abs(frequences[i] - english_frequencies[i - 'A']);
    } else if ('a' <= i && i <= 'z') {
      score += std::abs(frequences[i] - english_frequencies[i - 'a']);
    } else {
      score += frequences[i];
    }
  }
  return score;
}

std::vector<uint8_t> XorWithSingleByte(const std::vector<uint8_t>& input,
                                       uint8_t xor_byte) {
  std::vector<uint8_t> result(input.size());
  for (size_t i = 0; i < input.size(); ++i) {
    result[i] = input[i] ^ xor_byte;
  }

  return result;
}

uint8_t DetectSingleCharXor(const std::vector<uint8_t>& input) {
  int best_i = -1;
  double best_score = std::numeric_limits<double>::infinity();

  // From the task we know that we are looking for all lowercase letters.
  for (int i = 'a'; i <= 'z'; ++i) {
    double score = ScoreData(XorWithSingleByte(input, i));
    if (score < best_score) {
      best_score = score;
      best_i = i;
    }
  }

  return best_i;
}

std::vector<uint8_t> RepeatingKeyXor(const std::vector<uint8_t>& input,
                                     const std::vector<uint8_t>& key) {
  std::vector<uint8_t> result(input.size());

  int key_index = 0;
  for (size_t i = 0; i < input.size(); ++i) {
    result[i] = input[i] ^ key[key_index];
    key_index = (key_index + 1) % key.size();
  }

  return result;
}

std::vector<uint8_t> GetEqualDistanceBytes(const std::vector<uint8_t>& data,
                                           int start, int step) {
  std::vector<uint8_t> result;
  result.reserve((data.size() - start) / step);
  for (size_t i = start; i < data.size(); i += step) {
    result.push_back(data[i]);
  }
  return result;
}

#include <iostream>

TASK(59) {
  auto codes = Split(ReadFileIntoString("data/059_cipher.txt"), ',');
  std::vector<uint8_t> cipher(codes.size());
  std::transform(codes.begin(), codes.end(), cipher.begin(),
                 [](const std::string& s) { return std::stoi(s); });

  std::vector<uint8_t> key(3);
  for (int i = 0; i < 3; ++i) {
    auto transposed_data = GetEqualDistanceBytes(cipher, i, 3);
    key[i] = DetectSingleCharXor(transposed_data);
  }

  auto decoded_data = RepeatingKeyXor(cipher, key);

  return std::accumulate(decoded_data.begin(), decoded_data.end(), 0);
}
<commit_msg>Remove unnecessary include<commit_after>#include <algorithm>

#include "base/common.h"
#include "base/task.h"

static double english_frequencies[26] = {
    0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015,
    0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749,
    0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758,
    0.00978, 0.02360, 0.00150, 0.01974, 0.00074};

double ScoreData(const std::vector<uint8_t>& input) {
  double frequences[256] = {0.0};
  for (uint8_t element : input) {
    frequences[element] += 1;
  }
  for (double& f : frequences) {
    f /= input.size();
  }

  double score = 0.0;
  for (int i = 0; i < 256; ++i) {
    if ('A' <= i && i <= 'Z') {
      score += std::abs(frequences[i] - english_frequencies[i - 'A']);
    } else if ('a' <= i && i <= 'z') {
      score += std::abs(frequences[i] - english_frequencies[i - 'a']);
    } else {
      score += frequences[i];
    }
  }
  return score;
}

std::vector<uint8_t> XorWithSingleByte(const std::vector<uint8_t>& input,
                                       uint8_t xor_byte) {
  std::vector<uint8_t> result(input.size());
  for (size_t i = 0; i < input.size(); ++i) {
    result[i] = input[i] ^ xor_byte;
  }

  return result;
}

uint8_t DetectSingleCharXor(const std::vector<uint8_t>& input) {
  int best_i = -1;
  double best_score = std::numeric_limits<double>::infinity();

  // From the task we know that we are looking for all lowercase letters.
  for (int i = 'a'; i <= 'z'; ++i) {
    double score = ScoreData(XorWithSingleByte(input, i));
    if (score < best_score) {
      best_score = score;
      best_i = i;
    }
  }

  return best_i;
}

std::vector<uint8_t> RepeatingKeyXor(const std::vector<uint8_t>& input,
                                     const std::vector<uint8_t>& key) {
  std::vector<uint8_t> result(input.size());

  int key_index = 0;
  for (size_t i = 0; i < input.size(); ++i) {
    result[i] = input[i] ^ key[key_index];
    key_index = (key_index + 1) % key.size();
  }

  return result;
}

std::vector<uint8_t> GetEqualDistanceBytes(const std::vector<uint8_t>& data,
                                           int start, int step) {
  std::vector<uint8_t> result;
  result.reserve((data.size() - start) / step);
  for (size_t i = start; i < data.size(); i += step) {
    result.push_back(data[i]);
  }
  return result;
}

TASK(59) {
  auto codes = Split(ReadFileIntoString("data/059_cipher.txt"), ',');
  std::vector<uint8_t> cipher(codes.size());
  std::transform(codes.begin(), codes.end(), cipher.begin(),
                 [](const std::string& s) { return std::stoi(s); });

  std::vector<uint8_t> key(3);
  for (int i = 0; i < 3; ++i) {
    auto transposed_data = GetEqualDistanceBytes(cipher, i, 3);
    key[i] = DetectSingleCharXor(transposed_data);
  }

  auto decoded_data = RepeatingKeyXor(cipher, key);

  return std::accumulate(decoded_data.begin(), decoded_data.end(), 0);
}
<|endoftext|>