<commit_before>/**
 * Copyright (c) 2016-2017 mvs developers
 *
 * This file is part of metaverse-explorer.
 *
 * metaverse-explorer is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License with
 * additional permissions to the one published by the Free Software
 * Foundation, either version 3 of the License, or (at your option)
 * any later version. For more information see LICENSE.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

#include <metaverse/explorer/command.hpp>
#include <functional>
#include <memory>
#include <string>
#include <array>
#include <metaverse/explorer/command.hpp>
#include <metaverse/explorer/extensions/command_extension.hpp>
#include <metaverse/explorer/extensions/commands/private_send.hpp>  // for cmd move
#include <metaverse/explorer/extensions/commands/private_query.hpp>  // for cmd move
#include <metaverse/explorer/extensions/account_helper.hpp>
#include <metaverse/explorer/extensions/command_extension_func.hpp>

#include <metaverse/explorer/dispatch.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <metaverse/explorer/extensions/miner/stopall.hpp>
#include <metaverse/explorer/extensions/miner/stop.hpp>
#include <metaverse/explorer/extensions/miner/start.hpp>
#include <metaverse/explorer/extensions/blockchain/getinfo.hpp>
#include <metaverse/explorer/extensions/blockchain/getpeerinfo.hpp>
#include <metaverse/explorer/extensions/network/ping.hpp>
#include <metaverse/explorer/extensions/network/addnode.hpp>
#include <metaverse/explorer/extensions/miner/getmininginfo.hpp>
#include <metaverse/explorer/extensions/blockchain/getbestblockhash.hpp>
#include <metaverse/explorer/extensions/blockchain/getbestblockheader.hpp>
#include <metaverse/explorer/extensions/blockchain/fetchheaderext.hpp>
#include <metaverse/explorer/extensions/wallet/gettransaction.hpp>
#include <metaverse/explorer/extensions/wallet/backupwallet.hpp>
#include <metaverse/explorer/extensions/wallet/importwallet.hpp>
#include <metaverse/explorer/extensions/wallet/lockwallet.hpp>
#include <metaverse/explorer/extensions/wallet/exportaccountasfile.hpp>
#include <metaverse/explorer/extensions/wallet/importaccountfromfile.hpp>
#include <metaverse/explorer/extensions/wallet/importaccount.hpp>
#include <metaverse/explorer/extensions/wallet/getnewaccount.hpp>
#include <metaverse/explorer/extensions/wallet/getaccount.hpp>
#include <metaverse/explorer/extensions/wallet/deleteaccount.hpp>
#include <metaverse/explorer/extensions/wallet/lockaccount.hpp>
#include <metaverse/explorer/extensions/wallet/setaccountinfo.hpp>
#include <metaverse/explorer/extensions/wallet/listaddresses.hpp>
#include <metaverse/explorer/extensions/wallet/getnewaddress.hpp>
#include <metaverse/explorer/extensions/wallet/getaddress.hpp>
#include <metaverse/explorer/extensions/blockchain/getblock.hpp>
#include <metaverse/explorer/extensions/wallet/signmessage.hpp>
#include <metaverse/explorer/extensions/wallet/verifymessage.hpp>
#include <metaverse/explorer/extensions/wallet/createmultisig.hpp>
#include <metaverse/explorer/extensions/wallet/addmultisigaddress.hpp>
#include <metaverse/explorer/extensions/wallet/validateaddress.hpp>
#include <metaverse/explorer/extensions/wallet/listbalances.hpp>
#include <metaverse/explorer/extensions/wallet/getbalance.hpp>
#include <metaverse/explorer/extensions/wallet/listtxs.hpp>
#include <metaverse/explorer/extensions/wallet/xfetchbalance.hpp>
#include <metaverse/explorer/extensions/wallet/xfetchutxo.hpp>
#include <metaverse/explorer/extensions/wallet/gettx.hpp>
#include <metaverse/explorer/extensions/wallet/getaddresstx.hpp>
#include <metaverse/explorer/extensions/wallet/getaccounttx.hpp>
#include <metaverse/explorer/extensions/wallet/deposit.hpp>
#include <metaverse/explorer/extensions/wallet/send.hpp>
#include <metaverse/explorer/extensions/wallet/sendmore.hpp>
#include <metaverse/explorer/extensions/wallet/sendfrom.hpp>
#include <metaverse/explorer/extensions/wallet/listassets.hpp>
#include <metaverse/explorer/extensions/wallet/getasset.hpp>
#include <metaverse/explorer/extensions/wallet/getaddressasset.hpp>
#include <metaverse/explorer/extensions/wallet/getaccountasset.hpp>
#include <metaverse/explorer/extensions/wallet/createasset.hpp>
#include <metaverse/explorer/extensions/wallet/deleteasset.hpp>
#include <metaverse/explorer/extensions/wallet/issue.hpp>
#include <metaverse/explorer/extensions/wallet/issuefrom.hpp>
#include <metaverse/explorer/extensions/wallet/issuemore.hpp>
#include <metaverse/explorer/extensions/wallet/issuemorefrom.hpp>
#include <metaverse/explorer/extensions/wallet/sendasset.hpp>
#include <metaverse/explorer/extensions/wallet/sendassetfrom.hpp>
#include <metaverse/explorer/extensions/wallet/getdid.hpp>
#include <metaverse/explorer/extensions/wallet/setdid.hpp>
#include <metaverse/explorer/extensions/wallet/sendwithdid.hpp>
#include <metaverse/explorer/extensions/wallet/settxfee.hpp>
#include <metaverse/explorer/extensions/miner/getwork.hpp>
#include <metaverse/explorer/extensions/miner/submitwork.hpp>
#include <metaverse/explorer/extensions/miner/setminingaccount.hpp>
#include <metaverse/explorer/extensions/wallet/changepasswd.hpp>
#include <metaverse/explorer/extensions/wallet/encodeattachtx.hpp>
#include <metaverse/explorer/extensions/commands/private_query.hpp>
#include <metaverse/explorer/extensions/wallet/getmemorypool.hpp>

namespace libbitcoin {
namespace explorer {

void broadcast_extension(const function<void(shared_ptr<command>)> func)
{
    using namespace std;
    using namespace commands;
    func(make_shared<stopall>());
    func(make_shared<stop>());
    func(make_shared<start>());
    func(make_shared<getinfo>());
    func(make_shared<getpeerinfo>());
    func(make_shared<ping>());
    func(make_shared<addnode>());
    func(make_shared<getmininginfo>());
    func(make_shared<getbestblockhash>());
    func(make_shared<getbestblockheader>());
    func(make_shared<fetchheaderext>());
    func(make_shared<gettransaction>());
    func(make_shared<backupwallet>());
    func(make_shared<importwallet>());
    func(make_shared<lockwallet>());
    func(make_shared<exportaccountasfile>());
    func(make_shared<importaccountfromfile>());
    func(make_shared<importaccount>());
    func(make_shared<getnewaccount>());
    func(make_shared<getaccount>());
    func(make_shared<deleteaccount>());
    func(make_shared<lockaccount>());
    func(make_shared<setaccountinfo>());
    func(make_shared<listaddresses>());
    func(make_shared<getnewaddress>());
    func(make_shared<getaddress>());
    func(make_shared<getpublickey>());
    func(make_shared<getblock>());
    func(make_shared<signmessage>());
    func(make_shared<verifymessage>());
    func(make_shared<createmultisig>());
    func(make_shared<addmultisigaddress>());
    func(make_shared<validateaddress>());
    func(make_shared<listbalances>());
    func(make_shared<getbalance>());
    func(make_shared<listtxs>());
    func(make_shared<xfetchbalance>());
    func(make_shared<xfetchutxo>());
    func(make_shared<gettx>());
    func(make_shared<getaddresstx>());
    func(make_shared<getaccounttx>());
    func(make_shared<deposit>());
    func(make_shared<send>());
    func(make_shared<sendmore>());
    func(make_shared<sendfrom>());
    func(make_shared<listassets>());
    func(make_shared<getasset>());
    func(make_shared<getaddressasset>());
    func(make_shared<getaccountasset>());
    func(make_shared<createasset>());
    func(make_shared<deleteasset>());
    func(make_shared<issue>());
    func(make_shared<issuefrom>());
    func(make_shared<sendasset>());
    func(make_shared<sendassetfrom>());
    func(make_shared<getdid>());
    func(make_shared<setdid>());
    func(make_shared<sendwithdid>());
    func(make_shared<settxfee>());
    func(make_shared<getwork>());
    func(make_shared<submitwork>());
    func(make_shared<setminingaccount>());
    func(make_shared<changepasswd>());
    func(make_shared<getnewmultisig>());
    func(make_shared<listmultisig>());
    func(make_shared<deletemultisig>());
    func(make_shared<createmultisigtx>());
    func(make_shared<signmultisigtx>());
    func(make_shared<getmemorypool>());
}

shared_ptr<command> find_extension(const string& symbol)
{
    using namespace std;
    using namespace commands;
    if (symbol == stop::symbol())
        return make_shared<stop>();
    if (symbol == start::symbol())
        return make_shared<start>();
    if (symbol == getinfo::symbol())
        return make_shared<getinfo>();
    if (symbol == getpeerinfo::symbol())
        return make_shared<getpeerinfo>();
    if (symbol == ping::symbol())
        return make_shared<ping>();
    if (symbol == addnode::symbol())
        return make_shared<addnode>();
    if (symbol == getmininginfo::symbol())
        return make_shared<getmininginfo>();
    if (symbol == fetchheaderext::symbol())
        return make_shared<fetchheaderext>();
    if (symbol == gettransaction::symbol())
        return make_shared<gettransaction>();
    if (symbol == backupwallet::symbol())
        return make_shared<backupwallet>();
    if (symbol == importwallet::symbol())
        return make_shared<importwallet>();
    if (symbol == lockwallet::symbol())
        return make_shared<lockwallet>();
    if (symbol == exportaccountasfile::symbol())
        return make_shared<exportaccountasfile>();
    if (symbol == importaccountfromfile::symbol())
        return make_shared<importaccountfromfile>();
    if (symbol == importaccount::symbol())
        return make_shared<importaccount>();
    if (symbol == getnewaccount::symbol())
        return make_shared<getnewaccount>();
    if (symbol == getaccount::symbol())
        return make_shared<getaccount>();
    if (symbol == deleteaccount::symbol())
        return make_shared<deleteaccount>();
    if (symbol == lockaccount::symbol())
        return make_shared<lockaccount>();
    if (symbol == setaccountinfo::symbol())
        return make_shared<setaccountinfo>();
    if (symbol == listaddresses::symbol())
        return make_shared<listaddresses>();
    if (symbol == getnewaddress::symbol())
        return make_shared<getnewaddress>();
    if (symbol == getaddress::symbol())
        return make_shared<getaddress>();
    if (symbol == getpublickey::symbol())
        return make_shared<getpublickey>();
    if (symbol == getblock::symbol())
        return make_shared<getblock>();
    if (symbol == signmessage::symbol())
        return make_shared<signmessage>();
    if (symbol == verifymessage::symbol())
        return make_shared<verifymessage>();
    if (symbol == createmultisig::symbol())
        return make_shared<createmultisig>();
    if (symbol == addmultisigaddress::symbol())
        return make_shared<addmultisigaddress>();
    if (symbol == validateaddress::symbol())
        return make_shared<validateaddress>();
    if (symbol == listbalances::symbol())
        return make_shared<listbalances>();
    if (symbol == getbalance::symbol())
        return make_shared<getbalance>();
    if (symbol == getbestblockhash::symbol())
        return make_shared<getbestblockhash>();
    if (symbol == getbestblockheader::symbol())
        return make_shared<getbestblockheader>();
    if (symbol == listtxs::symbol())
        return make_shared<listtxs>();
    if (symbol == xfetchbalance::symbol())
        return make_shared<xfetchbalance>();
    if (symbol == xfetchutxo::symbol())
        return make_shared<xfetchutxo>();
    if (symbol == gettx::symbol())
        return make_shared<gettx>();
    if (symbol == getaddresstx::symbol())
        return make_shared<getaddresstx>();
    if (symbol == getaccounttx::symbol())
        return make_shared<getaccounttx>();
    if (symbol == deposit::symbol())
        return make_shared<deposit>();
    if (symbol == send::symbol())
        return make_shared<send>();
    if (symbol == sendmore::symbol())
        return make_shared<sendmore>();
    if (symbol == sendfrom::symbol())
        return make_shared<sendfrom>();
    if (symbol == listassets::symbol())
        return make_shared<listassets>();
    if (symbol == getasset::symbol())
        return make_shared<getasset>();
    if (symbol == getaddressasset::symbol())
        return make_shared<getaddressasset>();
    if (symbol == getaccountasset::symbol())
        return make_shared<getaccountasset>();
    if (symbol == createasset::symbol())
        return make_shared<createasset>();
    if (symbol == deleteasset::symbol())
        return make_shared<deleteasset>();
    if (symbol == issue::symbol())
        return make_shared<issue>();
    if (symbol == issuefrom::symbol())
        return make_shared<issuefrom>();
    if (symbol == sendasset::symbol())
        return make_shared<sendasset>();
    if (symbol == sendassetfrom::symbol())
        return make_shared<sendassetfrom>();
    if (symbol == getdid::symbol())
        return make_shared<getdid>();
    if (symbol == setdid::symbol())
        return make_shared<setdid>();
    if (symbol == sendwithdid::symbol())
        return make_shared<sendwithdid>();
    if (symbol == settxfee::symbol())
        return make_shared<settxfee>();
    if (symbol == encodeattachtx::symbol())
        return make_shared<encodeattachtx>();
    if (symbol == getwork::symbol())
        return make_shared<getwork>();
    if (symbol == submitwork::symbol())
        return make_shared<submitwork>();
    if (symbol == setminingaccount::symbol())
        return make_shared<setminingaccount>();
    if (symbol == changepasswd::symbol())
        return make_shared<changepasswd>();
    if (symbol == getnewmultisig::symbol())
        return make_shared<getnewmultisig>();
    if (symbol == listmultisig::symbol())
        return make_shared<listmultisig>();
    if (symbol == deletemultisig::symbol())
        return make_shared<deletemultisig>();
    if (symbol == createmultisigtx::symbol())
        return make_shared<createmultisigtx>();
    if (symbol == signmultisigtx::symbol())
        return make_shared<signmultisigtx>();
    if (symbol == issuefrom::symbol())
        return make_shared<issuefrom>();
    if (symbol == sendassetfrom::symbol())
        return make_shared<sendassetfrom>();
    if (symbol == stopall::symbol())
        return make_shared<stopall>();
    if (symbol == getmemorypool::symbol())
        return make_shared<getmemorypool>();
    return nullptr;
}

std::string formerly_extension(const string& former)
{
    return "";
}

} // namespace explorer
} // namespace libbitcoin

<commit_msg>#169 add broadcast tx command<commit_after>/**
 * Copyright (c) 2016-2017 mvs developers
 *
 * This file is part of metaverse-explorer.
 *
 * metaverse-explorer is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License with
 * additional permissions to the one published by the Free Software
 * Foundation, either version 3 of the License, or (at your option)
 * any later version. For more information see LICENSE.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

#include <metaverse/explorer/command.hpp>
#include <functional>
#include <memory>
#include <string>
#include <array>
#include <metaverse/explorer/command.hpp>
#include <metaverse/explorer/extensions/command_extension.hpp>
#include <metaverse/explorer/extensions/commands/private_send.hpp>  // for cmd move
#include <metaverse/explorer/extensions/commands/private_query.hpp>  // for cmd move
#include <metaverse/explorer/extensions/account_helper.hpp>
#include <metaverse/explorer/extensions/command_extension_func.hpp>

#include <metaverse/explorer/dispatch.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <metaverse/explorer/extensions/miner/stopall.hpp>
#include <metaverse/explorer/extensions/miner/stop.hpp>
#include <metaverse/explorer/extensions/miner/start.hpp>
#include <metaverse/explorer/extensions/blockchain/getinfo.hpp>
#include <metaverse/explorer/extensions/blockchain/getpeerinfo.hpp>
#include <metaverse/explorer/extensions/network/ping.hpp>
#include <metaverse/explorer/extensions/network/addnode.hpp>
#include <metaverse/explorer/extensions/miner/getmininginfo.hpp>
#include <metaverse/explorer/extensions/blockchain/getbestblockhash.hpp>
#include <metaverse/explorer/extensions/blockchain/getbestblockheader.hpp>
#include <metaverse/explorer/extensions/blockchain/fetchheaderext.hpp>
#include <metaverse/explorer/extensions/wallet/gettransaction.hpp>
#include <metaverse/explorer/extensions/wallet/backupwallet.hpp>
#include <metaverse/explorer/extensions/wallet/importwallet.hpp>
#include <metaverse/explorer/extensions/wallet/lockwallet.hpp>
#include <metaverse/explorer/extensions/wallet/exportaccountasfile.hpp>
#include <metaverse/explorer/extensions/wallet/importaccountfromfile.hpp>
#include <metaverse/explorer/extensions/wallet/importaccount.hpp>
#include <metaverse/explorer/extensions/wallet/getnewaccount.hpp>
#include <metaverse/explorer/extensions/wallet/getaccount.hpp>
#include <metaverse/explorer/extensions/wallet/deleteaccount.hpp>
#include <metaverse/explorer/extensions/wallet/lockaccount.hpp>
#include <metaverse/explorer/extensions/wallet/setaccountinfo.hpp>
#include <metaverse/explorer/extensions/wallet/listaddresses.hpp>
#include <metaverse/explorer/extensions/wallet/getnewaddress.hpp>
#include <metaverse/explorer/extensions/wallet/getaddress.hpp>
#include <metaverse/explorer/extensions/blockchain/getblock.hpp>
#include <metaverse/explorer/extensions/wallet/signmessage.hpp>
#include <metaverse/explorer/extensions/wallet/verifymessage.hpp>
#include <metaverse/explorer/extensions/wallet/createmultisig.hpp>
#include <metaverse/explorer/extensions/wallet/addmultisigaddress.hpp>
#include <metaverse/explorer/extensions/wallet/validateaddress.hpp>
#include <metaverse/explorer/extensions/wallet/listbalances.hpp>
#include <metaverse/explorer/extensions/wallet/getbalance.hpp>
#include <metaverse/explorer/extensions/wallet/listtxs.hpp>
#include <metaverse/explorer/extensions/wallet/xfetchbalance.hpp>
#include <metaverse/explorer/extensions/wallet/xfetchutxo.hpp>
#include <metaverse/explorer/extensions/wallet/gettx.hpp>
#include <metaverse/explorer/extensions/wallet/getaddresstx.hpp>
#include <metaverse/explorer/extensions/wallet/getaccounttx.hpp>
#include <metaverse/explorer/extensions/wallet/deposit.hpp>
#include <metaverse/explorer/extensions/wallet/send.hpp>
#include <metaverse/explorer/extensions/wallet/sendmore.hpp>
#include <metaverse/explorer/extensions/wallet/sendfrom.hpp>
#include <metaverse/explorer/extensions/wallet/listassets.hpp>
#include <metaverse/explorer/extensions/wallet/getasset.hpp>
#include <metaverse/explorer/extensions/wallet/getaddressasset.hpp>
#include <metaverse/explorer/extensions/wallet/getaccountasset.hpp>
#include <metaverse/explorer/extensions/wallet/createasset.hpp>
#include <metaverse/explorer/extensions/wallet/deleteasset.hpp>
#include <metaverse/explorer/extensions/wallet/issue.hpp>
#include <metaverse/explorer/extensions/wallet/issuefrom.hpp>
#include <metaverse/explorer/extensions/wallet/issuemore.hpp>
#include <metaverse/explorer/extensions/wallet/issuemorefrom.hpp>
#include <metaverse/explorer/extensions/wallet/sendasset.hpp>
#include <metaverse/explorer/extensions/wallet/sendassetfrom.hpp>
#include <metaverse/explorer/extensions/wallet/getdid.hpp>
#include <metaverse/explorer/extensions/wallet/setdid.hpp>
#include <metaverse/explorer/extensions/wallet/sendwithdid.hpp>
#include <metaverse/explorer/extensions/wallet/settxfee.hpp>
#include <metaverse/explorer/extensions/miner/getwork.hpp>
#include <metaverse/explorer/extensions/miner/submitwork.hpp>
#include <metaverse/explorer/extensions/miner/setminingaccount.hpp>
#include <metaverse/explorer/extensions/wallet/changepasswd.hpp>
#include <metaverse/explorer/extensions/wallet/encodeattachtx.hpp>
#include <metaverse/explorer/extensions/commands/private_query.hpp>
#include <metaverse/explorer/extensions/wallet/getmemorypool.hpp>

namespace libbitcoin {
namespace explorer {

void broadcast_extension(const function<void(shared_ptr<command>)> func)
{
    using namespace std;
    using namespace commands;
    func(make_shared<stopall>());
    func(make_shared<stop>());
    func(make_shared<start>());
    func(make_shared<getinfo>());
    func(make_shared<getpeerinfo>());
    func(make_shared<ping>());
    func(make_shared<addnode>());
    func(make_shared<getmininginfo>());
    func(make_shared<getbestblockhash>());
    func(make_shared<getbestblockheader>());
    func(make_shared<fetchheaderext>());
    func(make_shared<gettransaction>());
    func(make_shared<backupwallet>());
    func(make_shared<importwallet>());
    func(make_shared<lockwallet>());
    func(make_shared<exportaccountasfile>());
    func(make_shared<importaccountfromfile>());
    func(make_shared<importaccount>());
    func(make_shared<getnewaccount>());
    func(make_shared<getaccount>());
    func(make_shared<deleteaccount>());
    func(make_shared<lockaccount>());
    func(make_shared<setaccountinfo>());
    func(make_shared<listaddresses>());
    func(make_shared<getnewaddress>());
    func(make_shared<getaddress>());
    func(make_shared<getpublickey>());
    func(make_shared<getblock>());
    func(make_shared<signmessage>());
    func(make_shared<verifymessage>());
    func(make_shared<createmultisig>());
    func(make_shared<addmultisigaddress>());
    func(make_shared<validateaddress>());
    func(make_shared<listbalances>());
    func(make_shared<getbalance>());
    func(make_shared<listtxs>());
    func(make_shared<xfetchbalance>());
    func(make_shared<xfetchutxo>());
    func(make_shared<gettx>());
    func(make_shared<getaddresstx>());
    func(make_shared<getaccounttx>());
    func(make_shared<deposit>());
    func(make_shared<send>());
    func(make_shared<sendmore>());
    func(make_shared<sendfrom>());
    func(make_shared<listassets>());
    func(make_shared<getasset>());
    func(make_shared<getaddressasset>());
    func(make_shared<getaccountasset>());
    func(make_shared<createasset>());
    func(make_shared<deleteasset>());
    func(make_shared<issue>());
    func(make_shared<issuefrom>());
    func(make_shared<sendasset>());
    func(make_shared<sendassetfrom>());
    func(make_shared<getdid>());
    func(make_shared<setdid>());
    func(make_shared<sendwithdid>());
    func(make_shared<settxfee>());
    func(make_shared<getwork>());
    func(make_shared<submitwork>());
    func(make_shared<setminingaccount>());
    func(make_shared<changepasswd>());
    func(make_shared<getnewmultisig>());
    func(make_shared<listmultisig>());
    func(make_shared<deletemultisig>());
    func(make_shared<createmultisigtx>());
    func(make_shared<signmultisigtx>());
    func(make_shared<broadcasttx>());
    func(make_shared<getmemorypool>());
}

shared_ptr<command> find_extension(const string& symbol)
{
    using namespace std;
    using namespace commands;
    if (symbol == stop::symbol())
        return make_shared<stop>();
    if (symbol == start::symbol())
        return make_shared<start>();
    if (symbol == getinfo::symbol())
        return make_shared<getinfo>();
    if (symbol == getpeerinfo::symbol())
        return make_shared<getpeerinfo>();
    if (symbol == ping::symbol())
        return make_shared<ping>();
    if (symbol == addnode::symbol())
        return make_shared<addnode>();
    if (symbol == getmininginfo::symbol())
        return make_shared<getmininginfo>();
    if (symbol == fetchheaderext::symbol())
        return make_shared<fetchheaderext>();
    if (symbol == gettransaction::symbol())
        return make_shared<gettransaction>();
    if (symbol == backupwallet::symbol())
        return make_shared<backupwallet>();
    if (symbol == importwallet::symbol())
        return make_shared<importwallet>();
    if (symbol == lockwallet::symbol())
        return make_shared<lockwallet>();
    if (symbol == exportaccountasfile::symbol())
        return make_shared<exportaccountasfile>();
    if (symbol == importaccountfromfile::symbol())
        return make_shared<importaccountfromfile>();
    if (symbol == importaccount::symbol())
        return make_shared<importaccount>();
    if (symbol == getnewaccount::symbol())
        return make_shared<getnewaccount>();
    if (symbol == getaccount::symbol())
        return make_shared<getaccount>();
    if (symbol == deleteaccount::symbol())
        return make_shared<deleteaccount>();
    if (symbol == lockaccount::symbol())
        return make_shared<lockaccount>();
    if (symbol == setaccountinfo::symbol())
        return make_shared<setaccountinfo>();
    if (symbol == listaddresses::symbol())
        return make_shared<listaddresses>();
    if (symbol == getnewaddress::symbol())
        return make_shared<getnewaddress>();
    if (symbol == getaddress::symbol())
        return make_shared<getaddress>();
    if (symbol == getpublickey::symbol())
        return make_shared<getpublickey>();
    if (symbol == getblock::symbol())
        return make_shared<getblock>();
    if (symbol == signmessage::symbol())
        return make_shared<signmessage>();
    if (symbol == verifymessage::symbol())
        return make_shared<verifymessage>();
    if (symbol == createmultisig::symbol())
        return make_shared<createmultisig>();
    if (symbol == addmultisigaddress::symbol())
        return make_shared<addmultisigaddress>();
    if (symbol == validateaddress::symbol())
        return make_shared<validateaddress>();
    if (symbol == listbalances::symbol())
        return make_shared<listbalances>();
    if (symbol == getbalance::symbol())
        return make_shared<getbalance>();
    if (symbol == getbestblockhash::symbol())
        return make_shared<getbestblockhash>();
    if (symbol == getbestblockheader::symbol())
        return make_shared<getbestblockheader>();
    if (symbol == listtxs::symbol())
        return make_shared<listtxs>();
    if (symbol == xfetchbalance::symbol())
        return make_shared<xfetchbalance>();
    if (symbol == xfetchutxo::symbol())
        return make_shared<xfetchutxo>();
    if (symbol == gettx::symbol())
        return make_shared<gettx>();
    if (symbol == getaddresstx::symbol())
        return make_shared<getaddresstx>();
    if (symbol == getaccounttx::symbol())
        return make_shared<getaccounttx>();
    if (symbol == deposit::symbol())
        return make_shared<deposit>();
    if (symbol == send::symbol())
        return make_shared<send>();
    if (symbol == sendmore::symbol())
        return make_shared<sendmore>();
    if (symbol == sendfrom::symbol())
        return make_shared<sendfrom>();
    if (symbol == listassets::symbol())
        return make_shared<listassets>();
    if (symbol == getasset::symbol())
        return make_shared<getasset>();
    if (symbol == getaddressasset::symbol())
        return make_shared<getaddressasset>();
    if (symbol == getaccountasset::symbol())
        return make_shared<getaccountasset>();
    if (symbol == createasset::symbol())
        return make_shared<createasset>();
    if (symbol == deleteasset::symbol())
        return make_shared<deleteasset>();
    if (symbol == issue::symbol())
        return make_shared<issue>();
    if (symbol == issuefrom::symbol())
        return make_shared<issuefrom>();
    if (symbol == sendasset::symbol())
        return make_shared<sendasset>();
    if (symbol == sendassetfrom::symbol())
        return make_shared<sendassetfrom>();
    if (symbol == getdid::symbol())
        return make_shared<getdid>();
    if (symbol == setdid::symbol())
        return make_shared<setdid>();
    if (symbol == sendwithdid::symbol())
        return make_shared<sendwithdid>();
    if (symbol == settxfee::symbol())
        return make_shared<settxfee>();
    if (symbol == encodeattachtx::symbol())
        return make_shared<encodeattachtx>();
    if (symbol == getwork::symbol())
        return make_shared<getwork>();
    if (symbol == submitwork::symbol())
        return make_shared<submitwork>();
    if (symbol == setminingaccount::symbol())
        return make_shared<setminingaccount>();
    if (symbol == changepasswd::symbol())
        return make_shared<changepasswd>();
    if (symbol == getnewmultisig::symbol())
        return make_shared<getnewmultisig>();
    if (symbol == listmultisig::symbol())
        return make_shared<listmultisig>();
    if (symbol == deletemultisig::symbol())
        return make_shared<deletemultisig>();
    if (symbol == createmultisigtx::symbol())
        return make_shared<createmultisigtx>();
    if (symbol == signmultisigtx::symbol())
        return make_shared<signmultisigtx>();
    if (symbol == broadcasttx::symbol())
        return make_shared<broadcasttx>();
    if (symbol == issuefrom::symbol())
        return make_shared<issuefrom>();
    if (symbol == sendassetfrom::symbol())
        return make_shared<sendassetfrom>();
    if (symbol == stopall::symbol())
        return make_shared<stopall>();
    if (symbol == getmemorypool::symbol())
        return make_shared<getmemorypool>();
    return nullptr;
}

std::string formerly_extension(const string& former)
{
    return "";
}

} // namespace explorer
} // namespace libbitcoin

<|endoftext|>


<commit_before>//===-- Globals.cpp - Implement the Global object classes -----------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the GlobalValue & GlobalVariable classes for the VMCore
// library.
//
//===----------------------------------------------------------------------===//

#include "llvm/DerivedTypes.h"
#include "llvm/GlobalVariable.h"
#include "llvm/Module.h"
#include "llvm/SymbolTable.h"
#include "Support/LeakDetector.h"

using namespace llvm;

//===----------------------------------------------------------------------===//
//                            GlobalValue Class
//===----------------------------------------------------------------------===//

/// This could be named "SafeToDestroyGlobalValue". It just makes sure that
/// there are no non-constant uses of this GlobalValue. If there aren't then
/// this and the transitive closure of the constants can be deleted. See the
/// destructor for details.
namespace {
bool removeDeadConstantUsers(Constant* C) {
  while (!C->use_empty()) {
    if (Constant *User = dyn_cast<Constant>(C->use_back())) {
      if (!removeDeadConstantUsers(User))
        return false; // Constant wasn't dead
    } else {
      return false; // Non-constant usage;
    }
  }
  if (!isa<GlobalValue>(C))
    C->destroyConstant();
  return true;
}
}

/// removeDeadConstantUsers - If there are any dead constant users dangling
/// off of this global value, remove them.  This method is useful for clients
/// that want to check to see if a global is unused, but don't want to deal
/// with potentially dead constants hanging off of the globals.
///
/// This function returns true if the global value is now dead.  If all
/// users of this global are not dead, this method may return false and
/// leave some of them around.
bool GlobalValue::removeDeadConstantUsers() {
  while(!use_empty()) {
    if (Constant* User = dyn_cast<Constant>(use_back())) {
      if (!::removeDeadConstantUsers(User))
        return false; // Constant wasn't dead
    } else {
      return false; // Non-constant usage;
    }
  }
  return true;
}

/// This virtual destructor is responsible for deleting any transitively dead
/// Constants that are using the GlobalValue.
GlobalValue::~GlobalValue() {
  // Its an error to attempt destruction with non-constant uses remaining.
  bool okay_to_destruct = removeDeadConstantUsers();
  assert(okay_to_destruct &&
         "Can't destroy GlobalValue with non-constant uses.");
}

/// Override destroyConstant to make sure it doesn't get called on
/// GlobalValue's because they shouldn't be treated like other constants.
void GlobalValue::destroyConstant() {
  assert(0 && "You can't GV->destroyConstant()!");
  abort();
}
//===----------------------------------------------------------------------===//
// GlobalVariable Implementation
//===----------------------------------------------------------------------===//

GlobalVariable::GlobalVariable(const Type *Ty, bool constant, LinkageTypes Link,
                               Constant *Initializer,
                               const std::string &Name, Module *ParentModule)
  : GlobalValue(PointerType::get(Ty), Value::GlobalVariableVal, Link, Name),
    isConstantGlobal(constant) {
  if (Initializer) Operands.push_back(Use((Value*)Initializer, this));

  LeakDetector::addGarbageObject(this);

  if (ParentModule)
    ParentModule->getGlobalList().push_back(this);
}

void GlobalVariable::setParent(Module *parent) {
  if (getParent())
    LeakDetector::addGarbageObject(this);
  Parent = parent;
  if (getParent())
    LeakDetector::removeGarbageObject(this);
}

// Specialize setName to take care of symbol table majik
void GlobalVariable::setName(const std::string &name, SymbolTable *ST) {
  Module *P;
  assert((ST == 0 || (!getParent() || ST == &getParent()->getSymbolTable())) &&
         "Invalid symtab argument!");
  if ((P = getParent()) && hasName()) P->getSymbolTable().remove(this);
  Value::setName(name);
  if (P && hasName()) P->getSymbolTable().insert(this);
}

void GlobalVariable::replaceUsesOfWithOnConstant(Value *From, Value *To,
                                                 bool DisableChecking )
{
  // If you call this, then you better know this GVar has a constant
  // initializer worth replacing. Enforce that here.
  assert(getNumOperands() == 1 &&
         "Attempt to replace uses of Constants on a GVar with no initializer");

  // And, since you know it has an initializer, the From value better be
  // the initializer :)
  assert(getOperand(0) == From &&
         "Attempt to replace wrong constant initializer in GVar");

  // And, you better have a constant for the replacement value
  assert(isa<Constant>(To) &&
         "Attempt to replace GVar initializer with non-constant");

  // Okay, preconditions out of the way, replace the constant initializer.
  this->setOperand(0,To);
}

// vim: sw=2 ai

<commit_msg>Fix infinite loop gccld'ing povray<commit_after>//===-- Globals.cpp - Implement the Global object classes -----------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the GlobalValue & GlobalVariable classes for the VMCore
// library.
//
//===----------------------------------------------------------------------===//

#include "llvm/DerivedTypes.h"
#include "llvm/GlobalVariable.h"
#include "llvm/Module.h"
#include "llvm/SymbolTable.h"
#include "Support/LeakDetector.h"
using namespace llvm;

//===----------------------------------------------------------------------===//
//                            GlobalValue Class
//===----------------------------------------------------------------------===//

/// This could be named "SafeToDestroyGlobalValue". It just makes sure that
/// there are no non-constant uses of this GlobalValue. If there aren't then
/// this and the transitive closure of the constants can be deleted. See the
/// destructor for details.
static bool removeDeadConstantUsers(Constant* C) {
  if (isa<GlobalValue>(C)) return false; // Cannot remove this

  while (!C->use_empty())
    if (Constant *User = dyn_cast<Constant>(C->use_back())) {
      if (!removeDeadConstantUsers(User))
        return false; // Constant wasn't dead
    } else {
      return false; // Non-constant usage;
    }

  C->destroyConstant();
  return true;
}

/// removeDeadConstantUsers - If there are any dead constant users dangling
/// off of this global value, remove them.  This method is useful for clients
/// that want to check to see if a global is unused, but don't want to deal
/// with potentially dead constants hanging off of the globals.
///
/// This function returns true if the global value is now dead.  If all
/// users of this global are not dead, this method may return false and
/// leave some of them around.
bool GlobalValue::removeDeadConstantUsers() {
  while(!use_empty()) {
    if (Constant* User = dyn_cast<Constant>(use_back())) {
      if (!::removeDeadConstantUsers(User))
        return false; // Constant wasn't dead
    } else {
      return false; // Non-constant usage;
    }
  }
  return true;
}

/// This virtual destructor is responsible for deleting any transitively dead
/// Constants that are using the GlobalValue.
GlobalValue::~GlobalValue() {
  // Its an error to attempt destruction with non-constant uses remaining.
  bool okay_to_destruct = removeDeadConstantUsers();
  assert(okay_to_destruct &&
         "Can't destroy GlobalValue with non-constant uses.");
}

/// Override destroyConstant to make sure it doesn't get called on
/// GlobalValue's because they shouldn't be treated like other constants.
void GlobalValue::destroyConstant() {
  assert(0 && "You can't GV->destroyConstant()!");
  abort();
}
//===----------------------------------------------------------------------===//
// GlobalVariable Implementation
//===----------------------------------------------------------------------===//

GlobalVariable::GlobalVariable(const Type *Ty, bool constant, LinkageTypes Link,
                               Constant *Initializer,
                               const std::string &Name, Module *ParentModule)
  : GlobalValue(PointerType::get(Ty), Value::GlobalVariableVal, Link, Name),
    isConstantGlobal(constant) {
  if (Initializer) Operands.push_back(Use((Value*)Initializer, this));

  LeakDetector::addGarbageObject(this);

  if (ParentModule)
    ParentModule->getGlobalList().push_back(this);
}

void GlobalVariable::setParent(Module *parent) {
  if (getParent())
    LeakDetector::addGarbageObject(this);
  Parent = parent;
  if (getParent())
    LeakDetector::removeGarbageObject(this);
}

// Specialize setName to take care of symbol table majik
void GlobalVariable::setName(const std::string &name, SymbolTable *ST) {
  Module *P;
  assert((ST == 0 || (!getParent() || ST == &getParent()->getSymbolTable())) &&
         "Invalid symtab argument!");
  if ((P = getParent()) && hasName()) P->getSymbolTable().remove(this);
  Value::setName(name);
  if (P && hasName()) P->getSymbolTable().insert(this);
}

void GlobalVariable::replaceUsesOfWithOnConstant(Value *From, Value *To,
                                                 bool DisableChecking )
{
  // If you call this, then you better know this GVar has a constant
  // initializer worth replacing. Enforce that here.
  assert(getNumOperands() == 1 &&
         "Attempt to replace uses of Constants on a GVar with no initializer");

  // And, since you know it has an initializer, the From value better be
  // the initializer :)
  assert(getOperand(0) == From &&
         "Attempt to replace wrong constant initializer in GVar");

  // And, you better have a constant for the replacement value
  assert(isa<Constant>(To) &&
         "Attempt to replace GVar initializer with non-constant");

  // Okay, preconditions out of the way, replace the constant initializer.
  this->setOperand(0,To);
}

// vim: sw=2 ai

<|endoftext|>


<commit_before># include <iostream>

int main() {

    std::cout << "HelloWorld!" << std::endl;

}<commit_msg>Updating HelloWorld.cpp, changed cout message<commit_after># include <iostream>

int main() {

    std::cout << "Fight On!" << std::endl;

}
<|endoftext|>


<commit_before>#include <StdAfx.h>
#include <IO/Registry.h>

namespace registry
{
	// Registry settings
	// Creating a new reg key:
	// 1 - Define an accessor object using boolRegKey, wstringRegKey or dwordRegKey
	// 2 - Add pointer to the object to RegKeys vector
	// 3 - Add an extern for the object to registry.h
	// 4 - If the setting should show in options, ensure it has a unique options prompt value
	// Note: Accessor objects can be used in code as their underlying type, though some care may be needed with casting
#ifdef _DEBUG
	dwordRegKey debugTag{L"DebugTag", regoptStringHex, DBGAll, false, IDS_REGKEY_DEBUG_TAG};
#else
	dwordRegKey debugTag{L"DebugTag", regoptStringHex, DBGNoDebug, false, IDS_REGKEY_DEBUG_TAG};
#endif
	boolRegKey debugToFile{L"DebugToFile", false, false, IDS_REGKEY_DEBUG_TO_FILE};
	wstringRegKey debugFileName{L"DebugFileName", L"c:\\mfcmapi.log", false, IDS_REGKEY_DEBUG_FILE_NAME};
	boolRegKey getPropNamesOnAllProps{L"GetPropNamesOnAllProps", false, true, IDS_REGKEY_GETPROPNAMES_ON_ALL_PROPS};
	boolRegKey parseNamedProps{L"ParseNamedProps", false, true, IDS_REGKEY_PARSED_NAMED_PROPS};
	dwordRegKey throttleLevel{L"ThrottleLevel", regoptStringDec, 0, false, IDS_REGKEY_THROTTLE_LEVEL};
	boolRegKey hierExpandNotifications{L"HierExpandNotifications", true, false, IDS_REGKEY_HIER_EXPAND_NOTIFS};
	boolRegKey hierRootNotifs{L"HierRootNotifs", false, false, IDS_REGKEY_HIER_ROOT_NOTIFS};
	boolRegKey doSmartView{L"DoSmartView", true, true, IDS_REGKEY_DO_SMART_VIEW};
	boolRegKey onlyAdditionalProperties{L"OnlyAdditionalProperties", false, true, IDS_REGKEY_ONLYADDITIONALPROPERTIES};
	boolRegKey useRowDataForSinglePropList{L"UseRowDataForSinglePropList",
										   false,
										   true,
										   IDS_REGKEY_USE_ROW_DATA_FOR_SINGLEPROPLIST};
	boolRegKey useGetPropList{L"UseGetPropList", true, true, IDS_REGKEY_USE_GETPROPLIST};
	boolRegKey preferUnicodeProps{L"PreferUnicodeProps", true, true, IDS_REGKEY_PREFER_UNICODE_PROPS};
	boolRegKey cacheNamedProps{L"CacheNamedProps", true, false, IDS_REGKEY_CACHE_NAMED_PROPS};
	boolRegKey allowDupeColumns{L"AllowDupeColumns", false, false, IDS_REGKEY_ALLOW_DUPE_COLUMNS};
	boolRegKey doColumnNames{L"DoColumnNames", true, false, IDS_REGKEY_DO_COLUMN_NAMES};
	boolRegKey editColumnsOnLoad{L"EditColumnsOnLoad", false, false, IDS_REGKEY_EDIT_COLUMNS_ON_LOAD};
	boolRegKey forceMDBOnline{L"ForceMDBOnline", false, false, IDS_REGKEY_MDB_ONLINE};
	boolRegKey forceMapiNoCache{L"ForceMapiNoCache", false, false, IDS_REGKEY_MAPI_NO_CACHE};
	boolRegKey allowPersistCache{L"AllowPersistCache", false, false, IDS_REGKEY_ALLOW_PERSIST_CACHE};
	boolRegKey useIMAPIProgress{L"UseIMAPIProgress", false, false, IDS_REGKEY_USE_IMAPIPROGRESS};
	boolRegKey useMessageRaw{L"UseMessageRaw", false, false, IDS_REGKEY_USE_MESSAGERAW};
	boolRegKey suppressNotFound{L"SuppressNotFound", true, false, IDS_REGKEY_SUPPRESS_NOTFOUND};
	boolRegKey heapEnableTerminationOnCorruption{L"HeapEnableTerminationOnCorruption",
												 true,
												 false,
												 IDS_REGKEY_HEAPENABLETERMINATIONONCORRUPTION};
	boolRegKey loadAddIns{L"LoadAddIns", true, false, IDS_REGKEY_LOADADDINS};
	boolRegKey forceOutlookMAPI{L"ForceOutlookMAPI", false, false, IDS_REGKEY_FORCEOUTLOOKMAPI};
	boolRegKey forceSystemMAPI{L"ForceSystemMAPI", false, false, IDS_REGKEY_FORCESYSTEMMAPI};
	boolRegKey hexDialogDiag{L"HexDialogDiag", false, false, IDS_REGKEY_HEXDIALOGDIAG};
	boolRegKey displayAboutDialog{L"DisplayAboutDialog", true, false, NULL};
	wstringRegKey propertyColumnOrder{L"PropertyColumnOrder", L"", false, NULL};

	std::vector<__RegKey*> RegKeys = {
		&debugTag,
		&debugToFile,
		&debugFileName,
		&getPropNamesOnAllProps,
		&parseNamedProps,
		&throttleLevel,
		&hierExpandNotifications,
		&hierRootNotifs,
		&doSmartView,
		&onlyAdditionalProperties,
		&useRowDataForSinglePropList,
		&useGetPropList,
		&preferUnicodeProps,
		&cacheNamedProps,
		&allowDupeColumns,
		&doColumnNames,
		&editColumnsOnLoad,
		&forceMDBOnline,
		&forceMapiNoCache,
		&allowPersistCache,
		&useIMAPIProgress,
		&useMessageRaw,
		&suppressNotFound,
		&heapEnableTerminationOnCorruption,
		&loadAddIns,
		&forceOutlookMAPI,
		&forceSystemMAPI,
		&hexDialogDiag,
		&displayAboutDialog,
		&propertyColumnOrder,
	};

	// $--HrGetRegistryValue---------------------------------------------------------
	// Get a registry value - allocating memory using new to hold it.
	// -----------------------------------------------------------------------------
	_Check_return_ HRESULT HrGetRegistryValue(
		_In_ HKEY hKey, // the key.
		_In_ const std::wstring& lpszValue, // value name in key.
		_Out_ DWORD* lpType, // where to put type info.
		_Out_ LPVOID* lppData) // where to put the data.
	{
		output::DebugPrint(DBGGeneric, L"HrGetRegistryValue(%ws)\n", lpszValue.c_str());

		*lppData = nullptr;
		DWORD cb = NULL;

		// Get its size
		auto hRes = WC_W32(RegQueryValueExW(hKey, lpszValue.c_str(), nullptr, lpType, nullptr, &cb));

		// only handle types we know about - all others are bad
		if (hRes == S_OK && cb && (REG_SZ == *lpType || REG_DWORD == *lpType || REG_MULTI_SZ == *lpType))
		{
			*lppData = new BYTE[cb];

			if (*lppData)
			{
				// Get the current value
				hRes = EC_W32(RegQueryValueExW(
					hKey, lpszValue.c_str(), nullptr, lpType, static_cast<unsigned char*>(*lppData), &cb));

				if (FAILED(hRes))
				{
					delete[] * lppData;
					*lppData = nullptr;
				}
			}
		}
		else
			hRes = MAPI_E_INVALID_PARAMETER;

		return hRes;
	}

	// If the value is not set in the registry, return the default value
	DWORD ReadDWORDFromRegistry(_In_ HKEY hKey, _In_ const std::wstring& szValue, _In_ const DWORD dwDefaultVal)
	{
		if (szValue.empty()) return dwDefaultVal;
		DWORD dwKeyType = NULL;
		DWORD* lpValue = nullptr;
		auto ret = dwDefaultVal;

		const auto hRes = WC_H(HrGetRegistryValue(hKey, szValue, &dwKeyType, reinterpret_cast<LPVOID*>(&lpValue)));
		if (hRes == S_OK && REG_DWORD == dwKeyType && lpValue)
		{
			ret = *lpValue;
		}

		delete[] lpValue;
		return ret;
	}

	// If the value is not set in the registry, return the default value
	std::wstring
	ReadStringFromRegistry(_In_ HKEY hKey, _In_ const std::wstring& szValue, _In_ const std::wstring& szDefault)
	{
		if (szValue.empty()) return szDefault;
		output::DebugPrint(DBGGeneric, L"ReadStringFromRegistry(%ws)\n", szValue.c_str());

		DWORD dwKeyType = NULL;
		LPBYTE szBuf = nullptr;
		DWORD cb = NULL;

		// Get its size
		auto hRes = WC_W32(RegQueryValueExW(hKey, szValue.c_str(), nullptr, &dwKeyType, nullptr, &cb));

		if (hRes == S_OK && cb && !(cb % 2) && REG_SZ == dwKeyType)
		{
			szBuf = new (std::nothrow) BYTE[cb];
			if (szBuf)
			{
				// Get the current value
				hRes = EC_W32(RegQueryValueExW(hKey, szValue.c_str(), nullptr, &dwKeyType, szBuf, &cb));

				if (FAILED(hRes))
				{
					delete[] szBuf;
					szBuf = nullptr;
				}
			}
		}

		auto ret = szDefault;
		if (hRes == S_OK && cb && !(cb % 2) && REG_SZ == dwKeyType && szBuf)
		{
			ret = std::wstring(LPWSTR(szBuf), cb / sizeof WCHAR);
		}

		delete[] szBuf;
		return ret;
	}

	void ReadFromRegistry()
	{
		HKEY hRootKey = nullptr;
		WC_W32_S(RegOpenKeyExW(HKEY_CURRENT_USER, RKEY_ROOT, NULL, KEY_READ, &hRootKey));

		// Now that we have a root key, go get our values
		if (hRootKey)
		{
			for (auto& regKey : RegKeys)
			{
				if (!regKey) continue;

				if (regKey->ulRegKeyType == regDWORD)
				{
					regKey->ulCurDWORD = ReadDWORDFromRegistry(hRootKey, regKey->szKeyName, regKey->ulCurDWORD);
				}
				else if (regKey->ulRegKeyType == regSTRING)
				{
					regKey->szCurSTRING = ReadStringFromRegistry(hRootKey, regKey->szKeyName, regKey->szCurSTRING);
				}
			}

			EC_W32_S(RegCloseKey(hRootKey));
		}

		output::SetDebugLevel(debugTag);
		output::DebugPrintVersion(DBGVersionBanner);
	}

	void WriteDWORDToRegistry(_In_ HKEY hKey, _In_ const std::wstring& szValueName, DWORD dwValue)
	{
		WC_W32_S(RegSetValueExW(
			hKey, szValueName.c_str(), NULL, REG_DWORD, reinterpret_cast<LPBYTE>(&dwValue), sizeof(DWORD)));
	}

	void CommitDWORDIfNeeded(
		_In_ HKEY hKey,
		_In_ const std::wstring& szValueName,
		const DWORD dwValue,
		const DWORD dwDefaultValue)
	{
		if (dwValue != dwDefaultValue)
		{
			WriteDWORDToRegistry(hKey, szValueName, dwValue);
		}
		else
		{
			WC_W32_S(RegDeleteValueW(hKey, szValueName.c_str()));
		}
	}

	void WriteStringToRegistry(_In_ HKEY hKey, _In_ const std::wstring& szValueName, _In_ const std::wstring& szValue)
	{
		// Reg needs bytes, so CB is correct here
		auto cbValue = szValue.length() * sizeof(WCHAR);
		cbValue += sizeof(WCHAR); // NULL terminator

		WC_W32_S(RegSetValueExW(
			hKey, szValueName.c_str(), NULL, REG_SZ, LPBYTE(szValue.c_str()), static_cast<DWORD>(cbValue)));
	}

	void CommitStringIfNeeded(
		_In_ HKEY hKey,
		_In_ const std::wstring& szValueName,
		_In_ const std::wstring& szValue,
		_In_ const std::wstring& szDefaultValue)
	{
		if (strings::wstringToLower(szValue) != strings::wstringToLower(szDefaultValue))
		{
			WriteStringToRegistry(hKey, szValueName, szValue);
		}
		else
		{
			WC_W32_S(RegDeleteValueW(hKey, szValueName.c_str()));
		}
	}

	_Check_return_ HKEY CreateRootKey()
	{
		HKEY hkSub = nullptr;

		// Try to open the root key before we do the work to create it
		const auto hRes = WC_W32(RegOpenKeyExW(HKEY_CURRENT_USER, RKEY_ROOT, NULL, KEY_READ | KEY_WRITE, &hkSub));
		if (SUCCEEDED(hRes) && hkSub) return hkSub;

		WC_W32_S(RegCreateKeyExW(
			HKEY_CURRENT_USER, RKEY_ROOT, 0, nullptr, 0, KEY_READ | KEY_WRITE, nullptr, &hkSub, nullptr));

		return hkSub;
	}

	void WriteToRegistry()
	{
		const auto hRootKey = CreateRootKey();

		// Now that we have a root key, go set our values
		for (auto& regKey : RegKeys)
		{
			if (!regKey) continue;

			if (regKey->ulRegKeyType == regDWORD)
			{
				CommitDWORDIfNeeded(hRootKey, regKey->szKeyName, regKey->ulCurDWORD, regKey->ulDefDWORD);
			}
			else if (regKey->ulRegKeyType == regSTRING)
			{
				CommitStringIfNeeded(hRootKey, regKey->szKeyName, regKey->szCurSTRING, regKey->szDefSTRING);
			}
		}

		if (hRootKey) EC_W32_S(RegCloseKey(hRootKey));
	}
} // namespace registry<commit_msg>clean up comment<commit_after>#include <StdAfx.h>
#include <IO/Registry.h>

namespace registry
{
	// Registry settings
	// Creating a new reg key:
	// 1 - Define an accessor object using boolRegKey, wstringRegKey or dwordRegKey
	// 2 - Add pointer to the object to RegKeys vector
	// 3 - Add an extern for the object to registry.h
	// 4 - If the setting should show in options, ensure it has a unique options prompt value
	// Note: Accessor objects can be used in code as their underlying type, though some care may be needed with casting
#ifdef _DEBUG
	dwordRegKey debugTag{L"DebugTag", regoptStringHex, DBGAll, false, IDS_REGKEY_DEBUG_TAG};
#else
	dwordRegKey debugTag{L"DebugTag", regoptStringHex, DBGNoDebug, false, IDS_REGKEY_DEBUG_TAG};
#endif
	boolRegKey debugToFile{L"DebugToFile", false, false, IDS_REGKEY_DEBUG_TO_FILE};
	wstringRegKey debugFileName{L"DebugFileName", L"c:\\mfcmapi.log", false, IDS_REGKEY_DEBUG_FILE_NAME};
	boolRegKey getPropNamesOnAllProps{L"GetPropNamesOnAllProps", false, true, IDS_REGKEY_GETPROPNAMES_ON_ALL_PROPS};
	boolRegKey parseNamedProps{L"ParseNamedProps", false, true, IDS_REGKEY_PARSED_NAMED_PROPS};
	dwordRegKey throttleLevel{L"ThrottleLevel", regoptStringDec, 0, false, IDS_REGKEY_THROTTLE_LEVEL};
	boolRegKey hierExpandNotifications{L"HierExpandNotifications", true, false, IDS_REGKEY_HIER_EXPAND_NOTIFS};
	boolRegKey hierRootNotifs{L"HierRootNotifs", false, false, IDS_REGKEY_HIER_ROOT_NOTIFS};
	boolRegKey doSmartView{L"DoSmartView", true, true, IDS_REGKEY_DO_SMART_VIEW};
	boolRegKey onlyAdditionalProperties{L"OnlyAdditionalProperties", false, true, IDS_REGKEY_ONLYADDITIONALPROPERTIES};
	boolRegKey useRowDataForSinglePropList{L"UseRowDataForSinglePropList",
										   false,
										   true,
										   IDS_REGKEY_USE_ROW_DATA_FOR_SINGLEPROPLIST};
	boolRegKey useGetPropList{L"UseGetPropList", true, true, IDS_REGKEY_USE_GETPROPLIST};
	boolRegKey preferUnicodeProps{L"PreferUnicodeProps", true, true, IDS_REGKEY_PREFER_UNICODE_PROPS};
	boolRegKey cacheNamedProps{L"CacheNamedProps", true, false, IDS_REGKEY_CACHE_NAMED_PROPS};
	boolRegKey allowDupeColumns{L"AllowDupeColumns", false, false, IDS_REGKEY_ALLOW_DUPE_COLUMNS};
	boolRegKey doColumnNames{L"DoColumnNames", true, false, IDS_REGKEY_DO_COLUMN_NAMES};
	boolRegKey editColumnsOnLoad{L"EditColumnsOnLoad", false, false, IDS_REGKEY_EDIT_COLUMNS_ON_LOAD};
	boolRegKey forceMDBOnline{L"ForceMDBOnline", false, false, IDS_REGKEY_MDB_ONLINE};
	boolRegKey forceMapiNoCache{L"ForceMapiNoCache", false, false, IDS_REGKEY_MAPI_NO_CACHE};
	boolRegKey allowPersistCache{L"AllowPersistCache", false, false, IDS_REGKEY_ALLOW_PERSIST_CACHE};
	boolRegKey useIMAPIProgress{L"UseIMAPIProgress", false, false, IDS_REGKEY_USE_IMAPIPROGRESS};
	boolRegKey useMessageRaw{L"UseMessageRaw", false, false, IDS_REGKEY_USE_MESSAGERAW};
	boolRegKey suppressNotFound{L"SuppressNotFound", true, false, IDS_REGKEY_SUPPRESS_NOTFOUND};
	boolRegKey heapEnableTerminationOnCorruption{L"HeapEnableTerminationOnCorruption",
												 true,
												 false,
												 IDS_REGKEY_HEAPENABLETERMINATIONONCORRUPTION};
	boolRegKey loadAddIns{L"LoadAddIns", true, false, IDS_REGKEY_LOADADDINS};
	boolRegKey forceOutlookMAPI{L"ForceOutlookMAPI", false, false, IDS_REGKEY_FORCEOUTLOOKMAPI};
	boolRegKey forceSystemMAPI{L"ForceSystemMAPI", false, false, IDS_REGKEY_FORCESYSTEMMAPI};
	boolRegKey hexDialogDiag{L"HexDialogDiag", false, false, IDS_REGKEY_HEXDIALOGDIAG};
	boolRegKey displayAboutDialog{L"DisplayAboutDialog", true, false, NULL};
	wstringRegKey propertyColumnOrder{L"PropertyColumnOrder", L"", false, NULL};

	std::vector<__RegKey*> RegKeys = {
		&debugTag,
		&debugToFile,
		&debugFileName,
		&getPropNamesOnAllProps,
		&parseNamedProps,
		&throttleLevel,
		&hierExpandNotifications,
		&hierRootNotifs,
		&doSmartView,
		&onlyAdditionalProperties,
		&useRowDataForSinglePropList,
		&useGetPropList,
		&preferUnicodeProps,
		&cacheNamedProps,
		&allowDupeColumns,
		&doColumnNames,
		&editColumnsOnLoad,
		&forceMDBOnline,
		&forceMapiNoCache,
		&allowPersistCache,
		&useIMAPIProgress,
		&useMessageRaw,
		&suppressNotFound,
		&heapEnableTerminationOnCorruption,
		&loadAddIns,
		&forceOutlookMAPI,
		&forceSystemMAPI,
		&hexDialogDiag,
		&displayAboutDialog,
		&propertyColumnOrder,
	};

	// Get a registry value - allocating memory using new to hold it.
	_Check_return_ HRESULT HrGetRegistryValue(
		_In_ HKEY hKey, // the key.
		_In_ const std::wstring& lpszValue, // value name in key.
		_Out_ DWORD* lpType, // where to put type info.
		_Out_ LPVOID* lppData) // where to put the data.
	{
		output::DebugPrint(DBGGeneric, L"HrGetRegistryValue(%ws)\n", lpszValue.c_str());

		*lppData = nullptr;
		DWORD cb = NULL;

		// Get its size
		auto hRes = WC_W32(RegQueryValueExW(hKey, lpszValue.c_str(), nullptr, lpType, nullptr, &cb));

		// only handle types we know about - all others are bad
		if (hRes == S_OK && cb && (REG_SZ == *lpType || REG_DWORD == *lpType || REG_MULTI_SZ == *lpType))
		{
			*lppData = new BYTE[cb];

			if (*lppData)
			{
				// Get the current value
				hRes = EC_W32(RegQueryValueExW(
					hKey, lpszValue.c_str(), nullptr, lpType, static_cast<unsigned char*>(*lppData), &cb));

				if (FAILED(hRes))
				{
					delete[] * lppData;
					*lppData = nullptr;
				}
			}
		}
		else
			hRes = MAPI_E_INVALID_PARAMETER;

		return hRes;
	}

	// If the value is not set in the registry, return the default value
	DWORD ReadDWORDFromRegistry(_In_ HKEY hKey, _In_ const std::wstring& szValue, _In_ const DWORD dwDefaultVal)
	{
		if (szValue.empty()) return dwDefaultVal;
		DWORD dwKeyType = NULL;
		DWORD* lpValue = nullptr;
		auto ret = dwDefaultVal;

		const auto hRes = WC_H(HrGetRegistryValue(hKey, szValue, &dwKeyType, reinterpret_cast<LPVOID*>(&lpValue)));
		if (hRes == S_OK && REG_DWORD == dwKeyType && lpValue)
		{
			ret = *lpValue;
		}

		delete[] lpValue;
		return ret;
	}

	// If the value is not set in the registry, return the default value
	std::wstring
	ReadStringFromRegistry(_In_ HKEY hKey, _In_ const std::wstring& szValue, _In_ const std::wstring& szDefault)
	{
		if (szValue.empty()) return szDefault;
		output::DebugPrint(DBGGeneric, L"ReadStringFromRegistry(%ws)\n", szValue.c_str());

		DWORD dwKeyType = NULL;
		LPBYTE szBuf = nullptr;
		DWORD cb = NULL;

		// Get its size
		auto hRes = WC_W32(RegQueryValueExW(hKey, szValue.c_str(), nullptr, &dwKeyType, nullptr, &cb));

		if (hRes == S_OK && cb && !(cb % 2) && REG_SZ == dwKeyType)
		{
			szBuf = new (std::nothrow) BYTE[cb];
			if (szBuf)
			{
				// Get the current value
				hRes = EC_W32(RegQueryValueExW(hKey, szValue.c_str(), nullptr, &dwKeyType, szBuf, &cb));

				if (FAILED(hRes))
				{
					delete[] szBuf;
					szBuf = nullptr;
				}
			}
		}

		auto ret = szDefault;
		if (hRes == S_OK && cb && !(cb % 2) && REG_SZ == dwKeyType && szBuf)
		{
			ret = std::wstring(LPWSTR(szBuf), cb / sizeof WCHAR);
		}

		delete[] szBuf;
		return ret;
	}

	void ReadFromRegistry()
	{
		HKEY hRootKey = nullptr;
		WC_W32_S(RegOpenKeyExW(HKEY_CURRENT_USER, RKEY_ROOT, NULL, KEY_READ, &hRootKey));

		// Now that we have a root key, go get our values
		if (hRootKey)
		{
			for (auto& regKey : RegKeys)
			{
				if (!regKey) continue;

				if (regKey->ulRegKeyType == regDWORD)
				{
					regKey->ulCurDWORD = ReadDWORDFromRegistry(hRootKey, regKey->szKeyName, regKey->ulCurDWORD);
				}
				else if (regKey->ulRegKeyType == regSTRING)
				{
					regKey->szCurSTRING = ReadStringFromRegistry(hRootKey, regKey->szKeyName, regKey->szCurSTRING);
				}
			}

			EC_W32_S(RegCloseKey(hRootKey));
		}

		output::SetDebugLevel(debugTag);
		output::DebugPrintVersion(DBGVersionBanner);
	}

	void WriteDWORDToRegistry(_In_ HKEY hKey, _In_ const std::wstring& szValueName, DWORD dwValue)
	{
		WC_W32_S(RegSetValueExW(
			hKey, szValueName.c_str(), NULL, REG_DWORD, reinterpret_cast<LPBYTE>(&dwValue), sizeof(DWORD)));
	}

	void CommitDWORDIfNeeded(
		_In_ HKEY hKey,
		_In_ const std::wstring& szValueName,
		const DWORD dwValue,
		const DWORD dwDefaultValue)
	{
		if (dwValue != dwDefaultValue)
		{
			WriteDWORDToRegistry(hKey, szValueName, dwValue);
		}
		else
		{
			WC_W32_S(RegDeleteValueW(hKey, szValueName.c_str()));
		}
	}

	void WriteStringToRegistry(_In_ HKEY hKey, _In_ const std::wstring& szValueName, _In_ const std::wstring& szValue)
	{
		// Reg needs bytes, so CB is correct here
		auto cbValue = szValue.length() * sizeof(WCHAR);
		cbValue += sizeof(WCHAR); // NULL terminator

		WC_W32_S(RegSetValueExW(
			hKey, szValueName.c_str(), NULL, REG_SZ, LPBYTE(szValue.c_str()), static_cast<DWORD>(cbValue)));
	}

	void CommitStringIfNeeded(
		_In_ HKEY hKey,
		_In_ const std::wstring& szValueName,
		_In_ const std::wstring& szValue,
		_In_ const std::wstring& szDefaultValue)
	{
		if (strings::wstringToLower(szValue) != strings::wstringToLower(szDefaultValue))
		{
			WriteStringToRegistry(hKey, szValueName, szValue);
		}
		else
		{
			WC_W32_S(RegDeleteValueW(hKey, szValueName.c_str()));
		}
	}

	_Check_return_ HKEY CreateRootKey()
	{
		HKEY hkSub = nullptr;

		// Try to open the root key before we do the work to create it
		const auto hRes = WC_W32(RegOpenKeyExW(HKEY_CURRENT_USER, RKEY_ROOT, NULL, KEY_READ | KEY_WRITE, &hkSub));
		if (SUCCEEDED(hRes) && hkSub) return hkSub;

		WC_W32_S(RegCreateKeyExW(
			HKEY_CURRENT_USER, RKEY_ROOT, 0, nullptr, 0, KEY_READ | KEY_WRITE, nullptr, &hkSub, nullptr));

		return hkSub;
	}

	void WriteToRegistry()
	{
		const auto hRootKey = CreateRootKey();

		// Now that we have a root key, go set our values
		for (auto& regKey : RegKeys)
		{
			if (!regKey) continue;

			if (regKey->ulRegKeyType == regDWORD)
			{
				CommitDWORDIfNeeded(hRootKey, regKey->szKeyName, regKey->ulCurDWORD, regKey->ulDefDWORD);
			}
			else if (regKey->ulRegKeyType == regSTRING)
			{
				CommitStringIfNeeded(hRootKey, regKey->szKeyName, regKey->szCurSTRING, regKey->szDefSTRING);
			}
		}

		if (hRootKey) EC_W32_S(RegCloseKey(hRootKey));
	}
} // namespace registry<|endoftext|>


<commit_before>#ifndef SILICIUM_POSIX_PIPE_HPP
#define SILICIUM_POSIX_PIPE_HPP

#include <silicium/get_last_error.hpp>
#include <silicium/file_handle.hpp>
#include <silicium/error_or.hpp>
#ifdef _WIN32
#include <silicium/win32/win32.hpp>
#else
#include <fcntl.h>
#endif

namespace Si
{
	namespace detail
	{
#ifndef _WIN32
		inline boost::system::error_code
		set_close_on_exec(native_file_descriptor file) BOOST_NOEXCEPT
		{
			if (fcntl(file, F_SETFD, fcntl(file, F_GETFD) | FD_CLOEXEC) < 0)
			{
				return get_last_error();
			}
			return {};
		}
#endif
	}

	struct pipe
	{
		file_handle write, read;

		pipe() BOOST_NOEXCEPT
		{
		}

		void close() BOOST_NOEXCEPT
		{
			pipe().swap(*this);
		}

		void swap(pipe &other) BOOST_NOEXCEPT
		{
			write.swap(other.write);
			read.swap(other.read);
		}

#if !SILICIUM_COMPILER_GENERATES_MOVES
		pipe(pipe &&other) BOOST_NOEXCEPT : write(std::move(other.write)),
		                                    read(std::move(other.read))
		{
		}

		pipe &operator=(pipe &&other) BOOST_NOEXCEPT
		{
			write = std::move(other.write);
			read = std::move(other.read);
			return *this;
		}

		SILICIUM_DELETED_FUNCTION(pipe(pipe const &))
		SILICIUM_DELETED_FUNCTION(pipe &operator=(pipe const &))
#endif
	};

	inline error_or<pipe> make_pipe() BOOST_NOEXCEPT
	{
#ifdef _WIN32
		SECURITY_ATTRIBUTES security = {};
		security.nLength = sizeof(security);
		security.bInheritHandle = TRUE;
		HANDLE read, write;
		if (!CreatePipe(&read, &write, &security, 0))
		{
			return get_last_error();
		}
		pipe result;
		result.read = file_handle(read);
		result.write = file_handle(write);
		return std::move(result);
#else
		std::array<int, 2> fds;
		if (::pipe(fds.data()) < 0)
		{
			return get_last_error();
		}
		pipe result;
		result.read = file_handle(fds[0]);
		result.write = file_handle(fds[1]);
		return std::move(result);
#endif
	}
}

#endif
<commit_msg>Win32: make_pipe creates a non-inheritable pipe<commit_after>#ifndef SILICIUM_POSIX_PIPE_HPP
#define SILICIUM_POSIX_PIPE_HPP

#include <silicium/get_last_error.hpp>
#include <silicium/file_handle.hpp>
#include <silicium/error_or.hpp>
#ifdef _WIN32
#include <silicium/win32/win32.hpp>
#else
#include <fcntl.h>
#endif

namespace Si
{
	namespace detail
	{
#ifndef _WIN32
		inline boost::system::error_code
		set_close_on_exec(native_file_descriptor file) BOOST_NOEXCEPT
		{
			if (fcntl(file, F_SETFD, fcntl(file, F_GETFD) | FD_CLOEXEC) < 0)
			{
				return get_last_error();
			}
			return {};
		}
#endif
	}

	struct pipe
	{
		file_handle write, read;

		pipe() BOOST_NOEXCEPT
		{
		}

		void close() BOOST_NOEXCEPT
		{
			pipe().swap(*this);
		}

		void swap(pipe &other) BOOST_NOEXCEPT
		{
			write.swap(other.write);
			read.swap(other.read);
		}

#if !SILICIUM_COMPILER_GENERATES_MOVES
		pipe(pipe &&other) BOOST_NOEXCEPT : write(std::move(other.write)),
		                                    read(std::move(other.read))
		{
		}

		pipe &operator=(pipe &&other) BOOST_NOEXCEPT
		{
			write = std::move(other.write);
			read = std::move(other.read);
			return *this;
		}

		SILICIUM_DELETED_FUNCTION(pipe(pipe const &))
		SILICIUM_DELETED_FUNCTION(pipe &operator=(pipe const &))
#endif
	};

	inline error_or<pipe> make_pipe() BOOST_NOEXCEPT
	{
#ifdef _WIN32
		SECURITY_ATTRIBUTES security = {};
		security.nLength = sizeof(security);
		//usually you do not want to inherit random handles from the parent
		security.bInheritHandle = FALSE;
		HANDLE read, write;
		if (!CreatePipe(&read, &write, &security, 0))
		{
			return get_last_error();
		}
		pipe result;
		result.read = file_handle(read);
		result.write = file_handle(write);
		return std::move(result);
#else
		std::array<int, 2> fds;
		if (::pipe(fds.data()) < 0)
		{
			return get_last_error();
		}
		pipe result;
		result.read = file_handle(fds[0]);
		result.write = file_handle(fds[1]);
		return std::move(result);
#endif
	}
}

#endif
<|endoftext|>


<commit_before>/** File: test-iliopoulos-elimination.C
 *  Author: Zhendong Wan
 */

