<commit_before>#include "stdafx.h"
#include "csgo_net_chan.h"

#include "WrpConsole.h"

#include "addresses.h"
#include <SourceInterfaces.h>
#include <csgo/bitbuf/demofilebitbuf.h>

#include <build/protobuf/csgo/netmessages.pb.h>

#include <shared/AfxDetours.h>

#include <Windows.h>
#include <deps/release/Detours/src/detours.h>

int g_i_MirvPov = 0;

struct csgo_bf_read {
	char const* m_pDebugName;
	bool m_bOverflow;
	int m_nDataBits;
	size_t m_nDataBytes;
	unsigned int m_nInBufWord;
	int m_nBitsAvail;
	unsigned int const* m_pDataIn;
	unsigned int const* m_pBufferEnd;
	unsigned int const* m_pData;
};

typedef const SOURCESDK::QAngle& (__fastcall *csgo_C_CSPlayer_EyeAngles_t)(SOURCESDK::C_BaseEntity_csgo* This, void* Edx);
csgo_C_CSPlayer_EyeAngles_t Truecsgo_C_CSPlayer_EyeAngles;

const SOURCESDK::QAngle& __fastcall Mycsgo_C_CSPlayer_EyeAngles(SOURCESDK::C_BaseEntity_csgo * This, void * Edx)
{
	if (g_i_MirvPov)
	{
		if (This->entindex() == g_i_MirvPov)
		{
			DWORD ofs = AFXADDR_GET(csgo_C_CSPlayer_ofs_m_angEyeAngles);
			return *((SOURCESDK::QAngle*)((char *)This + ofs));
		}
	}

	return Truecsgo_C_CSPlayer_EyeAngles(This, Edx);
}

typedef void csgo_CNetChan_t;
typedef int(__fastcall* csgo_CNetChan_ProcessMessages_t)(csgo_CNetChan_t* This, void* edx, csgo_bf_read * pReadBuf, bool bWasReliable);
csgo_CNetChan_ProcessMessages_t Truecsgo_CNetChan_ProcessMessages = 0;

int __fastcall Mycsgo_CNetChan_ProcessMessages(csgo_CNetChan_t* This, void* Edx, csgo_bf_read* pReadBuf, bool bWasReliable)
{
	if (g_i_MirvPov)
	{
		SOURCESDK::CSGO::CBitRead readBuf(pReadBuf->m_pData, pReadBuf->m_nDataBytes);

		while (0 < readBuf.GetNumBytesLeft())
		{
			int packet_cmd = readBuf.ReadVarInt32();
			int packet_size = readBuf.ReadVarInt32();
			if (packet_size < readBuf.GetNumBytesLeft())
			{
				switch (packet_cmd)
				{
				case svc_ServerInfo:
					{
						CSVCMsg_ServerInfo msg;
						msg.ParseFromArray(readBuf.GetBasePointer() + readBuf.GetNumBytesRead(), packet_size);
						if (msg.has_is_hltv())
						{
							msg.set_is_hltv(false);
						}
						if (msg.has_player_slot())
						{
							msg.set_player_slot(g_i_MirvPov - 1);
						}
						msg.SerializePartialToArray(const_cast<unsigned char*>(readBuf.GetBasePointer()) + readBuf.GetNumBytesRead(), packet_size);
					}
					break;
				case svc_SetView:
					{
						CSVCMsg_SetView msg;
						msg.ParseFromArray(readBuf.GetBasePointer() + readBuf.GetNumBytesRead(), packet_size);
						if (msg.has_entity_index())
						{
							msg.set_entity_index(g_i_MirvPov);
						}
						msg.SerializePartialToArray(const_cast<unsigned char*>(readBuf.GetBasePointer()) + readBuf.GetNumBytesRead(), packet_size);
					}
					break;
				}

				readBuf.SeekRelative(packet_size * 8);
			}
			else
				break;
		}
	}

	bool result = Truecsgo_CNetChan_ProcessMessages(This, Edx, pReadBuf, bWasReliable);

	if (g_i_MirvPov)
	{
		static WrpConVarRef cvarClPredict;
		cvarClPredict.RetryIfNull("cl_predict"); // GOTV would have this on 0, so force it too.
		cvarClPredict.SetDirectHack(0);
	}

	return result;
}

bool csgo_CNetChan_ProcessMessages_Install(void)
{
	static bool firstResult = false;
	static bool firstRun = true;
	if (!firstRun) return firstResult;
	firstRun = false;

	if (AFXADDR_GET(csgo_CNetChan_ProcessMessages))
	{
		LONG error = NO_ERROR;

		Truecsgo_CNetChan_ProcessMessages = (csgo_CNetChan_ProcessMessages_t)AFXADDR_GET(csgo_CNetChan_ProcessMessages);

		DetourTransactionBegin();
		DetourUpdateThread(GetCurrentThread());
		DetourAttach(&(PVOID&)Truecsgo_CNetChan_ProcessMessages, Mycsgo_CNetChan_ProcessMessages);
		error = DetourTransactionCommit();

		firstResult = NO_ERROR == error;
	}

	return firstResult;
}

bool csgo_C_CSPlayer_EyeAngles_Install(void)
{
	static bool firstResult = false;
	static bool firstRun = true;
	if (!firstRun) return firstResult;
	firstRun = false;

	if (AFXADDR_GET(csgo_C_CSPlayer_vtable))
	{
		AfxDetourPtr((PVOID*)&(((DWORD*)AFXADDR_GET(csgo_C_CSPlayer_vtable))[169]), Mycsgo_C_CSPlayer_EyeAngles, (PVOID*)&Truecsgo_C_CSPlayer_EyeAngles);

		firstResult = true;
	}

	return firstResult;
}

typedef int(__fastcall* csgo_DamageIndicator_MessageFunc_t)(void* This, void* Edx, const char * pMsg);
csgo_DamageIndicator_MessageFunc_t Truecsgo_DamageIndicator_MessageFunc = 0;

bool __fastcall MYcsgo_DamageIndicator_MessageFunc(void* This, void* Edx, const char* pMsg)
{
	if (g_i_MirvPov)
	{
		bool abort = false;

		__asm mov eax, pMsg
		__asm mov eax, [eax + 0x10]
		__asm cmp eax, g_i_MirvPov
		__asm jz __cont
		__asm mov abort, 1
		__asm __cont:

		if (abort) return true;
	}

	return Truecsgo_DamageIndicator_MessageFunc(This, Edx, pMsg);
}

bool csgo_DamageIndicator_MessageFunc_Install(void)
{
	static bool firstResult = false;
	static bool firstRun = true;
	if (!firstRun) return firstResult;
	firstRun = false;

	if (AFXADDR_GET(csgo_DamageIndicator_MessageFunc))
	{
		LONG error = NO_ERROR;

		Truecsgo_DamageIndicator_MessageFunc = (csgo_DamageIndicator_MessageFunc_t)AFXADDR_GET(csgo_DamageIndicator_MessageFunc);

		DetourTransactionBegin();
		DetourUpdateThread(GetCurrentThread());
		DetourAttach(&(PVOID&)Truecsgo_DamageIndicator_MessageFunc, MYcsgo_DamageIndicator_MessageFunc);
		error = DetourTransactionCommit();

		firstResult = NO_ERROR == error;
	}

	return firstResult;
}

typedef void(__fastcall* csgo_C_CSPlayer_UpdateOnRemove_t)(SOURCESDK::C_BasePlayer_csgo* This, void* Edx);

csgo_C_CSPlayer_UpdateOnRemove_t Truecsgo_C_CSPlayer_UpdateOnRemove = nullptr;

typedef void(__fastcall* csgo_C_BasePlayer_SetAsLocalPlayer_t)(void* Ecx, void* Edx);

void __fastcall Mycsgo_C_CSPlayer_UpdateOnRemove(SOURCESDK::C_BasePlayer_csgo* This, void* Edx)
{
	if (g_i_MirvPov && This->entindex() == g_i_MirvPov)
	{
		if (SOURCESDK::IClientEntity_csgo* ce1 = SOURCESDK::g_Entitylist_csgo->GetClientEntity(1))
		{
			if (SOURCESDK::C_BaseEntity_csgo* be1 = ce1->GetBaseEntity())
			{
				if (be1->IsPlayer())
				{
					// The target fake local player is being deleted, emergency case, switch back to real one.

					static csgo_C_BasePlayer_SetAsLocalPlayer_t setAsLocalPlayer = (csgo_C_BasePlayer_SetAsLocalPlayer_t)AFXADDR_GET(csgo_C_BasePlayer_SetAsLocalPlayer);
					setAsLocalPlayer(be1, 0);
				}
			}
		}
	}

	Truecsgo_C_CSPlayer_UpdateOnRemove(This, Edx);
}

bool csgo_C_CSPlayer_UpdateOnRemove_Install(void)
{
	static bool firstResult = false;
	static bool firstRun = true;
	if (!firstRun) return firstResult;
	firstRun = false;

	if (AFXADDR_GET(csgo_C_CSPlayer_vtable))
	{
		AfxDetourPtr((PVOID*)&(((DWORD*)AFXADDR_GET(csgo_C_CSPlayer_vtable))[126]), Mycsgo_C_CSPlayer_UpdateOnRemove, (PVOID*)&Truecsgo_C_CSPlayer_UpdateOnRemove);

		firstResult = true;
	}

	return firstResult;
}

CON_COMMAND(mirv_pov, "Forces a POV on a GOTV demo.")
{
	if (!(AFXADDR_GET(csgo_C_CSPlayer_ofs_m_angEyeAngles)
		&& csgo_CNetChan_ProcessMessages_Install()
		&& csgo_C_CSPlayer_EyeAngles_Install()
		&& csgo_DamageIndicator_MessageFunc_Install()
		&& csgo_C_CSPlayer_UpdateOnRemove_Install()
		&& AFXADDR_GET(csgo_C_BasePlayer_SetAsLocalPlayer)
		))
	{
		Tier0_Warning("Not supported for your engine / missing hooks,!\n");
		return;
	}

	int argC = args->ArgC();

	if (2 <= argC)
	{
		g_i_MirvPov = atoi(args->ArgV(1));

		unsigned char* pData = (unsigned char *)AFXADDR_GET(csgo_crosshair_localplayer_check) + 15;

		MdtMemBlockInfos mbis;
		MdtMemAccessBegin(pData, 2, &mbis);

		if (g_i_MirvPov)
		{
			pData[0] = 0x90;
			pData[1] = 0x90;
		}
		else
		{
			pData[0] = 0x74;
			pData[1] = 0xcc;
		}

		MdtMemAccessEnd(&mbis);

		return;
	}

	Tier0_Msg(
		"mirv_pov <iPlayerEntityIndex> - Needs to be set before loading demo / connecting! Forces POV on a GOTV to the given player entity index, set 0 to disable.\n"
		"Current value: %i\n"
		, g_i_MirvPov
	);
}<commit_msg>Fixes #402 mirv_pov and FOV zooming<commit_after>#include "stdafx.h"
#include "csgo_net_chan.h"

#include "WrpConsole.h"

#include "addresses.h"
#include <SourceInterfaces.h>
#include <csgo/bitbuf/demofilebitbuf.h>

#include <build/protobuf/csgo/netmessages.pb.h>

#include <shared/AfxDetours.h>

#include <Windows.h>
#include <deps/release/Detours/src/detours.h>

int g_i_MirvPov = 0;

struct csgo_bf_read {
	char const* m_pDebugName;
	bool m_bOverflow;
	int m_nDataBits;
	size_t m_nDataBytes;
	unsigned int m_nInBufWord;
	int m_nBitsAvail;
	unsigned int const* m_pDataIn;
	unsigned int const* m_pBufferEnd;
	unsigned int const* m_pData;
};

