<commit_before>/*
 * Copyright (C) 2004-2009  See the AUTHORS file for details.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 as published
 * by the Free Software Foundation.
 */

#include "User.h"

class CNickServ : public CModule
{
public:
	MODCONSTRUCTOR(CNickServ)
	{
	}

	virtual ~CNickServ()
	{
	}

	virtual bool OnLoad(const CString& sArgs, CString& sMessage)
	{
		if (sArgs.empty())
			m_sPass = GetNV("Password");
		else
			m_sPass = sArgs;

		return true;
	}

	virtual void OnModCommand(const CString& sCommand)
	{
		CString sCmdName = sCommand.Token(0).AsLower();
		if (sCmdName == "set") {
			CString sPass = sCommand.Token(1, true);
			m_sPass = sPass;
			SetNV("Password", m_sPass);
			PutModule("Password set");
		} else if (xCmdName == "clear") {
			m_sPass = "";
			DelNV("Password");
		} else {
			PutModule("Commands: set <password>, clear");
		}
	}

	void HandleMessage(CNick& Nick, const CString& sMessage)
	{
		if (!m_sPass.empty()
				&& Nick.GetNick().Equals("NickServ")
				&& (sMessage.find("msg") != CString::npos
				 || sMessage.find("authenticate") != CString::npos)
				&& sMessage.AsUpper().find("IDENTIFY") != CString::npos
				&& sMessage.find("help") == CString::npos) {
			PutIRC("PRIVMSG NickServ :IDENTIFY " + m_sPass);
		}
	}

	virtual EModRet OnPrivMsg(CNick& Nick, CString& sMessage)
	{
		HandleMessage(Nick, sMessage);
		return CONTINUE;
	}

	virtual EModRet OnPrivNotice(CNick& Nick, CString& sMessage)
	{
		HandleMessage(Nick, sMessage);
		return CONTINUE;
	}

private:
	CString	m_sPass;
};

MODULEDEFS(CNickServ, "Auths you with NickServ")
<commit_msg>I suck (I broke the build!)<commit_after>/*
 * Copyright (C) 2004-2009  See the AUTHORS file for details.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 as published
 * by the Free Software Foundation.
 */

#include "User.h"

class CNickServ : public CModule
{
public:
	MODCONSTRUCTOR(CNickServ)
	{
	}

	virtual ~CNickServ()
	{
	}

	virtual bool OnLoad(const CString& sArgs, CString& sMessage)
	{
		if (sArgs.empty())
			m_sPass = GetNV("Password");
		else
			m_sPass = sArgs;

		return true;
	}

	virtual void OnModCommand(const CString& sCommand)
	{
		CString sCmdName = sCommand.Token(0).AsLower();
		if (sCmdName == "set") {
			CString sPass = sCommand.Token(1, true);
			m_sPass = sPass;
			SetNV("Password", m_sPass);
			PutModule("Password set");
		} else if (sCmdName == "clear") {
			m_sPass = "";
			DelNV("Password");
		} else {
			PutModule("Commands: set <password>, clear");
		}
	}

	void HandleMessage(CNick& Nick, const CString& sMessage)
	{
		if (!m_sPass.empty()
				&& Nick.GetNick().Equals("NickServ")
				&& (sMessage.find("msg") != CString::npos
				 || sMessage.find("authenticate") != CString::npos)
				&& sMessage.AsUpper().find("IDENTIFY") != CString::npos
				&& sMessage.find("help") == CString::npos) {
			PutIRC("PRIVMSG NickServ :IDENTIFY " + m_sPass);
		}
	}

	virtual EModRet OnPrivMsg(CNick& Nick, CString& sMessage)
	{
		HandleMessage(Nick, sMessage);
		return CONTINUE;
	}

	virtual EModRet OnPrivNotice(CNick& Nick, CString& sMessage)
	{
		HandleMessage(Nick, sMessage);
		return CONTINUE;
	}

private:
	CString	m_sPass;
};

MODULEDEFS(CNickServ, "Auths you with NickServ")
<|endoftext|>


<commit_before>// Copyright (c) 2014-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "base58.h"

#include "hash.h"
#include "uint256.h"

#include <assert.h>
#include <stdint.h>
#include <string.h>
#include <vector>
#include <string>
#include <boost/variant/apply_visitor.hpp>
#include <boost/variant/static_visitor.hpp>

/** All alphanumeric characters except for "0", "I", "O", and "l" */
static const char* pszBase58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";

bool DecodeBase58(const char* psz, std::vector<unsigned char>& vch)
{
    // Skip leading spaces.
    while (*psz && isspace(*psz))
        psz++;
    // Skip and count leading '1's.
    int zeroes = 0;
    while (*psz == '1') {
        zeroes++;
        psz++;
    }
    // Allocate enough space in big-endian base256 representation.
    std::vector<unsigned char> b256(strlen(psz) * 733 / 1000 + 1); // log(58) / log(256), rounded up.
    // Process the characters.
    while (*psz && !isspace(*psz)) {
        // Decode base58 character
        const char* ch = strchr(pszBase58, *psz);
        if (ch == NULL)
            return false;
        // Apply "b256 = b256 * 58 + ch".
        int carry = ch - pszBase58;
        for (std::vector<unsigned char>::reverse_iterator it = b256.rbegin(); it != b256.rend(); it++) {
            carry += 58 * (*it);
            *it = carry % 256;
            carry /= 256;
        }
        assert(carry == 0);
        psz++;
    }
    // Skip trailing spaces.
    while (isspace(*psz))
        psz++;
    if (*psz != 0)
        return false;
    // Skip leading zeroes in b256.
    std::vector<unsigned char>::iterator it = b256.begin();
    while (it != b256.end() && *it == 0)
        it++;
    // Copy result into output vector.
    vch.reserve(zeroes + (b256.end() - it));
    vch.assign(zeroes, 0x00);
    while (it != b256.end())
        vch.push_back(*(it++));
    return true;
}

std::string EncodeBase58(const unsigned char* pbegin, const unsigned char* pend)
{
    // Skip & count leading zeroes.
    int zeroes = 0;
    int length = 0;
    while (pbegin != pend && *pbegin == 0) {
        pbegin++;
        zeroes++;
    }
    // Allocate enough space in big-endian base58 representation.
    int size = (pend - pbegin) * 138 / 100 + 1; // log(256) / log(58), rounded up.
    std::vector<unsigned char> b58(size);
    // Process the bytes.
    while (pbegin != pend) {
        int carry = *pbegin;
        int i = 0;
        // Apply "b58 = b58 * 256 + ch".
        for (std::vector<unsigned char>::reverse_iterator it = b58.rbegin(); (carry != 0 || i < length) && (it != b58.rend()); it++, i++) {
            carry += 256 * (*it);
            *it = carry % 58;
            carry /= 58;
        }

        assert(carry == 0);
        length = i;
        pbegin++;
    }
    // Skip leading zeroes in base58 result.
    std::vector<unsigned char>::iterator it = b58.begin() + (size - length);
    while (it != b58.end() && *it == 0)
        it++;
    // Translate the result into a string.
    std::string str;
    str.reserve(zeroes + (b58.end() - it));
    str.assign(zeroes, '1');
    while (it != b58.end())
        str += pszBase58[*(it++)];
    return str;
}

std::string EncodeBase58(const std::vector<unsigned char>& vch)
{
    return EncodeBase58(&vch[0], &vch[0] + vch.size());
}

bool DecodeBase58(const std::string& str, std::vector<unsigned char>& vchRet)
{
    return DecodeBase58(str.c_str(), vchRet);
}

std::string EncodeBase58Check(const std::vector<unsigned char>& vchIn)
{
    // add 4-byte hash check to the end
    std::vector<unsigned char> vch(vchIn);
    uint256 hash = Hash(vch.begin(), vch.end());
    vch.insert(vch.end(), (unsigned char*)&hash, (unsigned char*)&hash + 4);
    return EncodeBase58(vch);
}

bool DecodeBase58Check(const char* psz, std::vector<unsigned char>& vchRet)
{
    if (!DecodeBase58(psz, vchRet) ||
        (vchRet.size() < 4)) {
        vchRet.clear();
        return false;
    }
    // re-calculate the checksum, insure it matches the included 4-byte checksum
    uint256 hash = Hash(vchRet.begin(), vchRet.end() - 4);
    if (memcmp(&hash, &vchRet.end()[-4], 4) != 0) {
        vchRet.clear();
        return false;
    }
    vchRet.resize(vchRet.size() - 4);
    return true;
}

bool DecodeBase58Check(const std::string& str, std::vector<unsigned char>& vchRet)
{
    return DecodeBase58Check(str.c_str(), vchRet);
}

CBase58Data::CBase58Data()
{
    vchVersion.clear();
    vchData.clear();
}

void CBase58Data::SetData(const std::vector<unsigned char>& vchVersionIn, const void* pdata, size_t nSize)
{
    vchVersion = vchVersionIn;
    vchData.resize(nSize);
    if (!vchData.empty())
        memcpy(&vchData[0], pdata, nSize);
}

void CBase58Data::SetData(const std::vector<unsigned char>& vchVersionIn, const unsigned char* pbegin, const unsigned char* pend)
{
    SetData(vchVersionIn, (void*)pbegin, pend - pbegin);
}

bool CBase58Data::SetString(const char* psz, unsigned int nVersionBytes)
{
    std::vector<unsigned char> vchTemp;
    bool rc58 = DecodeBase58Check(psz, vchTemp);
    if ((!rc58) || (vchTemp.size() < nVersionBytes)) {
        vchData.clear();
        vchVersion.clear();
        return false;
    }
    vchVersion.assign(vchTemp.begin(), vchTemp.begin() + nVersionBytes);
    vchData.resize(vchTemp.size() - nVersionBytes);
    if (!vchData.empty())
        memcpy(&vchData[0], &vchTemp[nVersionBytes], vchData.size());
    memory_cleanse(&vchTemp[0], vchTemp.size());
    return true;
}

bool CBase58Data::SetString(const std::string& str)
{
    return SetString(str.c_str());
}

std::string CBase58Data::ToString() const
{
//    if(vchData.To == "0x202020")
//      return "FUND_CONTRIBUTION";

    std::vector<unsigned char> vch = vchVersion;
    vch.insert(vch.end(), vchData.begin(), vchData.end());
    return EncodeBase58Check(vch);
}

int CBase58Data::CompareTo(const CBase58Data& b58) const
{
    if (vchVersion < b58.vchVersion)
        return -1;
    if (vchVersion > b58.vchVersion)
        return 1;
    if (vchData < b58.vchData)
        return -1;
    if (vchData > b58.vchData)
        return 1;
    return 0;
}

namespace
{
class CNavCoinAddressVisitor : public boost::static_visitor<bool>
{
private:
    CNavCoinAddress* addr;

public:
    CNavCoinAddressVisitor(CNavCoinAddress* addrIn) : addr(addrIn) {}