#include <linbox/blackbox/dense.h>
#include <linbox/field/ntl-ZZ.h>
#include <linbox/field/modular-int.h>
#include <linbox/algorithms/last-invariant-factor.h>
#include <linbox/algorithms/iliopoulos-elimination.h>
#include <linbox/algorithms/rational-solver.h>
#include <linbox/randiter/random-prime.h>
#include <time.h>
#include <linbox/util/commentator.h>
#include <linbox/vector/stream.h>
#include "test-common.h"
#include <linbox/algorithms/matrix-mod.h>
#include <linbox/field/PIR-ntl-ZZ_p.h>

using namespace LinBox;

template <class Ring, class Vector>
bool testRandom(const Ring& R,
		LinBox::VectorStream<Vector>& stream1) {

	using namespace std;

	ostringstream str;

	str << "Testing Iloipoulos elimination:";

        commentator.start (str.str ().c_str (), "testRandom", stream1.m ());

        bool ret = true;

        bool iter_passed = true;

        VectorDomain<Ring> VD (R);

	Vector d, x;

	VectorWrapper::ensureDim (d, stream1.n ());

	VectorWrapper::ensureDim (x, stream1.n ());

	int n = d. size();

	 while (stream1) {

                commentator.startIteration (stream1.j ());

		ostream &report = commentator.report (Commentator::LEVEL_IMPORTANT, INTERNAL_DESCRIPTION);

                iter_passed = true;

                stream1.next (d);

		report << "Input vector:  ";
		VD.write (report, d);
                report << endl;

		DenseMatrix<Ring> D(R, n, n), L(R, n, n), U(R, n, n), A(R,n,n);

		int i, j;

		for(i = 0; i < n; ++i) { R. assign (D[i][i], d[i]); R. init (L[i][i], 1); R. init (U[i][i], 1);}

		for (i = 0; i < n; ++ i)

			for (j = 0; j < i; ++ j) {

				R.init(L[i][j], rand() % 10);

				R.init(U[j][i], rand() % 10);
			}

		std::vector<typename Ring::Element> tmp1(n), tmp2(n), e(n);

		typename DenseMatrix<Ring>::ColIterator col_p;

		i = 0;
		for (col_p = A.colBegin(); col_p != A.colEnd(); ++ col_p, ++ i) {

			R.init(e[i],1);
			U.apply(tmp1, e);
			D.apply(tmp2, tmp1);
			L.apply(*col_p, tmp2);
			R.init(e[i],0);
		}

		typename Ring::Element s;

		R. init (s, 1);

		typename Vector::iterator d_p;

		for(d_p = d.begin(); d_p!= d.end(); ++ d_p)

			R. lcm (s, s, *d_p);

		report << "Last Invariant factor: " ;

		R. write (report, s);

		report << '\n';

		PIR_ntl_ZZ_p PIR(s);

		DenseMatrix<PIR_ntl_ZZ_p>* Ap;

		MatrixMod::mod (Ap, A, PIR);

		IliopoulosElimination::smithIn (*Ap);

		report << "Computed Smith form: \n";

		for ( unsigned int i = 0; i < A. rowdim(); ++ i)
			report << (*Ap)[i][i] << " ";

		report << '\n';

		typename std::vector<typename Ring::Element>::iterator p1, p2;
		typename Ring::Element g;

		i = 0;

		for (p1 = x. begin(); p1 != x. end(); ++ p1, ++ i) {

			if (PIR.isZero((*Ap)[i][i]))

				R.assign (*p1, s);

			else

				R.assign (*p1, NTL::rep((*Ap)[i][i]));
		}

		for (p1 = d.begin(); p1 != d.end(); ++ p1) {

			for ( p2 = p1 + 1; p2 != d.end(); ++ p2) {

				if (R. isUnit(*p1))  break;

				else if (R. isZero (*p2)) continue;

				else if (R. isZero (*p1)) {
                                                std::swap (*p1, *p2);
				}

				else {
					R. gcd (g, *p1, *p2);

					R. divin (*p2, g);

					R. mulin (*p2, *p1);

					R. assign (*p1, g);
				}
			}
		}

		report << "Expected smith form:\n";

		for (p1 = d.begin(); p1 != d.end(); ++ p1)
			report << * p1 << " ";

		report << '\n';

		if (!VD.areEqual (d, x))

			ret = iter_passed = false;

                if (!iter_passed)

                        commentator.report (Commentator::LEVEL_IMPORTANT, INTERNAL_ERROR)
				<< "ERROR: Computed Smith form is incorrect" << endl;

                commentator.stop ("done");

                commentator.progress ();

	 }

	 //stream1.reset ();

	  commentator.stop (MSG_STATUS (ret), (const char *) 0, "testRandom");

	  return ret;

}

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

        using namespace LinBox;

        bool pass = true;

        static size_t n = 20;

        static int iterations = 20;

        static Argument args[] = {
                { 'n', "-n N", "Set order of test matrices to N (default 20)",  TYPE_INT,     &n },
                { 'i', "-i I", "Perform each test for I iterations (default 10)"
,           TYPE_INT,     &iterations },
        };

        parseArguments (argc, argv, args);

        typedef NTL_ZZ      Ring;

        Ring R;

	std::cout << std::endl << "Ilioloulos Elimination test suite:\n";

        commentator.getMessageClass (INTERNAL_DESCRIPTION).setMaxDepth (5);

        RandomDenseStream<Ring> s1 (R, n, iterations);

        if (!testRandom(R, s1)) pass = false;

        return pass ? 0 : -1;

}
<commit_msg>In IliopoulosElimination, when modulus is small, using PIRModular<int>, otherwise using PIR_ntl_ZZ_p.<commit_after>/** File: test-iliopoulos-elimination.C
 *  Author: Zhendong Wan
 */