typedef const SOURCESDK::QAngle& (__fastcall *csgo_C_CSPlayer_EyeAngles_t)(SOURCESDK::C_BaseEntity_csgo* This, void* Edx);
csgo_C_CSPlayer_EyeAngles_t Truecsgo_C_CSPlayer_EyeAngles;

const SOURCESDK::QAngle& __fastcall Mycsgo_C_CSPlayer_EyeAngles(SOURCESDK::C_BaseEntity_csgo * This, void * Edx)
{
	if (g_i_MirvPov)
	{
		if (This->entindex() == g_i_MirvPov)
		{
			DWORD ofs = AFXADDR_GET(csgo_C_CSPlayer_ofs_m_angEyeAngles);
			return *((SOURCESDK::QAngle*)((char *)This + ofs));
		}
	}

	return Truecsgo_C_CSPlayer_EyeAngles(This, Edx);
}

typedef void csgo_CNetChan_t;
typedef int(__fastcall* csgo_CNetChan_ProcessMessages_t)(csgo_CNetChan_t* This, void* edx, csgo_bf_read * pReadBuf, bool bWasReliable);
csgo_CNetChan_ProcessMessages_t Truecsgo_CNetChan_ProcessMessages = 0;

int __fastcall Mycsgo_CNetChan_ProcessMessages(csgo_CNetChan_t* This, void* Edx, csgo_bf_read* pReadBuf, bool bWasReliable)
{
	if (g_i_MirvPov)
	{
		SOURCESDK::CSGO::CBitRead readBuf(pReadBuf->m_pData, pReadBuf->m_nDataBytes);

		while (0 < readBuf.GetNumBytesLeft())
		{
			int packet_cmd = readBuf.ReadVarInt32();
			int packet_size = readBuf.ReadVarInt32();
			if (packet_size < readBuf.GetNumBytesLeft())
			{
				switch (packet_cmd)
				{
				case svc_ServerInfo:
					{
						CSVCMsg_ServerInfo msg;
						msg.ParseFromArray(readBuf.GetBasePointer() + readBuf.GetNumBytesRead(), packet_size);
						if (msg.has_is_hltv())
						{
							msg.set_is_hltv(false);
						}
						if (msg.has_player_slot())
						{
							msg.set_player_slot(g_i_MirvPov - 1);
						}
						msg.SerializePartialToArray(const_cast<unsigned char*>(readBuf.GetBasePointer()) + readBuf.GetNumBytesRead(), packet_size);
					}
					break;
				case svc_SetView:
					{
						CSVCMsg_SetView msg;
						msg.ParseFromArray(readBuf.GetBasePointer() + readBuf.GetNumBytesRead(), packet_size);
						if (msg.has_entity_index())
						{
							msg.set_entity_index(g_i_MirvPov);
						}
						msg.SerializePartialToArray(const_cast<unsigned char*>(readBuf.GetBasePointer()) + readBuf.GetNumBytesRead(), packet_size);
					}
					break;
				}

				readBuf.SeekRelative(packet_size * 8);
			}
			else
				break;
		}
	}

	bool result = Truecsgo_CNetChan_ProcessMessages(This, Edx, pReadBuf, bWasReliable);

	if (g_i_MirvPov)
	{
		static WrpConVarRef cvarClPredict;
		cvarClPredict.RetryIfNull("cl_predict"); // GOTV would have this on 0, so force it too.
		cvarClPredict.SetDirectHack(0);
	}

	return result;
}

bool csgo_CNetChan_ProcessMessages_Install(void)
{
	static bool firstResult = false;
	static bool firstRun = true;
	if (!firstRun) return firstResult;
	firstRun = false;

	if (AFXADDR_GET(csgo_CNetChan_ProcessMessages))
	{
		LONG error = NO_ERROR;

		Truecsgo_CNetChan_ProcessMessages = (csgo_CNetChan_ProcessMessages_t)AFXADDR_GET(csgo_CNetChan_ProcessMessages);

		DetourTransactionBegin();
		DetourUpdateThread(GetCurrentThread());
		DetourAttach(&(PVOID&)Truecsgo_CNetChan_ProcessMessages, Mycsgo_CNetChan_ProcessMessages);
		error = DetourTransactionCommit();

		firstResult = NO_ERROR == error;
	}

	return firstResult;
}

bool csgo_C_CSPlayer_EyeAngles_Install(void)
{
	static bool firstResult = false;
	static bool firstRun = true;
	if (!firstRun) return firstResult;
	firstRun = false;

	if (AFXADDR_GET(csgo_C_CSPlayer_vtable))
	{
		AfxDetourPtr((PVOID*)&(((DWORD*)AFXADDR_GET(csgo_C_CSPlayer_vtable))[169]), Mycsgo_C_CSPlayer_EyeAngles, (PVOID*)&Truecsgo_C_CSPlayer_EyeAngles);

		firstResult = true;
	}

	return firstResult;
}

typedef float(__fastcall* csgo_C_CS_Player__GetFOV_t)(SOURCESDK::C_BasePlayer_csgo* This, void* Edx);

csgo_C_CS_Player__GetFOV_t True_csgo_C_CS_Player__GetFOV;

float __fastcall My_csgo_C_CS_Player__GetFOV(SOURCESDK::C_BasePlayer_csgo * This, void* Edx)
{
	if (g_i_MirvPov && This->entindex() == g_i_MirvPov)
	{
		bool* pIsLocalPlayer = (bool*)((char*)This + AFXADDR_GET(csgo_C_BasePlayer_ofs_m_bIsLocalPlayer));

		bool oldIsLocalPlayer = *pIsLocalPlayer;

		*pIsLocalPlayer = false;

		float result = True_csgo_C_CS_Player__GetFOV(This, Edx);

		*pIsLocalPlayer = oldIsLocalPlayer;

		return result;
	}

	return True_csgo_C_CS_Player__GetFOV(This, Edx);
}

bool Install_csgo_C_CS_Player__GetFOVs(void)
{
	static bool firstResult = false;
	static bool firstRun = true;
	if (!firstRun) return firstResult;
	firstRun = false;

	if (AFXADDR_GET(csgo_C_CSPlayer_vtable))
	{
		AfxDetourPtr((PVOID*)&(((DWORD*)AFXADDR_GET(csgo_C_CSPlayer_vtable))[331]), My_csgo_C_CS_Player__GetFOV, (PVOID*)&True_csgo_C_CS_Player__GetFOV);

		firstResult = true;
	}

	return firstResult;
}

typedef int(__fastcall* csgo_DamageIndicator_MessageFunc_t)(void* This, void* Edx, const char * pMsg);
csgo_DamageIndicator_MessageFunc_t Truecsgo_DamageIndicator_MessageFunc = 0;

bool __fastcall MYcsgo_DamageIndicator_MessageFunc(void* This, void* Edx, const char* pMsg)
{
	if (g_i_MirvPov)
	{
		bool abort = false;

		__asm mov eax, pMsg
		__asm mov eax, [eax + 0x10]
		__asm cmp eax, g_i_MirvPov
		__asm jz __cont
		__asm mov abort, 1
		__asm __cont:

		if (abort) return true;
	}

	return Truecsgo_DamageIndicator_MessageFunc(This, Edx, pMsg);
}

bool csgo_DamageIndicator_MessageFunc_Install(void)
{
	static bool firstResult = false;
	static bool firstRun = true;
	if (!firstRun) return firstResult;
	firstRun = false;

	if (AFXADDR_GET(csgo_DamageIndicator_MessageFunc))
	{
		LONG error = NO_ERROR;

		Truecsgo_DamageIndicator_MessageFunc = (csgo_DamageIndicator_MessageFunc_t)AFXADDR_GET(csgo_DamageIndicator_MessageFunc);

		DetourTransactionBegin();
		DetourUpdateThread(GetCurrentThread());
		DetourAttach(&(PVOID&)Truecsgo_DamageIndicator_MessageFunc, MYcsgo_DamageIndicator_MessageFunc);
		error = DetourTransactionCommit();

		firstResult = NO_ERROR == error;
	}

	return firstResult;
}

typedef void(__fastcall* csgo_C_CSPlayer_UpdateOnRemove_t)(SOURCESDK::C_BasePlayer_csgo* This, void* Edx);

csgo_C_CSPlayer_UpdateOnRemove_t Truecsgo_C_CSPlayer_UpdateOnRemove = nullptr;

typedef void(__fastcall* csgo_C_BasePlayer_SetAsLocalPlayer_t)(void* Ecx, void* Edx);

void __fastcall Mycsgo_C_CSPlayer_UpdateOnRemove(SOURCESDK::C_BasePlayer_csgo* This, void* Edx)
{
	if (g_i_MirvPov && This->entindex() == g_i_MirvPov)
	{
		if (SOURCESDK::IClientEntity_csgo* ce1 = SOURCESDK::g_Entitylist_csgo->GetClientEntity(1))
		{
			if (SOURCESDK::C_BaseEntity_csgo* be1 = ce1->GetBaseEntity())
			{
				if (be1->IsPlayer())
				{
					// The target fake local player is being deleted, emergency case, switch back to real one.

					static csgo_C_BasePlayer_SetAsLocalPlayer_t setAsLocalPlayer = (csgo_C_BasePlayer_SetAsLocalPlayer_t)AFXADDR_GET(csgo_C_BasePlayer_SetAsLocalPlayer);
					setAsLocalPlayer(be1, 0);
				}
			}
		}
	}

	Truecsgo_C_CSPlayer_UpdateOnRemove(This, Edx);
}

bool csgo_C_CSPlayer_UpdateOnRemove_Install(void)
{
	static bool firstResult = false;
	static bool firstRun = true;
	if (!firstRun) return firstResult;
	firstRun = false;

	if (AFXADDR_GET(csgo_C_CSPlayer_vtable))
	{
		AfxDetourPtr((PVOID*)&(((DWORD*)AFXADDR_GET(csgo_C_CSPlayer_vtable))[126]), Mycsgo_C_CSPlayer_UpdateOnRemove, (PVOID*)&Truecsgo_C_CSPlayer_UpdateOnRemove);

		firstResult = true;
	}

	return firstResult;
}

CON_COMMAND(mirv_pov, "Forces a POV on a GOTV demo.")
{
	if (!(AFXADDR_GET(csgo_C_CSPlayer_ofs_m_angEyeAngles)
		&& csgo_CNetChan_ProcessMessages_Install()
		&& csgo_C_CSPlayer_EyeAngles_Install()
		&& csgo_DamageIndicator_MessageFunc_Install()
		&& csgo_C_CSPlayer_UpdateOnRemove_Install()
		&& Install_csgo_C_CS_Player__GetFOVs()
		&& AFXADDR_GET(csgo_C_BasePlayer_SetAsLocalPlayer)
		))
	{
		Tier0_Warning("Not supported for your engine / missing hooks,!\n");
		return;
	}

	int argC = args->ArgC();

	if (2 <= argC)
	{
		g_i_MirvPov = atoi(args->ArgV(1));

		unsigned char* pData = (unsigned char *)AFXADDR_GET(csgo_crosshair_localplayer_check) + 15;

		MdtMemBlockInfos mbis;
		MdtMemAccessBegin(pData, 2, &mbis);

		if (g_i_MirvPov)
		{
			pData[0] = 0x90;
			pData[1] = 0x90;
		}
		else
		{
			pData[0] = 0x74;
			pData[1] = 0xcc;
		}

		MdtMemAccessEnd(&mbis);

		return;
	}

	Tier0_Msg(
		"mirv_pov <iPlayerEntityIndex> - Needs to be set before loading demo / connecting! Forces POV on a GOTV to the given player entity index, set 0 to disable.\n"
		"Current value: %i\n"
		, g_i_MirvPov
	);
}<|endoftext|>


<commit_before>/*
 * File:   main.cpp
 * Author: vlad
 *
 * Created on December 12, 2013, 10:38 PM
 */