    bool operator()(const CKeyID& id) const { return addr->Set(id); }
    bool operator()(const CScriptID& id) const { return addr->Set(id); }
    bool operator()(const CNoDestination& no) const { return false; }
};

} // anon namespace

bool CNavCoinAddress::Set(const CKeyID& id)
{
    SetData(Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS), &id, 20);
    return true;
}

bool CNavCoinAddress::Set(const CScriptID& id)
{
    SetData(Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS), &id, 20);
    return true;
}

bool CNavCoinAddress::Set(const CTxDestination& dest)
{
    return boost::apply_visitor(CNavCoinAddressVisitor(this), dest);
}

bool CNavCoinAddress::IsValid() const
{
    return IsValid(Params());
}

bool CNavCoinAddress::IsValid(const CChainParams& params) const
{
    bool fCorrectSize = vchData.size() == 20;
    bool fKnownVersion = vchVersion == params.Base58Prefix(CChainParams::PUBKEY_ADDRESS) ||
                         vchVersion == params.Base58Prefix(CChainParams::SCRIPT_ADDRESS);
    return fCorrectSize && fKnownVersion;
}

CTxDestination CNavCoinAddress::Get() const
{
    if (!IsValid())
        return CNoDestination();
    uint160 id;
    memcpy(&id, &vchData[0], 20);
    if (vchVersion == Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS))
        return CKeyID(id);
    else if (vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS))
        return CScriptID(id);
    else
        return CNoDestination();
}

bool CNavCoinAddress::GetIndexKey(uint160& hashBytes, int& type) const
{
    if (!IsValid()) {
        return false;
    } else if (vchVersion == Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS)) {
        memcpy(&hashBytes, &vchData[0], 20);
        type = 1;
        return true;
    } else if (vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS)) {
        memcpy(&hashBytes, &vchData[0], 20);
        type = 2;
        return true;
    }

    return false;
}

bool CNavCoinAddress::GetKeyID(CKeyID& keyID) const
{
    if (!IsValid() || vchVersion != Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS))
        return false;
    uint160 id;
    memcpy(&id, &vchData[0], 20);
    keyID = CKeyID(id);
    return true;
}

bool CNavCoinAddress::IsScript() const
{
    return IsValid() && vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS);
}

void CNavCoinSecret::SetKey(const CKey& vchSecret)
{
    assert(vchSecret.IsValid());
    SetData(Params().Base58Prefix(CChainParams::SECRET_KEY), vchSecret.begin(), vchSecret.size());
    if (vchSecret.IsCompressed())
        vchData.push_back(1);
}

CKey CNavCoinSecret::GetKey()
{
    CKey ret;
    assert(vchData.size() >= 32);
    ret.Set(vchData.begin(), vchData.begin() + 32, vchData.size() > 32 && vchData[32] == 1);
    return ret;
}

bool CNavCoinSecret::IsValid() const
{
    bool fExpectedFormat = vchData.size() == 32 || (vchData.size() == 33 && vchData[32] == 1);
    bool fCorrectVersion = vchVersion == Params().Base58Prefix(CChainParams::SECRET_KEY);
    return fExpectedFormat && fCorrectVersion;
}

bool CNavCoinSecret::SetString(const char* pszSecret)
{
    return CBase58Data::SetString(pszSecret) && IsValid();
}

bool CNavCoinSecret::SetString(const std::string& strSecret)
{
    return SetString(strSecret.c_str());
}
<commit_msg>remove comment<commit_after>// Copyright (c) 2014-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "base58.h"

#include "hash.h"
#include "uint256.h"

#include <assert.h>
#include <stdint.h>
#include <string.h>
#include <vector>
#include <string>
#include <boost/variant/apply_visitor.hpp>
#include <boost/variant/static_visitor.hpp>

/** All alphanumeric characters except for "0", "I", "O", and "l" */
static const char* pszBase58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";

bool DecodeBase58(const char* psz, std::vector<unsigned char>& vch)
{
    // Skip leading spaces.
    while (*psz && isspace(*psz))
        psz++;
    // Skip and count leading '1's.
    int zeroes = 0;
    while (*psz == '1') {
        zeroes++;
        psz++;
    }
    // Allocate enough space in big-endian base256 representation.
    std::vector<unsigned char> b256(strlen(psz) * 733 / 1000 + 1); // log(58) / log(256), rounded up.
    // Process the characters.
    while (*psz && !isspace(*psz)) {
        // Decode base58 character
        const char* ch = strchr(pszBase58, *psz);
        if (ch == NULL)
            return false;
        // Apply "b256 = b256 * 58 + ch".
        int carry = ch - pszBase58;
        for (std::vector<unsigned char>::reverse_iterator it = b256.rbegin(); it != b256.rend(); it++) {
            carry += 58 * (*it);
            *it = carry % 256;
            carry /= 256;
        }
        assert(carry == 0);
        psz++;
    }
    // Skip trailing spaces.
    while (isspace(*psz))
        psz++;
    if (*psz != 0)
        return false;
    // Skip leading zeroes in b256.
    std::vector<unsigned char>::iterator it = b256.begin();
    while (it != b256.end() && *it == 0)
        it++;
    // Copy result into output vector.
    vch.reserve(zeroes + (b256.end() - it));
    vch.assign(zeroes, 0x00);
    while (it != b256.end())
        vch.push_back(*(it++));
    return true;
}

std::string EncodeBase58(const unsigned char* pbegin, const unsigned char* pend)
{
    // Skip & count leading zeroes.
    int zeroes = 0;
    int length = 0;
    while (pbegin != pend && *pbegin == 0) {
        pbegin++;
        zeroes++;
    }
    // Allocate enough space in big-endian base58 representation.
    int size = (pend - pbegin) * 138 / 100 + 1; // log(256) / log(58), rounded up.
    std::vector<unsigned char> b58(size);
    // Process the bytes.
    while (pbegin != pend) {
        int carry = *pbegin;
        int i = 0;
        // Apply "b58 = b58 * 256 + ch".
        for (std::vector<unsigned char>::reverse_iterator it = b58.rbegin(); (carry != 0 || i < length) && (it != b58.rend()); it++, i++) {
            carry += 256 * (*it);
            *it = carry % 58;
            carry /= 58;
        }

        assert(carry == 0);
        length = i;
        pbegin++;
    }
    // Skip leading zeroes in base58 result.
    std::vector<unsigned char>::iterator it = b58.begin() + (size - length);
    while (it != b58.end() && *it == 0)
        it++;
    // Translate the result into a string.
    std::string str;
    str.reserve(zeroes + (b58.end() - it));
    str.assign(zeroes, '1');
    while (it != b58.end())
        str += pszBase58[*(it++)];
    return str;
}

std::string EncodeBase58(const std::vector<unsigned char>& vch)
{
    return EncodeBase58(&vch[0], &vch[0] + vch.size());
}

bool DecodeBase58(const std::string& str, std::vector<unsigned char>& vchRet)
{
    return DecodeBase58(str.c_str(), vchRet);
}

std::string EncodeBase58Check(const std::vector<unsigned char>& vchIn)
{
    // add 4-byte hash check to the end
    std::vector<unsigned char> vch(vchIn);
    uint256 hash = Hash(vch.begin(), vch.end());
    vch.insert(vch.end(), (unsigned char*)&hash, (unsigned char*)&hash + 4);
    return EncodeBase58(vch);
}

bool DecodeBase58Check(const char* psz, std::vector<unsigned char>& vchRet)
{
    if (!DecodeBase58(psz, vchRet) ||
        (vchRet.size() < 4)) {
        vchRet.clear();
        return false;
    }
    // re-calculate the checksum, insure it matches the included 4-byte checksum
    uint256 hash = Hash(vchRet.begin(), vchRet.end() - 4);
    if (memcmp(&hash, &vchRet.end()[-4], 4) != 0) {
        vchRet.clear();
        return false;
    }
    vchRet.resize(vchRet.size() - 4);
    return true;
}

bool DecodeBase58Check(const std::string& str, std::vector<unsigned char>& vchRet)
{
    return DecodeBase58Check(str.c_str(), vchRet);
}

CBase58Data::CBase58Data()
{
    vchVersion.clear();
    vchData.clear();
}

void CBase58Data::SetData(const std::vector<unsigned char>& vchVersionIn, const void* pdata, size_t nSize)
{
    vchVersion = vchVersionIn;
    vchData.resize(nSize);
    if (!vchData.empty())
        memcpy(&vchData[0], pdata, nSize);
}

void CBase58Data::SetData(const std::vector<unsigned char>& vchVersionIn, const unsigned char* pbegin, const unsigned char* pend)
{
    SetData(vchVersionIn, (void*)pbegin, pend - pbegin);
}

bool CBase58Data::SetString(const char* psz, unsigned int nVersionBytes)
{
    std::vector<unsigned char> vchTemp;
    bool rc58 = DecodeBase58Check(psz, vchTemp);
    if ((!rc58) || (vchTemp.size() < nVersionBytes)) {
        vchData.clear();
        vchVersion.clear();
        return false;
    }
    vchVersion.assign(vchTemp.begin(), vchTemp.begin() + nVersionBytes);
    vchData.resize(vchTemp.size() - nVersionBytes);
    if (!vchData.empty())
        memcpy(&vchData[0], &vchTemp[nVersionBytes], vchData.size());
    memory_cleanse(&vchTemp[0], vchTemp.size());
    return true;
}

bool CBase58Data::SetString(const std::string& str)
{
    return SetString(str.c_str());
}

std::string CBase58Data::ToString() const
{
    std::vector<unsigned char> vch = vchVersion;
    vch.insert(vch.end(), vchData.begin(), vchData.end());
    return EncodeBase58Check(vch);
}

int CBase58Data::CompareTo(const CBase58Data& b58) const
{
    if (vchVersion < b58.vchVersion)
        return -1;
    if (vchVersion > b58.vchVersion)
        return 1;
    if (vchData < b58.vchData)
        return -1;
    if (vchData > b58.vchData)
        return 1;
    return 0;
}

namespace
{
class CNavCoinAddressVisitor : public boost::static_visitor<bool>
{
private:
    CNavCoinAddress* addr;

public:
    CNavCoinAddressVisitor(CNavCoinAddress* addrIn) : addr(addrIn) {}

    bool operator()(const CKeyID& id) const { return addr->Set(id); }
    bool operator()(const CScriptID& id) const { return addr->Set(id); }
    bool operator()(const CNoDestination& no) const { return false; }
};

} // anon namespace

bool CNavCoinAddress::Set(const CKeyID& id)
{
    SetData(Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS), &id, 20);
    return true;
}

bool CNavCoinAddress::Set(const CScriptID& id)
{
    SetData(Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS), &id, 20);
    return true;
}

bool CNavCoinAddress::Set(const CTxDestination& dest)
{
    return boost::apply_visitor(CNavCoinAddressVisitor(this), dest);
}

bool CNavCoinAddress::IsValid() const
{
    return IsValid(Params());
}