#include <linbox/blackbox/dense.h>
#include <linbox/field/ntl-ZZ.h>
#include <linbox/field/modular-int.h>
#include <linbox/algorithms/last-invariant-factor.h>
#include <linbox/algorithms/iliopoulos-elimination.h>
#include <linbox/algorithms/rational-solver.h>
#include <linbox/randiter/random-prime.h>
#include <time.h>
#include <linbox/util/commentator.h>
#include <linbox/vector/stream.h>
#include "test-common.h"
#include <linbox/algorithms/matrix-mod.h>
#include <linbox/field/PIR-ntl-ZZ_p.h>
#include <linbox/field/PIR-modular-int.h>

using namespace LinBox;

template <class Ring, class Vector>
bool testRandom(const Ring& R,
		LinBox::VectorStream<Vector>& stream1) {

	using namespace std;

	ostringstream str;

	str << "Testing Iloipoulos elimination:";

        commentator.start (str.str ().c_str (), "testRandom", stream1.m ());

        bool ret = true;

        bool iter_passed = true;

        VectorDomain<Ring> VD (R);

	Vector d, x;

	VectorWrapper::ensureDim (d, stream1.n ());

	VectorWrapper::ensureDim (x, stream1.n ());

	int n = d. size();

	 while (stream1) {

                commentator.startIteration (stream1.j ());

		ostream &report = commentator.report (Commentator::LEVEL_IMPORTANT, INTERNAL_DESCRIPTION);

                iter_passed = true;

                stream1.next (d);

		report << "Input vector:  ";
		VD.write (report, d);
                report << endl;

		DenseMatrix<Ring> D(R, n, n), L(R, n, n), U(R, n, n), A(R,n,n);

		int i, j;

		for(i = 0; i < n; ++i) { R. assign (D[i][i], d[i]); R. init (L[i][i], 1); R. init (U[i][i], 1);}

		for (i = 0; i < n; ++ i)

			for (j = 0; j < i; ++ j) {

				R.init(L[i][j], rand() % 10);

				R.init(U[j][i], rand() % 10);
			}

		std::vector<typename Ring::Element> tmp1(n), tmp2(n), e(n);

		typename DenseMatrix<Ring>::ColIterator col_p;

		i = 0;
		for (col_p = A.colBegin(); col_p != A.colEnd(); ++ col_p, ++ i) {

			R.init(e[i],1);
			U.apply(tmp1, e);
			D.apply(tmp2, tmp1);
			L.apply(*col_p, tmp2);
			R.init(e[i],0);
		}

		typename Ring::Element s;

		R. init (s, 1);

		typename Vector::iterator d_p;

		for(d_p = d.begin(); d_p!= d.end(); ++ d_p)

			R. lcm (s, s, *d_p);

		report << "Last Invariant factor: " ;

		R. write (report, s);

		report << '\n';

		if (s >= LINBOX_MAX_MODULUS) {

			report << "Using PIR_ntl_ZZ_p\n";

			PIR_ntl_ZZ_p PIR(s);

			DenseMatrix<PIR_ntl_ZZ_p>* Ap;

			MatrixMod::mod (Ap, A, PIR);

			IliopoulosElimination::smithIn (*Ap);

			report << "Computed Smith form: \n";

			for ( unsigned int i = 0; i < A. rowdim(); ++ i)
				report << (*Ap)[i][i] << " ";

			report << '\n';

			int i = 0;

			typename std::vector<typename Ring::Element>::iterator p1;

			for (p1 = x. begin(); p1 != x. end(); ++ p1, ++ i) {

				if (PIR.isZero((*Ap)[i][i]))

					R.assign (*p1, s);

				else

					R.assign (*p1, NTL::rep((*Ap)[i][i]));
			}
		}

		else {

			report << "Using PIRModular<int>\n";

			PIRModular<int> PIR(s % LINBOX_MAX_MODULUS);

			DenseMatrix<PIRModular<int> >* Ap;

			MatrixMod::mod (Ap, A, PIR);

			IliopoulosElimination::smithIn (*Ap);

			report << "Computed Smith form: \n";

			for ( unsigned int i = 0; i < A. rowdim(); ++ i)
				report << (*Ap)[i][i] << " ";

			report << '\n';

			typename std::vector<typename Ring::Element>::iterator p1;
			int i = 0;

			for (p1 = x. begin(); p1 != x. end(); ++ p1, ++ i) {

				if (PIR.isZero((*Ap)[i][i]))

					R.assign (*p1, s);

				else

					R.init (*p1, (*Ap)[i][i]);
			}
		}

		typename std::vector<typename Ring::Element>::iterator p1, p2;

		typename Ring::Element g;

		for (p1 = d.begin(); p1 != d.end(); ++ p1) {

			for ( p2 = p1 + 1; p2 != d.end(); ++ p2) {

				if (R. isUnit(*p1))  break;

				else if (R. isZero (*p2)) continue;

				else if (R. isZero (*p1)) {
                                                std::swap (*p1, *p2);
				}

				else {
					R. gcd (g, *p1, *p2);

					R. divin (*p2, g);

					R. mulin (*p2, *p1);

					R. assign (*p1, g);
				}
			}
		}

		report << "Expected smith form:\n";

		for (p1 = d.begin(); p1 != d.end(); ++ p1)
			report << * p1 << " ";

		report << '\n';

		if (!VD.areEqual (d, x))

			ret = iter_passed = false;

                if (!iter_passed)

                        commentator.report (Commentator::LEVEL_IMPORTANT, INTERNAL_ERROR)
				<< "ERROR: Computed Smith form is incorrect" << endl;

                commentator.stop ("done");

                commentator.progress ();

	 }

	 //stream1.reset ();

	  commentator.stop (MSG_STATUS (ret), (const char *) 0, "testRandom");

	  return ret;

}

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

        using namespace LinBox;

        bool pass = true;

        static size_t n = 20;

        static int iterations = 20;

        static Argument args[] = {
                { 'n', "-n N", "Set order of test matrices to N (default 20)",  TYPE_INT,     &n },
                { 'i', "-i I", "Perform each test for I iterations (default 10)"
,           TYPE_INT,     &iterations },
        };

        parseArguments (argc, argv, args);

        typedef NTL_ZZ      Ring;

        Ring R;

	std::cout << std::endl << "Ilioloulos Elimination test suite:\n";

        commentator.getMessageClass (INTERNAL_DESCRIPTION).setMaxDepth (5);

        RandomDenseStream<Ring> s1 (R, n, iterations);

        if (!testRandom(R, s1)) pass = false;

        return pass ? 0 : -1;

}
<|endoftext|>