#include <iostream>

#include "qpp.h"
//#include "matlab.h" // support for MATLAB

// TODO: expandout function
// TODO: dyad function
// TODO: proj (dya) function
// TODO: ip (inner product function) function, make it general to return matrices
// TODO: Error class
// TODO: change all for(s) to column major order
// TODO: use .data() raw pointer instead of looping

using namespace std;

using namespace qpp;
using namespace qpp::types;

//int main(int argc, char **argv)
int main()
{
	_init();

	// Display formatting
	std::cout << std::fixed; // use fixed format for nice formatting
//	std::cout << std::scientific;
	std::cout << std::setprecision(4); // only for fixed or scientific modes

	cout << "Starting qpp..." << endl;

	// TIMING
	Timer t,total;  // start the timer
	size_t N = 10000;
	cmat testmat = cmat::Random(N, N);
	t.toc();
	cout << "It took me " << t.ticks() << " ticks (" << t.secs()
				<< " seconds) to initialize a " << N << " x " << N
				<< " random complex matrix."<<endl;
	t.reset();
	cout << "The norm of a " << N << " x " << N
			<< " random complex matrix is: "<<endl;
	cout << norm(testmat) << endl;
	t.toc(); // read the time
	cout << "It took me " << t.ticks() << " ticks (" << t.secs()
			<< " seconds) to compute the norm." << endl;

	cout << "Total time: " << total.ticks() << " ticks (" << total.secs()
				<< " seconds)." << endl;
	// END TIMING

	cout << endl << "Exiting qpp..." << endl;
}
<commit_msg>commit<commit_after>/*
 * File:   main.cpp
 * Author: vlad
 *
 * Created on December 12, 2013, 10:38 PM
 */

#include <iostream>

#include "qpp.h"
//#include "matlab.h" // support for MATLAB

// TODO: expandout function
// TODO: dyad function
// TODO: proj (dya) function
// TODO: ip (inner product function) function, make it general to return matrices
// TODO: Error class
// TODO: change all for(s) to column major order
// TODO: use .data() raw pointer instead of looping

using namespace std;

using namespace qpp;
using namespace qpp::types;

//int main(int argc, char **argv)
int main()
{
	_init();

	// Display formatting
	std::cout << std::fixed; // use fixed format for nice formatting
//	std::cout << std::scientific;
	std::cout << std::setprecision(4); // only for fixed or scientific modes

	cout << "Starting qpp..." << endl;

	// TIMING
	Timer t,total;  // start the timer
	size_t N = 10000;
	cmat testmat = cmat::Random(N, N);
	t.toc();
	cout << "It took me " << t.ticks() << " ticks (" << t.secs()
				<< " seconds) to initialize a " << N << " x " << N
				<< " random complex matrix."<<endl;
	t.reset();
	cout << "The norm of a " << N << " x " << N
			<< " random complex matrix is: "<<endl;
	cout << norm(testmat) << endl;
	t.toc(); // read the time
	cout << "It took me " << t.ticks() << " ticks (" << t.secs()
			<< " seconds) to compute the norm." << endl;

	total.toc();
	cout << "Total time: " << total.ticks() << " ticks (" << total.secs()
				<< " seconds)." << endl;
	// END TIMING

	cout << endl << "Exiting qpp..." << endl;
}
<|endoftext|>


<commit_before>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) University College London (UCL).
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include "QmitkDataStorageComboBoxWithSelectNone.h"
#include <QDebug>

const QString QmitkDataStorageComboBoxWithSelectNone::ZERO_ENTRY_STRING = "please select";

//-----------------------------------------------------------------------------
QmitkDataStorageComboBoxWithSelectNone::QmitkDataStorageComboBoxWithSelectNone(
    QWidget* parent,
    bool autoSelectNewNodes )
: QmitkDataStorageComboBox(parent, autoSelectNewNodes)
, m_CurrentPath("")
{
}

//-----------------------------------------------------------------------------
QmitkDataStorageComboBoxWithSelectNone::QmitkDataStorageComboBoxWithSelectNone(
    mitk::DataStorage* dataStorage,
    const mitk::NodePredicateBase* predicate,
    QWidget* parent, bool autoSelectNewNodes )
: QmitkDataStorageComboBox(dataStorage, predicate, parent, autoSelectNewNodes)
{
}

//-----------------------------------------------------------------------------
QmitkDataStorageComboBoxWithSelectNone::~QmitkDataStorageComboBoxWithSelectNone()
{
}

//-----------------------------------------------------------------------------
int QmitkDataStorageComboBoxWithSelectNone::Find( const mitk::DataNode* dataNode ) const
{
  int index = QmitkDataStorageComboBox::Find(dataNode);
  if (index != -1)
  {
    index += 1;
  }
  return index;
}

//-----------------------------------------------------------------------------
mitk::DataNode::Pointer QmitkDataStorageComboBoxWithSelectNone::GetNode( int index ) const
{
  mitk::DataNode::Pointer result = NULL;

  if (this->HasIndex(index))
  {
    if (index != 0)
    {
      result = m_Nodes.at(index - 1);
    }
  }
  return result;
}

//-----------------------------------------------------------------------------
mitk::DataNode::Pointer QmitkDataStorageComboBoxWithSelectNone::GetSelectedNode() const
{
  return this->GetNode(this->currentIndex());
}

//-----------------------------------------------------------------------------
void QmitkDataStorageComboBoxWithSelectNone::SetSelectedNode(const mitk::DataNode::Pointer& node)
{
  int currentIndex = -1;
  for (int i = 0; i < m_Nodes.size(); i++)
  {
    if (m_Nodes[i] == node.GetPointer())
    {
      currentIndex = i;
      break;
    }
  }
  if (currentIndex == -1)
  {
    // didn't find it, so set the value to 0.
    currentIndex = 0;
  }
  else
  {
    currentIndex += 1; // because the combo box contains "please select" at position zero.
  }
  this->setCurrentIndex(currentIndex);
}

//-----------------------------------------------------------------------------
void QmitkDataStorageComboBoxWithSelectNone::RemoveNode( int index )
{
  if(index > 0 && this->HasIndex(index))
  {

    // remove itk::Event observer
    mitk::DataNode* dataNode = m_Nodes.at(index - 1);

    // get name property first
    mitk::BaseProperty* nameProperty = dataNode->GetProperty("name");

    // if prop exists remove modified listener
    if(nameProperty)
    {
      nameProperty->RemoveObserver(m_NodesModifiedObserverTags[index-1]);

      // remove name property map
      m_PropertyToNode.erase(dataNode);
    }

    // then remove delete listener on the node itself
    dataNode->RemoveObserver(m_NodesDeleteObserverTags[index-1]);

    // remove observer tags from lists
    m_NodesModifiedObserverTags.erase(m_NodesModifiedObserverTags.begin()+index-1);
    m_NodesDeleteObserverTags.erase(m_NodesDeleteObserverTags.begin()+index-1);

    // remove node name from combobox
    this->removeItem(index);

    // remove node from node vector
    m_Nodes.erase(m_Nodes.begin()+index-1);
  }
}

//-----------------------------------------------------------------------------
void QmitkDataStorageComboBoxWithSelectNone::SetNode(int index, const mitk::DataNode* dataNode)
{
  if(index > 0 && this->HasIndex(index))
  {
    QmitkDataStorageComboBox::InsertNode(index - 1, dataNode);
  }
}

//-----------------------------------------------------------------------------
bool QmitkDataStorageComboBoxWithSelectNone::HasIndex(unsigned int index) const
{
  return (m_Nodes.size() > 0 && index <= m_Nodes.size());
}

//-----------------------------------------------------------------------------
void QmitkDataStorageComboBoxWithSelectNone::InsertNode(int index, const mitk::DataNode* dataNode)
{
  if (index != 0)
  {
    QmitkDataStorageComboBox::InsertNode(index - 1, dataNode);
  }
}

//-----------------------------------------------------------------------------
void QmitkDataStorageComboBoxWithSelectNone::Reset()
{
  QmitkDataStorageComboBox::Reset();
  this->insertItem(0, ZERO_ENTRY_STRING);
}

//-----------------------------------------------------------------------------
void QmitkDataStorageComboBoxWithSelectNone::SetZeroEntryText(const QString& zeroEntryString)
{
  this->setItemText(0, zeroEntryString);
}

//-----------------------------------------------------------------------------
QString QmitkDataStorageComboBoxWithSelectNone::currentValue() const
{
  return m_CurrentPath;
}

//-----------------------------------------------------------------------------
void QmitkDataStorageComboBoxWithSelectNone::setCurrentValue(const QString& path)
{
  m_CurrentPath = path;
}
<commit_msg>Add checks for node renaming<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) University College London (UCL).
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include "QmitkDataStorageComboBoxWithSelectNone.h"
#include <QDebug>

const QString QmitkDataStorageComboBoxWithSelectNone::ZERO_ENTRY_STRING = "please select";

//-----------------------------------------------------------------------------
QmitkDataStorageComboBoxWithSelectNone::QmitkDataStorageComboBoxWithSelectNone(
    QWidget* parent,
    bool autoSelectNewNodes )
: QmitkDataStorageComboBox(parent, autoSelectNewNodes)
, m_CurrentPath("")
{
}

//-----------------------------------------------------------------------------
QmitkDataStorageComboBoxWithSelectNone::QmitkDataStorageComboBoxWithSelectNone(
    mitk::DataStorage* dataStorage,
    const mitk::NodePredicateBase* predicate,
    QWidget* parent, bool autoSelectNewNodes )
: QmitkDataStorageComboBox(dataStorage, predicate, parent, autoSelectNewNodes)
{
}

//-----------------------------------------------------------------------------
QmitkDataStorageComboBoxWithSelectNone::~QmitkDataStorageComboBoxWithSelectNone()
{
}

//-----------------------------------------------------------------------------
int QmitkDataStorageComboBoxWithSelectNone::Find( const mitk::DataNode* dataNode ) const
{
  int index = QmitkDataStorageComboBox::Find(dataNode);
  if (index != -1)
  {
    index += 1;
  }
  return index;
}

//-----------------------------------------------------------------------------
mitk::DataNode::Pointer QmitkDataStorageComboBoxWithSelectNone::GetNode( int index ) const
{
  mitk::DataNode::Pointer result = NULL;

  if (this->HasIndex(index))
  {
    if (index != 0)
    {
      result = m_Nodes.at(index - 1);
    }
  }
  return result;
}

//-----------------------------------------------------------------------------
mitk::DataNode::Pointer QmitkDataStorageComboBoxWithSelectNone::GetSelectedNode() const
{
  return this->GetNode(this->currentIndex());
}

//-----------------------------------------------------------------------------
void QmitkDataStorageComboBoxWithSelectNone::SetSelectedNode(const mitk::DataNode::Pointer& node)
{
  int currentIndex = -1;
  for (int i = 0; i < m_Nodes.size(); i++)
  {
    if (m_Nodes[i] == node.GetPointer())
    {
      currentIndex = i;
      break;
    }
  }
  if (currentIndex == -1)
  {
    // didn't find it, so set the value to 0.
    currentIndex = 0;
  }
  else
  {
    currentIndex += 1; // because the combo box contains "please select" at position zero.
  }
  this->setCurrentIndex(currentIndex);
}