bool CNavCoinAddress::IsValid(const CChainParams& params) const
{
    bool fCorrectSize = vchData.size() == 20;
    bool fKnownVersion = vchVersion == params.Base58Prefix(CChainParams::PUBKEY_ADDRESS) ||
                         vchVersion == params.Base58Prefix(CChainParams::SCRIPT_ADDRESS);
    return fCorrectSize && fKnownVersion;
}

CTxDestination CNavCoinAddress::Get() const
{
    if (!IsValid())
        return CNoDestination();
    uint160 id;
    memcpy(&id, &vchData[0], 20);
    if (vchVersion == Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS))
        return CKeyID(id);
    else if (vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS))
        return CScriptID(id);
    else
        return CNoDestination();
}

bool CNavCoinAddress::GetIndexKey(uint160& hashBytes, int& type) const
{
    if (!IsValid()) {
        return false;
    } else if (vchVersion == Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS)) {
        memcpy(&hashBytes, &vchData[0], 20);
        type = 1;
        return true;
    } else if (vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS)) {
        memcpy(&hashBytes, &vchData[0], 20);
        type = 2;
        return true;
    }

    return false;
}

bool CNavCoinAddress::GetKeyID(CKeyID& keyID) const
{
    if (!IsValid() || vchVersion != Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS))
        return false;
    uint160 id;
    memcpy(&id, &vchData[0], 20);
    keyID = CKeyID(id);
    return true;
}

bool CNavCoinAddress::IsScript() const
{
    return IsValid() && vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS);
}

void CNavCoinSecret::SetKey(const CKey& vchSecret)
{
    assert(vchSecret.IsValid());
    SetData(Params().Base58Prefix(CChainParams::SECRET_KEY), vchSecret.begin(), vchSecret.size());
    if (vchSecret.IsCompressed())
        vchData.push_back(1);
}

CKey CNavCoinSecret::GetKey()
{
    CKey ret;
    assert(vchData.size() >= 32);
    ret.Set(vchData.begin(), vchData.begin() + 32, vchData.size() > 32 && vchData[32] == 1);
    return ret;
}

bool CNavCoinSecret::IsValid() const
{
    bool fExpectedFormat = vchData.size() == 32 || (vchData.size() == 33 && vchData[32] == 1);
    bool fCorrectVersion = vchVersion == Params().Base58Prefix(CChainParams::SECRET_KEY);
    return fExpectedFormat && fCorrectVersion;
}

bool CNavCoinSecret::SetString(const char* pszSecret)
{
    return CBase58Data::SetString(pszSecret) && IsValid();
}

bool CNavCoinSecret::SetString(const std::string& strSecret)
{
    return SetString(strSecret.c_str());
}
<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <activemq/connector/openwire/commands/ActiveMQDestination.h>
#include <activemq/exceptions/NullPointerException.h>
#include <activemq/util/URISupport.h>

using namespace std;
using namespace activemq;
using namespace activemq::util;
using namespace activemq::exceptions;
using namespace activemq::connector;
using namespace activemq::connector::openwire;
using namespace activemq::connector::openwire::commands;

////////////////////////////////////////////////////////////////////////////////
const std::string ActiveMQDestination::ADVISORY_PREFIX = "ActiveMQ.Advisory.";
const std::string ActiveMQDestination::CONSUMER_ADVISORY_PREFIX =
    ActiveMQDestination::ADVISORY_PREFIX + "Consumers.";
const std::string ActiveMQDestination::PRODUCER_ADVISORY_PREFIX =
    ActiveMQDestination::ADVISORY_PREFIX + "Producers.";
const std::string ActiveMQDestination::CONNECTION_ADVISORY_PREFIX =
    ActiveMQDestination::ADVISORY_PREFIX + "Connections.";
const std::string ActiveMQDestination::DEFAULT_ORDERED_TARGET = "coordinator";
const std::string ActiveMQDestination::TEMP_PREFIX = "{TD{";
const std::string ActiveMQDestination::TEMP_POSTFIX = "}TD}";
const std::string ActiveMQDestination::COMPOSITE_SEPARATOR = ",";
const std::string ActiveMQDestination::DestinationFilter::ANY_CHILD = ">";
const std::string ActiveMQDestination::DestinationFilter::ANY_DESCENDENT = "*";

////////////////////////////////////////////////////////////////////////////////
ActiveMQDestination::ActiveMQDestination() {

    this->physicalName = "";
    this->orderedTarget = DEFAULT_ORDERED_TARGET;
    this->exclusive = false;
    this->ordered = false;
    this->advisory = false;
}

////////////////////////////////////////////////////////////////////////////////
ActiveMQDestination::ActiveMQDestination( const std::string& physicalName ) {

    this->setPhysicalName( physicalName );
    this->orderedTarget = DEFAULT_ORDERED_TARGET;
    this->exclusive = false;
    this->ordered = false;
    this->advisory = false;
}

////////////////////////////////////////////////////////////////////////////////
void ActiveMQDestination::setPhysicalName( const std::string& physicalName ) {

    this->physicalName = physicalName;

    size_t pos = physicalName.find_first_of('?');
    if( pos != string::npos ) {

        std::string optstring = physicalName.substr( pos + 1 );
        this->physicalName = physicalName.substr( 0, pos );
        URISupport::parseQuery( optstring, &options );
    }

    this->advisory = physicalName.find_first_of( ADVISORY_PREFIX ) == 0;
}

////////////////////////////////////////////////////////////////////////////////
void ActiveMQDestination::copyDataStructure( const DataStructure* src ) {

    // Copy the data of the base class or classes
    BaseDataStructure::copyDataStructure( src );

    const ActiveMQDestination* srcPtr =
        dynamic_cast<const ActiveMQDestination*>( src );

    if( srcPtr == NULL || src == NULL ) {

        throw exceptions::NullPointerException(
            __FILE__, __LINE__,
            "BrokerId::copyDataStructure - src is NULL or invalid" );
    }

    this->setPhysicalName( srcPtr->getPhysicalName() );
    this->setAdvisory( srcPtr->isAdvisory() );
    this->setOrdered( srcPtr->isOrdered() );
    this->setExclusive( srcPtr->isExclusive() );
    this->setOrderedTarget( srcPtr->getOrderedTarget() );
}

////////////////////////////////////////////////////////////////////////////////
std::string ActiveMQDestination::toString() const {
    std::ostringstream stream;

    stream << "Begin Class = ActiveMQDestination" << std::endl;

    stream << " Value of exclusive = "
           << std::boolalpha << exclusive << std::endl;
    stream << " Value of ordered = "
           << std::boolalpha << ordered << std::endl;
    stream << " Value of advisory = "
           << std::boolalpha << advisory << std::endl;
    stream << " Value of orderedTarget = " << orderedTarget << std::endl;
    stream << " Value of physicalName = " << physicalName << std::endl;
    stream << " Value of options = " << this->options.toString() << std::endl;
    stream << BaseDataStructure::toString();
    stream << "End Class = ActiveMQDestination" << std::endl;

    return stream.str();
}

////////////////////////////////////////////////////////////////////////////////
unsigned char ActiveMQDestination::getDataStructureType() const
{
    return ActiveMQDestination::ID_ACTIVEMQDESTINATION;
}

////////////////////////////////////////////////////////////////////////////////
std::string ActiveMQDestination::getClientId(
    const ActiveMQDestination* destination )
{
    std::string answer = "";
    if( destination != NULL && destination->isTemporary() ) {
        std::string name = destination->getPhysicalName();
        size_t start = name.find( TEMP_PREFIX );
        if( start != std::string::npos ) {
            start += TEMP_PREFIX.length();
            size_t stop = name.rfind( TEMP_POSTFIX );
            if( stop > start && stop < name.length() ) {
                answer = name.substr( start, stop-start );
            }
        }
    }
    return answer;
}
<commit_msg>https://issues.apache.org/activemq/browse/AMQCPP-112<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <activemq/connector/openwire/commands/ActiveMQDestination.h>
#include <activemq/exceptions/NullPointerException.h>
#include <activemq/util/URISupport.h>

using namespace std;
using namespace activemq;
using namespace activemq::util;
using namespace activemq::exceptions;
using namespace activemq::connector;
using namespace activemq::connector::openwire;
using namespace activemq::connector::openwire::commands;

////////////////////////////////////////////////////////////////////////////////
const std::string ActiveMQDestination::ADVISORY_PREFIX = "ActiveMQ.Advisory.";
const std::string ActiveMQDestination::CONSUMER_ADVISORY_PREFIX =
    ActiveMQDestination::ADVISORY_PREFIX + "Consumers.";
const std::string ActiveMQDestination::PRODUCER_ADVISORY_PREFIX =
    ActiveMQDestination::ADVISORY_PREFIX + "Producers.";
const std::string ActiveMQDestination::CONNECTION_ADVISORY_PREFIX =
    ActiveMQDestination::ADVISORY_PREFIX + "Connections.";
const std::string ActiveMQDestination::DEFAULT_ORDERED_TARGET = "coordinator";
const std::string ActiveMQDestination::TEMP_PREFIX = "{TD{";
const std::string ActiveMQDestination::TEMP_POSTFIX = "}TD}";
const std::string ActiveMQDestination::COMPOSITE_SEPARATOR = ",";
const std::string ActiveMQDestination::DestinationFilter::ANY_CHILD = ">";
const std::string ActiveMQDestination::DestinationFilter::ANY_DESCENDENT = "*";

////////////////////////////////////////////////////////////////////////////////
ActiveMQDestination::ActiveMQDestination() {

    this->physicalName = "";
    this->orderedTarget = DEFAULT_ORDERED_TARGET;
    this->exclusive = false;
    this->ordered = false;
    this->advisory = false;
}

////////////////////////////////////////////////////////////////////////////////
ActiveMQDestination::ActiveMQDestination( const std::string& physicalName ) {

    this->setPhysicalName( physicalName );
    this->orderedTarget = DEFAULT_ORDERED_TARGET;
    this->exclusive = false;
    this->ordered = false;
    this->advisory = false;
}

////////////////////////////////////////////////////////////////////////////////
void ActiveMQDestination::setPhysicalName( const std::string& physicalName ) {

    this->physicalName = physicalName;

    size_t pos = physicalName.find_first_of('?');
    if( pos != string::npos ) {

        std::string optstring = physicalName.substr( pos + 1 );
        this->physicalName = physicalName.substr( 0, pos );
        URISupport::parseQuery( optstring, &options );
    }

    this->advisory = physicalName.find_first_of( ADVISORY_PREFIX ) == 0;
}

////////////////////////////////////////////////////////////////////////////////
void ActiveMQDestination::copyDataStructure( const DataStructure* src ) {

    // Copy the data of the base class or classes
    BaseDataStructure::copyDataStructure( src );

    const ActiveMQDestination* srcPtr =
        dynamic_cast<const ActiveMQDestination*>( src );

    if( srcPtr == NULL || src == NULL ) {

        throw exceptions::NullPointerException(
            __FILE__, __LINE__,
            "BrokerId::copyDataStructure - src is NULL or invalid" );
    }

    this->setPhysicalName( srcPtr->getPhysicalName() );
    this->setAdvisory( srcPtr->isAdvisory() );
    this->setOrdered( srcPtr->isOrdered() );
    this->setExclusive( srcPtr->isExclusive() );
    this->setOrderedTarget( srcPtr->getOrderedTarget() );
    this->options.copy( &srcPtr->getOptions() );
}