<commit_before>#include "net.hpp"
#include "net_cpu.hpp"
#include "net_gpu.hpp"

#include <armadillo>
#include <iostream>

int main(int argc, char * argv[]) {
  arma::Mat<float> A;
  A.load("mnist.arma");
  A.shed_row(0); //remove header labels
  const int n_rows = 40000;
  const int output_cols = 10;
  const int test_num = 2000;
  arma::Mat<float> labels(n_rows, output_cols, arma::fill::zeros);
  arma::Mat<float> test_labels(test_num, output_cols, arma::fill::zeros);
  int i=0;
  int j=0;
  for (auto iter = A.begin_col(0); iter != A.end_col(0); ++iter) {
    if (i >= n_rows) {
      if (j >= test_num) {
        break;
      }
      test_labels(j, *iter) = 1;
      j += 1;
      continue;
    }
    labels(i, *iter) = 1;
    i += 1;
  }

  std::cout << labels << std::endl;
  A.shed_col(0);
  A /= 256;
  A -= .5;
  arma::Mat<float> test = A.rows(n_rows, n_rows + test_num - 1);

  A.shed_rows(n_rows, A.n_rows-1);
  std::cout << A.n_rows << "," << labels.n_rows << std::endl;
  arma::Mat<float> data = join_rows(labels, A);
  const int feature_size = 784;
  FeedForward_Network<> f(feature_size, 1000, 10);
  randomize(f);
  std::cout << "train" << std::endl;
  for (int i=0; i <80; i++) {
    std::cout << i << std::endl;
    gpu_train_batch(f, data.cols(output_cols, data.n_cols - 1).rows(0, n_rows-1), data.cols(0, output_cols-1), 0.03f, 10);
    std::cout << "start score" << std::endl;
    arma::Mat<float> result = gpu_predict(f, data.cols(output_cols, data.n_cols-1).rows(0,n_rows-1));
    std::cout << "Score: " << classify_percent_score(result, data.cols(0, output_cols-1)) << std::endl;

    result = predict(f, test);
    std::cout << "TestS: " << classify_percent_score(result, test_labels) << std::endl;
    std::cout << "Shuffling" << std::endl;
    data = shuffle(data);
  }

  return 0;
}
<commit_msg>removed old mnist sample<commit_after><|endoftext|>