//-----------------------------------------------------------------------------
void QmitkDataStorageComboBoxWithSelectNone::RemoveNode( int index )
{
  if(index > 0 && this->HasIndex(index))
  {

    // remove itk::Event observer
    mitk::DataNode* dataNode = m_Nodes.at(index - 1);

    // get name property first
    mitk::BaseProperty* nameProperty = dataNode->GetProperty("name");

    // if prop exists remove modified listener
    if(nameProperty)
    {
      nameProperty->RemoveObserver(m_NodesModifiedObserverTags[index-1]);

      // remove name property map
      m_PropertyToNode.erase(dataNode);
    }

    // then remove delete listener on the node itself
    dataNode->RemoveObserver(m_NodesDeleteObserverTags[index-1]);

    // remove observer tags from lists
    m_NodesModifiedObserverTags.erase(m_NodesModifiedObserverTags.begin()+index-1);
    m_NodesDeleteObserverTags.erase(m_NodesDeleteObserverTags.begin()+index-1);

    // remove node name from combobox
    this->removeItem(index);

    // remove node from node vector
    m_Nodes.erase(m_Nodes.begin()+index-1);
  }
}

//-----------------------------------------------------------------------------
void QmitkDataStorageComboBoxWithSelectNone::SetNode(int index, const mitk::DataNode* dataNode)
{
  if(index > 0 && this->HasIndex(index))
  {
    // if node identical, we only update the name in the QComboBoxItem
    if( dataNode == this->m_Nodes.at(index-1 ) )
    {
      mitk::BaseProperty* nameProperty = dataNode->GetProperty("name");
      std::string dataNodeNameStr = nameProperty->GetValueAsString();

      this->setItemText(index, QString::fromStdString( dataNodeNameStr) );
    }
    else
      QmitkDataStorageComboBox::InsertNode(index - 1, dataNode);
  }
}

//-----------------------------------------------------------------------------
bool QmitkDataStorageComboBoxWithSelectNone::HasIndex(unsigned int index) const
{
  return (m_Nodes.size() > 0 && index <= m_Nodes.size());
}

//-----------------------------------------------------------------------------
void QmitkDataStorageComboBoxWithSelectNone::InsertNode(int index, const mitk::DataNode* dataNode)
{
  if (index != 0)
  {
    QmitkDataStorageComboBox::InsertNode(index - 1, dataNode);
  }
}

//-----------------------------------------------------------------------------
void QmitkDataStorageComboBoxWithSelectNone::Reset()
{
  QmitkDataStorageComboBox::Reset();
  this->insertItem(0, ZERO_ENTRY_STRING);
}

//-----------------------------------------------------------------------------
void QmitkDataStorageComboBoxWithSelectNone::SetZeroEntryText(const QString& zeroEntryString)
{
  this->setItemText(0, zeroEntryString);
}

//-----------------------------------------------------------------------------
QString QmitkDataStorageComboBoxWithSelectNone::currentValue() const
{
  return m_CurrentPath;
}