////////////////////////////////////////////////////////////////////////////////
std::string ActiveMQDestination::toString() const {
    std::ostringstream stream;

    stream << "Begin Class = ActiveMQDestination" << std::endl;

    stream << " Value of exclusive = "
           << std::boolalpha << exclusive << std::endl;
    stream << " Value of ordered = "
           << std::boolalpha << ordered << std::endl;
    stream << " Value of advisory = "
           << std::boolalpha << advisory << std::endl;
    stream << " Value of orderedTarget = " << orderedTarget << std::endl;
    stream << " Value of physicalName = " << physicalName << std::endl;
    stream << " Value of options = " << this->options.toString() << std::endl;
    stream << BaseDataStructure::toString();
    stream << "End Class = ActiveMQDestination" << std::endl;

    return stream.str();
}

////////////////////////////////////////////////////////////////////////////////
unsigned char ActiveMQDestination::getDataStructureType() const
{
    return ActiveMQDestination::ID_ACTIVEMQDESTINATION;
}

////////////////////////////////////////////////////////////////////////////////
std::string ActiveMQDestination::getClientId(
    const ActiveMQDestination* destination )
{
    std::string answer = "";
    if( destination != NULL && destination->isTemporary() ) {
        std::string name = destination->getPhysicalName();
        size_t start = name.find( TEMP_PREFIX );
        if( start != std::string::npos ) {
            start += TEMP_PREFIX.length();
            size_t stop = name.rfind( TEMP_POSTFIX );
            if( stop > start && stop < name.length() ) {
                answer = name.substr( start, stop-start );
            }
        }
    }
    return answer;
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland
 * All rights reserved.
 *
 * This library/application is free software; you can redistribute and/or modify it under the terms of
 * the license that is included with this library/application in the file license.txt.
 */

//--- interface include --------------------------------------------------------
#include "AnythingUtils.h"

//--- standard modules used ----------------------------------------------------
#include "StringStream.h"
#include "Renderer.h"
#include "Dbg.h"

//-- StoreCopier ---------------------------------------------------------------
void StoreCopier::Operate(Context &c, Anything &dest, const Anything &config, char delim, char indexdelim)
{
	StartTrace(StoreCopier.Operate);
	ROAnything ROconfig(config);
	Operate(c, dest, ROconfig, delim, indexdelim);
}

void StoreCopier::Operate(Context &c, Anything &dest, const ROAnything &config, char delim, char indexdelim)
{
	StartTrace(StoreCopier.Operate);
	TraceAny(config, "Config");

	Trace("delim [" << delim << "], indexdelim [" << indexdelim << "]");
	long sz = config.GetSize();
	for (long i = 0; i < sz; i++) {
		String sourceLookupName = config.SlotName(i);
		String destSlot;
		Renderer::RenderOnString(destSlot, c, config[i]);
		if ( sourceLookupName && destSlot ) {
			dest[destSlot] = c.Lookup(sourceLookupName, delim, indexdelim).DeepClone();
		}
	}
}

//-- StoreFinder ---------------------------------------------------------------

void StoreFinder::Operate(Context &c, Anything &dest, const Anything &config)
{
	StartTrace(StoreFinder.Operate);
	ROAnything ROconfig(config);
	Operate(c, dest, ROconfig);
}

void StoreFinder::Operate(Context &context, Anything &dest, const ROAnything &config)
{
	StartTrace(StoreFinder.Operate);
	TraceAny(config, "Config");

	String store = config["Store"].AsString("");
	dest = FindStore(context, store);

	String destSlotname;
	Renderer::RenderOnString(destSlotname, context, config["Slot"]);
	Trace("Destination slotname [" << destSlotname << "]");
	Anything anyConfig;
	anyConfig["Slot"] = destSlotname;
	if (config.IsDefined("Delim")) {
		anyConfig["Delim"] = config["Delim"].AsCharPtr(".")[0L];
	}
	if (config.IsDefined("IndexDelim")) {
		anyConfig["IndexDelim"] = config["IndexDelim"].AsCharPtr(":")[0L];
	}

	SlotFinder::Operate(dest, dest, anyConfig);
}

Anything &StoreFinder::FindStore(Context &c, String &storeName)
{
	StartTrace(StoreFinder.FindStore);

	if ( storeName == "Role" ) {
		return c.GetRoleStoreGlobal();
	}
	if ( storeName == "Session" ) {
		return c.GetSessionStore();
	}
	if ( storeName == "Request" ) {
		return c.GetRequest();
	}
	return c.GetTmpStore();
}

//-- StorePutter ---------------------------------------------------------------

void StorePutter::Operate(Anything &source, Context &c, const Anything &config)
{
	StartTrace(StorePutter.Operate);
	ROAnything ROconfig(config);
	Operate(source, c, ROconfig);
}

void StorePutter::Operate(Anything &source, Context &c, const ROAnything &config)
{
	StartTrace(StorePutter.Operate);
	TraceAny(config, "Config");

	Anything clonedConfig = config.DeepClone();
	String destSlotname;
	Renderer::RenderOnString(destSlotname, c, config["Slot"]);
	clonedConfig["Slot"] = destSlotname;
	if (config.IsDefined("Delim")) {
		clonedConfig["Delim"] = config["Delim"].AsCharPtr(".")[0L];
	}
	if (config.IsDefined("IndexDelim")) {
		clonedConfig["IndexDelim"] = config["IndexDelim"].AsCharPtr(":")[0L];
	}

	String store = config["Store"].AsString("");
	SlotPutter::Operate(source, StoreFinder::FindStore(c, store), clonedConfig);
}
<commit_msg>changed SlotPutter method used to the one using simple params instead of an anything<commit_after>/*
 * Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland
 * All rights reserved.
 *
 * This library/application is free software; you can redistribute and/or modify it under the terms of
 * the license that is included with this library/application in the file license.txt.
 */

//--- interface include --------------------------------------------------------
#include "AnythingUtils.h"

//--- standard modules used ----------------------------------------------------
#include "StringStream.h"
#include "Renderer.h"
#include "Dbg.h"

//-- StoreCopier ---------------------------------------------------------------
void StoreCopier::Operate(Context &c, Anything &dest, const Anything &config, char delim, char indexdelim)
{
	StartTrace(StoreCopier.Operate);
	ROAnything ROconfig(config);
	Operate(c, dest, ROconfig, delim, indexdelim);
}

void StoreCopier::Operate(Context &c, Anything &dest, const ROAnything &config, char delim, char indexdelim)
{
	StartTrace(StoreCopier.Operate);
	TraceAny(config, "Config");

	Trace("delim [" << delim << "], indexdelim [" << indexdelim << "]");
	long sz = config.GetSize();
	for (long i = 0; i < sz; i++) {
		String sourceLookupName = config.SlotName(i);
		String destSlot;
		Renderer::RenderOnString(destSlot, c, config[i]);
		if ( sourceLookupName && destSlot ) {
			dest[destSlot] = c.Lookup(sourceLookupName, delim, indexdelim).DeepClone();
		}
	}
}

//-- StoreFinder ---------------------------------------------------------------

void StoreFinder::Operate(Context &c, Anything &dest, const Anything &config)
{
	StartTrace(StoreFinder.Operate);
	ROAnything ROconfig(config);
	Operate(c, dest, ROconfig);
}

void StoreFinder::Operate(Context &context, Anything &dest, const ROAnything &config)
{
	StartTrace(StoreFinder.Operate);
	TraceAny(config, "Config");

	String store = config["Store"].AsString("");
	dest = FindStore(context, store);

	String destSlotname;
	Renderer::RenderOnString(destSlotname, context, config["Slot"]);
	Trace("Destination slotname [" << destSlotname << "]");
	Anything anyConfig;
	anyConfig["Slot"] = destSlotname;
	if (config.IsDefined("Delim")) {
		anyConfig["Delim"] = config["Delim"].AsCharPtr(".")[0L];
	}
	if (config.IsDefined("IndexDelim")) {
		anyConfig["IndexDelim"] = config["IndexDelim"].AsCharPtr(":")[0L];
	}

	SlotFinder::Operate(dest, dest, anyConfig);
}

Anything &StoreFinder::FindStore(Context &c, String &storeName)
{
	StartTrace(StoreFinder.FindStore);

	if ( storeName == "Role" ) {
		return c.GetRoleStoreGlobal();
	}
	if ( storeName == "Session" ) {
		return c.GetSessionStore();
	}
	if ( storeName == "Request" ) {
		return c.GetRequest();
	}
	return c.GetTmpStore();
}

//-- StorePutter ---------------------------------------------------------------

void StorePutter::Operate(Anything &source, Context &c, const Anything &config)
{
	StartTrace(StorePutter.Operate);
	ROAnything ROconfig(config);
	Operate(source, c, ROconfig);
}

void StorePutter::Operate(Anything &source, Context &c, const ROAnything &config)
{
	StartTrace(StorePutter.Operate);
	TraceAny(config, "Config");
	String strStoreName = config["Store"].AsString("");
	SlotPutter::Operate(source, StoreFinder::FindStore(c, strStoreName), Renderer::RenderToString(c, config["Slot"]), config["Append"].AsBool(false), config["Delim"].AsCharPtr(".")[0L], config["IndexDelim"].AsCharPtr(":")[0L]);
}
<|endoftext|>


<commit_before>/**
 * Clever programming language
 * Copyright (c) 2011 Clever Team
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */

#include <iostream>
#include <cstdlib>
#include "compiler/value.h"
#include "compiler/symboltable.h"
#include "modules/std/os/os.h"
#include "types/nativetypes.h"

namespace clever { namespace packages { namespace std {

namespace os {

/**
 * system(string command)
 * Calls a command and returns the exit code.
 */
static CLEVER_FUNCTION(system) {
	retval->setInteger(::system(args->at(0)->getString().c_str()));
}

} // namespace io

/**
 * Initializes Standard module
 */
void OSModule::init() throw() {
	using namespace os;

	addFunction(new Function("system", &CLEVER_FUNC_NAME(system), CLEVER_INT))
		->addArg("command", CLEVER_STR);
}

}}} // clever::packages::std
<commit_msg>Removed <iostream> from os.cc includes (unnecessary).<commit_after>/**
 * Clever programming language
 * Copyright (c) 2011 Clever Team
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */

#include <cstdlib>
#include "compiler/value.h"
#include "compiler/symboltable.h"
#include "modules/std/os/os.h"
#include "types/nativetypes.h"

namespace clever { namespace packages { namespace std {

namespace os {

/**
 * system(string command)
 * Calls a command and returns the exit code.
 */
static CLEVER_FUNCTION(system) {
	retval->setInteger(::system(args->at(0)->getString().c_str()));
}

} // namespace io

/**
 * Initializes Standard module
 */
void OSModule::init() throw() {
	using namespace os;

	addFunction(new Function("system", &CLEVER_FUNC_NAME(system), CLEVER_INT))
		->addArg("command", CLEVER_STR);
}

}}} // clever::packages::std
<|endoftext|>


<commit_before>#ifndef SRC_CORE_DETAIL_CONNECTION_HPP_
#define SRC_CORE_DETAIL_CONNECTION_HPP_

#include <type_traits>

#include "core/function_traits.hpp"
#include "core/traits.hpp"

namespace fc
{

namespace detail
{

enum void_flag
{
	payload_void,
	payload_not_void,
	invalid,
};

template<class source,class sink, class... P>
constexpr auto void_check(int) ->  decltype(std::declval<sink>()(), std::declval<source>()(std::declval<P>()...), void_flag())
{
	return payload_void;
}

template<class source,class sink, class... P>
constexpr auto void_check(int) ->  decltype(std::declval<sink>()(std::declval<source>()(std::declval<P>()...)), void_flag())
{
	return payload_not_void;
}

template<void_flag vflag, class source_t, class sink_t, class... param>
struct invoke_helper
{
};

template<class source_t, class sink_t>
struct invoke_helper<payload_void, source_t, sink_t>
{
	template<class... param>
	decltype(auto) operator()(source_t& source, sink_t& sink, param&&... p)
	{
		source(p...);
		return sink();
	}
};

template<class source_t, class sink_t>
struct invoke_helper<payload_not_void, source_t, sink_t>
{
	template<class... param>
	decltype(auto) operator()(source_t& source, sink_t& sink, param&&... p)
	{
		return sink(source(p...));
	}
};

} //namespace detail

/**
 * \brief defines basic connection object, which is connectable.
 * \tparam source_t the source node of the connection, data flows from here to the sink.
 * \tparam sink_t is the sink node of the connection, data goes here.
 * \tparam param_void is true if the parameter of operator() of source_t is void
 * \result_void param_void is true if the result of operator() of sink_t is void
 * \payload_void param_void is true if the result of operator() of source_t is void
 * the return value of source_t needs to be convertible to the parameter of sink_t.
 */
template<
		class source_t,
		class sink_t
		>
struct connection
{
	source_t source;
	sink_t sink;

	/**
	 * \brief call operator, calls source and then sink with the result of source
	 *
	 * redundant return type specification is necessary at the moment,
	 * as it causes missing operator() in source and sink to appear in function declaration
	 * and thus be a substitution failure.
	 */
	template<class S = source_t, class T = sink_t, class... param>
	auto operator()(param&&... p)
	-> decltype(detail::invoke_helper<
				detail::void_check<S, T, param...>(0),
				S,T
			>()
			(source,sink,p...))
	{
		constexpr auto test = detail::void_check<S, T, param...>(0);
		return detail::invoke_helper<
					test,
					S,T
				>()
				(source,sink,p...);
	}
};

/// internals of flexcore, everything here can change any time.
namespace detail
{

template<class source_t, class sink_t, class Enable = void>
struct connect_impl
{
	auto operator()(source_t&& source, sink_t&& sink)
	{
		return connection<source_t, sink_t>
				{std::forward<source_t>(source), std::forward<sink_t>(sink)};
	}
};

} // namespace detail

template <typename T>
using rm_ref_t = std::remove_reference_t<T>;

/**
 * \brief Connect takes two connectables and returns a connection.
 *
 * \param source is the source of the data flowing through the connection.
 * \param sink is the target of the data flowing through the connection.
 * \returns connection object which has its type determined by the source_t and sink_t.
 *
 * If source_t and sink_t fulfill connectable, the result is connectable.
 * If one of source_t and sink_t fulfills receive_connectable and the other
 * fulfills send_connectable, the result is not non_connectable.
 * If either source_t or sink_t fulfill send_connectable, the result is send_connectable.
 * If either source_t or sink_t fulfill receive_connectable, the result is receive_connectable.
 */
template
	<	class source_t,
		class sink_t
	>
auto connect (source_t&& source, sink_t&& sink)
{
	return detail::connect_impl<source_t, sink_t>()(
	        std::forward<source_t>(source), std::forward<sink_t>(sink));
}

/**
 * \brief Operator >> takes two connectables and returns a connection.
 *
 * This operator is syntactic sugar for Connect.
 */
template<class source_t, class sink_t, class enable = std::enable_if_t<
		(is_connectable<source_t>::value || is_active<rm_ref_t<source_t>>{})
		&& (is_connectable<sink_t>::value || is_active<rm_ref_t<sink_t>>{})>>
auto operator >>(source_t&& source, sink_t&& sink)
{
	return connect(std::forward<source_t>(source), std::forward<sink_t>(sink));
}

//todo: does not belong here
template <class source_t, class sink_t>
struct is_passive_sink<connection<source_t, sink_t>> : is_passive_sink<rm_ref_t<sink_t>>
{};

template <class source_t, class sink_t>
struct result_of<connection<source_t, sink_t>> : result_of<rm_ref_t<sink_t>>
{};

} //namespace fc

#endif /* SRC_CORE_CONNECTION_HPP_ */
<commit_msg>connection: add extra checks in operator>> related to active connectables.<commit_after>#ifndef SRC_CORE_DETAIL_CONNECTION_HPP_
#define SRC_CORE_DETAIL_CONNECTION_HPP_

#include <type_traits>

#include "core/function_traits.hpp"
#include "core/traits.hpp"

namespace fc
{

namespace detail
{

enum void_flag
{
	payload_void,
	payload_not_void,
	invalid,
};

template<class source,class sink, class... P>
constexpr auto void_check(int) ->  decltype(std::declval<sink>()(), std::declval<source>()(std::declval<P>()...), void_flag())
{
	return payload_void;
}

template<class source,class sink, class... P>
constexpr auto void_check(int) ->  decltype(std::declval<sink>()(std::declval<source>()(std::declval<P>()...)), void_flag())
{
	return payload_not_void;
}

template<void_flag vflag, class source_t, class sink_t, class... param>
struct invoke_helper
{
};

template<class source_t, class sink_t>
struct invoke_helper<payload_void, source_t, sink_t>
{
	template<class... param>
	decltype(auto) operator()(source_t& source, sink_t& sink, param&&... p)
	{
		source(p...);
		return sink();
	}
};

template<class source_t, class sink_t>
struct invoke_helper<payload_not_void, source_t, sink_t>
{
	template<class... param>
	decltype(auto) operator()(source_t& source, sink_t& sink, param&&... p)
	{
		return sink(source(p...));
	}
};

} //namespace detail

/**
 * \brief defines basic connection object, which is connectable.
 * \tparam source_t the source node of the connection, data flows from here to the sink.
 * \tparam sink_t is the sink node of the connection, data goes here.
 * \tparam param_void is true if the parameter of operator() of source_t is void
 * \result_void param_void is true if the result of operator() of sink_t is void
 * \payload_void param_void is true if the result of operator() of source_t is void
 * the return value of source_t needs to be convertible to the parameter of sink_t.
 */
template<
		class source_t,
		class sink_t
		>
struct connection
{
	source_t source;
	sink_t sink;

	/**
	 * \brief call operator, calls source and then sink with the result of source
	 *
	 * redundant return type specification is necessary at the moment,
	 * as it causes missing operator() in source and sink to appear in function declaration
	 * and thus be a substitution failure.
	 */
	template<class S = source_t, class T = sink_t, class... param>
	auto operator()(param&&... p)
	-> decltype(detail::invoke_helper<
				detail::void_check<S, T, param...>(0),
				S,T
			>()
			(source,sink,p...))
	{
		constexpr auto test = detail::void_check<S, T, param...>(0);
		return detail::invoke_helper<
					test,
					S,T
				>()
				(source,sink,p...);
	}
};

/// internals of flexcore, everything here can change any time.
namespace detail
{

template<class source_t, class sink_t, class Enable = void>
struct connect_impl
{
	auto operator()(source_t&& source, sink_t&& sink)
	{
		return connection<source_t, sink_t>
				{std::forward<source_t>(source), std::forward<sink_t>(sink)};
	}
};

} // namespace detail

template <typename T>
using rm_ref_t = std::remove_reference_t<T>;

/**
 * \brief Connect takes two connectables and returns a connection.
 *
 * \param source is the source of the data flowing through the connection.
 * \param sink is the target of the data flowing through the connection.
 * \returns connection object which has its type determined by the source_t and sink_t.
 *
 * If source_t and sink_t fulfill connectable, the result is connectable.
 * If one of source_t and sink_t fulfills receive_connectable and the other
 * fulfills send_connectable, the result is not non_connectable.
 * If either source_t or sink_t fulfill send_connectable, the result is send_connectable.
 * If either source_t or sink_t fulfill receive_connectable, the result is receive_connectable.
 */
template
	<	class source_t,
		class sink_t
	>
auto connect (source_t&& source, sink_t&& sink)
{
	return detail::connect_impl<source_t, sink_t>()(
	        std::forward<source_t>(source), std::forward<sink_t>(sink));
}

/**
 * \brief Operator >> takes two connectables and returns a connection.
 *
 * This operator is syntactic sugar for Connect.
 */
template<class source_t, class sink_t, class enable = std::enable_if_t<
		(is_connectable<source_t>::value || is_active_source<rm_ref_t<source_t>>{})
		&& (is_connectable<sink_t>::value || is_active_sink<rm_ref_t<sink_t>>{})>>
auto operator >>(source_t&& source, sink_t&& sink)
{
	static_assert(!(is_active<rm_ref_t<source_t>>{} && is_active<rm_ref_t<sink_t>>{}),
	              "event_source can not be connected to state_sink.");
	return connect(std::forward<source_t>(source), std::forward<sink_t>(sink));
}

//todo: does not belong here
template <class source_t, class sink_t>
struct is_passive_sink<connection<source_t, sink_t>> : is_passive_sink<rm_ref_t<sink_t>>
{};

template <class source_t, class sink_t>
struct result_of<connection<source_t, sink_t>> : result_of<rm_ref_t<sink_t>>
{};

} //namespace fc

#endif /* SRC_CORE_CONNECTION_HPP_ */
<|endoftext|>


<commit_before>/*
 * FilePathTests.cpp
 *
 * Copyright (C) 2009-20 by RStudio, PBC
 *
 * Unless you have received this program directly from RStudio pursuant
 * to the terms of a commercial license agreement with RStudio, then
 * this program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

#define RSTUDIO_NO_TESTTHAT_ALIASES
#include <tests/TestThat.hpp>

#include <shared_core/Error.hpp>
#include <shared_core/FilePath.hpp>

namespace rstudio {
namespace core {
namespace tests {

namespace {

#ifdef _WIN32

// helper for creating a path with the system drive
// prefixed for Windows. we try to use the current
// drive if at all possible; if we cannot retrieve
// that for some reason then we just fall back to
// the default system drive (normally C:)
std::string getDrivePrefix()
{
   char buffer[MAX_PATH];
   DWORD n = GetCurrentDirectory(MAX_PATH, buffer);
   if (n < 2)
      return ::getenv("SYSTEMDRIVE");

   if (buffer[1] != ':')
      return ::getenv("SYSTEMDRIVE");

   return std::string(buffer, 2);
}

FilePath createPath(const std::string& path = "/")
{
   static const std::string prefix = getDrivePrefix();
   return FilePath(prefix + path);
}

#else

FilePath createPath(const std::string& path)
{
   return FilePath(path);
}

#endif /* _WIN32 */

} // end anonymous namespace
TEST_CASE("file paths")
{
   SECTION("relative path construction")
   {
      FilePath rootPath = createPath();
      FilePath pPath = createPath("/path/to");
      FilePath aPath = createPath("/path/to/a");
      FilePath bPath = createPath("/path/to/b");

      CHECK(aPath.isWithin(pPath));
      CHECK(bPath.isWithin(pPath));
      CHECK(!aPath.isWithin(bPath));

      CHECK(aPath.getRelativePath(pPath) == "a");
   }

   SECTION("path containment pathology")
   {
      // isWithin should not be fooled by directory traversal; the first path is not inside the
      // second even though it appears to be lexically
      FilePath aPath = createPath("/path/to/a/../b");
      FilePath bPath = createPath("/path/to/a");
      CHECK(!aPath.isWithin(bPath));

      // isWithin should not be fooled by substrings
      FilePath cPath = createPath("/path/to/foo");
      FilePath dPath = createPath("/path/to/foobar");
      CHECK(!dPath.isWithin(cPath));
   }

   SECTION("child path completion")
   {
      // simple path completion should do what's expected
      FilePath aPath = createPath("/path/to/a");
      FilePath bPath = createPath("/path/to/a/b");
      CHECK(aPath.completeChildPath("b") == bPath);

      // trying to complete to a path outside should fail and return the original path
      FilePath cPath = createPath("/path/to/foo");
      CHECK(cPath.completeChildPath("../bar") == cPath);
      CHECK(cPath.completeChildPath("/path/to/quux") == cPath);

      // trailing slashes are okay
      FilePath dPath = createPath("/path/to/");
      FilePath ePath = createPath("/path/to/e");
      CHECK(dPath.completeChildPath("e") == ePath);
   }

   SECTION("general path completion")
   {
      // simple path completion should do what's expected
      FilePath aPath = createPath("/path/to/a");
      FilePath bPath = createPath("/path/to/a/b");
      CHECK(aPath.completePath("b") == bPath);

      // absolute paths are allowed
      FilePath cPath = createPath("/path/to/c");
      FilePath dPath = createPath("/path/to/d");
      CHECK(cPath.completePath("/path/to/d") == dPath);

      // directory traversal is allowed
      FilePath ePath = createPath("/path/to/e");
      FilePath fPath = createPath("/path/to/f");
      CHECK(ePath.completePath("../f").getLexicallyNormalPath() == fPath.getAbsolutePath());
   }

#ifdef _WIN32

   SECTION("relative paths for UNC shares")
   {
      // NOTE: need to be robust against mixed separators as these can
      // leak in depending on the API used to request the file path.
      //
      // https://github.com/rstudio/rstudio/issues/6587
      FilePath pPath(R"(//LOCALHOST/c$/p)");
      FilePath aPath(R"(\\LOCALHOST\c$\p\a)");
      CHECK(aPath.getRelativePath(pPath) == "a");
   }

#endif /* _WIN32 */

}

} // end namespace tests
} // end namespace core
} // end namespace rstudio
<commit_msg>fix build<commit_after>/*
 * FilePathTests.cpp
 *
 * Copyright (C) 2009-20 by RStudio, PBC
 *
 * Unless you have received this program directly from RStudio pursuant
 * to the terms of a commercial license agreement with RStudio, then
 * this program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

#define RSTUDIO_NO_TESTTHAT_ALIASES
#include <tests/TestThat.hpp>

#include <shared_core/Error.hpp>
#include <shared_core/FilePath.hpp>

namespace rstudio {
namespace core {
namespace tests {

namespace {

#ifdef _WIN32

// helper for creating a path with the system drive
// prefixed for Windows. we try to use the current
// drive if at all possible; if we cannot retrieve
// that for some reason then we just fall back to
// the default system drive (normally C:)
std::string getDrivePrefix()
{
   char buffer[MAX_PATH];
   DWORD n = GetCurrentDirectory(MAX_PATH, buffer);
   if (n < 2)
      return ::getenv("SYSTEMDRIVE");

   if (buffer[1] != ':')
      return ::getenv("SYSTEMDRIVE");

   return std::string(buffer, 2);
}

FilePath createPath(const std::string& path = "/")
{
   static const std::string prefix = getDrivePrefix();
   return FilePath(prefix + path);
}

#else

FilePath createPath(const std::string& path = "/")
{
   return FilePath(path);
}

#endif /* _WIN32 */

} // end anonymous namespace
TEST_CASE("file paths")
{
   SECTION("relative path construction")
   {
      FilePath rootPath = createPath();
      FilePath pPath = createPath("/path/to");
      FilePath aPath = createPath("/path/to/a");
      FilePath bPath = createPath("/path/to/b");

      CHECK(aPath.isWithin(pPath));
      CHECK(bPath.isWithin(pPath));
      CHECK(!aPath.isWithin(bPath));

      CHECK(aPath.getRelativePath(pPath) == "a");
   }

   SECTION("path containment pathology")
   {
      // isWithin should not be fooled by directory traversal; the first path is not inside the
      // second even though it appears to be lexically
      FilePath aPath = createPath("/path/to/a/../b");
      FilePath bPath = createPath("/path/to/a");
      CHECK(!aPath.isWithin(bPath));

      // isWithin should not be fooled by substrings
      FilePath cPath = createPath("/path/to/foo");
      FilePath dPath = createPath("/path/to/foobar");
      CHECK(!dPath.isWithin(cPath));
   }

   SECTION("child path completion")
   {
      // simple path completion should do what's expected
      FilePath aPath = createPath("/path/to/a");
      FilePath bPath = createPath("/path/to/a/b");
      CHECK(aPath.completeChildPath("b") == bPath);

      // trying to complete to a path outside should fail and return the original path
      FilePath cPath = createPath("/path/to/foo");
      CHECK(cPath.completeChildPath("../bar") == cPath);
      CHECK(cPath.completeChildPath("/path/to/quux") == cPath);

      // trailing slashes are okay
      FilePath dPath = createPath("/path/to/");
      FilePath ePath = createPath("/path/to/e");
      CHECK(dPath.completeChildPath("e") == ePath);
   }

   SECTION("general path completion")
   {
      // simple path completion should do what's expected
      FilePath aPath = createPath("/path/to/a");
      FilePath bPath = createPath("/path/to/a/b");
      CHECK(aPath.completePath("b") == bPath);

      // absolute paths are allowed
      FilePath cPath = createPath("/path/to/c");
      FilePath dPath = createPath("/path/to/d");
      CHECK(cPath.completePath("/path/to/d") == dPath);

      // directory traversal is allowed
      FilePath ePath = createPath("/path/to/e");
      FilePath fPath = createPath("/path/to/f");
      CHECK(ePath.completePath("../f").getLexicallyNormalPath() == fPath.getAbsolutePath());
   }

#ifdef _WIN32

   SECTION("relative paths for UNC shares")
   {
      // NOTE: need to be robust against mixed separators as these can
      // leak in depending on the API used to request the file path.
      //
      // https://github.com/rstudio/rstudio/issues/6587
      FilePath pPath(R"(//LOCALHOST/c$/p)");
      FilePath aPath(R"(\\LOCALHOST\c$\p\a)");
      CHECK(aPath.getRelativePath(pPath) == "a");
   }

#endif /* _WIN32 */

}

} // end namespace tests
} // end namespace core
} // end namespace rstudio
<|endoftext|>