<commit_before>#include <iostream>
#include "List.h"

using namespace std;
using namespace List_h;

int main() {
    Slink_list sl{ 1, 2, 3, 4, 5 };
    Slink_list tl;

    const Link *list = sl.get_head();

    print_link(tl.get_head());

    sl.push_back(nullptr);
    tl.push_back(new Link{ 120 });

    print_link(list);
    print_link(tl.get_head());

    return 0;
}<commit_msg>Change the example<commit_after>#include <iostream>
#include "List.h"

using namespace std;
using namespace List_h;

void foo() {
    Skip_list ll;

    for (auto i = -50; i < 50000; ++i) {
        ll.push_back(i);
    }

    ll.display();
}

int main() {
    Skip_list sl;

    sl.push_back(3);
    sl.push_back(6);
    sl.push_back(7);
    sl.push_back(9);
    sl.push_back(12);
    sl.push_back(17);
    sl.push_back(19);
    sl.push_back(25);
    sl.push_back(26);

    sl.insert(40, 40);
    sl.push_front(1);

    sl.delete_node(1);
    sl.delete_node(17);

    sl.display();

    int val;

    std::cout << "Please enter a number to search: ";
    std::cin >> val;

    if (sl.search(val)) {
        std::cout << val << " was found" << std::endl;
    }
    else {
        std::cout << val << " was not found" << std::endl;
    }

    return 0;
}<|endoftext|>