//-----------------------------------------------------------------------------
void QmitkDataStorageComboBoxWithSelectNone::setCurrentValue(const QString& path)
{
  m_CurrentPath = path;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/mman.h>
#include <pwd.h>
#include <fcntl.h>
using namespace std;

static int *glob_flag;

//output login @ machine $
void prompt(){
	struct passwd *log;
	int pid = fork();
	if(pid == -1){
		perror("fork() presented error");
		exit(1);
	}
	else if(pid==0){
		char host[50];
		if ((gethostname(host, sizeof(host)-1))==-1) {
		host[0] = 'h';
		host[1] = 'o';
		host[2] = 's';
		host[3] = 't';
		host[4] = '\0';
		perror("Error trying to get hostname");
		}
		log = getpwuid(getuid());
		if(log == '\0'){
			perror("Error trying to get user login");
		}

		cout << log->pw_name << "@" << host << "$ ";
		exit(1);
	}else if(pid>0){
		if(-1 == wait(0))
		perror("wait() presented error");

	}
}

void execute(char *str[], int size){

	char * newstr[512];
	char * connector;
	int i, j, aux;

	for (i = 0; i<size; i++){
		*glob_flag = 0;
		//newstr[0] receives commands, first parameter after a connector
		newstr[0] = str[i];
		if(memcmp(newstr[0],"exit",4)==0) exit(0);
		aux = 1;
		//test command without flags carryng a ';'
		connector = strchr(newstr[0], ';');
		if (connector != NULL) newstr[0][connector - newstr[0]] = '\0';
		else
			for (j = i + 1; j<size; j++){
			connector = strchr(str[j], ';');
			if (connector != NULL){
				//erase the last character if ';'
				str[j][connector - str[j]] = '\0';
			}
			//check for && setting a flag to 1
			if (memcmp(str[j], "&&", 2) == 0){
				*glob_flag = 1;
				i = j;
				break;
			}
			//check for || setting a flag to 3
			if (memcmp(str[j], "||", 2) == 0){
				*glob_flag = 3;
				i = j;
				break;
			}

			//add flags to newstr
			newstr[aux] = str[j];
			aux++;
			i = j;

			if (connector != NULL) break;
			}

		int pid = fork();
		if (pid == -1){
			perror("fork() presented error");
			exit(1);
		}
		else if (pid == 0){
			if (-1 == execvp(newstr[0], newstr)){
				perror("There was an error");
				//flag 1 means, first command must be successfull to apply the second
				if (*glob_flag == 1) *glob_flag = 2;
				//flag 3 means, first command must be failed to apply the second
				//number 5 won't pass in the breaking loop
				if (*glob_flag == 3) *glob_flag = 5;
			}
			exit(1);
		}
		else if (pid>0){

			int status;

			wait(&status);
			if (-1 == status)
				perror("wait() presented error");
			else if (status>0){
				//flag 1 means, first command must be successfull to apply the second
				if (*glob_flag == 1){
					int flag2 = 0;
					for (int p = i; p<size; p++){
						//in case command fails look for a semicolon to reestart from there
						connector = strchr(str[p], ';');
						if (connector != NULL){
							i = p;
							//changing this flag will make the parent loop do not break because a semicolon was found
							flag2 = 1;
							break;
						}
					}
					//if there is no more semicolons parent loop will break
					if (flag2 == 0) *glob_flag = 2;
				}
				//flag 3 means, first command must be failed to apply the second
				//number 5 won't pass in the breaking loop
				if (*glob_flag == 3) *glob_flag = 5;
			}

		}

		// clear the vector newstr in order to execute new commands
		for (int k = 0; k<aux; k++)newstr[k] = '\0';

		//break loop due to a non valid previous command connected by &&
		if (*glob_flag == 2) break;
		//break loop due to a valid previous command connected by ||
		if (*glob_flag == 3) break;
	}
}

void out(char *str[], int size){
	int i;
	int fdo;
	char * newstr[512];
	for(i=0;i<size;i++){
		if (memcmp(str[i], ">\0", 2) == 0){
			//open file descriptor as the argument after '>'
			fdo = open(str[i+1], O_WRONLY);
			if(fdo == -1){
				perror("open failed");
				exit(1);
			}

			if(dup2(fdo,1) == -1){
				perror("dup failed");
				exit(1);
			}
			break;
		}
		//newstr receive arguments before '>'
		newstr[i] = str[i];
	}

	if (execvp(newstr[0], newstr) == -1)
		perror("execvp 'out' failed");
}

void in(char * str[], int size){
	int i;
	int fdi;
	char * newstr[512];
	for(i=0;i<size;i++){
		if (memcmp(str[i], "<\0", 2) == 0){
			cerr<<"achei"<<endl;
			//open file descriptor as the argument after '>'
			fdi = open(str[i+1], O_RDONLY);
			if(fdi == -1){
				perror("open failed");
				exit(1);
			}

			if(dup2(fdi,0) == -1){
				perror("dup failed");
				exit(1);
			}
			break;
		}
		//newstr receive arguments before '<'
		newstr[i] = str[i];
	}

	if (execvp(newstr[0], newstr) == -1)
		perror("execvp 'in' failed");
}

//checks which procedure it should follows for I/O redirection
int checkline(char *str[], int size){
	int r=-1;
	for(int i=0; i<size; i++){
		if (memcmp(str[i], "|\0", 2) == 0){
			return 0;
		}
		if (memcmp(str[i], "<\0", 2) == 0){
			r = 1;
		}
		if (memcmp(str[i], ">\0", 2) == 0){
			r = 2;
		}
		if (memcmp(str[i], ">>\0", 2) == 0){
			r = 3;
		}
	}
	return r;
}

int main(){
	int index;
	string line;
	char * str[512];
	char * pch;

	while (true){
		do{
			//output login @ machine $
			prompt();
			getline(cin, line);
		} while (line[0] == '#');

		//look for '#', if find erase everything until the end of line
		size_t found = line.find('#');
		if (found != std::string::npos)
			line.erase(found, line.length() - found);

		//create a dynamic char that is a copy of input
		char * input = new char[line.length() + 1];
		strcpy(input, line.c_str());

		//built in function to finish program when typed 'EXIT'
		if (memcmp(input, "exit", 4) == 0) exit(0);

		index = 0;
		pch = strtok(input, " ");

		while (pch != NULL){
			str[index] = pch;
			pch = strtok(NULL, " ");
			index++;
		}

		str[index] = NULL;

	//create a shared memory to be accessed from child and process
	glob_flag = (int*)mmap(NULL, sizeof *glob_flag, PROT_READ | PROT_WRITE,
		MAP_SHARED | MAP_ANONYMOUS, -1, 0);

		int pos = checkline(str, index);

		int fid = fork();
		if(fid<0){
			perror("fork failed");
			exit(1);
		}
		if(fid == 0) {
			if(pos==0){}
			else if(pos == 1) in(str, index);
			else if(pos == 2) out(str,index);
			else if(pos == 3){}
			else if(pos == -1)
				execute(str, index);
			exit(1);
		}else if(fid>0){
			if(wait(0) == -1)
				perror("wait failed");
		}
	}
	return 0;
}
<commit_msg>simple >> redirection working<commit_after>#include <iostream>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/mman.h>
#include <pwd.h>
#include <fcntl.h>
using namespace std;

static int *glob_flag;

//output login @ machine $
void prompt(){
	struct passwd *log;
	int pid = fork();
	if(pid == -1){
		perror("fork() presented error");
		exit(1);
	}
	else if(pid==0){
		char host[50];
		if ((gethostname(host, sizeof(host)-1))==-1) {
		host[0] = 'h';
		host[1] = 'o';
		host[2] = 's';
		host[3] = 't';
		host[4] = '\0';
		perror("Error trying to get hostname");
		}
		log = getpwuid(getuid());
		if(log == '\0'){
			perror("Error trying to get user login");
		}

		cout << log->pw_name << "@" << host << "$ ";
		exit(1);
	}else if(pid>0){
		if(-1 == wait(0))
		perror("wait() presented error");

	}
}

void execute(char *str[], int size){

	char * newstr[512];
	char * connector;
	int i, j, aux;

	for (i = 0; i<size; i++){
		*glob_flag = 0;
		//newstr[0] receives commands, first parameter after a connector
		newstr[0] = str[i];
		if(memcmp(newstr[0],"exit",4)==0) exit(0);
		aux = 1;
		//test command without flags carryng a ';'
		connector = strchr(newstr[0], ';');
		if (connector != NULL) newstr[0][connector - newstr[0]] = '\0';
		else
			for (j = i + 1; j<size; j++){
			connector = strchr(str[j], ';');
			if (connector != NULL){
				//erase the last character if ';'
				str[j][connector - str[j]] = '\0';
			}
			//check for && setting a flag to 1
			if (memcmp(str[j], "&&", 2) == 0){
				*glob_flag = 1;
				i = j;
				break;
			}
			//check for || setting a flag to 3
			if (memcmp(str[j], "||", 2) == 0){
				*glob_flag = 3;
				i = j;
				break;
			}

			//add flags to newstr
			newstr[aux] = str[j];
			aux++;
			i = j;

			if (connector != NULL) break;
			}

		int pid = fork();
		if (pid == -1){
			perror("fork() presented error");
			exit(1);
		}
		else if (pid == 0){
			if (-1 == execvp(newstr[0], newstr)){
				perror("There was an error");
				//flag 1 means, first command must be successfull to apply the second
				if (*glob_flag == 1) *glob_flag = 2;
				//flag 3 means, first command must be failed to apply the second
				//number 5 won't pass in the breaking loop
				if (*glob_flag == 3) *glob_flag = 5;
			}
			exit(1);
		}
		else if (pid>0){

			int status;

			wait(&status);
			if (-1 == status)
				perror("wait() presented error");
			else if (status>0){
				//flag 1 means, first command must be successfull to apply the second
				if (*glob_flag == 1){
					int flag2 = 0;
					for (int p = i; p<size; p++){
						//in case command fails look for a semicolon to reestart from there
						connector = strchr(str[p], ';');
						if (connector != NULL){
							i = p;
							//changing this flag will make the parent loop do not break because a semicolon was found
							flag2 = 1;
							break;
						}
					}
					//if there is no more semicolons parent loop will break
					if (flag2 == 0) *glob_flag = 2;
				}
				//flag 3 means, first command must be failed to apply the second
				//number 5 won't pass in the breaking loop
				if (*glob_flag == 3) *glob_flag = 5;
			}

		}

		// clear the vector newstr in order to execute new commands
		for (int k = 0; k<aux; k++)newstr[k] = '\0';

		//break loop due to a non valid previous command connected by &&
		if (*glob_flag == 2) break;
		//break loop due to a valid previous command connected by ||
		if (*glob_flag == 3) break;
	}
}

void out(char *str[], int size, bool symbol){
	int i;
	int fdo;
	char * newstr[512];
	for(i=0;i<size;i++){
		if (memcmp(str[i], ">", 1) == 0){
			//open file descriptor as the argument after '>'
			if(symbol){
				fdo = open(str[i+1], O_RDWR|O_CREAT|O_APPEND, 0666);
				if(fdo == -1){
					perror("open failed");
					exit(1);
				}
			}
			else{
				fdo = open(str[i+1], O_RDWR|O_CREAT, 0666);
				if(fdo == -1){
					perror("open failed");
					exit(1);
				}
			}

			if(dup2(fdo,1) == -1){
				perror("dup failed");
				exit(1);
			}
			break;
		}
		//newstr receive arguments before '>'
		newstr[i] = str[i];
	}

	if (execvp(newstr[0], newstr) == -1)
		perror("execvp 'out' failed");
}

void in(char * str[], int size){
	int i;
	int fdi;
	char * newstr[512];
	for(i=0;i<size;i++){
		if (memcmp(str[i], "<\0", 2) == 0){
			cerr<<"achei"<<endl;
			//open file descriptor as the argument after '>'
			fdi = open(str[i+1], O_RDONLY);
			if(fdi == -1){
				perror("open failed");
				exit(1);
			}

			if(dup2(fdi,0) == -1){
				perror("dup failed");
				exit(1);
			}
			break;
		}
		//newstr receive arguments before '<'
		newstr[i] = str[i];
	}

	if (execvp(newstr[0], newstr) == -1)
		perror("execvp 'in' failed");
}

//checks which procedure it should follows for I/O redirection
int checkline(char *str[], int size){
	int r=-1;
	for(int i=0; i<size; i++){
		if (memcmp(str[i], "|\0", 2) == 0){
			return 0;
		}
		if (memcmp(str[i], "<\0", 2) == 0){
			r = 1;
		}
		if (memcmp(str[i], ">\0", 2) == 0){
			r = 2;
		}
		if (memcmp(str[i], ">>\0", 3) == 0){
			r = 3;
		}
	}
	return r;
}

int main(){
	int index;
	string line;
	char * str[512];
	char * pch;

	while (true){
		do{
			//output login @ machine $
			prompt();
			getline(cin, line);
		} while (line[0] == '#');

		//look for '#', if find erase everything until the end of line
		size_t found = line.find('#');
		if (found != std::string::npos)
			line.erase(found, line.length() - found);

		//create a dynamic char that is a copy of input
		char * input = new char[line.length() + 1];
		strcpy(input, line.c_str());

		//built in function to finish program when typed 'EXIT'
		if (memcmp(input, "exit", 4) == 0) exit(0);

		index = 0;
		pch = strtok(input, " ");

		while (pch != NULL){
			str[index] = pch;
			pch = strtok(NULL, " ");
			index++;
		}

		str[index] = NULL;

	//create a shared memory to be accessed from child and process
	glob_flag = (int*)mmap(NULL, sizeof *glob_flag, PROT_READ | PROT_WRITE,
		MAP_SHARED | MAP_ANONYMOUS, -1, 0);

		int pos = checkline(str, index);

		int fid = fork();
		if(fid<0){
			perror("fork failed");
			exit(1);
		}
		if(fid == 0) {
			if(pos==0){}
			else if(pos == 1) in(str, index);
			else if(pos == 2) out(str,index, false);
			else if(pos == 3) out(str,index, true);
			else if(pos == -1)
				execute(str, index);
			exit(1);
		}else if(fid>0){
			if(wait(0) == -1)
				perror("wait failed");
		}
	}
	return 0;
}
<|endoftext|>


<commit_before>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1        *
*                (c) 2006-2011 MGH, INRIA, USTL, UJF, CNRS                    *
*                                                                             *
* This library is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU Lesser General Public License as published by    *
* the Free Software Foundation; either version 2.1 of the License, or (at     *
* your option) any later version.                                             *
*                                                                             *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details.                                                           *
*                                                                             *
* You should have received a copy of the GNU Lesser General Public License    *
* along with this library; if not, write to the Free Software Foundation,     *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.          *
*******************************************************************************
*                               SOFA :: Modules                               *
*                                                                             *
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/
#ifndef SOFA_COMPONENT_TOPOLOGY_TOPOLOGYSUBSETDATAHANDLER_INL
#define SOFA_COMPONENT_TOPOLOGY_TOPOLOGYSUBSETDATAHANDLER_INL

#include <sofa/component/topology/TopologySubsetDataHandler.h>

namespace sofa
{

namespace component
{

namespace topology
{

///////////////////// Private functions on TopologySubsetDataHandler changes /////////////////////////////
template <typename TopologyElementType, typename VecT>
void TopologySubsetDataHandler <TopologyElementType, VecT>::swap( unsigned int i1, unsigned int i2 )
{
    container_type& data = *(m_topologyData->beginEdit());

    iterator it= std::find(data.begin(),data.end(),i1);
    if (it!=data.end())
        (*it)=i2;
    m_topologyData->endEdit();
}

template <typename TopologyElementType, typename VecT>
void TopologySubsetDataHandler <TopologyElementType, VecT>::add(unsigned int nbElements,
        const sofa::helper::vector<sofa::helper::vector<unsigned int> > &ancestors,
        const sofa::helper::vector<sofa::helper::vector<double> > &coefs)
{
    // Using default values
    container_type& data = *(m_topologyData->beginEdit());

    unsigned int size = data.size();
    bool test;
    for (unsigned int i = 0; i < nbElements; ++i)
    {
        if (ancestors.empty() || coefs.empty())
        {
            const sofa::helper::vector< unsigned int > empty_vecint;
            const sofa::helper::vector< double > empty_vecdouble;
            test = this->applyTestCreateFunction(size + i, empty_vecint, empty_vecdouble);
        }
        else
            test = this->applyTestCreateFunction(size + i, ancestors[i], coefs[i]);

        if (test)
            data.push_back( size+i );
    }
    this->lastElementIndex+=nbElements;
}

template <typename TopologyElementType, typename VecT>
void TopologySubsetDataHandler <TopologyElementType, VecT>::add(unsigned int nbElements,
        const sofa::helper::vector< TopologyElementType >& ,
        const sofa::helper::vector<sofa::helper::vector<unsigned int> > &ancestors,
        const sofa::helper::vector<sofa::helper::vector<double> > &coefs)
{
    this->add(nbElements, ancestors, coefs);
}

template <typename TopologyElementType, typename VecT>
void TopologySubsetDataHandler <TopologyElementType, VecT>::move( const sofa::helper::vector<unsigned int> &,
        const sofa::helper::vector< sofa::helper::vector< unsigned int > >& ,
        const sofa::helper::vector< sofa::helper::vector< double > >& )
{
    std::cerr << "WARNING: move event on topology subsetData is not yet handled" << std::endl;
}

template <typename TopologyElementType, typename VecT>
void TopologySubsetDataHandler <TopologyElementType, VecT>::remove( const sofa::helper::vector<unsigned int> &index )
{
    container_type& data = *(m_topologyData->beginEdit());
    unsigned int it1;
    unsigned int it2;

    for (unsigned int i = 0; i < index.size(); ++i)
    {
        it1=0;
        while(it1<data.size())
        {
            if(data[it1]==index[i])
                break;
            else
                it1+=1;
        }

        if (it1<data.size())
        {
            it2=0;
            while(it2<data.size())
            {
                if(data[it2]==this->lastElementIndex)
                    break;
                else
                    it2+=1;
            }

            if (it2<data.size())
                data[it2]=index[i];

            data[it1]=data[data.size()-1];
            this->applyDestroyFunction(index[i], data[index[i]]);

            // Fix "vector size specified is too large" exception.
            if (data.size() > 0)
                data.resize(data.size() - 1);
            else
                data.resize(0);
        }
        else
        {
            it2=0;
            while(it2<data.size())
            {
                if(data[it2]==this->lastElementIndex)
                    break;
                else
                    it2+=1;
            }

            if (it2<data.size())
            {
                data[it2]=index[i];
            }
        }
        --this->lastElementIndex;
    }

    m_topologyData->endEdit();
}

template <typename TopologyElementType, typename VecT>
void TopologySubsetDataHandler <TopologyElementType, VecT>::renumber( const sofa::helper::vector<unsigned int> &index )
{
    container_type& data = *(m_topologyData->beginEdit());
    container_type copy = m_topologyData->getValue(); // not very efficient memory-wise, but I can see no better solution...

    for (unsigned int i = 0; i < data.size(); ++i)
    {
        data[i] = copy[ index[i] ];
    }
    m_topologyData->endEdit();
}

template <typename TopologyElementType, typename VecT>
void TopologySubsetDataHandler <TopologyElementType, VecT>::addOnMovedPosition(const sofa::helper::vector<unsigned int> &,
        const sofa::helper::vector<TopologyElementType> &)
{
    std::cerr << "WARNING: addOnMovedPosition event on topology subsetData is not yet handled" << std::endl;
}

template <typename TopologyElementType, typename VecT>
void TopologySubsetDataHandler <TopologyElementType, VecT>::removeOnMovedPosition(const sofa::helper::vector<unsigned int> &)
{
    std::cerr << "WARNING: removeOnMovedPosition event on topology subsetData is not yet handled" << std::endl;
}

} // namespace topology

} // namespace component

} // namespace sofa

#endif // SOFA_COMPONENT_TOPOLOGY_TOPOLOGYSUBSETDATAHANDLER_INL
<commit_msg>r11554/sofa-dev : FIX: problem of double suppression of elements while handling topology event using handlers.<commit_after>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1        *
*                (c) 2006-2011 MGH, INRIA, USTL, UJF, CNRS                    *
*                                                                             *
* This library is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU Lesser General Public License as published by    *
* the Free Software Foundation; either version 2.1 of the License, or (at     *
* your option) any later version.                                             *
*                                                                             *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details.                                                           *
*                                                                             *
* You should have received a copy of the GNU Lesser General Public License    *
* along with this library; if not, write to the Free Software Foundation,     *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.          *
*******************************************************************************
*                               SOFA :: Modules                               *
*                                                                             *
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/
#ifndef SOFA_COMPONENT_TOPOLOGY_TOPOLOGYSUBSETDATAHANDLER_INL
#define SOFA_COMPONENT_TOPOLOGY_TOPOLOGYSUBSETDATAHANDLER_INL

#include <sofa/component/topology/TopologySubsetDataHandler.h>

namespace sofa
{

namespace component
{

namespace topology
{

///////////////////// Private functions on TopologySubsetDataHandler changes /////////////////////////////
template <typename TopologyElementType, typename VecT>
void TopologySubsetDataHandler <TopologyElementType, VecT>::swap( unsigned int i1, unsigned int i2 )
{
    container_type& data = *(m_topologyData->beginEdit());

    iterator it= std::find(data.begin(),data.end(),i1);
    if (it!=data.end())
        (*it)=i2;
    m_topologyData->endEdit();
}

template <typename TopologyElementType, typename VecT>
void TopologySubsetDataHandler <TopologyElementType, VecT>::add(unsigned int nbElements,
        const sofa::helper::vector<sofa::helper::vector<unsigned int> > &ancestors,
        const sofa::helper::vector<sofa::helper::vector<double> > &coefs)
{
    // Using default values
    container_type& data = *(m_topologyData->beginEdit());

    unsigned int size = data.size();
    bool test;
    for (unsigned int i = 0; i < nbElements; ++i)
    {
        if (ancestors.empty() || coefs.empty())
        {
            const sofa::helper::vector< unsigned int > empty_vecint;
            const sofa::helper::vector< double > empty_vecdouble;
            test = this->applyTestCreateFunction(size + i, empty_vecint, empty_vecdouble);
        }
        else
            test = this->applyTestCreateFunction(size + i, ancestors[i], coefs[i]);

        if (test)
            data.push_back( size+i );
    }
    this->lastElementIndex+=nbElements;
}

template <typename TopologyElementType, typename VecT>
void TopologySubsetDataHandler <TopologyElementType, VecT>::add(unsigned int nbElements,
        const sofa::helper::vector< TopologyElementType >& ,
        const sofa::helper::vector<sofa::helper::vector<unsigned int> > &ancestors,
        const sofa::helper::vector<sofa::helper::vector<double> > &coefs)
{
    this->add(nbElements, ancestors, coefs);
}

template <typename TopologyElementType, typename VecT>
void TopologySubsetDataHandler <TopologyElementType, VecT>::move( const sofa::helper::vector<unsigned int> &,
        const sofa::helper::vector< sofa::helper::vector< unsigned int > >& ,
        const sofa::helper::vector< sofa::helper::vector< double > >& )
{
    std::cerr << "WARNING: move event on topology subsetData is not yet handled" << std::endl;
}

template <typename TopologyElementType, typename VecT>
void TopologySubsetDataHandler <TopologyElementType, VecT>::remove( const sofa::helper::vector<unsigned int> &index )
{
    container_type& data = *(m_topologyData->beginEdit());
    unsigned int it1;
    unsigned int it2;

    for (unsigned int i = 0; i < index.size(); ++i)
    {
        it1=0;
        while(it1<data.size())
        {
            if(data[it1]==index[i])
                break;
            else
                it1+=1;
        }

        if (it1<data.size())
        {
            it2=0;
            while(it2<data.size())
            {
                if(data[it2]==this->lastElementIndex)
                    break;
                else
                    it2+=1;
            }

            if (it2<data.size())
                data[it2]=index[i];

            data[it1]=data[data.size()-1];
            unsigned int size_before = data.size();

            // Call destroy function implemented in specific component
            this->applyDestroyFunction(index[i], data[index[i]]);

            // As applyDestroyFunction could already perfom the suppression, if implemented. Size is checked again. If no change this handler really perform the suppresion
            if (size_before == data.size())
                data.resize(data.size() - 1);
        }
        else
        {
            it2=0;
            while(it2<data.size())
            {
                if(data[it2]==this->lastElementIndex)
                    break;
                else
                    it2+=1;
            }

            if (it2<data.size())
            {
                data[it2]=index[i];
            }
        }
        --this->lastElementIndex;
    }

    m_topologyData->endEdit();
}

template <typename TopologyElementType, typename VecT>
void TopologySubsetDataHandler <TopologyElementType, VecT>::renumber( const sofa::helper::vector<unsigned int> &index )
{
    container_type& data = *(m_topologyData->beginEdit());
    container_type copy = m_topologyData->getValue(); // not very efficient memory-wise, but I can see no better solution...

    for (unsigned int i = 0; i < data.size(); ++i)
    {
        data[i] = copy[ index[i] ];
    }
    m_topologyData->endEdit();
}

template <typename TopologyElementType, typename VecT>
void TopologySubsetDataHandler <TopologyElementType, VecT>::addOnMovedPosition(const sofa::helper::vector<unsigned int> &,
        const sofa::helper::vector<TopologyElementType> &)
{
    std::cerr << "WARNING: addOnMovedPosition event on topology subsetData is not yet handled" << std::endl;
}

template <typename TopologyElementType, typename VecT>
void TopologySubsetDataHandler <TopologyElementType, VecT>::removeOnMovedPosition(const sofa::helper::vector<unsigned int> &)
{
    std::cerr << "WARNING: removeOnMovedPosition event on topology subsetData is not yet handled" << std::endl;
}

} // namespace topology

} // namespace component

} // namespace sofa

#endif // SOFA_COMPONENT_TOPOLOGY_TOPOLOGYSUBSETDATAHANDLER_INL
<|endoftext|>


<commit_before>#include<cstdio>
#include<cmath>
#include<cstdlib>
#include<cstring>
#include "defs.h"
#include "prbg.h"

#define MAX_PASSWD 128
#define MIN(X,Y) ((X) < (Y) ? (X) : (Y))
using namespace std;

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

  //Checking input

  if(!(argc==3 && atoi(argv[1]))){
    //perror("Incorrect arguments");
    printf("\nCorrect usage:\n%s <KEY> [input file]\n\n<KEY>\n  Can be any integer with more than 4 digits which is not symetrical\n (not like this: 321321).\n\n[file]\n  Name of the input file.\n ",argv[0]);
    return -1;
  }

  //initializations and checks
  const int key1size=strlen(argv[1])/2;
  char ckey1[key1size];
  char ckey2[key1size+1];

  if(strlen(argv[1])%2==0){
    for(int i=0;i<key1size;++i){
      ckey1[i]=argv[1][i];
      ckey2[i]=argv[1][key1size+i];
	}
  }
  else{
    for(int i=0;i<key1size;++i){
      ckey1[i]=argv[1][i];
      ckey2[i]=argv[1][key1size+i];
	}
    ckey2[key1size]=argv[1][2*key1size];
  }
  double key1=(double)atoi(ckey1), key2=(double)atoi(ckey2);
   if(key1==key2){perror("Key cannot be symmetrical! Use your imagination!\n"); return -1;}
   //end of initializations of key1, key2

   double eskey1=pow(key1,2)*pow(10,((-1)*cdigits(pow(key1,2)))+1),
	  eskey2=pow(key2,2)*pow(10,((-1)*cdigits(pow(key2,2)))+1);

   Y1[0]=eskey1-floor(eskey1);
   Y2[0]=eskey2-floor(eskey2);
   //end initializations and checks
   //eskey = key^2*10^(-keydigits+1)
   FILE *fin,*fout;

   _byte c=0;
   char *pch=strstr(argv[2],".hid");
   char *outpfile;
   if(pch==NULL){

     int maxsize = MIN(strlen(argv[2])+4,MAX_PASSWD);
     outpfile= (char*) calloc(maxsize,sizeof(char));
     strncpy(outpfile,argv[2], maxsize);
     strcat(outpfile,".hid");
   }
   else {
     int maxsize = MIN(strlen(argv[2])-4,MAX_PASSWD);
     outpfile= (char*) calloc(maxsize,sizeof(char));
     for(int i = 0; i<maxsize; ++i)
       outpfile[i]=argv[2][i];
   }

    if((fin=fopen(argv[2],"rb"))!=NULL){
      if((fout=fopen(outpfile,"wb"))!=NULL){
	free(outpfile);
	while(!feof(fin)){
	  c=getc(fin);
	  c^=prbg(&eskey1,&eskey2);
	  putc(c,fout);
	}
	fclose(fout);
      }
      else{
	printf("No output file\n");
      }
      fclose(fin);
    }
    else{
      printf("No input file\n");
    }

return 0;
}
<commit_msg>Fixed indentaiton<commit_after>#include<cstdio>
#include<cmath>
#include<cstdlib>
#include<cstring>
#include "defs.h"
#include "prbg.h"