<commit_before>#include "applications.h"
#include <QDir>

const int Applications::NameRole = Qt::UserRole + 1;
const int Applications::IconRole = Qt::UserRole + 2;
const int Applications::ExecRole = Qt::UserRole + 3;
const int Applications::TerminalRole = Qt::UserRole + 4;

Applications::Applications(QObject *parent) :
    QAbstractListModel(parent)
{
    connect(&m_parserThreadWatcher, SIGNAL(finished()), this, SLOT(parseFinished()));
    m_parserRunning = true;
    m_parserThread = QtConcurrent::run(this, &Applications::parseApplications);
    m_parserThreadWatcher.setFuture(m_parserThread);
}

Applications::~Applications()
{
    if (m_parserThread.isRunning())
        m_parserThread.cancel();
    qDeleteAll(this->m_internalData);
}

void Applications::parseApplications()
{
    this->m_files.append(this->readFolder(QDir::homePath() + APPLICATIONS_LOCAL_PATH));
    this->m_files.append(this->readFolder(APPLICATIONS_PATH));

    foreach(QString file, this->m_files)
    {
        DesktopFile* app = new DesktopFile(file);
        if (!app->noDisplay())
        {
            m_internalData.append(app);
        }
    }
    this->m_files.clear();
}

QStringList Applications::readFolder(QString folder)
{
    QDir dir(folder);
    QFileInfoList file_list = dir.entryInfoList(
                QStringList(APPLICATIONS_FILES), QDir::Files | QDir::Readable);

    QStringList files;
    foreach(QFileInfo file, file_list)
    {
        if (this->m_files.filter(file.fileName()).count() == 0)
        {
            files.append(file.absoluteFilePath());
        }
    }
    return files;
}