<commit_before>#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <stdio.h>
#include <unistd.h>

#include <string.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <errno.h>
#include "FireLog.h"
#include "FireUtils.h"
#include "version.h"
#include "FireStepSerial.h"

using namespace std;
using namespace firestep;

FireStepSerial::FireStepSerial(const char *serialPath, int32_t msResponse)
    : serialPath(serialPath), msResponse(msResponse), usb(serialPath)
{
}

FireStepSerial::~FireStepSerial() {
	close();
}

int FireStepSerial::executeCore(const std::string &request, std::string &response) {
	int rc = 0;
	usb.write(request);
	response = usb.readln(msResponse);
	if (request.compare("\n") == 0) { // simple LF should be echoed
		for (int i=0; response.size() == 0 && i<4; i++) {
			LOGDEBUG1("FireStepClient::console() wait %ldms", (long) msResponse);
			response = usb.readln(msResponse);
		}
	} else { // JSON response should end with }-SPACE-LF
		int nRead = 0;
		for (int i=0; response.find("} \n")==string::npos && (nRead != response.size() || i<4); i++) {
			nRead = response.size();
			LOGDEBUG1("FireStepClient::console() wait %ldms", (long) msResponse);
			response += usb.readln(msResponse);
		}
	}

	return rc;
}

int FireStepSerial::reset() {
    int rc = 0;
    if (isOpen()) {
		const char *msg ="FireStepSerial::reset() sending LF to interrupt FireStep";
		cerr << "RESET	: " << msg << endl;
		LOGINFO1("%s", msg);
		usb.writeln(); // interrupt any current processing
        rc = close();
    }
    if (rc == 0) {
		LOGINFO("FireStepSerial::reset() configure(hup)");
        rc = usb.configure(true);
    }
    if (rc != 0) {
		const char *msg = "could not configure serial port (hup) ";
        cerr << "ERROR	: " << msg << serialPath << endl;
		LOGERROR2("%s%s", msg, serialPath.c_str());
        return rc;
    }
    rc = open();
    if (rc == 0) {
		LOGINFO("FireStepSerial::reset() configure(nohup)");
        rc = close(); // hup reset happens here
    }

    if (rc == 0) {
        rc = usb.configure(false);
    }
    if (rc != 0) {
		const char *msg = "could not configure serial port (nohup) ";
        cerr << "ERROR	: " << msg << serialPath << endl;
		LOGERROR2("%s%s", msg, serialPath.c_str());
        return rc;
	}
    rc = open();
    if (rc == 0) { // clear out startup text
        string ignore = usb.readln(5000);
		cerr << "RESET	: re-open " << serialPath;
        while (ignore.size()) {
            LOGINFO1("FireStepSerial::reset() ignored:%ldB", (long) ignore.size());
            LOGDEBUG1("FireStepSerial::reset() ignore:%s", ignore.c_str());
			cerr << ".";
            ignore = usb.readln();
        }
		cerr << endl;
        rc = close(); // nohup
    }
	LOGINFO("FireStepSerial::reset() complete");
	return rc;
}