#define MAX_PASSWD 128
#define MIN(X,Y) ((X) < (Y) ? (X) : (Y))
using namespace std;

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

  //Checking input

  if(!(argc==3 && atoi(argv[1]))){
    //perror("Incorrect arguments");
    printf("\nCorrect usage:\n%s <KEY> [input file]\n\n<KEY>\n  Can be any integer with more than 4 digits which is not symetrical\n (not like this: 321321).\n\n[file]\n  Name of the input file.\n ",argv[0]);
    return -1;
  }

  //initializations and checks
  const int key1size=strlen(argv[1])/2;
  char ckey1[key1size];
  char ckey2[key1size+1];

  if (strlen(argv[1])%2==0) {
    for (int i=0;i<key1size;++i) {
      ckey1[i]=argv[1][i];
      ckey2[i]=argv[1][key1size+i];
		}
  }

  else {
    for (int i=0;i<key1size;++i){
      ckey1[i]=argv[1][i];
      ckey2[i]=argv[1][key1size+i];
	}
    ckey2[key1size]=argv[1][2*key1size];
  }

	double key1=(double)atoi(ckey1), key2=(double)atoi(ckey2);
  if (key1==key2) { perror("Key cannot be symmetrical! Use your imagination!\n"); return -1; }
  //end of initializations of key1, key2

  double eskey1=pow(key1,2)*pow(10,((-1)*cdigits(pow(key1,2)))+1),
	  	 	 eskey2=pow(key2,2)*pow(10,((-1)*cdigits(pow(key2,2)))+1);

  Y1[0]=eskey1-floor(eskey1);
  Y2[0]=eskey2-floor(eskey2);
  //end initializations and checks
  //eskey = key^2*10^(-keydigits+1)
  FILE *fin,*fout;

	_byte c=0;
	char *pch=strstr(argv[2],".hid");
	char *outpfile;
	if(pch==NULL){

	  int maxsize = MIN(strlen(argv[2])+4,MAX_PASSWD);
	  outpfile= (char*) calloc(maxsize,sizeof(char));
	  strncpy(outpfile,argv[2], maxsize);
	  strcat(outpfile,".hid");
  }

  else {
    int maxsize = MIN(strlen(argv[2])-4,MAX_PASSWD);
    outpfile= (char*) calloc(maxsize,sizeof(char));
    for(int i = 0; i<maxsize; ++i)
       outpfile[i]=argv[2][i];
  }

  if ((fin=fopen(argv[2],"rb"))!=NULL) {
  	if ((fout=fopen(outpfile,"wb"))!=NULL) {
			free(outpfile);

			while (!feof(fin)) {
	  		c=getc(fin);
	  		c^=prbg(&eskey1,&eskey2);
	  		putc(c,fout);
			}

			fclose(fout);
    }

		else {
			printf("No output file\n");
    }

    fclose(fin);
  }

  else {
  	printf("No input file\n");
  }

  return 0;
}

<|endoftext|>


<commit_before>/**
 * libcec-daemon
 * A simple daemon to connect libcec to uinput. That is, using your TV to control your PC!
 * by Andrew Brampton
 *
 * TODO
 *
 */
#include "main.h"

#define VERSION     "libcec-daemon v0.9"

#define CEC_NAME    "linux PC"
#define UINPUT_NAME "libcec-daemon"

#include <algorithm>
#include <cstdio>
#include <iostream>
#include <cstdint>
#include <cstddef>
#include <csignal>
#include <vector>

#include <boost/program_options.hpp>
#include "accumulator.hpp"