void Applications::add(DesktopFile *item)
{
    beginInsertRows(QModelIndex(), m_data.size(), m_data.size());
    m_data.append(item);
    endInsertRows();
    emit countChanged(m_data.size());
}

void Applications::sort()
{
    std::sort(this->m_data.begin(), this->m_data.end(),
              [](const DesktopFile* left, const DesktopFile* right) -> bool
    {
        return QString::compare(left->name(),right->name(), Qt::CaseInsensitive) < 0;
    });
}

DesktopFile* Applications::get(int index) const
{
    return m_data.at(index);
}

void Applications::filter(QString search)
{
    if (m_parserRunning) return;
    beginRemoveRows(QModelIndex(), 0, m_data.size());
    m_data.clear();
    endRemoveRows();
    foreach(DesktopFile* file, m_internalData)
    {
        if(file->name().contains(search,Qt::CaseInsensitive)
                || file->comment().contains(search, Qt::CaseInsensitive)
                || file->exec().contains(search, Qt::CaseInsensitive))
        {
            this->add(file);
        }
    }
    this->sort();
}

int Applications::rowCount(const QModelIndex &) const
{
    return m_data.count();
}

QVariant Applications::data(const QModelIndex &index, int role) const
{
    if (!index.isValid())
        return QVariant();
    if (index.row() > (m_data.size()-1) )
        return QVariant();

    DesktopFile* obj = m_data.at(index.row());
    switch(role)
    {
        case Qt::DisplayRole:
        case NameRole:
            return QVariant::fromValue(obj->name());
        break;

        case IconRole:
            return QVariant::fromValue(obj->icon());

        case ExecRole:
            return QVariant::fromValue(obj->exec());

        case TerminalRole:
            return QVariant::fromValue(obj->terminal());

        default:
            return QVariant();
    }
}