int FireStepSerial::open() {
    if (!isOpen() && usb.open() != 0) {
		const char *msg = "FireStepSerial::open() failed:";
		cerr << "ERROR	: " << msg << serialPath << endl;
		LOGERROR2("%s%s", msg, serialPath.c_str());
		return STATUS_USB_OPEN;
	}
	return IFireStep::open();
}

int FireStepSerial::close() {
    if (isOpen() && usb.close() != 0) {
		const char *msg = "FireStepSerial::close() failed:";
		cerr << "ERROR	: " << msg << serialPath << endl;
		LOGERROR2("%s%s", msg, serialPath.c_str());
        return STATUS_USB_CLOSE;
    }
    return IFireStep::close();
}

<commit_msg>firestep client display startup text<commit_after>#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <stdio.h>
#include <unistd.h>

#include <string.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <errno.h>
#include "FireLog.h"
#include "FireUtils.h"
#include "version.h"
#include "FireStepSerial.h"

using namespace std;
using namespace firestep;

FireStepSerial::FireStepSerial(const char *serialPath, int32_t msResponse)
    : serialPath(serialPath), msResponse(msResponse), usb(serialPath)
{
}

FireStepSerial::~FireStepSerial() {
	close();
}

int FireStepSerial::executeCore(const std::string &request, std::string &response) {
	int rc = 0;
	usb.write(request);
	response = usb.readln(msResponse);
	if (request.compare("\n") == 0) { // simple LF should be echoed
		for (int i=0; response.size() == 0 && i<4; i++) {
			LOGDEBUG1("FireStepClient::console() wait %ldms", (long) msResponse);
			response = usb.readln(msResponse);
		}
	} else { // JSON response should end with }-SPACE-LF
		int nRead = 0;
		for (int i=0; response.find("} \n")==string::npos && (nRead != response.size() || i<4); i++) {
			nRead = response.size();
			LOGDEBUG1("FireStepClient::console() wait %ldms", (long) msResponse);
			response += usb.readln(msResponse);
		}
	}

	return rc;
}