#include <log4cplus/logger.h>
#include <log4cplus/loggingmacros.h>
#include <log4cplus/configurator.h>

using namespace CEC;
using namespace log4cplus;

using std::cout;
using std::cerr;
using std::endl;
using std::min;
using std::string;
using std::vector;

static Logger logger = Logger::getInstance("main");

const vector<__u16> Main::uinputCecMap = Main::setupUinputMap();

Main & Main::instance() {
	// Singleton pattern so we can use main from a sighandle
	static Main main;
	return main;
}

Main::Main() : cec(CEC_NAME, this), uinput(UINPUT_NAME, uinputCecMap), running(true) {
	LOG4CPLUS_TRACE_STR(logger, "Main::Main()");

	signal (SIGINT,  &Main::signalHandler);
	signal (SIGTERM, &Main::signalHandler);
}

Main::~Main() {
	LOG4CPLUS_TRACE_STR(logger, "Main::~Main()");
	stop();
}

void Main::loop() {
	LOG4CPLUS_TRACE_STR(logger, "Main::loop()");

	cec.open();
	while (running) {
		LOG4CPLUS_TRACE_STR(logger, "Loop");
		sleep(1);
	}
	cec.close();
}

void Main::stop() {
	LOG4CPLUS_TRACE_STR(logger, "Main::stop()");
	running = false;
}

void Main::listDevices() {
	LOG4CPLUS_TRACE_STR(logger, "Main::listDevices()");
	cec.listDevices(cout);
}

void Main::signalHandler(int sigNum) {
	LOG4CPLUS_DEBUG_STR(logger, "Main::signalHandler()");

	Main::instance().stop();
}

const std::vector<__u16> & Main::setupUinputMap() {
	static std::vector<__u16> uinputCecMap;

	if (uinputCecMap.empty()) {
		uinputCecMap.resize(CEC_USER_CONTROL_CODE_MAX + 1, 0);
		uinputCecMap[CEC_USER_CONTROL_CODE_SELECT                      ] = KEY_ENTER;
		uinputCecMap[CEC_USER_CONTROL_CODE_UP                          ] = KEY_UP;
		uinputCecMap[CEC_USER_CONTROL_CODE_DOWN                        ] = KEY_DOWN;
		uinputCecMap[CEC_USER_CONTROL_CODE_LEFT                        ] = KEY_LEFT;
		uinputCecMap[CEC_USER_CONTROL_CODE_RIGHT                       ] = KEY_RIGHT;
		uinputCecMap[CEC_USER_CONTROL_CODE_RIGHT_UP                    ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_RIGHT_DOWN                  ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_LEFT_UP                     ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_LEFT_DOWN                   ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_ROOT_MENU                   ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_SETUP_MENU                  ] = KEY_SETUP;
		uinputCecMap[CEC_USER_CONTROL_CODE_CONTENTS_MENU               ] = KEY_MENU;
		uinputCecMap[CEC_USER_CONTROL_CODE_FAVORITE_MENU               ] = KEY_FAVORITES;
		uinputCecMap[CEC_USER_CONTROL_CODE_EXIT                        ] = KEY_BACKSPACE;
		uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER0                     ] = KEY_0;
		uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER1                     ] = KEY_1;
		uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER2                     ] = KEY_2;
		uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER3                     ] = KEY_3;
		uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER4                     ] = KEY_4;
		uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER5                     ] = KEY_5;
		uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER6                     ] = KEY_6;
		uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER7                     ] = KEY_7;
		uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER8                     ] = KEY_8;
		uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER9                     ] = KEY_9;
		uinputCecMap[CEC_USER_CONTROL_CODE_DOT                         ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_ENTER                       ] = KEY_ENTER;
		uinputCecMap[CEC_USER_CONTROL_CODE_CLEAR                       ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_NEXT_FAVORITE               ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_CHANNEL_UP                  ] = KEY_CHANNELUP;
		uinputCecMap[CEC_USER_CONTROL_CODE_CHANNEL_DOWN                ] = KEY_CHANNELDOWN;
		uinputCecMap[CEC_USER_CONTROL_CODE_PREVIOUS_CHANNEL            ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_SOUND_SELECT                ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_INPUT_SELECT                ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_DISPLAY_INFORMATION         ] = KEY_INFO;
		uinputCecMap[CEC_USER_CONTROL_CODE_HELP                        ] = KEY_HELP;
		uinputCecMap[CEC_USER_CONTROL_CODE_PAGE_UP                     ] = KEY_PAGEUP;
		uinputCecMap[CEC_USER_CONTROL_CODE_PAGE_DOWN                   ] = KEY_PAGEDOWN;
		uinputCecMap[CEC_USER_CONTROL_CODE_POWER                       ] = KEY_POWER;
		uinputCecMap[CEC_USER_CONTROL_CODE_VOLUME_UP                   ] = KEY_VOLUMEUP;
		uinputCecMap[CEC_USER_CONTROL_CODE_VOLUME_DOWN                 ] = KEY_VOLUMEDOWN;
		uinputCecMap[CEC_USER_CONTROL_CODE_MUTE                        ] = KEY_MUTE;
		uinputCecMap[CEC_USER_CONTROL_CODE_PLAY                        ] = KEY_PLAY;
		uinputCecMap[CEC_USER_CONTROL_CODE_STOP                        ] = KEY_STOP;
		uinputCecMap[CEC_USER_CONTROL_CODE_PAUSE                       ] = KEY_PAUSE;
		uinputCecMap[CEC_USER_CONTROL_CODE_RECORD                      ] = KEY_RECORD;
		uinputCecMap[CEC_USER_CONTROL_CODE_REWIND                      ] = KEY_REWIND;
		uinputCecMap[CEC_USER_CONTROL_CODE_FAST_FORWARD                ] = KEY_FASTFORWARD;
		uinputCecMap[CEC_USER_CONTROL_CODE_EJECT                       ] = KEY_EJECTCD;
		uinputCecMap[CEC_USER_CONTROL_CODE_FORWARD                     ] = KEY_NEXTSONG;
		uinputCecMap[CEC_USER_CONTROL_CODE_BACKWARD                    ] = KEY_PREVIOUSSONG;
		uinputCecMap[CEC_USER_CONTROL_CODE_STOP_RECORD                 ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_PAUSE_RECORD                ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_ANGLE                       ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_SUB_PICTURE                 ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_VIDEO_ON_DEMAND             ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_ELECTRONIC_PROGRAM_GUIDE    ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_TIMER_PROGRAMMING           ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_INITIAL_CONFIGURATION       ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_PLAY_FUNCTION               ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_PAUSE_PLAY_FUNCTION         ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_RECORD_FUNCTION             ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_PAUSE_RECORD_FUNCTION       ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_STOP_FUNCTION               ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_MUTE_FUNCTION               ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_RESTORE_VOLUME_FUNCTION     ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_TUNE_FUNCTION               ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_SELECT_MEDIA_FUNCTION       ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_SELECT_AV_INPUT_FUNCTION    ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_SELECT_AUDIO_INPUT_FUNCTION ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_POWER_TOGGLE_FUNCTION       ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_POWER_OFF_FUNCTION          ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_POWER_ON_FUNCTION           ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_F1_BLUE                     ] = KEY_BLUE;
		uinputCecMap[CEC_USER_CONTROL_CODE_F2_RED                      ] = KEY_RED;
		uinputCecMap[CEC_USER_CONTROL_CODE_F3_GREEN                    ] = KEY_GREEN;
		uinputCecMap[CEC_USER_CONTROL_CODE_F4_YELLOW                   ] = KEY_YELLOW;
		uinputCecMap[CEC_USER_CONTROL_CODE_F5                          ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_DATA                        ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_AN_RETURN                   ] = 0;
	}

	return uinputCecMap;
}

int Main::onCecLogMessage(const cec_log_message &message) {
	LOG4CPLUS_DEBUG(logger, "Main::onCecLogMessage(" << message << ")");
	return 1;
}

int Main::onCecKeyPress(const cec_keypress &key) {
	LOG4CPLUS_DEBUG(logger, "Main::onCecKeyPress(" << key << ")");

	int uinputKey = 0;

	// Check bounds and find uinput code for this cec keypress
	if (key.keycode >= 0 && key.keycode <= CEC_USER_CONTROL_CODE_MAX)
		uinputKey = uinputCecMap[key.keycode];

	if (uinputKey != 0) {
		LOG4CPLUS_DEBUG(logger, "sent " << uinputKey);

		uinput.send_event(EV_KEY, uinputKey, key.duration == 0 ? 1 : 0);
		uinput.sync();
	}

	return 1;
}

int Main::onCecCommand(const cec_command & command) {
	LOG4CPLUS_DEBUG(logger, "Main::onCecCommand(" << command << ")");
	return 1;
}

int Main::onCecConfigurationChanged(const libcec_configuration & configuration) {
	LOG4CPLUS_DEBUG(logger, "Main::onCecConfigurationChanged(" << configuration << ")");
	return 1;
}

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

    BasicConfigurator config;
    config.configure();

    int loglevel = 0;

	namespace po = boost::program_options;

	po::options_description desc("Allowed options");
	desc.add_options()
	    ("help,h",    "show help message")
	    ("version,V", "show version (and exit)")
	    ("daemon,d",  "daemon mode, run in background")
	    ("list,l",    "list available CEC adapters and devices")
	    ("verbose,v", accumulator<int>(&loglevel)->implicit_value(1), "verbose output (use -vv for more)")
	    ("quiet,q",   "quiet output (print almost nothing)")
	    ("usb", po::value<std::string>(), "USB adapter path (as shown by --list)")
	;

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

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

	if (vm.count("help")) {
		cout << "Usage: " << argv[0] << " [-h] [-v] [-d] [usb]" << endl << endl;
	    cout << desc << endl;
	    return 0;
	}

	if (vm.count("version")) {
		cout << VERSION << endl;
		return 0;
	}

	if(vm.count("quiet")) {
		loglevel = -1;
	} else {
		loglevel = min(loglevel, 2);
	}

	switch (loglevel) {
		case 2:  logger.setLogLevel(TRACE_LOG_LEVEL); break;
		case 1:  logger.setLogLevel(DEBUG_LOG_LEVEL); break;
		default: logger.setLogLevel(INFO_LOG_LEVEL); break;
		case -1: logger.setLogLevel(FATAL_LOG_LEVEL); break;
	}

	try {
		// Create the main
		Main & main = Main::instance();

		if (vm.count("list")) {
			main.listDevices();
			return 0;
		}

		if (vm.count("usb")) {
			cout << vm["usb"].as< string >() << endl;
		}

		if (vm.count("daemon")) {
			daemon(0, 0);
		}

		main.loop();

	} catch (std::exception & e) {
		cerr << e.what() << endl;
		return -1;
	}

	return 0;
}

<commit_msg>Ensure the root logger's log level is set.<commit_after>/**
 * libcec-daemon
 * A simple daemon to connect libcec to uinput. That is, using your TV to control your PC!
 * by Andrew Brampton
 *
 * TODO
 *
 */
#include "main.h"

#define VERSION     "libcec-daemon v0.9"

#define CEC_NAME    "linux PC"
#define UINPUT_NAME "libcec-daemon"

#include <algorithm>
#include <cstdio>
#include <iostream>
#include <cstdint>
#include <cstddef>
#include <csignal>
#include <vector>

#include <boost/program_options.hpp>
#include "accumulator.hpp"

#include <log4cplus/logger.h>
#include <log4cplus/loggingmacros.h>
#include <log4cplus/configurator.h>

using namespace CEC;
using namespace log4cplus;

using std::cout;
using std::cerr;
using std::endl;
using std::min;
using std::string;
using std::vector;

static Logger logger = Logger::getInstance("main");

const vector<__u16> Main::uinputCecMap = Main::setupUinputMap();

Main & Main::instance() {
	// Singleton pattern so we can use main from a sighandle
	static Main main;
	return main;
}