QHash<int, QByteArray> Applications::roleNames() const
{
    QHash<int, QByteArray> roles = QAbstractListModel::roleNames();
    roles.insert(NameRole, QByteArray("name"));
    roles.insert(IconRole, QByteArray("icon"));
    roles.insert(ExecRole, QByteArray("exec"));
    roles.insert(TerminalRole, QByteArray("terminal"));
    return roles;
}

void Applications::parseFinished()
{
    m_parserRunning = false;
    this->filter("");
    emit ready();
}
<commit_msg>Hide termianl apps<commit_after>#include "applications.h"
#include <QDir>

const int Applications::NameRole = Qt::UserRole + 1;
const int Applications::IconRole = Qt::UserRole + 2;
const int Applications::ExecRole = Qt::UserRole + 3;
const int Applications::TerminalRole = Qt::UserRole + 4;

Applications::Applications(QObject *parent) :
    QAbstractListModel(parent)
{
    connect(&m_parserThreadWatcher, SIGNAL(finished()), this, SLOT(parseFinished()));
    m_parserRunning = true;
    m_parserThread = QtConcurrent::run(this, &Applications::parseApplications);
    m_parserThreadWatcher.setFuture(m_parserThread);
}

Applications::~Applications()
{
    if (m_parserThread.isRunning())
        m_parserThread.cancel();
    qDeleteAll(this->m_internalData);
}

void Applications::parseApplications()
{
    this->m_files.append(this->readFolder(QDir::homePath() + APPLICATIONS_LOCAL_PATH));
    this->m_files.append(this->readFolder(APPLICATIONS_PATH));

    foreach(QString file, this->m_files)
    {
        DesktopFile* app = new DesktopFile(file);
        if (!app->noDisplay() && !app->terminal())
        {
            m_internalData.append(app);
        }
    }
    this->m_files.clear();
}

QStringList Applications::readFolder(QString folder)
{
    QDir dir(folder);
    QFileInfoList file_list = dir.entryInfoList(
                QStringList(APPLICATIONS_FILES), QDir::Files | QDir::Readable);

    QStringList files;
    foreach(QFileInfo file, file_list)
    {
        if (this->m_files.filter(file.fileName()).count() == 0)
        {
            files.append(file.absoluteFilePath());
        }
    }
    return files;
}

void Applications::add(DesktopFile *item)
{
    beginInsertRows(QModelIndex(), m_data.size(), m_data.size());
    m_data.append(item);
    endInsertRows();
    emit countChanged(m_data.size());
}

void Applications::sort()
{
    std::sort(this->m_data.begin(), this->m_data.end(),
              [](const DesktopFile* left, const DesktopFile* right) -> bool
    {
        return QString::compare(left->name(),right->name(), Qt::CaseInsensitive) < 0;
    });
}

DesktopFile* Applications::get(int index) const
{
    return m_data.at(index);
}

void Applications::filter(QString search)
{
    if (m_parserRunning) return;
    beginRemoveRows(QModelIndex(), 0, m_data.size());
    m_data.clear();
    endRemoveRows();
    foreach(DesktopFile* file, m_internalData)
    {
        if(file->name().contains(search,Qt::CaseInsensitive)
                || file->comment().contains(search, Qt::CaseInsensitive)
                || file->exec().contains(search, Qt::CaseInsensitive))
        {
            this->add(file);
        }
    }
    this->sort();
}

int Applications::rowCount(const QModelIndex &) const
{
    return m_data.count();
}

QVariant Applications::data(const QModelIndex &index, int role) const
{
    if (!index.isValid())
        return QVariant();
    if (index.row() > (m_data.size()-1) )
        return QVariant();

    DesktopFile* obj = m_data.at(index.row());
    switch(role)
    {
        case Qt::DisplayRole:
        case NameRole:
            return QVariant::fromValue(obj->name());
        break;

        case IconRole:
            return QVariant::fromValue(obj->icon());

        case ExecRole:
            return QVariant::fromValue(obj->exec());

        case TerminalRole:
            return QVariant::fromValue(obj->terminal());

        default:
            return QVariant();
    }
}

QHash<int, QByteArray> Applications::roleNames() const
{
    QHash<int, QByteArray> roles = QAbstractListModel::roleNames();
    roles.insert(NameRole, QByteArray("name"));
    roles.insert(IconRole, QByteArray("icon"));
    roles.insert(ExecRole, QByteArray("exec"));
    roles.insert(TerminalRole, QByteArray("terminal"));
    return roles;
}

void Applications::parseFinished()
{
    m_parserRunning = false;
    this->filter("");
    emit ready();
}
<|endoftext|>


<commit_before>//-------------------------------------------------------------------------------
// The MIT License (MIT)
//
// Copyright (c) 2014 Vadim Macagon
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//-------------------------------------------------------------------------------

#include "KlawrRuntimePluginPrivatePCH.h"
#include "KlawrScriptContext.h"

namespace Klawr {

FScriptContext::FScriptContext()
{
	ScriptObjectInfo.InstanceID = 0;
}

FScriptContext::~FScriptContext()
{
	DestroyScriptObject();
}

bool FScriptContext::Initialize(const FString& Code, UObject* Owner)
{
	// TODO:
	// [editor-only] save the code out to a file
	// [editor-only][advanced] generate a C# class for each blueprint class in the inheritance hierarchy
	// [editor-only] update the .csproj
	// [editor-only] rebuild the .csproj
	// [editor-only] copy the assembly to a directory in the search path
	// [editor-only] reload the engine app domain

	// create an instance of the managed class
	//return IClrHost::Get()->CreateScriptObject(TEXT("Klawr.UnrealEngine.TestActor"), Owner, ScriptObjectInfo);
	return false;
}

void FScriptContext::DestroyScriptObject()
{
	if (ScriptObjectInfo.InstanceID != 0)
	{
		//IClrHost::Get()->DestroyScriptObject(ScriptObjectInfo.InstanceID);
		ScriptObjectInfo.InstanceID = 0;
	}
}

void FScriptContext::BeginPlay()
{
	if (ScriptObjectInfo.BeginPlay)
	{
		ScriptObjectInfo.BeginPlay();
	}
}

void FScriptContext::Tick(float DeltaTime)
{
	if (ScriptObjectInfo.Tick)
	{
		ScriptObjectInfo.Tick(DeltaTime);
	}
}

void FScriptContext::Destroy()
{
	// clean up anything created in BeginPlay/Tick
	if (ScriptObjectInfo.Destroy)
	{
		ScriptObjectInfo.Destroy();
	}
	// the managed object will not be accessed from here on, so get rid of it now
	DestroyScriptObject();
}

bool FScriptContext::CanTick()
{
	return ScriptObjectInfo.Tick != nullptr;
}

bool FScriptContext::CallFunction(const FString& FunctionName)
{
	// TODO:
	return false;
}

void FScriptContext::InvokeScriptFunction(FFrame& Stack, RESULT_DECL)
{
	P_FINISH;
	CallFunction(Stack.CurrentNativeFunction->GetName());
}

} // namespace Klawr
<commit_msg>Renaming to KlawrScriptContext<commit_after>//-------------------------------------------------------------------------------
// The MIT License (MIT)
//
// Copyright (c) 2014 Vadim Macagon
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//-------------------------------------------------------------------------------

#include "KlawrRuntimePluginPrivatePCH.h"
#include "KlawrScriptContext.h"

namespace Klawr {

FKlawrScriptContext::FKlawrScriptContext()
{
	ScriptObjectInfo.InstanceID = 0;
}

FKlawrScriptContext::~FKlawrScriptContext()
{
	DestroyScriptObject();
}

bool FKlawrScriptContext::Initialize(const FString& Code, UObject* Owner)
{
	// TODO:
	// [editor-only] save the code out to a file
	// [editor-only][advanced] generate a C# class for each blueprint class in the inheritance hierarchy
	// [editor-only] update the .csproj
	// [editor-only] rebuild the .csproj
	// [editor-only] copy the assembly to a directory in the search path
	// [editor-only] reload the engine app domain

	// create an instance of the managed class
	//return IClrHost::Get()->CreateScriptObject(TEXT("Klawr.UnrealEngine.TestActor"), Owner, ScriptObjectInfo);
	return false;
}

void FKlawrScriptContext::DestroyScriptObject()
{
	if (ScriptObjectInfo.InstanceID != 0)
	{
		//IClrHost::Get()->DestroyScriptObject(ScriptObjectInfo.InstanceID);
		ScriptObjectInfo.InstanceID = 0;
	}
}

void FKlawrScriptContext::BeginPlay()
{
	if (ScriptObjectInfo.BeginPlay)
	{
		ScriptObjectInfo.BeginPlay();
	}
}

void FKlawrScriptContext::Tick(float DeltaTime)
{
	if (ScriptObjectInfo.Tick)
	{
		ScriptObjectInfo.Tick(DeltaTime);
	}
}

void FKlawrScriptContext::Destroy()
{
	// clean up anything created in BeginPlay/Tick
	if (ScriptObjectInfo.Destroy)
	{
		ScriptObjectInfo.Destroy();
	}
	// the managed object will not be accessed from here on, so get rid of it now
	DestroyScriptObject();
}

bool FKlawrScriptContext::CanTick()
{
	return ScriptObjectInfo.Tick != nullptr;
}

bool FKlawrScriptContext::CallFunction(const FString& FunctionName)
{
	// TODO:
	return false;
}

void FKlawrScriptContext::InvokeScriptFunction(FFrame& Stack, RESULT_DECL)
{
	P_FINISH;
	CallFunction(Stack.CurrentNativeFunction->GetName());
}

} // namespace Klawr
<|endoftext|>


<commit_before>/**
 * This file is part of the "FnordMetric" project
 *   Copyright (c) 2011-2014 Paul Asmuth, Google Inc.
 *
 * FnordMetric is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License v3.0. You should have received a
 * copy of the GNU General Public License along with this program. If not, see
 * <http://www.gnu.org/licenses/>.
 */

#include <vector>
#include <string>
#include <fnordmetric/cli/cli.h>
#include <fnordmetric/cli/flagparser.h>
#include <fnordmetric/ev/eventloop.h>
#include <fnordmetric/ev/acceptor.h>
#include <fnordmetric/http/httpserver.h>
#include <fnordmetric/util/exceptionhandler.h>
#include <fnordmetric/util/inputstream.h>
#include <fnordmetric/util/outputstream.h>
#include <fnordmetric/util/runtimeexception.h>
#include <fnordmetric/web/webinterface.h>
#include <fnordmetric/web/queryendpoint.h>