int FireStepSerial::reset() {
    int rc = 0;
    if (isOpen()) {
		const char *msg ="FireStepSerial::reset() sending LF to interrupt FireStep";
		cerr << "RESET	: " << msg << endl;
		LOGINFO1("%s", msg);
		usb.writeln(); // interrupt any current processing
        rc = close();
    }
    if (rc == 0) {
		LOGINFO("FireStepSerial::reset() configure(hup)");
        rc = usb.configure(true);
    }
    if (rc != 0) {
		const char *msg = "could not configure serial port (hup) ";
        cerr << "ERROR	: " << msg << serialPath << endl;
		LOGERROR2("%s%s", msg, serialPath.c_str());
        return rc;
    }
    rc = open();
    if (rc == 0) {
		LOGINFO("FireStepSerial::reset() configure(nohup)");
        rc = close(); // hup reset happens here
    }

    if (rc == 0) {
        rc = usb.configure(false);
    }
    if (rc != 0) {
		const char *msg = "could not configure serial port (nohup) ";
        cerr << "ERROR	: " << msg << serialPath << endl;
		LOGERROR2("%s%s", msg, serialPath.c_str());
        return rc;
	}
    rc = open();
    if (rc == 0) { // clear out startup text
        string ignore = usb.readln(5000);
		cerr << "RESET	: re-open " << serialPath << endl;
        while (ignore.size()) {
            LOGINFO1("FireStepSerial::reset() ignored:%ldB", (long) ignore.size());
            LOGDEBUG1("FireStepSerial::reset() ignore:%s", ignore.c_str());
			cerr << ignore ;
            ignore = usb.readln();
        }
        rc = close(); // nohup
    }
	LOGINFO("FireStepSerial::reset() complete");
	return rc;
}

int FireStepSerial::open() {
    if (!isOpen() && usb.open() != 0) {
		const char *msg = "FireStepSerial::open() failed:";
		cerr << "ERROR	: " << msg << serialPath << endl;
		LOGERROR2("%s%s", msg, serialPath.c_str());
		return STATUS_USB_OPEN;
	}
	return IFireStep::open();
}

int FireStepSerial::close() {
    if (isOpen() && usb.close() != 0) {
		const char *msg = "FireStepSerial::close() failed:";
		cerr << "ERROR	: " << msg << serialPath << endl;
		LOGERROR2("%s%s", msg, serialPath.c_str());
        return STATUS_USB_CLOSE;
    }
    return IFireStep::close();
}

<|endoftext|>


<commit_before>
#include <Wire.h>
#include <Arduino.h>
#include "i2cdetect.h"

void i2cdetect(uint8_t first, uint8_t last) {
  uint8_t i, j, address, error;

  // header
  Serial.print("   ");
  for (i = 0; i < 16; i++) {
    Serial.printf("%3x", i);
  }
  Serial.println("");

  for (j = 0; j < 8; j++) {
    Serial.printf("%02d:", j*10);
    for (i = 0; i < 16; i++) {
      address = i + j*16;
      if (address >= first && address <= last) {
        Wire.beginTransmission(address);
        error = Wire.endTransmission();
        if (error) {
          Serial.print(" --");
        } else {
          Serial.printf(" %02x", address);
        }
      } else {
        Serial.print("   ");
      }
    }
    Serial.println("");
  }
}

void i2cdetect() {
  i2cdetect(0x03, 0x77);
}

<commit_msg>Fixed printf<commit_after>
#include <Wire.h>
#include <Arduino.h>
#include "i2cdetect.h"

// _printf base code: http://playground.arduino.cc/Main/Printf
#include <stdarg.h>
#define PRINTF_BUF 80 // define the tmp buffer size (change if desired)
void _printf(const char *format, ...)
{
  char buf[PRINTF_BUF];
  va_list ap;
  va_start(ap, format);
  vsnprintf(buf, sizeof(buf), format, ap);
  for(char *p = &buf[0]; *p; p++) // emulate cooked mode for newlines
  {
    if(*p == '\n')
      Serial.write('\r');
    Serial.write(*p);
  }
  va_end(ap);
}

void i2cdetect(uint8_t first, uint8_t last) {
  uint8_t i, j, address, error;

  // header
  Serial.print("   ");
  for (i = 0; i < 16; i++) {
    printf("%3x", i);
  }
  Serial.println("");

  for (j = 0; j < 8; j++) {
    _printf("%02d:", j*10);
    for (i = 0; i < 16; i++) {
      address = i + j*16;
      if (address >= first && address <= last) {
        Wire.beginTransmission(address);
        error = Wire.endTransmission();
        if (error) {
          Serial.print(" --");
        } else {
          _printf(" %02x", address);
        }
      } else {
        Serial.print("   ");
      }
    }
    Serial.println("");
  }
}

void i2cdetect() {
  i2cdetect(0x03, 0x77);
}

<|endoftext|>


<commit_before>#include<d3d9.h>
#include "object.h"

void object::init(LPDIRECT3DDEVICE9 g_pd3dDevice, int VertexSize, int IndexSize, CUSTOMVERTEX Vertices[], WORD Indices[],int PrimitiveCount)
{

	m_VertexSize = VertexSize;
	m_IndexSize = IndexSize;
	m_PrimitiveCount = PrimitiveCount;
	g_pd3dDevice->CreateVertexBuffer(m_VertexSize*sizeof(CUSTOMVERTEX), 0, D3DFVF_CUSTOMVERTEX, D3DPOOL_DEFAULT, &m_pVertexBuffer, NULL);
	g_pd3dDevice->CreateIndexBuffer(m_IndexSize*sizeof(WORD), 0, D3DFMT_INDEX16, D3DPOOL_DEFAULT, &m_pIndexBuffer, NULL);
	WriteInVertexBuffer(Vertices);
	WriteInIndexBuffer(Indices);
}

object::~object()
{
	SAFE_RELEASE(m_pVertexBuffer);
	SAFE_RELEASE(m_pIndexBuffer);
}

object::object()
{
	m_VertexSize = 0;
	m_IndexSize = 0;
	m_PrimitiveCount = 0;
	m_pVertexBuffer = NULL;
	m_pIndexBuffer = NULL;
	mVertices = NULL;
	mIndices = NULL;
}

void object::WriteInVertexBuffer(CUSTOMVERTEX Vertices[])
{
	m_pVertexBuffer->Lock(0, 0, (void**)&mVertices, 0);
	memcpy(mVertices, Vertices, m_VertexSize*sizeof(CUSTOMVERTEX));
	m_pIndexBuffer->Unlock();
}

void object::WriteInIndexBuffer(WORD Indices[])
{
	m_pIndexBuffer->Lock(0, 0, (void**)&mIndices, 0);
	memcpy(mIndices, Indices, m_IndexSize*sizeof(WORD));
	m_pIndexBuffer->Unlock();
}

void object::ObjectPrint(LPDIRECT3DDEVICE9 g_pd3dDevice)
{
	g_pd3dDevice->SetStreamSource(0, m_pVertexBuffer, 0, sizeof(CUSTOMVERTEX));
	g_pd3dDevice->SetFVF(D3DFVF_CUSTOMVERTEX);
	g_pd3dDevice->SetIndices(m_pIndexBuffer);
	g_pd3dDevice->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, m_VertexSize, 0,(UINT)m_PrimitiveCount);
}<commit_msg>solve a big bug!<commit_after>#include<d3d9.h>
#include "object.h"

void object::init(LPDIRECT3DDEVICE9 g_pd3dDevice, int VertexSize, int IndexSize, CUSTOMVERTEX Vertices[], WORD Indices[],int PrimitiveCount)
{

	m_VertexSize = VertexSize;
	m_IndexSize = IndexSize;
	m_PrimitiveCount = PrimitiveCount;
	g_pd3dDevice->CreateVertexBuffer(m_VertexSize*sizeof(CUSTOMVERTEX), 0, D3DFVF_CUSTOMVERTEX, D3DPOOL_DEFAULT, &m_pVertexBuffer, NULL);
	g_pd3dDevice->CreateIndexBuffer(m_IndexSize*sizeof(WORD), 0, D3DFMT_INDEX16, D3DPOOL_DEFAULT, &m_pIndexBuffer, NULL);
	WriteInVertexBuffer(Vertices);
	WriteInIndexBuffer(Indices);
}

object::~object()
{
	SAFE_RELEASE(m_pVertexBuffer);
	SAFE_RELEASE(m_pIndexBuffer);
}

object::object()
{
	m_VertexSize = 0;
	m_IndexSize = 0;
	m_PrimitiveCount = 0;
	m_pVertexBuffer = NULL;
	m_pIndexBuffer = NULL;
	mVertices = NULL;
	mIndices = NULL;
}

void object::WriteInVertexBuffer(CUSTOMVERTEX Vertices[])
{
	m_pVertexBuffer->Lock(0, 0, (void**)&mVertices, 0);
	memcpy(mVertices, Vertices, m_VertexSize*sizeof(CUSTOMVERTEX));
	m_pVertexBuffer->Unlock();
}

void object::WriteInIndexBuffer(WORD Indices[])
{
	m_pIndexBuffer->Lock(0, 0, (void**)&mIndices, 0);
	memcpy(mIndices, Indices, m_IndexSize*sizeof(WORD));
	m_pIndexBuffer->Unlock();
}

void object::ObjectPrint(LPDIRECT3DDEVICE9 g_pd3dDevice)
{
	g_pd3dDevice->SetStreamSource(0, m_pVertexBuffer, 0, sizeof(CUSTOMVERTEX));
	g_pd3dDevice->SetFVF(D3DFVF_CUSTOMVERTEX);
	g_pd3dDevice->SetIndices(m_pIndexBuffer);
	g_pd3dDevice->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, m_VertexSize, 0,(UINT)m_PrimitiveCount);
}<|endoftext|>


<commit_before>/*
 * Copyright (c) 2013-2014 Nicholas Corgan (n.corgan@gmail.com)
 *
 * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
 * or copy at http://opensource.org/licenses/MIT)
 */
#ifndef INCLUDED_GAME_SAVE_IMPL_HPP
#define INCLUDED_GAME_SAVE_IMPL_HPP

#include <pkmn/game_save.hpp>

#include "conversions/trainer.hpp"

namespace pkmn
{
    class game_save_impl: public game_save
    {
        public:

            game_save_impl() {};

            unsigned int get_game_id() const;

            trainer::sptr get_trainer() const;

            bag::sptr get_trainer_bag() const;

            void get_trainer_party(pokemon_team_t& party);
            void set_trainer_party(pokemon_team_t& party);

            pokemon_text get_trainer_name() const;
            void set_trainer_name(pokemon_text trainer_name);

        protected:

            unsigned int _game_id;
            trainer::sptr _trainer;
    };
}
#endif /* INCLUDED_GAME_SAVE_IMPL_HPP */<commit_msg>Made game_save_impl a subclass of boost::noncopyable, added a filepath protected variable<commit_after>/*
 * Copyright (c) 2013-2014 Nicholas Corgan (n.corgan@gmail.com)
 *
 * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
 * or copy at http://opensource.org/licenses/MIT)
 */
#ifndef INCLUDED_GAME_SAVE_IMPL_HPP
#define INCLUDED_GAME_SAVE_IMPL_HPP

#include <boost/filesystem.hpp>
#include <boost/noncopyable.hpp>

#include <pkmn/game_save.hpp>

#include "conversions/trainer.hpp"

namespace pkmn
{
    class game_save_impl: public game_save, boost::noncopyable
    {
        public:

            game_save_impl() {};

            unsigned int get_game_id() const;

            trainer::sptr get_trainer() const;

            bag::sptr get_trainer_bag() const;

            void get_trainer_party(pokemon_team_t& party);
            void set_trainer_party(pokemon_team_t& party);

            pokemon_text get_trainer_name() const;
            void set_trainer_name(pokemon_text trainer_name);

        protected:

            boost::filesystem::path filepath;

            unsigned int _game_id;
            trainer::sptr _trainer;
    };
}
#endif /* INCLUDED_GAME_SAVE_IMPL_HPP */
<|endoftext|>