Main::Main() : cec(CEC_NAME, this), uinput(UINPUT_NAME, uinputCecMap), running(true) {
	LOG4CPLUS_TRACE_STR(logger, "Main::Main()");

	signal (SIGINT,  &Main::signalHandler);
	signal (SIGTERM, &Main::signalHandler);
}

Main::~Main() {
	LOG4CPLUS_TRACE_STR(logger, "Main::~Main()");
	stop();
}

void Main::loop() {
	LOG4CPLUS_TRACE_STR(logger, "Main::loop()");

	cec.open();
	while (running) {
		LOG4CPLUS_TRACE_STR(logger, "Loop");
		sleep(1);
	}
	cec.close();
}

void Main::stop() {
	LOG4CPLUS_TRACE_STR(logger, "Main::stop()");
	running = false;
}

void Main::listDevices() {
	LOG4CPLUS_TRACE_STR(logger, "Main::listDevices()");
	cec.listDevices(cout);
}

void Main::signalHandler(int sigNum) {
	LOG4CPLUS_DEBUG_STR(logger, "Main::signalHandler()");

	Main::instance().stop();
}

const std::vector<__u16> & Main::setupUinputMap() {
	static std::vector<__u16> uinputCecMap;

	if (uinputCecMap.empty()) {
		uinputCecMap.resize(CEC_USER_CONTROL_CODE_MAX + 1, 0);
		uinputCecMap[CEC_USER_CONTROL_CODE_SELECT                      ] = KEY_ENTER;
		uinputCecMap[CEC_USER_CONTROL_CODE_UP                          ] = KEY_UP;
		uinputCecMap[CEC_USER_CONTROL_CODE_DOWN                        ] = KEY_DOWN;
		uinputCecMap[CEC_USER_CONTROL_CODE_LEFT                        ] = KEY_LEFT;
		uinputCecMap[CEC_USER_CONTROL_CODE_RIGHT                       ] = KEY_RIGHT;
		uinputCecMap[CEC_USER_CONTROL_CODE_RIGHT_UP                    ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_RIGHT_DOWN                  ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_LEFT_UP                     ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_LEFT_DOWN                   ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_ROOT_MENU                   ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_SETUP_MENU                  ] = KEY_SETUP;
		uinputCecMap[CEC_USER_CONTROL_CODE_CONTENTS_MENU               ] = KEY_MENU;
		uinputCecMap[CEC_USER_CONTROL_CODE_FAVORITE_MENU               ] = KEY_FAVORITES;
		uinputCecMap[CEC_USER_CONTROL_CODE_EXIT                        ] = KEY_BACKSPACE;
		uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER0                     ] = KEY_0;
		uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER1                     ] = KEY_1;
		uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER2                     ] = KEY_2;
		uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER3                     ] = KEY_3;
		uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER4                     ] = KEY_4;
		uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER5                     ] = KEY_5;
		uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER6                     ] = KEY_6;
		uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER7                     ] = KEY_7;
		uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER8                     ] = KEY_8;
		uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER9                     ] = KEY_9;
		uinputCecMap[CEC_USER_CONTROL_CODE_DOT                         ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_ENTER                       ] = KEY_ENTER;
		uinputCecMap[CEC_USER_CONTROL_CODE_CLEAR                       ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_NEXT_FAVORITE               ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_CHANNEL_UP                  ] = KEY_CHANNELUP;
		uinputCecMap[CEC_USER_CONTROL_CODE_CHANNEL_DOWN                ] = KEY_CHANNELDOWN;
		uinputCecMap[CEC_USER_CONTROL_CODE_PREVIOUS_CHANNEL            ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_SOUND_SELECT                ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_INPUT_SELECT                ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_DISPLAY_INFORMATION         ] = KEY_INFO;
		uinputCecMap[CEC_USER_CONTROL_CODE_HELP                        ] = KEY_HELP;
		uinputCecMap[CEC_USER_CONTROL_CODE_PAGE_UP                     ] = KEY_PAGEUP;
		uinputCecMap[CEC_USER_CONTROL_CODE_PAGE_DOWN                   ] = KEY_PAGEDOWN;
		uinputCecMap[CEC_USER_CONTROL_CODE_POWER                       ] = KEY_POWER;
		uinputCecMap[CEC_USER_CONTROL_CODE_VOLUME_UP                   ] = KEY_VOLUMEUP;
		uinputCecMap[CEC_USER_CONTROL_CODE_VOLUME_DOWN                 ] = KEY_VOLUMEDOWN;
		uinputCecMap[CEC_USER_CONTROL_CODE_MUTE                        ] = KEY_MUTE;
		uinputCecMap[CEC_USER_CONTROL_CODE_PLAY                        ] = KEY_PLAY;
		uinputCecMap[CEC_USER_CONTROL_CODE_STOP                        ] = KEY_STOP;
		uinputCecMap[CEC_USER_CONTROL_CODE_PAUSE                       ] = KEY_PAUSE;
		uinputCecMap[CEC_USER_CONTROL_CODE_RECORD                      ] = KEY_RECORD;
		uinputCecMap[CEC_USER_CONTROL_CODE_REWIND                      ] = KEY_REWIND;
		uinputCecMap[CEC_USER_CONTROL_CODE_FAST_FORWARD                ] = KEY_FASTFORWARD;
		uinputCecMap[CEC_USER_CONTROL_CODE_EJECT                       ] = KEY_EJECTCD;
		uinputCecMap[CEC_USER_CONTROL_CODE_FORWARD                     ] = KEY_NEXTSONG;
		uinputCecMap[CEC_USER_CONTROL_CODE_BACKWARD                    ] = KEY_PREVIOUSSONG;
		uinputCecMap[CEC_USER_CONTROL_CODE_STOP_RECORD                 ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_PAUSE_RECORD                ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_ANGLE                       ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_SUB_PICTURE                 ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_VIDEO_ON_DEMAND             ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_ELECTRONIC_PROGRAM_GUIDE    ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_TIMER_PROGRAMMING           ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_INITIAL_CONFIGURATION       ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_PLAY_FUNCTION               ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_PAUSE_PLAY_FUNCTION         ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_RECORD_FUNCTION             ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_PAUSE_RECORD_FUNCTION       ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_STOP_FUNCTION               ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_MUTE_FUNCTION               ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_RESTORE_VOLUME_FUNCTION     ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_TUNE_FUNCTION               ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_SELECT_MEDIA_FUNCTION       ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_SELECT_AV_INPUT_FUNCTION    ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_SELECT_AUDIO_INPUT_FUNCTION ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_POWER_TOGGLE_FUNCTION       ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_POWER_OFF_FUNCTION          ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_POWER_ON_FUNCTION           ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_F1_BLUE                     ] = KEY_BLUE;
		uinputCecMap[CEC_USER_CONTROL_CODE_F2_RED                      ] = KEY_RED;
		uinputCecMap[CEC_USER_CONTROL_CODE_F3_GREEN                    ] = KEY_GREEN;
		uinputCecMap[CEC_USER_CONTROL_CODE_F4_YELLOW                   ] = KEY_YELLOW;
		uinputCecMap[CEC_USER_CONTROL_CODE_F5                          ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_DATA                        ] = 0;
		uinputCecMap[CEC_USER_CONTROL_CODE_AN_RETURN                   ] = 0;
	}

	return uinputCecMap;
}

int Main::onCecLogMessage(const cec_log_message &message) {
	LOG4CPLUS_DEBUG(logger, "Main::onCecLogMessage(" << message << ")");
	return 1;
}

int Main::onCecKeyPress(const cec_keypress &key) {
	LOG4CPLUS_DEBUG(logger, "Main::onCecKeyPress(" << key << ")");

	int uinputKey = 0;

	// Check bounds and find uinput code for this cec keypress
	if (key.keycode >= 0 && key.keycode <= CEC_USER_CONTROL_CODE_MAX)
		uinputKey = uinputCecMap[key.keycode];

	if (uinputKey != 0) {
		LOG4CPLUS_DEBUG(logger, "sent " << uinputKey);

		uinput.send_event(EV_KEY, uinputKey, key.duration == 0 ? 1 : 0);
		uinput.sync();
	}

	return 1;
}

int Main::onCecCommand(const cec_command & command) {
	LOG4CPLUS_DEBUG(logger, "Main::onCecCommand(" << command << ")");
	return 1;
}

int Main::onCecConfigurationChanged(const libcec_configuration & configuration) {
	LOG4CPLUS_DEBUG(logger, "Main::onCecConfigurationChanged(" << configuration << ")");
	return 1;
}

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

    BasicConfigurator config;
    config.configure();

    int loglevel = 0;

	namespace po = boost::program_options;

	po::options_description desc("Allowed options");
	desc.add_options()
	    ("help,h",    "show help message")
	    ("version,V", "show version (and exit)")
	    ("daemon,d",  "daemon mode, run in background")
	    ("list,l",    "list available CEC adapters and devices")
	    ("verbose,v", accumulator<int>(&loglevel)->implicit_value(1), "verbose output (use -vv for more)")
	    ("quiet,q",   "quiet output (print almost nothing)")
	    ("usb", po::value<std::string>(), "USB adapter path (as shown by --list)")
	;

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

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

	if (vm.count("help")) {
		cout << "Usage: " << argv[0] << " [-h] [-v] [-d] [usb]" << endl << endl;
	    cout << desc << endl;
	    return 0;
	}

	if (vm.count("version")) {
		cout << VERSION << endl;
		return 0;
	}

	if(vm.count("quiet")) {
		loglevel = -1;
	} else {
		loglevel = min(loglevel, 2);
	}

	Logger root = Logger::getRoot();
	switch (loglevel) {
		case 2:  root.setLogLevel(TRACE_LOG_LEVEL); break;
		case 1:  root.setLogLevel(DEBUG_LOG_LEVEL); break;
		default: root.setLogLevel(INFO_LOG_LEVEL); break;
		case -1: root.setLogLevel(FATAL_LOG_LEVEL); break;
	}

	try {
		// Create the main
		Main & main = Main::instance();

		if (vm.count("list")) {
			main.listDevices();
			return 0;
		}

		if (vm.count("usb")) {
			cout << vm["usb"].as< string >() << endl;
		}

		if (vm.count("daemon")) {
			daemon(0, 0);
		}

		main.loop();

	} catch (std::exception & e) {
		cerr << e.what() << endl;
		return -1;
	}

	return 0;
}

<|endoftext|>


<commit_before>#include <iostream>
#include <vector>
#include "MuMaterial.h"
#include "rhythm.hpp"

using namespace std;

void PrintVector (vector<float> v, string message);

int main ()
{
    MuInit();

    Rhythm rhythm(4, 4, 60);

    rhythm.GenerateBaseRhythm(2);

    vector<float> base_rhythm = rhythm.base_rhythm;

    PrintVector(rhythm.base_rhythm, "base_rhythm");

    cout << endl << "Ok!" << endl;
    return 0;
}

void PrintVector (vector<float> v, string message)
{
    cout << message << ": ";
    for (unsigned int index = 0; index < v.size(); index++)
    {
        cout << v[index] << " ";
    }
    cout << endl;
}
<commit_msg>Make print vector as auto function<commit_after>#include <iostream>
#include <vector>
#include "MuMaterial.h"
#include "rhythm.hpp"

using namespace std;

void PrintVector (auto const v, string message);

int main ()
{
    MuInit();

    Rhythm rhythm(4, 4, 60);

    rhythm.GenerateBaseRhythm(2);

    vector<float> base_rhythm = rhythm.base_rhythm;

    PrintVector(rhythm.base_rhythm, "base_rhythm");

    cout << endl << "Ok!" << endl;
    return 0;
}

void PrintVector (auto const v, string message)
{
    cout << message << ": ";
    for (unsigned int index = 0; index < v.size(); index++)
    {
        cout << v[index] << " ";
    }
    cout << endl;
}
<|endoftext|>