namespace fnordmetric {
namespace cli {

FlagParser CLI::getDefaultFlagParser() {
  FlagParser flag_parser;

  // Execute queries from the commandline:
  flag_parser.defineFlag(
      "format",
      FlagParser::T_STRING,
      false,
      "f",
      "table",
      "The output format { svg, csv, table }",
      "<format>");

  flag_parser.defineFlag(
      "output",
      FlagParser::T_STRING,
      false,
      "o",
      NULL,
      "Write output to a file",
      "<format>");

  // Start a user interface:
  flag_parser.defineFlag(
      "repl",
      FlagParser::T_SWITCH,
      false,
      NULL,
      NULL,
      "Start an interactive readline shell",
      NULL);

  flag_parser.defineFlag(
      "web",
      FlagParser::T_INTEGER,
      false,
      NULL,
      NULL,
      "Start a web interface on this port",
      "<port>");

  flag_parser.defineFlag(
      "cgi",
      FlagParser::T_SWITCH,
      false,
      NULL,
      NULL,
      "Run as CGI script");

  flag_parser.defineFlag(
      "verbose",
      FlagParser::T_SWITCH,
      false,
      NULL,
      NULL,
      "Be verbose");

  flag_parser.defineFlag(
      "help",
      FlagParser::T_SWITCH,
      false,
      "h",
      NULL,
      "You are reading it...");

  return flag_parser;
}

int CLI::executeSafely(
      const std::vector<std::string>& argv,
      std::shared_ptr<util::OutputStream> error_stream) {
  bool verbose = true;
  auto flag_parser = getDefaultFlagParser();

  try {
    flag_parser.parseArgv(argv);
    verbose = flag_parser.isSet("verbose");
    execute(flag_parser, error_stream);
  } catch (util::RuntimeException e) {
    if (e.getTypeName() == "UsageError") {
      flag_parser.printUsage(error_stream.get());
      return 1;
    }

    error_stream->printf("fatal error: %s\n", e.getMessage().c_str());

    if (verbose) {
      e.debugPrint();
    }

    return 1;
  }

  return 0;
}

void CLI::execute(
      const std::vector<std::string>& argv,
      std::shared_ptr<util::OutputStream> error_stream) {
  /* parse flags */
  auto flag_parser = getDefaultFlagParser();
  flag_parser.parseArgv(argv);
  bool verbose = flag_parser.isSet("verbose");
  const auto& args = flag_parser.getArgv();
  execute(flag_parser, error_stream);
}

void CLI::execute(
      const FlagParser& flag_parser,
      std::shared_ptr<util::OutputStream> error_stream) {
  const auto& args = flag_parser.getArgv();
  bool verbose = flag_parser.isSet("verbose");

  /* web / cgi mode */
  if (flag_parser.isSet("web")) {
    fnordmetric::util::ThreadPool thread_pool(
        32,
        std::unique_ptr<util::ExceptionHandler>(
            new util::CatchAndPrintExceptionHandler(error_stream)));

    fnordmetric::ev::EventLoop ev_loop;
    fnordmetric::ev::Acceptor acceptor(&ev_loop);
    fnordmetric::http::ThreadedHTTPServer http(&thread_pool);
    http.addHandler(fnordmetric::web::WebInterface::getHandler());
    http.addHandler(fnordmetric::web::QueryEndpoint::getHandler());
    acceptor.listen(flag_parser.getInt("web"), &http);
    ev_loop.loop();
  }

  /* open input stream */
  std::unique_ptr<util::InputStream> input;
  if (args.size() == 1) {
    if (args[0] == "-") {
      if (verbose) {
        error_stream->printf("[INFO] input from stdin %s\n");
      }

      input = std::move(util::InputStream::getStdin());
    } else {
      if (verbose) {
        error_stream->printf("[INFO] input file: %s\n", args[0].c_str());
      }

      input = std::move(util::FileInputStream::openFile(args[0]));
    }
  } else {
    RAISE(UsageError);
  }

  /* open output stream */
  std::unique_ptr<util::OutputStream> output;
  if (flag_parser.isSet("output")) {
    auto output_file = flag_parser.getString("output");

    if (verbose) {
      error_stream->printf("[INFO] output file: %s\n", output_file.c_str());
    }

    output = std::move(util::FileOutputStream::openFile(output_file));
  } else {
    if (verbose) {
      error_stream->printf("[INFO] output to stdout\n");
    }
    output = std::move(util::OutputStream::getStdout());
  }

  /* execute query */
  query::QueryService query_service;
  query_service.executeQuery(
      input.get(),
      getOutputFormat(flag_parser),
      output.get());
}

const query::QueryService::kFormat CLI::getOutputFormat(
    const FlagParser& flags) {
  return query::QueryService::FORMAT_TABLE;
}

}
}
<commit_msg>implement output format<commit_after>/**
 * This file is part of the "FnordMetric" project
 *   Copyright (c) 2011-2014 Paul Asmuth, Google Inc.
 *
 * FnordMetric is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License v3.0. You should have received a
 * copy of the GNU General Public License along with this program. If not, see
 * <http://www.gnu.org/licenses/>.
 */

#include <vector>
#include <string>
#include <fnordmetric/cli/cli.h>
#include <fnordmetric/cli/flagparser.h>
#include <fnordmetric/ev/eventloop.h>
#include <fnordmetric/ev/acceptor.h>
#include <fnordmetric/http/httpserver.h>
#include <fnordmetric/util/exceptionhandler.h>
#include <fnordmetric/util/inputstream.h>
#include <fnordmetric/util/outputstream.h>
#include <fnordmetric/util/runtimeexception.h>
#include <fnordmetric/web/webinterface.h>
#include <fnordmetric/web/queryendpoint.h>

namespace fnordmetric {
namespace cli {

FlagParser CLI::getDefaultFlagParser() {
  FlagParser flag_parser;

  // Execute queries from the commandline:
  flag_parser.defineFlag(
      "format",
      FlagParser::T_STRING,
      false,
      "f",
      "table",
      "The output format { svg, csv, table }",
      "<format>");

  flag_parser.defineFlag(
      "output",
      FlagParser::T_STRING,
      false,
      "o",
      NULL,
      "Write output to a file",
      "<format>");

  // Start a user interface:
  flag_parser.defineFlag(
      "repl",
      FlagParser::T_SWITCH,
      false,
      NULL,
      NULL,
      "Start an interactive readline shell",
      NULL);

  flag_parser.defineFlag(
      "web",
      FlagParser::T_INTEGER,
      false,
      NULL,
      NULL,
      "Start a web interface on this port",
      "<port>");

  flag_parser.defineFlag(
      "cgi",
      FlagParser::T_SWITCH,
      false,
      NULL,
      NULL,
      "Run as CGI script");

  flag_parser.defineFlag(
      "verbose",
      FlagParser::T_SWITCH,
      false,
      NULL,
      NULL,
      "Be verbose");

  flag_parser.defineFlag(
      "help",
      FlagParser::T_SWITCH,
      false,
      "h",
      NULL,
      "You are reading it...");

  return flag_parser;
}

int CLI::executeSafely(
      const std::vector<std::string>& argv,
      std::shared_ptr<util::OutputStream> error_stream) {
  bool verbose = true;
  auto flag_parser = getDefaultFlagParser();

  try {
    flag_parser.parseArgv(argv);
    verbose = flag_parser.isSet("verbose");
    execute(flag_parser, error_stream);
  } catch (util::RuntimeException e) {
    if (e.getTypeName() == "UsageError") {
      flag_parser.printUsage(error_stream.get());
      return 1;
    }

    error_stream->printf("fatal error: %s\n", e.getMessage().c_str());

    if (verbose) {
      e.debugPrint();
    }

    return 1;
  }

  return 0;
}

void CLI::execute(
      const std::vector<std::string>& argv,
      std::shared_ptr<util::OutputStream> error_stream) {
  /* parse flags */
  auto flag_parser = getDefaultFlagParser();
  flag_parser.parseArgv(argv);
  bool verbose = flag_parser.isSet("verbose");
  const auto& args = flag_parser.getArgv();
  execute(flag_parser, error_stream);
}

void CLI::execute(
      const FlagParser& flag_parser,
      std::shared_ptr<util::OutputStream> error_stream) {
  const auto& args = flag_parser.getArgv();
  bool verbose = flag_parser.isSet("verbose");

  /* web / cgi mode */
  if (flag_parser.isSet("web")) {
    fnordmetric::util::ThreadPool thread_pool(
        32,
        std::unique_ptr<util::ExceptionHandler>(
            new util::CatchAndPrintExceptionHandler(error_stream)));

    fnordmetric::ev::EventLoop ev_loop;
    fnordmetric::ev::Acceptor acceptor(&ev_loop);
    fnordmetric::http::ThreadedHTTPServer http(&thread_pool);
    http.addHandler(fnordmetric::web::WebInterface::getHandler());
    http.addHandler(fnordmetric::web::QueryEndpoint::getHandler());
    acceptor.listen(flag_parser.getInt("web"), &http);
    ev_loop.loop();
  }

  /* open input stream */
  std::unique_ptr<util::InputStream> input;
  if (args.size() == 1) {
    if (args[0] == "-") {
      if (verbose) {
        error_stream->printf("[INFO] input from stdin %s\n");
      }

      input = std::move(util::InputStream::getStdin());
    } else {
      if (verbose) {
        error_stream->printf("[INFO] input file: %s\n", args[0].c_str());
      }

      input = std::move(util::FileInputStream::openFile(args[0]));
    }
  } else {
    RAISE(UsageError);
  }

  /* open output stream */
  std::unique_ptr<util::OutputStream> output;
  if (flag_parser.isSet("output")) {
    auto output_file = flag_parser.getString("output");

    if (verbose) {
      error_stream->printf("[INFO] output file: %s\n", output_file.c_str());
    }

    output = std::move(util::FileOutputStream::openFile(output_file));
  } else {
    if (verbose) {
      error_stream->printf("[INFO] output to stdout\n");
    }
    output = std::move(util::OutputStream::getStdout());
  }

  /* execute query */
  query::QueryService query_service;
  query_service.executeQuery(
      input.get(),
      getOutputFormat(flag_parser),
      output.get());
}

const query::QueryService::kFormat CLI::getOutputFormat(
    const FlagParser& flags) {
  if (!flags.isSet("format")) {
    return query::QueryService::FORMAT_TABLE;
  }

  auto format_str = flags.getString("format");

  if (format_str == "csv") {
    return query::QueryService::FORMAT_CSV;
  }

  if (format_str == "json") {
    return query::QueryService::FORMAT_JSON;
  }

  if (format_str == "svg") {
    return query::QueryService::FORMAT_SVG;
  }

  if (format_str == "table") {
    return query::QueryService::FORMAT_TABLE;
  }

  RAISE(
      util::RuntimeException,
      "invalid format: '%s', allowed formats are "
      "'svg', 'csv', 'json' and 'table'",
      format_str.c_str());
}

}
}
<|endoftext|>