text
stringlengths 54
60.6k
|
---|
<commit_before>/*
*
* ledger_api_blockchain_explorer_tests
* ledger-core
*
* Created by Pierre Pollastri on 10/03/2017.
*
* The MIT License (MIT)
*
* Copyright (c) 2016 Ledger
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
#include <gtest/gtest.h>
#include <wallet/bitcoin/networks.hpp>
#include <wallet/ethereum/ethereumNetworks.hpp>
#include <wallet/bitcoin/explorers/LedgerApiBitcoinLikeBlockchainExplorer.hpp>
#include <wallet/ethereum/explorers/LedgerApiEthereumLikeBlockchainExplorer.h>
#include "BaseFixture.h"
#include "../../fixtures/http_cache_LedgerApiBitcoinLikeBlockchainExplorerTests_GetTransactions.h"
template <typename CurrencyExplorer, typename NetworkParameters>
class LedgerApiBlockchainExplorerTests : public BaseFixture {
public:
void SetUp() override {
BaseFixture::SetUp();
auto worker = dispatcher->getSerialExecutionContext("worker");
auto threadpoolWorker = dispatcher->getThreadPoolExecutionContext("threadpoolWorker");
auto client = std::make_shared<HttpClient>(explorerEndpoint, http, worker, threadpoolWorker);
explorer = std::make_shared<CurrencyExplorer>(worker, client, params, api::DynamicObject::newInstance());
logger = ledger::core::logger::create("test_logs",
dispatcher->getSerialExecutionContext("logger"),
resolver,
printer,
2000000000
);
client->setLogger(logger);
}
NetworkParameters params;
std::string explorerEndpoint;
std::shared_ptr<spdlog::logger> logger;
std::shared_ptr<CurrencyExplorer> explorer;
};
class LedgerApiBitcoinLikeBlockchainExplorerTests : public LedgerApiBlockchainExplorerTests<LedgerApiBitcoinLikeBlockchainExplorer, api::BitcoinLikeNetworkParameters> {
public:
LedgerApiBitcoinLikeBlockchainExplorerTests() {
params = networks::getNetworkParameters("bitcoin");
explorerEndpoint = "https://explorers.api.live.ledger.com";
}
};
TEST_F(LedgerApiBitcoinLikeBlockchainExplorerTests, GetRawTransaction) {
auto transaction = uv::wait(explorer->getRawTransaction("9d7945129b78e2f63a72fed93e8ebe38567bdc9318591cfe8c8a7de76c5cb1a3"));
auto hex = transaction.toHex();
EXPECT_EQ(hex.str(), "0100000001d62dad27a2bdd0c5e72a6288acb4e0acac088b4bc5588e60ff5c3861c4584d71010000006b483045022100d72a8e43c74764a18c5dfec225f1e60dceb12a9bf4931afa1093f14c471f55d202202cf4ed0956fd68dc9ba9d026a4ae04758092487cebff1618e320dcc12d736577012102b62b6c66c0d69ca3272ed3d0884a40bd4fb50ab08bec6de6d899b7389f40e9b5ffffffff026fa40200000000001976a91459fa62dab1f04b4528e5c5446f4c897b53fc983c88ace58f8b00000000001976a914b026e605bb239cf7eafb6437667f0f7f80e827f488ac00000000");
}
TEST_F(LedgerApiBitcoinLikeBlockchainExplorerTests, GetTransactionByHash) {
auto transaction = uv::wait(explorer->getTransactionByHash("9fdbe15a16fe282291426df15894ab1473e252bc31f244e4d923a17e11743eda"));
auto &tx = *transaction.get();
EXPECT_EQ(tx.inputs.size(), 1);
EXPECT_EQ(tx.hash, "9fdbe15a16fe282291426df15894ab1473e252bc31f244e4d923a17e11743eda");
EXPECT_EQ(tx.inputs[0].value.getValue().toString(), "1634001");
EXPECT_EQ(tx.inputs[0].address.getValue(), "1Nd2kJid5fFmPks9KSRpoHQX4VpkPhuATm");
EXPECT_EQ(tx.fees.getValue().toString(), "11350");
EXPECT_EQ(tx.outputs.size(), 2);
EXPECT_EQ(tx.outputs[0].value.toString(), "1000");
EXPECT_EQ(tx.outputs[1].value.toString(), "1621651");
EXPECT_EQ(tx.outputs[0].address.getValue(), "1QKJghDW4kLqCsH2pq3XKKsSSeYNPcL5PD");
EXPECT_EQ(tx.outputs[1].address.getValue(), "19j8biFtMSy5HFRX6mXiurjz3jszg7nLN5");
EXPECT_EQ(tx.block.getValue().hash, "0000000000000000026aa418ef33e0b079a42d348f35bc0a2fa4bc150a9c459d");
EXPECT_EQ(tx.block.getValue().height, 403912);
// Checked that real value of 2016-03-23T11:54:21Z corresponds to 1458734061000
//Disabled due to a bug in the explorer: the value is random (1458734061000 or 1458730461000)
//EXPECT_EQ(std::chrono::duration_cast<std::chrono::milliseconds>(tx.block.getValue().time.time_since_epoch()).count(), 1458734061000);
//EXPECT_EQ(std::chrono::duration_cast<std::chrono::milliseconds>(tx.receivedAt.time_since_epoch()).count(), 1458734061000);
}
TEST_F(LedgerApiBitcoinLikeBlockchainExplorerTests, GetTransactionByHash_2) {
auto transaction = uv::wait(explorer->getTransactionByHash("16da85a108a63ff318458be597f34f0a7f6b9f703528249056ba2f48722ae44e"));
auto &tx = *transaction;
EXPECT_EQ(tx.inputs.size(), 1);
EXPECT_EQ(tx.hash, "16da85a108a63ff318458be597f34f0a7f6b9f703528249056ba2f48722ae44e");
EXPECT_EQ(tx.inputs.size(), 1);
EXPECT_EQ(tx.outputs.size(), 1);
EXPECT_EQ(tx.inputs[0].coinbase.getValue(), "03070c070004ebabf05804496e151608bef5342d8b2800000a425720537570706f727420384d200a666973686572206a696e78696e092f425720506f6f6c2f");
EXPECT_EQ(tx.outputs[0].address.getValue(), "1BQLNJtMDKmMZ4PyqVFfRuBNvoGhjigBKF");
EXPECT_EQ(tx.outputs[0].value.toString(), "1380320309");
}
TEST_F(LedgerApiBitcoinLikeBlockchainExplorerTests, GetTransactionByHash_3) {
auto transaction = uv::wait(explorer->getTransactionByHash("8d2a0ccbe3a71f3e505be1557995c57f2a26f1951a72931f23a61f18fa4b3d2d"));
auto &tx = *transaction;
EXPECT_EQ(tx.hash, "8d2a0ccbe3a71f3e505be1557995c57f2a26f1951a72931f23a61f18fa4b3d2d");
EXPECT_EQ(tx.inputs.size(), 8);
EXPECT_EQ(tx.outputs.size(), 2);
EXPECT_EQ(tx.inputs[5].value.getValue().toString(), "270000");
EXPECT_EQ(tx.inputs[5].index, 5);
EXPECT_EQ(tx.inputs[5].address.getValue(), "1BEG75jXGZgH7QsSNjmm9RGJ2fgWcXVbxm");
EXPECT_EQ(tx.inputs[5].signatureScript.getValue(), "483045022100b21b21023b15be3d71fc660513adc4ef1aaa299ee58b9a5c1b8401015d045622022031847f047494c83b199a743d5edd5dbeb33b2dae03dcdff12485b212061d0463012102a7e1245393aa50cf6e08077ac5f4460c2db9c54858f6b0958d91b8d62f39c3bb");
EXPECT_EQ(tx.inputs[5].previousTxHash.getValue(), "64717373eef15249771032b0153daae92d18ea63e997c1c70a33879698b43329");
EXPECT_EQ(tx.inputs[5].previousTxOutputIndex.getValue(), 9);
EXPECT_EQ(tx.outputs[0].address.getValue(), "14w1wdDMV5uSnBd92yf3N9LfgS6TKVzyYr");
EXPECT_EQ(tx.outputs[1].address.getValue(), "1pCL4HJ3wbNXKiDde8eNmu9uMs1Tkd9hD");
}
TEST_F(LedgerApiBitcoinLikeBlockchainExplorerTests, GetCurrentBlock) {
auto block = uv::wait(explorer->getCurrentBlock());
EXPECT_GT(block->height, 462400);
}
TEST_F(LedgerApiBitcoinLikeBlockchainExplorerTests, GetTransactions) {
http->addCache(HTTP_CACHE_LedgerApiBitcoinLikeBlockchainExplorerTests_GetTransactions::URL,
HTTP_CACHE_LedgerApiBitcoinLikeBlockchainExplorerTests_GetTransactions::BODY);
auto result = uv::wait(explorer
->getTransactions(
{"1H6ZZpRmMnrw8ytepV3BYwMjYYnEkWDqVP", "1DxPxrQtUXVcebgNYETn163RQaEKxAvxqP"},
Option<std::string>(), Option<void *>()));
EXPECT_TRUE(result->hasNext);
EXPECT_TRUE(result->transactions.size() > 0);
}
TEST_F(LedgerApiBitcoinLikeBlockchainExplorerTests, GetFees) {
auto result = uv::wait(explorer->getFees());
EXPECT_NE(result.size(), 0);
if (result.size() > 1) {
EXPECT_GE(result[0]->intValue(), result[1]->intValue());
}
}
class LedgerApiEthereumLikeBlockchainExplorerTests : public LedgerApiBlockchainExplorerTests<LedgerApiEthereumLikeBlockchainExplorer, api::EthereumLikeNetworkParameters> {
public:
LedgerApiEthereumLikeBlockchainExplorerTests() {
params = networks::getEthLikeNetworkParameters("ethereum_ropsten");
explorerEndpoint = "https://explorers.api.live.ledger.com";
}
};
TEST_F(LedgerApiEthereumLikeBlockchainExplorerTests, GetGasPrice) {
auto result = uv::wait(explorer->getGasPrice());
EXPECT_NE(result->toUint64(), 0);
}
TEST_F(LedgerApiEthereumLikeBlockchainExplorerTests, GetEstimatedGasLimit) {
auto result = uv::wait(explorer->getEstimatedGasLimit("0x57e8ba2a915285f984988282ab9346c1336a4e11"));
EXPECT_GE(result->toUint64(), 10000);
}
TEST_F(LedgerApiEthereumLikeBlockchainExplorerTests, PostEstimatedGasLimit) {
auto request = api::EthereumGasLimitRequest(
optional<std::string>(),
optional<std::string>(),
optional<std::string>(),
std::string("0xa9059cbb00000000000000000000000013C5d95f25688f8A7544582D9e311f201A56de630000000000000000000000000000000000000000000000000000000000000000"),
optional<std::string>(),
optional<std::string>(),
std::string("1.5"));
auto result = uv::wait(explorer->getDryRunGasLimit(
"0x57e8ba2a915285f984988282ab9346c1336a4e11", request));
EXPECT_GE(result->toUint64(), 10000);
}
<commit_msg>fix more tests<commit_after>/*
*
* ledger_api_blockchain_explorer_tests
* ledger-core
*
* Created by Pierre Pollastri on 10/03/2017.
*
* The MIT License (MIT)
*
* Copyright (c) 2016 Ledger
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
#include <gtest/gtest.h>
#include <wallet/bitcoin/networks.hpp>
#include <wallet/ethereum/ethereumNetworks.hpp>
#include <wallet/bitcoin/explorers/LedgerApiBitcoinLikeBlockchainExplorer.hpp>
#include <wallet/ethereum/explorers/LedgerApiEthereumLikeBlockchainExplorer.h>
#include "BaseFixture.h"
#include "../../fixtures/http_cache_LedgerApiBitcoinLikeBlockchainExplorerTests_GetTransactions.h"
template <typename CurrencyExplorer, typename NetworkParameters>
class LedgerApiBlockchainExplorerTests : public BaseFixture {
public:
void SetUp() override {
BaseFixture::SetUp();
auto worker = dispatcher->getSerialExecutionContext("worker");
auto threadpoolWorker = dispatcher->getThreadPoolExecutionContext("threadpoolWorker");
auto client = std::make_shared<HttpClient>(explorerEndpoint, http, worker, threadpoolWorker);
auto configuration = DynamicObject::newInstance();
configuration->putString(api::Configuration::BLOCKCHAIN_EXPLORER_VERSION, "v3");
explorer = std::make_shared<CurrencyExplorer>(worker, client, params, configuration);
logger = ledger::core::logger::create("test_logs",
dispatcher->getSerialExecutionContext("logger"),
resolver,
printer,
2000000000
);
client->setLogger(logger);
}
NetworkParameters params;
std::string explorerEndpoint;
std::shared_ptr<spdlog::logger> logger;
std::shared_ptr<CurrencyExplorer> explorer;
};
class LedgerApiBitcoinLikeBlockchainExplorerTests : public LedgerApiBlockchainExplorerTests<LedgerApiBitcoinLikeBlockchainExplorer, api::BitcoinLikeNetworkParameters> {
public:
LedgerApiBitcoinLikeBlockchainExplorerTests() {
params = networks::getNetworkParameters("bitcoin");
explorerEndpoint = "https://explorers.api.live.ledger.com";
}
};
TEST_F(LedgerApiBitcoinLikeBlockchainExplorerTests, GetRawTransaction) {
auto transaction = uv::wait(explorer->getRawTransaction("9d7945129b78e2f63a72fed93e8ebe38567bdc9318591cfe8c8a7de76c5cb1a3"));
auto hex = transaction.toHex();
EXPECT_EQ(hex.str(), "0100000001d62dad27a2bdd0c5e72a6288acb4e0acac088b4bc5588e60ff5c3861c4584d71010000006b483045022100d72a8e43c74764a18c5dfec225f1e60dceb12a9bf4931afa1093f14c471f55d202202cf4ed0956fd68dc9ba9d026a4ae04758092487cebff1618e320dcc12d736577012102b62b6c66c0d69ca3272ed3d0884a40bd4fb50ab08bec6de6d899b7389f40e9b5ffffffff026fa40200000000001976a91459fa62dab1f04b4528e5c5446f4c897b53fc983c88ace58f8b00000000001976a914b026e605bb239cf7eafb6437667f0f7f80e827f488ac00000000");
}
TEST_F(LedgerApiBitcoinLikeBlockchainExplorerTests, GetTransactionByHash) {
auto transaction = uv::wait(explorer->getTransactionByHash("9fdbe15a16fe282291426df15894ab1473e252bc31f244e4d923a17e11743eda"));
auto &tx = *transaction.get();
EXPECT_EQ(tx.inputs.size(), 1);
EXPECT_EQ(tx.hash, "9fdbe15a16fe282291426df15894ab1473e252bc31f244e4d923a17e11743eda");
EXPECT_EQ(tx.inputs[0].value.getValue().toString(), "1634001");
EXPECT_EQ(tx.inputs[0].address.getValue(), "1Nd2kJid5fFmPks9KSRpoHQX4VpkPhuATm");
EXPECT_EQ(tx.fees.getValue().toString(), "11350");
EXPECT_EQ(tx.outputs.size(), 2);
EXPECT_EQ(tx.outputs[0].value.toString(), "1000");
EXPECT_EQ(tx.outputs[1].value.toString(), "1621651");
EXPECT_EQ(tx.outputs[0].address.getValue(), "1QKJghDW4kLqCsH2pq3XKKsSSeYNPcL5PD");
EXPECT_EQ(tx.outputs[1].address.getValue(), "19j8biFtMSy5HFRX6mXiurjz3jszg7nLN5");
EXPECT_EQ(tx.block.getValue().hash, "0000000000000000026aa418ef33e0b079a42d348f35bc0a2fa4bc150a9c459d");
EXPECT_EQ(tx.block.getValue().height, 403912);
// Checked that real value of 2016-03-23T11:54:21Z corresponds to 1458734061000
//Disabled due to a bug in the explorer: the value is random (1458734061000 or 1458730461000)
//EXPECT_EQ(std::chrono::duration_cast<std::chrono::milliseconds>(tx.block.getValue().time.time_since_epoch()).count(), 1458734061000);
//EXPECT_EQ(std::chrono::duration_cast<std::chrono::milliseconds>(tx.receivedAt.time_since_epoch()).count(), 1458734061000);
}
TEST_F(LedgerApiBitcoinLikeBlockchainExplorerTests, GetTransactionByHash_2) {
auto transaction = uv::wait(explorer->getTransactionByHash("16da85a108a63ff318458be597f34f0a7f6b9f703528249056ba2f48722ae44e"));
auto &tx = *transaction;
EXPECT_EQ(tx.inputs.size(), 1);
EXPECT_EQ(tx.hash, "16da85a108a63ff318458be597f34f0a7f6b9f703528249056ba2f48722ae44e");
EXPECT_EQ(tx.inputs.size(), 1);
EXPECT_EQ(tx.outputs.size(), 1);
EXPECT_EQ(tx.inputs[0].coinbase.getValue(), "03070c070004ebabf05804496e151608bef5342d8b2800000a425720537570706f727420384d200a666973686572206a696e78696e092f425720506f6f6c2f");
EXPECT_EQ(tx.outputs[0].address.getValue(), "1BQLNJtMDKmMZ4PyqVFfRuBNvoGhjigBKF");
EXPECT_EQ(tx.outputs[0].value.toString(), "1380320309");
}
TEST_F(LedgerApiBitcoinLikeBlockchainExplorerTests, GetTransactionByHash_3) {
auto transaction = uv::wait(explorer->getTransactionByHash("8d2a0ccbe3a71f3e505be1557995c57f2a26f1951a72931f23a61f18fa4b3d2d"));
auto &tx = *transaction;
EXPECT_EQ(tx.hash, "8d2a0ccbe3a71f3e505be1557995c57f2a26f1951a72931f23a61f18fa4b3d2d");
EXPECT_EQ(tx.inputs.size(), 8);
EXPECT_EQ(tx.outputs.size(), 2);
bool inputFound = false;
for(const auto& input : tx.inputs) {
if (input.previousTxHash.getValue() == "64717373eef15249771032b0153daae92d18ea63e997c1c70a33879698b43329") {
EXPECT_EQ(input.value.getValue().toString(), "270000");
EXPECT_EQ(input.address.getValue(), "1BEG75jXGZgH7QsSNjmm9RGJ2fgWcXVbxm");
EXPECT_EQ(input.signatureScript.getValue(), "483045022100b21b21023b15be3d71fc660513adc4ef1aaa299ee58b9a5c1b8401015d045622022031847f047494c83b199a743d5edd5dbeb33b2dae03dcdff12485b212061d0463012102a7e1245393aa50cf6e08077ac5f4460c2db9c54858f6b0958d91b8d62f39c3bb");
EXPECT_EQ(input.previousTxOutputIndex.getValue(), 9);
inputFound = true;
break;
}
}
EXPECT_EQ(inputFound, true);
EXPECT_EQ(tx.outputs[0].address.getValue(), "14w1wdDMV5uSnBd92yf3N9LfgS6TKVzyYr");
EXPECT_EQ(tx.outputs[1].address.getValue(), "1pCL4HJ3wbNXKiDde8eNmu9uMs1Tkd9hD");
}
TEST_F(LedgerApiBitcoinLikeBlockchainExplorerTests, GetCurrentBlock) {
auto block = uv::wait(explorer->getCurrentBlock());
EXPECT_GT(block->height, 462400);
}
TEST_F(LedgerApiBitcoinLikeBlockchainExplorerTests, GetTransactions) {
http->addCache(HTTP_CACHE_LedgerApiBitcoinLikeBlockchainExplorerTests_GetTransactions::URL,
HTTP_CACHE_LedgerApiBitcoinLikeBlockchainExplorerTests_GetTransactions::BODY);
auto result = uv::wait(explorer
->getTransactions(
{"1H6ZZpRmMnrw8ytepV3BYwMjYYnEkWDqVP", "1DxPxrQtUXVcebgNYETn163RQaEKxAvxqP"},
Option<std::string>(), Option<void *>()));
EXPECT_TRUE(result->hasNext);
EXPECT_TRUE(result->transactions.size() > 0);
}
TEST_F(LedgerApiBitcoinLikeBlockchainExplorerTests, GetFees) {
auto result = uv::wait(explorer->getFees());
EXPECT_NE(result.size(), 0);
if (result.size() > 1) {
EXPECT_GE(result[0]->intValue(), result[1]->intValue());
}
}
class LedgerApiEthereumLikeBlockchainExplorerTests : public LedgerApiBlockchainExplorerTests<LedgerApiEthereumLikeBlockchainExplorer, api::EthereumLikeNetworkParameters> {
public:
LedgerApiEthereumLikeBlockchainExplorerTests() {
params = networks::getEthLikeNetworkParameters("ethereum_ropsten");
explorerEndpoint = "https://explorers.api.live.ledger.com";
}
};
TEST_F(LedgerApiEthereumLikeBlockchainExplorerTests, GetGasPrice) {
auto result = uv::wait(explorer->getGasPrice());
EXPECT_NE(result->toUint64(), 0);
}
TEST_F(LedgerApiEthereumLikeBlockchainExplorerTests, GetEstimatedGasLimit) {
auto result = uv::wait(explorer->getEstimatedGasLimit("0x57e8ba2a915285f984988282ab9346c1336a4e11"));
EXPECT_GE(result->toUint64(), 10000);
}
TEST_F(LedgerApiEthereumLikeBlockchainExplorerTests, PostEstimatedGasLimit) {
auto request = api::EthereumGasLimitRequest(
optional<std::string>(),
optional<std::string>(),
optional<std::string>(),
std::string("0xa9059cbb00000000000000000000000013C5d95f25688f8A7544582D9e311f201A56de630000000000000000000000000000000000000000000000000000000000000000"),
optional<std::string>(),
optional<std::string>(),
std::string("1.5"));
auto result = uv::wait(explorer->getDryRunGasLimit(
"0x57e8ba2a915285f984988282ab9346c1336a4e11", request));
EXPECT_GE(result->toUint64(), 10000);
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2004-2009 Hyperic, Inc.
* Copyright (c) 2009 SpringSource, Inc.
* Copyright (c) 2009-2010 VMware, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdio.h>
#include <chrono>
#include <system_error>
#ifdef WIN32
#include <process.h>
#endif
#include "sigar.h"
#include "sigar_private.h"
SIGAR_DECLARE(int) sigar_open(sigar_t** sigar) {
try {
*sigar = sigar_t::New();
return SIGAR_OK;
} catch (const std::bad_alloc&) {
return ENOMEM;
} catch (const std::system_error& ex) {
return ex.code().value();
} catch (...) {
return EINVAL;
}
}
SIGAR_DECLARE(int) sigar_close(sigar_t* sigar) {
delete sigar;
return SIGAR_OK;
}
SIGAR_DECLARE(sigar_pid_t) sigar_pid_get(sigar_t* sigar) {
// There isn't much point of trying to cache the pid (it would break
// if the paren't ever called fork()). We don't use the variable
// internally, and if the caller don't want the overhead of a system
// call they can always cache it themselves
return getpid();
}
SIGAR_DECLARE(int) sigar_mem_get(sigar_t* sigar, sigar_mem_t* mem) {
if (!sigar || !mem) {
return EINVAL;
}
*mem = {};
try {
return sigar->get_memory(*mem);
} catch (const std::bad_alloc&) {
return ENOMEM;
} catch (const std::system_error& ex) {
return ex.code().value();
} catch (...) {
return EINVAL;
}
}
SIGAR_DECLARE(int) sigar_swap_get(sigar_t* sigar, sigar_swap_t* swap) {
if (!sigar || !swap) {
return EINVAL;
}
swap->total = SIGAR_FIELD_NOTIMPL;
swap->used = SIGAR_FIELD_NOTIMPL;
swap->free = SIGAR_FIELD_NOTIMPL;
swap->page_in = SIGAR_FIELD_NOTIMPL;
swap->page_out = SIGAR_FIELD_NOTIMPL;
swap->allocstall = SIGAR_FIELD_NOTIMPL;
swap->allocstall_dma = SIGAR_FIELD_NOTIMPL;
swap->allocstall_dma32 = SIGAR_FIELD_NOTIMPL;
swap->allocstall_normal = SIGAR_FIELD_NOTIMPL;
swap->allocstall_movable = SIGAR_FIELD_NOTIMPL;
try {
return sigar->get_swap(*swap);
} catch (const std::bad_alloc&) {
return ENOMEM;
} catch (const std::system_error& ex) {
return ex.code().value();
} catch (...) {
return EINVAL;
}
}
SIGAR_DECLARE(int) sigar_cpu_get(sigar_t* sigar, sigar_cpu_t* cpu) {
if (!sigar || !cpu) {
return EINVAL;
}
#if 0
// The correct thing to do would be to initialize to not impl, as
// linux is the only platform adding some of these fields, but
// it looks like people don't check if they're implemented or not
cpu->user = SIGAR_FIELD_NOTIMPL;
cpu->sys = SIGAR_FIELD_NOTIMPL;
cpu->nice = SIGAR_FIELD_NOTIMPL;
cpu->idle = SIGAR_FIELD_NOTIMPL;
cpu->wait = SIGAR_FIELD_NOTIMPL;
cpu->irq = SIGAR_FIELD_NOTIMPL;
cpu->soft_irq = SIGAR_FIELD_NOTIMPL;
cpu->stolen = SIGAR_FIELD_NOTIMPL;
cpu->total = SIGAR_FIELD_NOTIMPL;
#endif
*cpu = {};
try {
return sigar->get_cpu(*cpu);
} catch (const std::bad_alloc&) {
return ENOMEM;
} catch (const std::system_error& ex) {
return ex.code().value();
} catch (...) {
return EINVAL;
}
}
static uint64_t sigar_time_now_millis() {
auto now = std::chrono::system_clock::now();
return std::chrono::duration_cast<std::chrono::milliseconds>(
now.time_since_epoch())
.count();
}
int sigar_t::get_proc_cpu(sigar_pid_t pid, sigar_proc_cpu_t& proccpu) {
const auto time_now = sigar_time_now_millis();
sigar_proc_cpu_t prev = {};
auto iter = process_cache.find(pid);
const bool found = iter != process_cache.end();
if (!found) {
prev = iter->second;
}
auto status = get_proc_time(pid, *(sigar_proc_time_t*)&proccpu);
if (status != SIGAR_OK) {
if (found) {
process_cache.erase(iter);
}
return status;
}
proccpu.last_time = time_now;
if (!found || (prev.start_time != proccpu.start_time)) {
// This is a new process or a different process we have in the cache
process_cache[pid] = proccpu;
return SIGAR_OK;
}
auto time_diff = time_now - prev.last_time;
if (!time_diff) {
// we don't want divide by zero
time_diff = 1;
}
proccpu.percent = (proccpu.total - prev.total) / (double)time_diff;
process_cache[pid] = proccpu;
return SIGAR_OK;
}
SIGAR_DECLARE(int)
sigar_proc_mem_get(sigar_t* sigar, sigar_pid_t pid, sigar_proc_mem_t* procmem) {
if (!sigar || !procmem) {
return EINVAL;
}
procmem->size = SIGAR_FIELD_NOTIMPL;
procmem->resident = SIGAR_FIELD_NOTIMPL;
procmem->share = SIGAR_FIELD_NOTIMPL;
procmem->minor_faults = SIGAR_FIELD_NOTIMPL;
procmem->major_faults = SIGAR_FIELD_NOTIMPL;
procmem->page_faults = SIGAR_FIELD_NOTIMPL;
try {
return sigar->get_proc_memory(pid, *procmem);
} catch (const std::bad_alloc&) {
return ENOMEM;
} catch (const std::system_error& ex) {
return ex.code().value();
} catch (...) {
return EINVAL;
}
}
SIGAR_DECLARE(int)
sigar_proc_cpu_get(sigar_t* sigar, sigar_pid_t pid, sigar_proc_cpu_t* proccpu) {
if (!sigar || !proccpu) {
return EINVAL;
}
*proccpu = {};
try {
return sigar->get_proc_cpu(pid, *proccpu);
} catch (const std::bad_alloc&) {
return ENOMEM;
} catch (const std::system_error& ex) {
return ex.code().value();
} catch (...) {
return EINVAL;
}
}
SIGAR_DECLARE(int)
sigar_proc_state_get(sigar_t* sigar,
sigar_pid_t pid,
sigar_proc_state_t* procstate) {
if (!sigar || !procstate) {
return EINVAL;
}
*procstate = {};
procstate->tty = SIGAR_FIELD_NOTIMPL;
procstate->nice = SIGAR_FIELD_NOTIMPL;
procstate->threads = SIGAR_FIELD_NOTIMPL;
procstate->processor = SIGAR_FIELD_NOTIMPL;
try {
return sigar->get_proc_state(pid, *procstate);
} catch (const std::bad_alloc&) {
return ENOMEM;
} catch (const std::system_error& ex) {
return ex.code().value();
} catch (...) {
return EINVAL;
}
}
SIGAR_PUBLIC_API
void sigar::iterate_child_processes(sigar_t* sigar,
sigar_pid_t pid,
IterateChildProcessCallback callback) {
sigar->iterate_child_processes(pid, callback);
}
<commit_msg>Don't dereference iterator pointing to end()<commit_after>/*
* Copyright (c) 2004-2009 Hyperic, Inc.
* Copyright (c) 2009 SpringSource, Inc.
* Copyright (c) 2009-2010 VMware, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdio.h>
#include <chrono>
#include <system_error>
#ifdef WIN32
#include <process.h>
#endif
#include "sigar.h"
#include "sigar_private.h"
SIGAR_DECLARE(int) sigar_open(sigar_t** sigar) {
try {
*sigar = sigar_t::New();
return SIGAR_OK;
} catch (const std::bad_alloc&) {
return ENOMEM;
} catch (const std::system_error& ex) {
return ex.code().value();
} catch (...) {
return EINVAL;
}
}
SIGAR_DECLARE(int) sigar_close(sigar_t* sigar) {
delete sigar;
return SIGAR_OK;
}
SIGAR_DECLARE(sigar_pid_t) sigar_pid_get(sigar_t* sigar) {
// There isn't much point of trying to cache the pid (it would break
// if the paren't ever called fork()). We don't use the variable
// internally, and if the caller don't want the overhead of a system
// call they can always cache it themselves
return getpid();
}
SIGAR_DECLARE(int) sigar_mem_get(sigar_t* sigar, sigar_mem_t* mem) {
if (!sigar || !mem) {
return EINVAL;
}
*mem = {};
try {
return sigar->get_memory(*mem);
} catch (const std::bad_alloc&) {
return ENOMEM;
} catch (const std::system_error& ex) {
return ex.code().value();
} catch (...) {
return EINVAL;
}
}
SIGAR_DECLARE(int) sigar_swap_get(sigar_t* sigar, sigar_swap_t* swap) {
if (!sigar || !swap) {
return EINVAL;
}
swap->total = SIGAR_FIELD_NOTIMPL;
swap->used = SIGAR_FIELD_NOTIMPL;
swap->free = SIGAR_FIELD_NOTIMPL;
swap->page_in = SIGAR_FIELD_NOTIMPL;
swap->page_out = SIGAR_FIELD_NOTIMPL;
swap->allocstall = SIGAR_FIELD_NOTIMPL;
swap->allocstall_dma = SIGAR_FIELD_NOTIMPL;
swap->allocstall_dma32 = SIGAR_FIELD_NOTIMPL;
swap->allocstall_normal = SIGAR_FIELD_NOTIMPL;
swap->allocstall_movable = SIGAR_FIELD_NOTIMPL;
try {
return sigar->get_swap(*swap);
} catch (const std::bad_alloc&) {
return ENOMEM;
} catch (const std::system_error& ex) {
return ex.code().value();
} catch (...) {
return EINVAL;
}
}
SIGAR_DECLARE(int) sigar_cpu_get(sigar_t* sigar, sigar_cpu_t* cpu) {
if (!sigar || !cpu) {
return EINVAL;
}
#if 0
// The correct thing to do would be to initialize to not impl, as
// linux is the only platform adding some of these fields, but
// it looks like people don't check if they're implemented or not
cpu->user = SIGAR_FIELD_NOTIMPL;
cpu->sys = SIGAR_FIELD_NOTIMPL;
cpu->nice = SIGAR_FIELD_NOTIMPL;
cpu->idle = SIGAR_FIELD_NOTIMPL;
cpu->wait = SIGAR_FIELD_NOTIMPL;
cpu->irq = SIGAR_FIELD_NOTIMPL;
cpu->soft_irq = SIGAR_FIELD_NOTIMPL;
cpu->stolen = SIGAR_FIELD_NOTIMPL;
cpu->total = SIGAR_FIELD_NOTIMPL;
#endif
*cpu = {};
try {
return sigar->get_cpu(*cpu);
} catch (const std::bad_alloc&) {
return ENOMEM;
} catch (const std::system_error& ex) {
return ex.code().value();
} catch (...) {
return EINVAL;
}
}
static uint64_t sigar_time_now_millis() {
auto now = std::chrono::system_clock::now();
return std::chrono::duration_cast<std::chrono::milliseconds>(
now.time_since_epoch())
.count();
}
int sigar_t::get_proc_cpu(sigar_pid_t pid, sigar_proc_cpu_t& proccpu) {
const auto time_now = sigar_time_now_millis();
sigar_proc_cpu_t prev = {};
auto iter = process_cache.find(pid);
const bool found = iter != process_cache.end();
if (found) {
prev = iter->second;
}
auto status = get_proc_time(pid, *(sigar_proc_time_t*)&proccpu);
if (status != SIGAR_OK) {
if (found) {
process_cache.erase(iter);
}
return status;
}
proccpu.last_time = time_now;
if (!found || (prev.start_time != proccpu.start_time)) {
// This is a new process or a different process we have in the cache
process_cache[pid] = proccpu;
return SIGAR_OK;
}
auto time_diff = time_now - prev.last_time;
if (!time_diff) {
// we don't want divide by zero
time_diff = 1;
}
proccpu.percent = (proccpu.total - prev.total) / (double)time_diff;
process_cache[pid] = proccpu;
return SIGAR_OK;
}
SIGAR_DECLARE(int)
sigar_proc_mem_get(sigar_t* sigar, sigar_pid_t pid, sigar_proc_mem_t* procmem) {
if (!sigar || !procmem) {
return EINVAL;
}
procmem->size = SIGAR_FIELD_NOTIMPL;
procmem->resident = SIGAR_FIELD_NOTIMPL;
procmem->share = SIGAR_FIELD_NOTIMPL;
procmem->minor_faults = SIGAR_FIELD_NOTIMPL;
procmem->major_faults = SIGAR_FIELD_NOTIMPL;
procmem->page_faults = SIGAR_FIELD_NOTIMPL;
try {
return sigar->get_proc_memory(pid, *procmem);
} catch (const std::bad_alloc&) {
return ENOMEM;
} catch (const std::system_error& ex) {
return ex.code().value();
} catch (...) {
return EINVAL;
}
}
SIGAR_DECLARE(int)
sigar_proc_cpu_get(sigar_t* sigar, sigar_pid_t pid, sigar_proc_cpu_t* proccpu) {
if (!sigar || !proccpu) {
return EINVAL;
}
*proccpu = {};
try {
return sigar->get_proc_cpu(pid, *proccpu);
} catch (const std::bad_alloc&) {
return ENOMEM;
} catch (const std::system_error& ex) {
return ex.code().value();
} catch (...) {
return EINVAL;
}
}
SIGAR_DECLARE(int)
sigar_proc_state_get(sigar_t* sigar,
sigar_pid_t pid,
sigar_proc_state_t* procstate) {
if (!sigar || !procstate) {
return EINVAL;
}
*procstate = {};
procstate->tty = SIGAR_FIELD_NOTIMPL;
procstate->nice = SIGAR_FIELD_NOTIMPL;
procstate->threads = SIGAR_FIELD_NOTIMPL;
procstate->processor = SIGAR_FIELD_NOTIMPL;
try {
return sigar->get_proc_state(pid, *procstate);
} catch (const std::bad_alloc&) {
return ENOMEM;
} catch (const std::system_error& ex) {
return ex.code().value();
} catch (...) {
return EINVAL;
}
}
SIGAR_PUBLIC_API
void sigar::iterate_child_processes(sigar_t* sigar,
sigar_pid_t pid,
IterateChildProcessCallback callback) {
sigar->iterate_child_processes(pid, callback);
}
<|endoftext|> |
<commit_before>/***********************************************************************
filename: SampleData.cpp
created: 4/6/2012
author: Lukas E Meindl
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#include "SampleData.h"
#include "Sample.h"
#include "Samples_xmlHandler.h"
#include "CEGUI/DynamicModule.h"
#include "CEGUI/Version.h"
#include "CEGUI/Exceptions.h"
#include "CEGUI/System.h"
#include "CEGUI/TextureTarget.h"
#include "CEGUI/BasicImage.h"
#include "CEGUI/GUIContext.h"
#include "CEGUI/Texture.h"
#include "CEGUI/ImageManager.h"
#include "CEGUI/Window.h"
using namespace CEGUI;
#define S_(X) #X
#define STRINGIZE(X) S_(X)
typedef Sample& (*getSampleInstance)();
#define GetSampleInstanceFuncName "getSampleInstance"
SampleData::SampleData(CEGUI::String sampleName, CEGUI::String summary,
CEGUI::String description, SampleType sampleTypeEnum)
: d_name(sampleName),
d_summary(summary),
d_description(description),
d_type(sampleTypeEnum),
d_guiContext(0),
d_textureTarget(0),
d_textureTargetImage(0),
d_sampleWindow(0),
d_usedFilesString("")
{
}
SampleData::~SampleData()
{
}
CEGUI::String SampleData::getName()
{
return d_name;
}
CEGUI::String SampleData::getSummary()
{
return d_summary;
}
CEGUI::String SampleData::getSampleTypeString()
{
switch(d_type)
{
case ST_Module:
return SampleDataHandler::SampleTypeCppModule;
break;
case ST_Lua:
return SampleDataHandler::SampleTypeLua;
break;
case ST_Python:
return SampleDataHandler::SampleTypePython;
default:
return "";
}
}
CEGUI::String SampleData::getDescription()
{
return d_description;
}
CEGUI::String SampleData::getUsedFilesString()
{
return d_usedFilesString;
}
void SampleData::setSampleWindow(CEGUI::Window* sampleWindow)
{
d_sampleWindow = sampleWindow;
}
CEGUI::Window* SampleData::getSampleWindow()
{
return d_sampleWindow;
}
void SampleData::initialise()
{
CEGUI::System& system(System::getSingleton());
d_textureTarget = system.getRenderer()->createTextureTarget();
d_guiContext = &system.createGUIContext((RenderTarget&)*d_textureTarget);
CEGUI::String imageName(d_textureTarget->getTexture().getName());
d_textureTargetImage = static_cast<CEGUI::BasicImage*>(&CEGUI::ImageManager::getSingleton().create("BasicImage", "SampleBrowser/" + imageName));
d_textureTargetImage->setTexture(&d_textureTarget->getTexture());
}
void SampleData::deinitialise()
{
CEGUI::System& system(System::getSingleton());
if(d_guiContext)
{
system.destroyGUIContext(*d_guiContext);
d_guiContext = 0;
}
if(d_textureTarget)
{
system.getRenderer()->destroyTextureTarget(d_textureTarget);
d_textureTarget = 0;
}
}
GUIContext* SampleData::getGuiContext()
{
return d_guiContext;
}
void SampleData::handleNewWindowSize(float width, float height)
{
CEGUI::Sizef windowSize(width, height);
CEGUI::Rectf renderArea(CEGUI::Rectf(0.f, height, width, 0.f));
d_textureTargetImage->setArea(renderArea);
d_textureTarget->declareRenderSize(windowSize);
d_sampleWindow->getRenderingSurface()->invalidate();
}
CEGUI::Image& SampleData::getRTTImage()
{
return *d_textureTargetImage;
}
void SampleData::setGUIContextRTT()
{
d_guiContext->setRenderTarget(*d_textureTarget);
}
void SampleData::clearRTTTexture()
{
d_textureTarget->clear();
}
SampleDataModule::SampleDataModule(CEGUI::String sampleName, CEGUI::String summary,
CEGUI::String description, SampleType sampleTypeEnum)
: SampleData(sampleName, summary, description ,sampleTypeEnum)
{
}
SampleDataModule::~SampleDataModule()
{
}
void SampleDataModule::initialise()
{
SampleData::initialise();
getSampleInstanceFromDLL();
d_usedFilesString = d_sample->getUsedFilesString();
d_sample->initialise(d_guiContext);
}
void SampleDataModule::deinitialise()
{
SampleData::deinitialise();
d_sample->deinitialise();
}
void SampleDataModule::getSampleInstanceFromDLL()
{
// Version suffix for the dlls
static const CEGUI::String versionSuffix( "-" STRINGIZE(CEGUI_VERSION_MAJOR) "." STRINGIZE(CEGUI_VERSION_MINOR) );
CEGUI::DynamicModule* sampleModule = new CEGUI::DynamicModule(d_name + versionSuffix);
getSampleInstance functionPointerGetSample = (getSampleInstance)sampleModule->getSymbolAddress(CEGUI::String(GetSampleInstanceFuncName));
if(functionPointerGetSample == 0)
{
CEGUI::String errorMessage = "The sample creation function is not defined in the dynamic library of " + d_name;
CEGUI_THROW(CEGUI::InvalidRequestException(errorMessage.c_str()));
}
d_sample = &(functionPointerGetSample());
}<commit_msg>MOD: Start size fix<commit_after>/***********************************************************************
filename: SampleData.cpp
created: 4/6/2012
author: Lukas E Meindl
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#include "SampleData.h"
#include "Sample.h"
#include "Samples_xmlHandler.h"
#include "CEGUI/DynamicModule.h"
#include "CEGUI/Version.h"
#include "CEGUI/Exceptions.h"
#include "CEGUI/System.h"
#include "CEGUI/TextureTarget.h"
#include "CEGUI/BasicImage.h"
#include "CEGUI/GUIContext.h"
#include "CEGUI/Texture.h"
#include "CEGUI/ImageManager.h"
#include "CEGUI/Window.h"
using namespace CEGUI;
#define S_(X) #X
#define STRINGIZE(X) S_(X)
typedef Sample& (*getSampleInstance)();
#define GetSampleInstanceFuncName "getSampleInstance"
SampleData::SampleData(CEGUI::String sampleName, CEGUI::String summary,
CEGUI::String description, SampleType sampleTypeEnum)
: d_name(sampleName),
d_summary(summary),
d_description(description),
d_type(sampleTypeEnum),
d_guiContext(0),
d_textureTarget(0),
d_textureTargetImage(0),
d_sampleWindow(0),
d_usedFilesString("")
{
}
SampleData::~SampleData()
{
}
CEGUI::String SampleData::getName()
{
return d_name;
}
CEGUI::String SampleData::getSummary()
{
return d_summary;
}
CEGUI::String SampleData::getSampleTypeString()
{
switch(d_type)
{
case ST_Module:
return SampleDataHandler::SampleTypeCppModule;
break;
case ST_Lua:
return SampleDataHandler::SampleTypeLua;
break;
case ST_Python:
return SampleDataHandler::SampleTypePython;
default:
return "";
}
}
CEGUI::String SampleData::getDescription()
{
return d_description;
}
CEGUI::String SampleData::getUsedFilesString()
{
return d_usedFilesString;
}
void SampleData::setSampleWindow(CEGUI::Window* sampleWindow)
{
d_sampleWindow = sampleWindow;
}
CEGUI::Window* SampleData::getSampleWindow()
{
return d_sampleWindow;
}
void SampleData::initialise()
{
CEGUI::System& system(System::getSingleton());
d_textureTarget = system.getRenderer()->createTextureTarget();
d_guiContext = &system.createGUIContext((RenderTarget&)*d_textureTarget);
d_textureTarget->declareRenderSize(CEGUI::Sizef(200.f, 200.f));
CEGUI::String imageName(d_textureTarget->getTexture().getName());
d_textureTargetImage = static_cast<CEGUI::BasicImage*>(&CEGUI::ImageManager::getSingleton().create("BasicImage", "SampleBrowser/" + imageName));
d_textureTargetImage->setTexture(&d_textureTarget->getTexture());
}
void SampleData::deinitialise()
{
CEGUI::System& system(System::getSingleton());
if(d_guiContext)
{
system.destroyGUIContext(*d_guiContext);
d_guiContext = 0;
}
if(d_textureTarget)
{
system.getRenderer()->destroyTextureTarget(d_textureTarget);
d_textureTarget = 0;
}
}
GUIContext* SampleData::getGuiContext()
{
return d_guiContext;
}
void SampleData::handleNewWindowSize(float width, float height)
{
CEGUI::Sizef windowSize(width, height);
CEGUI::Rectf renderArea(CEGUI::Rectf(0.f, height, width, 0.f));
d_textureTargetImage->setArea(renderArea);
d_textureTarget->declareRenderSize(windowSize);
d_sampleWindow->getRenderingSurface()->invalidate();
}
CEGUI::Image& SampleData::getRTTImage()
{
return *d_textureTargetImage;
}
void SampleData::setGUIContextRTT()
{
d_guiContext->setRenderTarget(*d_textureTarget);
}
void SampleData::clearRTTTexture()
{
d_textureTarget->clear();
}
SampleDataModule::SampleDataModule(CEGUI::String sampleName, CEGUI::String summary,
CEGUI::String description, SampleType sampleTypeEnum)
: SampleData(sampleName, summary, description ,sampleTypeEnum)
{
}
SampleDataModule::~SampleDataModule()
{
}
void SampleDataModule::initialise()
{
SampleData::initialise();
getSampleInstanceFromDLL();
d_usedFilesString = d_sample->getUsedFilesString();
d_sample->initialise(d_guiContext);
}
void SampleDataModule::deinitialise()
{
SampleData::deinitialise();
d_sample->deinitialise();
}
void SampleDataModule::getSampleInstanceFromDLL()
{
// Version suffix for the dlls
static const CEGUI::String versionSuffix( "-" STRINGIZE(CEGUI_VERSION_MAJOR) "." STRINGIZE(CEGUI_VERSION_MINOR) );
CEGUI::DynamicModule* sampleModule = new CEGUI::DynamicModule(d_name + versionSuffix);
getSampleInstance functionPointerGetSample = (getSampleInstance)sampleModule->getSymbolAddress(CEGUI::String(GetSampleInstanceFuncName));
if(functionPointerGetSample == 0)
{
CEGUI::String errorMessage = "The sample creation function is not defined in the dynamic library of " + d_name;
CEGUI_THROW(CEGUI::InvalidRequestException(errorMessage.c_str()));
}
d_sample = &(functionPointerGetSample());
}<|endoftext|> |
<commit_before>#if !defined(__CINT__) || defined(__MAKECINT__)
#include <Rtypes.h>
#include <TString.h>
#include "AliAnalysisTaskHypertriton3.h"
#include "AliAnalysisManager.h"
#include "AliAnalysisDataContainer.h"
#include "AliMCEventHandler.h"
#include "AliPID.h"
#endif
AliAnalysisTaskHypertriton3 *AddTaskHypertriton3(Bool_t readMC=kFALSE, Bool_t fillTree=kFALSE){
// Creates, configures and attaches to the train the task for pi, K , p spectra
// with ITS standalone tracks
// Get the pointer to the existing analysis manager via the static access method.
//==============================================================================
::Info("AddTaskHypertriton3","Adding a new task with this settings readMC = %i",readMC);
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
::Error("AddTaskHypertriton3", "No analysis manager to connect to.");
return NULL;
}
// Check the analysis type using the event handlers connected to the analysis manager.
//==============================================================================
if (!mgr->GetInputEventHandler()) {
::Error("AddTaskHypertriton3", "This task requires an input event handler");
return NULL;
}
TString type = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"
if(type.Contains("AOD")){
::Error("AddTaskHypertriton3", "This task requires to run on ESD");
return NULL;
}
// Add MC handler (for kinematics)
if(readMC){
AliMCEventHandler* handler = new AliMCEventHandler;
handler->SetReadTR(kFALSE);
mgr->SetMCtruthEventHandler(handler);
}
// Create and configure the task
AliAnalysisTaskHypertriton3 *taskhyp = new AliAnalysisTaskHypertriton3();
taskhyp->SetReadMC(kFALSE);
taskhyp->SetFillTree(kFALSE);
mgr->AddTask(taskhyp);
// Create ONLY the output containers for the data produced by the task.
// Get and connect other common input/output containers via the manager as below
//==============================================================================
TString outputFileName = AliAnalysisManager::GetCommonFileName();
outputFileName += ":ESDHypertriton";
AliAnalysisDataContainer *coutput =0x0;
coutput = mgr->CreateContainer("listHypertriton",
TList::Class(),
AliAnalysisManager::kOutputContainer,
"trogolo_HyperTri.root" );
mgr->ConnectInput(taskhyp, 0, mgr->GetCommonInputContainer());
mgr->ConnectOutput(taskhyp, 1, coutput);
if(fillTree){
AliAnalysisDataContainer *coutput2 = mgr->CreateContainer("trogolo_HyperTree", TTree::Class(),
AliAnalysisManager::kOutputContainer,
"trogolo_HyperNt.root");
coutput2->SetSpecialOutput();
mgr->ConnectOutput(taskhyp, 2, coutput2);
}
return taskhyp;
}
<commit_msg>modify output file name<commit_after>#if !defined(__CINT__) || defined(__MAKECINT__)
#include <Rtypes.h>
#include <TString.h>
#include "AliAnalysisTaskHypertriton3.h"
#include "AliAnalysisManager.h"
#include "AliAnalysisDataContainer.h"
#include "AliMCEventHandler.h"
#include "AliPID.h"
#endif
AliAnalysisTaskHypertriton3 *AddTaskHypertriton3(Bool_t readMC=kFALSE, Bool_t fillTree=kFALSE){
// Creates, configures and attaches to the train the task for pi, K , p spectra
// with ITS standalone tracks
// Get the pointer to the existing analysis manager via the static access method.
//==============================================================================
::Info("AddTaskHypertriton3","Adding a new task with this settings readMC = %i",readMC);
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
::Error("AddTaskHypertriton3", "No analysis manager to connect to.");
return NULL;
}
// Check the analysis type using the event handlers connected to the analysis manager.
//==============================================================================
if (!mgr->GetInputEventHandler()) {
::Error("AddTaskHypertriton3", "This task requires an input event handler");
return NULL;
}
TString type = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"
if(type.Contains("AOD")){
::Error("AddTaskHypertriton3", "This task requires to run on ESD");
return NULL;
}
// Add MC handler (for kinematics)
if(readMC){
AliMCEventHandler* handler = new AliMCEventHandler;
handler->SetReadTR(kFALSE);
mgr->SetMCtruthEventHandler(handler);
}
// Create and configure the task
AliAnalysisTaskHypertriton3 *taskhyp = new AliAnalysisTaskHypertriton3();
taskhyp->SetReadMC(kFALSE);
taskhyp->SetFillTree(kFALSE);
mgr->AddTask(taskhyp);
// Create ONLY the output containers for the data produced by the task.
// Get and connect other common input/output containers via the manager as below
//==============================================================================
TString outputFileName = AliAnalysisManager::GetCommonFileName();
outputFileName += ":ESDHypertriton";
AliAnalysisDataContainer *coutput =0x0;
coutput = mgr->CreateContainer("listHypertriton",
TList::Class(),
AliAnalysisManager::kOutputContainer,
AliAnalysisManager::GetCommonFileName());
mgr->ConnectInput(taskhyp, 0, mgr->GetCommonInputContainer());
mgr->ConnectOutput(taskhyp, 1, coutput);
if(fillTree){
AliAnalysisDataContainer *coutput2 = mgr->CreateContainer("trogolo_HyperTree", TTree::Class(),
AliAnalysisManager::kOutputContainer,
"trogolo_HyperNt.root");
coutput2->SetSpecialOutput();
mgr->ConnectOutput(taskhyp, 2, coutput2);
}
return taskhyp;
}
<|endoftext|> |
<commit_before>#include <nan.h>
#include <v8.h>
#include <poppler.h>
#include <cairo.h>
#include <cairo-svg.h>
#include <vector>
namespace sspdf {
using v8::Local;
using v8::Value;
using v8::Function;
using v8::Exception;
using v8::Isolate;
using v8::Object;
using v8::Array;
using v8::Uint8Array;
using v8::ArrayBuffer;
using Nan::Callback;
using Nan::GetFunction;
using Nan::Set;
using Nan::Null;
using Nan::New;
using Nan::AsyncWorker;
using Nan::HandleScope;
using Nan::ThrowTypeError;
using Nan::Persistent;
using Nan::ObjectWrap;
using std::vector;
const char* MSG_EXCEPTION_ZEROLEN = "Zero length buffer provided.";
const char* MSG_EXCEPTION_PAGE_FAIL = "Unable to open that page.";
const char* MSG_EXCEPTION_PAGE_OUT_OF_RANGE = "Page index out of range.";
class PdfssWorker : public AsyncWorker {
public:
char* pdfData = NULL;
size_t pdfLen = 0;
double pw, ph;
char* txt;
PopplerRectangle* rects;
guint rectLen;
char* error = NULL; // Error stored here from {constructor, Execute} freed in HandleOKCallback.
int destPage;
vector<char> svgData;
// pdf data copied.
PdfssWorker(Callback* cb, Local<Uint8Array> hPdf, int destPage)
: AsyncWorker(cb) {
this->destPage = destPage;
this->pdfLen = (*hPdf)->ByteLength();
if (this->pdfLen == 0) {
this->error = new char[strlen(MSG_EXCEPTION_ZEROLEN)];
strcpy(this->error, MSG_EXCEPTION_ZEROLEN);
} else {
char* pdfData = (((char*)(*(*hPdf)->Buffer())->GetContents().Data())) + (*hPdf)->ByteOffset();
this->pdfData = new char[this->pdfLen];
memcpy(this->pdfData, pdfData, this->pdfLen);
}
}
void Execute () {
if (this->error != NULL) {
return;
}
GError* gerror = NULL;
PopplerDocument* popperDoc = poppler_document_new_from_data(this->pdfData, this->pdfLen, NULL, &gerror);
if (popperDoc == NULL) {
this->error = new char[strlen(gerror->message)];
strcpy(this->error, gerror->message);
g_error_free(gerror);
gerror = NULL;
return;
}
int nPages = poppler_document_get_n_pages(popperDoc);
if (this->destPage >= nPages) {
this->error = new char[strlen(MSG_EXCEPTION_PAGE_OUT_OF_RANGE)];
strcpy(this->error, MSG_EXCEPTION_PAGE_OUT_OF_RANGE);
g_object_unref(popperDoc);
return;
}
PopplerPage* page = poppler_document_get_page(popperDoc, this->destPage);
g_object_unref(popperDoc);
popperDoc = NULL;
if (page == NULL) {
this->error = new char[strlen(MSG_EXCEPTION_PAGE_FAIL)];
strcpy(this->error, MSG_EXCEPTION_PAGE_FAIL);
return;
}
poppler_page_get_size(page, &this->pw, &this->ph);
this->txt = poppler_page_get_text(page);
poppler_page_get_text_layout(page, &this->rects, &this->rectLen);
// this->rects require freeing by us, freed on HandleOKCallback.
cairo_surface_t* svgSurface = cairo_svg_surface_create_for_stream((cairo_write_func_t) PdfssWorker::writeFunc, this, this->pw, this->ph);
cairo_t* svg = cairo_create(svgSurface);
poppler_page_render(page, svg);
cairo_surface_destroy(svgSurface);
cairo_destroy(svg);
g_object_unref(page);
}
void HandleOKCallback () {
HandleScope scope;
Local<Object> obj;
Local<Array> rects;
Local<Value> argv[] = {
Null(), Null()
};
if (this->error == NULL) {
obj = New<Object>();
Set(obj, New<v8::String>("width").ToLocalChecked(), New<v8::Number>(this->pw));
Set(obj, New<v8::String>("height").ToLocalChecked(), New<v8::Number>(this->ph));
Set(obj, New<v8::String>("text").ToLocalChecked(), New<v8::String>(this->txt).ToLocalChecked());
rects = New<v8::Array>(this->rectLen);
for (guint i = 0; i < this->rectLen; i ++) {
Local<Object> xy = New<Object>();
Set(xy, New<v8::String>("x1").ToLocalChecked(), New<v8::Number>(this->rects[i].x1));
Set(xy, New<v8::String>("y1").ToLocalChecked(), New<v8::Number>(this->rects[i].y1));
Set(xy, New<v8::String>("x2").ToLocalChecked(), New<v8::Number>(this->rects[i].x2));
Set(xy, New<v8::String>("y2").ToLocalChecked(), New<v8::Number>(this->rects[i].y2));
Set(rects, New<v8::Number>(i), xy);
}
Set(obj, New<v8::String>("rects").ToLocalChecked(), rects);
g_free(this->rects);
g_free(this->txt);
argv[1] = obj;
if (this->svgData.size() > 0) {
auto ml = node::Buffer::Copy(Isolate::GetCurrent(), &(*this->svgData.begin()), this->svgData.size());
if (ml.IsEmpty()) {
argv[0] = v8::Exception::Error(New<v8::String>("Can't return svg data.").ToLocalChecked());
} else {
Set(obj, New<v8::String>("svg").ToLocalChecked(), ml.ToLocalChecked());
}
} else {
Set(obj, New<v8::String>("svg").ToLocalChecked(), Null());
}
} else {
argv[0] = v8::Exception::Error(New<v8::String>(this->error).ToLocalChecked());
delete this->error;
this->error = NULL;
}
this->callback->Call(2, argv);
if (this->pdfData != NULL) {
delete this->pdfData;
this->pdfData = NULL;
}
}
static cairo_status_t writeFunc (void* closure, const unsigned char* data, unsigned int length) {
PdfssWorker* worker = (PdfssWorker*) closure;
worker->svgData.reserve(worker->svgData.size() + length);
for (unsigned int i = 0; i < length; i ++) {
worker->svgData.push_back(data[i]);
}
return CAIRO_STATUS_SUCCESS;
}
};
NAN_METHOD(getPage) {
if (info.Length() != 3) {
ThrowTypeError("getPage(pdfBuffer, pageNum, callback)");
return;
}
if (!info[0]->IsUint8Array()) {
ThrowTypeError("arg[0] is not a buffer.");
return;
}
if (!info[1]->IsInt32()) {
ThrowTypeError("arg[1] is not a int32.");
return;
}
if (!info[2]->IsFunction()) {
ThrowTypeError("arg[2] is not a function.");
return;
}
int pn = (int)(*info[1].As<v8::Number>())->Value();
if (pn < 0) {
ThrowTypeError("arg[1] shouldn't be < 0.");
return;
}
auto pdfBuffer = info[0].As<Uint8Array>();
if (pdfBuffer.IsEmpty()) {
ThrowTypeError("arg[0] can't resolve.");
return;
}
Callback *callback = new Callback(info[2].As<Function>());
AsyncQueueWorker(new PdfssWorker(callback, pdfBuffer, pn));
}
NAN_MODULE_INIT(Init) {
Set(target
, New<v8::String>("getPage").ToLocalChecked()
, New<v8::FunctionTemplate>(getPage)->GetFunction());
}
NODE_MODULE(sspdf, Init)
}
<commit_msg>Looks like strlen don't count \0.<commit_after>#include <nan.h>
#include <v8.h>
#include <poppler.h>
#include <cairo.h>
#include <cairo-svg.h>
#include <vector>
namespace sspdf {
using v8::Local;
using v8::Value;
using v8::Function;
using v8::Exception;
using v8::Isolate;
using v8::Object;
using v8::Array;
using v8::Uint8Array;
using v8::ArrayBuffer;
using Nan::Callback;
using Nan::GetFunction;
using Nan::Set;
using Nan::Null;
using Nan::New;
using Nan::AsyncWorker;
using Nan::HandleScope;
using Nan::ThrowTypeError;
using Nan::Persistent;
using Nan::ObjectWrap;
using std::vector;
const char* MSG_EXCEPTION_ZEROLEN = "Zero length buffer provided.";
const char* MSG_EXCEPTION_PAGE_FAIL = "Unable to open that page.";
const char* MSG_EXCEPTION_PAGE_OUT_OF_RANGE = "Page index out of range.";
class PdfssWorker : public AsyncWorker {
public:
char* pdfData = NULL;
size_t pdfLen = 0;
double pw, ph;
char* txt;
PopplerRectangle* rects;
guint rectLen;
char* error = NULL; // Error stored here from {constructor, Execute} freed in HandleOKCallback.
int destPage;
vector<char> svgData;
// pdf data copied.
PdfssWorker(Callback* cb, Local<Uint8Array> hPdf, int destPage)
: AsyncWorker(cb) {
this->destPage = destPage;
this->pdfLen = (*hPdf)->ByteLength();
if (this->pdfLen == 0) {
this->error = new char[strlen(MSG_EXCEPTION_ZEROLEN) + 1];
strcpy(this->error, MSG_EXCEPTION_ZEROLEN);
} else {
char* pdfData = (((char*)(*(*hPdf)->Buffer())->GetContents().Data())) + (*hPdf)->ByteOffset();
this->pdfData = new char[this->pdfLen];
memcpy(this->pdfData, pdfData, this->pdfLen);
}
}
void Execute () {
if (this->error != NULL) {
return;
}
GError* gerror = NULL;
PopplerDocument* popperDoc = poppler_document_new_from_data(this->pdfData, this->pdfLen, NULL, &gerror);
if (popperDoc == NULL) {
this->error = new char[strlen(gerror->message) + 1];
strcpy(this->error, gerror->message);
g_error_free(gerror);
gerror = NULL;
return;
}
int nPages = poppler_document_get_n_pages(popperDoc);
if (this->destPage >= nPages) {
this->error = new char[strlen(MSG_EXCEPTION_PAGE_OUT_OF_RANGE) + 1];
strcpy(this->error, MSG_EXCEPTION_PAGE_OUT_OF_RANGE);
g_object_unref(popperDoc);
return;
}
PopplerPage* page = poppler_document_get_page(popperDoc, this->destPage);
g_object_unref(popperDoc);
popperDoc = NULL;
if (page == NULL) {
this->error = new char[strlen(MSG_EXCEPTION_PAGE_FAIL) + 1];
strcpy(this->error, MSG_EXCEPTION_PAGE_FAIL);
return;
}
poppler_page_get_size(page, &this->pw, &this->ph);
this->txt = poppler_page_get_text(page);
poppler_page_get_text_layout(page, &this->rects, &this->rectLen);
// this->rects require freeing by us, freed on HandleOKCallback.
cairo_surface_t* svgSurface = cairo_svg_surface_create_for_stream((cairo_write_func_t) PdfssWorker::writeFunc, this, this->pw, this->ph);
cairo_t* svg = cairo_create(svgSurface);
poppler_page_render(page, svg);
cairo_surface_destroy(svgSurface);
cairo_destroy(svg);
g_object_unref(page);
}
void HandleOKCallback () {
HandleScope scope;
Local<Object> obj;
Local<Array> rects;
Local<Value> argv[] = {
Null(), Null()
};
if (this->error == NULL) {
obj = New<Object>();
Set(obj, New<v8::String>("width").ToLocalChecked(), New<v8::Number>(this->pw));
Set(obj, New<v8::String>("height").ToLocalChecked(), New<v8::Number>(this->ph));
Set(obj, New<v8::String>("text").ToLocalChecked(), New<v8::String>(this->txt).ToLocalChecked());
rects = New<v8::Array>(this->rectLen);
for (guint i = 0; i < this->rectLen; i ++) {
Local<Object> xy = New<Object>();
Set(xy, New<v8::String>("x1").ToLocalChecked(), New<v8::Number>(this->rects[i].x1));
Set(xy, New<v8::String>("y1").ToLocalChecked(), New<v8::Number>(this->rects[i].y1));
Set(xy, New<v8::String>("x2").ToLocalChecked(), New<v8::Number>(this->rects[i].x2));
Set(xy, New<v8::String>("y2").ToLocalChecked(), New<v8::Number>(this->rects[i].y2));
Set(rects, New<v8::Number>(i), xy);
}
Set(obj, New<v8::String>("rects").ToLocalChecked(), rects);
g_free(this->rects);
g_free(this->txt);
argv[1] = obj;
if (this->svgData.size() > 0) {
auto ml = node::Buffer::Copy(Isolate::GetCurrent(), &(*this->svgData.begin()), this->svgData.size());
if (ml.IsEmpty()) {
argv[0] = v8::Exception::Error(New<v8::String>("Can't return svg data.").ToLocalChecked());
} else {
Set(obj, New<v8::String>("svg").ToLocalChecked(), ml.ToLocalChecked());
}
} else {
Set(obj, New<v8::String>("svg").ToLocalChecked(), Null());
}
} else {
argv[0] = v8::Exception::Error(New<v8::String>(this->error).ToLocalChecked());
delete this->error;
this->error = NULL;
}
this->callback->Call(2, argv);
if (this->pdfData != NULL) {
delete this->pdfData;
this->pdfData = NULL;
}
}
static cairo_status_t writeFunc (void* closure, const unsigned char* data, unsigned int length) {
PdfssWorker* worker = (PdfssWorker*) closure;
worker->svgData.reserve(worker->svgData.size() + length);
for (unsigned int i = 0; i < length; i ++) {
worker->svgData.push_back(data[i]);
}
return CAIRO_STATUS_SUCCESS;
}
};
NAN_METHOD(getPage) {
if (info.Length() != 3) {
ThrowTypeError("getPage(pdfBuffer, pageNum, callback)");
return;
}
if (!info[0]->IsUint8Array()) {
ThrowTypeError("arg[0] is not a buffer.");
return;
}
if (!info[1]->IsInt32()) {
ThrowTypeError("arg[1] is not a int32.");
return;
}
if (!info[2]->IsFunction()) {
ThrowTypeError("arg[2] is not a function.");
return;
}
int pn = (int)(*info[1].As<v8::Number>())->Value();
if (pn < 0) {
ThrowTypeError("arg[1] shouldn't be < 0.");
return;
}
auto pdfBuffer = info[0].As<Uint8Array>();
if (pdfBuffer.IsEmpty()) {
ThrowTypeError("arg[0] can't resolve.");
return;
}
Callback *callback = new Callback(info[2].As<Function>());
AsyncQueueWorker(new PdfssWorker(callback, pdfBuffer, pn));
}
NAN_MODULE_INIT(Init) {
Set(target
, New<v8::String>("getPage").ToLocalChecked()
, New<v8::FunctionTemplate>(getPage)->GetFunction());
}
NODE_MODULE(sspdf, Init)
}
<|endoftext|> |
<commit_before>/**
* @file
* @author 2012 Stefan Radomski ([email protected])
* @copyright Simplified BSD
*
* @cond
* This program is free software: you can redistribute it and/or modify
* it under the terms of the FreeBSD license as published by the FreeBSD
* project.
*
* 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.
*
* You should have received a copy of the FreeBSD license along with this
* program. If not, see <http://www.opensource.org/licenses/bsd-license>.
* @endcond
*/
#ifdef WIN32
#include <time.h>
#include <WinSock2.h>
#include <ws2tcpip.h>
#include <Windows.h>
#endif
#include "umundo/connection/zeromq/ZeroMQPublisher.h"
#include "umundo/connection/zeromq/ZeroMQNode.h"
#include "umundo/common/Message.h"
#include "umundo/common/UUID.h"
#include "umundo/config.h"
#if defined UNIX || defined IOS || defined IOSSIM
#include <string.h> // strlen, memcpy
#include <stdio.h> // snprintf
#endif
namespace umundo {
shared_ptr<Implementation> ZeroMQPublisher::create(void* facade) {
shared_ptr<Implementation> instance(new ZeroMQPublisher());
boost::static_pointer_cast<ZeroMQPublisher>(instance)->_facade = facade;
return instance;
}
void ZeroMQPublisher::destroy() {
delete(this);
}
void ZeroMQPublisher::init(shared_ptr<Configuration> config) {
_uuid = (_uuid.length() > 0 ? _uuid : UUID::getUUID());
_config = boost::static_pointer_cast<PublisherConfig>(config);
_transport = "tcp";
(_socket = zmq_socket(ZeroMQNode::getZeroMQContext(), ZMQ_XPUB)) || LOG_WARN("zmq_socket: %s",zmq_strerror(errno));
(_closer = zmq_socket(ZeroMQNode::getZeroMQContext(), ZMQ_SUB)) || LOG_WARN("zmq_socket: %s",zmq_strerror(errno));
zmq_setsockopt(_closer, ZMQ_SUBSCRIBE, _uuid.c_str(), _uuid.size()) && LOG_WARN("zmq_setsockopt: %s",zmq_strerror(errno));
int hwm = NET_ZEROMQ_SND_HWM;
zmq_setsockopt(_socket, ZMQ_SNDHWM, &hwm, sizeof(hwm)) && LOG_WARN("zmq_setsockopt: %s",zmq_strerror(errno));
std::stringstream ssInProc;
ssInProc << "inproc://" << _uuid;
zmq_bind(_socket, ssInProc.str().c_str()) && LOG_WARN("zmq_bind: %s",zmq_strerror(errno));
uint16_t port = 4242;
std::stringstream ssNet;
ssNet << _transport << "://*:" << port;
while(zmq_bind(_socket, ssNet.str().c_str()) < 0) {
switch(errno) {
case EADDRINUSE:
port++;
ssNet.clear(); // clear error bits
ssNet.str(string()); // reset string
ssNet << _transport << "://*:" << port;
break;
default:
LOG_WARN("zmq_bind: %s",zmq_strerror(errno));
Thread::sleepMs(100);
}
}
_port = port;
start();
LOG_INFO("creating publisher for %s on %s", _channelName.c_str(), ssNet.str().c_str());
LOG_DEBUG("creating publisher on %s", ssInProc.str().c_str());
}
ZeroMQPublisher::ZeroMQPublisher() {
}
ZeroMQPublisher::~ZeroMQPublisher() {
LOG_INFO("deleting publisher for %s", _channelName.c_str());
stop();
join();
zmq_close(_socket) && LOG_WARN("zmq_close: %s",zmq_strerror(errno));
zmq_close(_closer) && LOG_WARN("zmq_close: %s",zmq_strerror(errno));
}
void ZeroMQPublisher::join() {
UMUNDO_LOCK(_mutex);
stop();
std::stringstream ssInProc;
ssInProc << "inproc://" << _uuid;
zmq_connect(_closer, ssInProc.str().c_str()) && LOG_WARN("zmq_connect: %s", zmq_strerror(errno));
Thread::join();
UMUNDO_UNLOCK(_mutex);
}
void ZeroMQPublisher::suspend() {
if (_isSuspended)
return;
_isSuspended = true;
stop();
join();
zmq_close(_socket) && LOG_WARN("zmq_close: %s",zmq_strerror(errno));
zmq_close(_closer) && LOG_WARN("zmq_close: %s",zmq_strerror(errno));
}
void ZeroMQPublisher::resume() {
if (!_isSuspended)
return;
_isSuspended = false;
init(_config);
}
void ZeroMQPublisher::run() {
// read subscription requests from the pub socket
while(isStarted()) {
zmq_msg_t message;
zmq_msg_init(&message) && LOG_WARN("zmq_msg_init: %s", zmq_strerror(errno));
int rv;
{
ScopeLock lock(&_mutex);
while ((rv = zmq_recvmsg(_socket, &message, ZMQ_DONTWAIT)) < 0) {
if (errno == EAGAIN) // no messages available at the moment
break;
if (errno != EINTR)
LOG_WARN("zmq_recvmsg: %s",zmq_strerror(errno));
}
}
// zmq_recvmsg is blocking and we use an ipc socket _closer to unblock in join() - not needed as we use ZMQ_DONTWAIT
//if (!isStarted()) {
// zmq_msg_close(&message) && LOG_WARN("zmq_msg_close: %s", zmq_strerror(errno));
// return;
//}
if (rv > 0) {
size_t msgSize = zmq_msg_size(&message);
// every subscriber will sent its uuid as a subscription as well
if (msgSize == 37) {
//ScopeLock lock(&_mutex);
char* data = (char*)zmq_msg_data(&message);
bool subscription = (data[0] == 0x1);
char* subId = data+1;
subId[msgSize - 1] = 0;
if (subscription) {
LOG_INFO("%s received ZMQ subscription from %s", _channelName.c_str(), subId);
_pendingZMQSubscriptions.insert(subId);
addedSubscriber("", subId);
} else {
LOG_INFO("%s received ZMQ unsubscription from %s", _channelName.c_str(), subId);
}
}
// zmq_msg_close(&message) && LOG_WARN("zmq_msg_close: %s", zmq_strerror(errno));
} else {
Thread::sleepMs(50);
}
}
}
/**
* Block until we have a given number of subscribers.
*/
int ZeroMQPublisher::waitForSubscribers(int count, int timeoutMs) {
while (_subscriptions.size() < (unsigned int)count) {
UMUNDO_WAIT(_pubLock);
#ifdef WIN32
// even after waiting for the signal from ZMQ subscriptions Windows needs a moment
//Thread::sleepMs(300);
#endif
}
return _subscriptions.size();
}
void ZeroMQPublisher::addedSubscriber(const string remoteId, const string subId) {
ScopeLock lock(&_mutex);
// ZeroMQPublisher::run calls us without a remoteId
if (remoteId.length() != 0) {
// we already know about this subscription
if (_pendingSubscriptions.find(subId) != _pendingSubscriptions.end())
return;
_pendingSubscriptions[subId] = remoteId;
}
// if we received a subscription from xpub and the node socket
if (_pendingSubscriptions.find(subId) == _pendingSubscriptions.end() ||
_pendingZMQSubscriptions.find(subId) == _pendingZMQSubscriptions.end()) {
return;
}
_subscriptions[subId] = _pendingSubscriptions[subId];
_pendingSubscriptions.erase(subId);
_pendingZMQSubscriptions.erase(subId);
if (_greeter != NULL)
_greeter->welcome((Publisher*)_facade, _pendingSubscriptions[subId], subId);
UMUNDO_SIGNAL(_pubLock);
}
void ZeroMQPublisher::removedSubscriber(const string remoteId, const string subId) {
ScopeLock lock(&_mutex);
assert(_subscriptions.find(subId) != _subscriptions.end());
_subscriptions.erase(subId);
if (_greeter != NULL)
_greeter->farewell((Publisher*)_facade, _pendingSubscriptions[subId], subId);
UMUNDO_SIGNAL(_pubLock);
}
void ZeroMQPublisher::send(Message* msg) {
//LOG_DEBUG("ZeroMQPublisher sending msg on %s", _channelName.c_str());
if (_isSuspended) {
LOG_WARN("Not sending message on suspended publisher");
return;
}
// topic name or explicit subscriber id is first message in envelope
zmq_msg_t channelEnvlp;
if (msg->getMeta().find("subscriber") != msg->getMeta().end()) {
// explicit destination
ZMQ_PREPARE_STRING(channelEnvlp, msg->getMeta("subscriber").c_str(), msg->getMeta("subscriber").size());
} else {
// everyone on channel
ZMQ_PREPARE_STRING(channelEnvlp, _channelName.c_str(), _channelName.size());
}
zmq_sendmsg(_socket, &channelEnvlp, ZMQ_SNDMORE) >= 0 || LOG_WARN("zmq_sendmsg: %s",zmq_strerror(errno));
zmq_msg_close(&channelEnvlp) && LOG_WARN("zmq_msg_close: %s",zmq_strerror(errno));
// mandatory meta fields
msg->putMeta("publisher", _uuid);
msg->putMeta("proc", procUUID);
// all our meta information
map<string, string>::const_iterator metaIter;
for (metaIter = msg->getMeta().begin(); metaIter != msg->getMeta().end(); metaIter++) {
// string key(metaIter->first);
// string value(metaIter->second);
// std::cout << key << ": " << value << std::endl;
// string length of key + value + two null bytes as string delimiters
size_t metaSize = (metaIter->first).length() + (metaIter->second).length() + 2;
zmq_msg_t metaMsg;
ZMQ_PREPARE(metaMsg, metaSize);
char* writePtr = (char*)zmq_msg_data(&metaMsg);
memcpy(writePtr, (metaIter->first).data(), (metaIter->first).length());
// indexes start at zero, so length is the byte after the string
((char*)zmq_msg_data(&metaMsg))[(metaIter->first).length()] = '\0';
assert(strlen((char*)zmq_msg_data(&metaMsg)) == (metaIter->first).length());
assert(strlen(writePtr) == (metaIter->first).length()); // just to be sure
// increment write pointer
writePtr += (metaIter->first).length() + 1;
memcpy(writePtr,
(metaIter->second).data(),
(metaIter->second).length());
// first string + null byte + second string
((char*)zmq_msg_data(&metaMsg))[(metaIter->first).length() + 1 + (metaIter->second).length()] = '\0';
assert(strlen(writePtr) == (metaIter->second).length());
zmq_sendmsg(_socket, &metaMsg, ZMQ_SNDMORE) >= 0 || LOG_WARN("zmq_sendmsg: %s",zmq_strerror(errno));
zmq_msg_close(&metaMsg) && LOG_WARN("zmq_msg_close: %s",zmq_strerror(errno));
}
// data as the second part of a multipart message
zmq_msg_t publication;
ZMQ_PREPARE_DATA(publication, msg->data(), msg->size());
zmq_sendmsg(_socket, &publication, 0) >= 0 || LOG_WARN("zmq_sendmsg: %s",zmq_strerror(errno));
zmq_msg_close(&publication) && LOG_WARN("zmq_msg_close: %s",zmq_strerror(errno));
}
}<commit_msg>Added todo<commit_after>/**
* @file
* @author 2012 Stefan Radomski ([email protected])
* @copyright Simplified BSD
*
* @cond
* This program is free software: you can redistribute it and/or modify
* it under the terms of the FreeBSD license as published by the FreeBSD
* project.
*
* 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.
*
* You should have received a copy of the FreeBSD license along with this
* program. If not, see <http://www.opensource.org/licenses/bsd-license>.
* @endcond
*/
#ifdef WIN32
#include <time.h>
#include <WinSock2.h>
#include <ws2tcpip.h>
#include <Windows.h>
#endif
#include "umundo/connection/zeromq/ZeroMQPublisher.h"
#include "umundo/connection/zeromq/ZeroMQNode.h"
#include "umundo/common/Message.h"
#include "umundo/common/UUID.h"
#include "umundo/config.h"
#if defined UNIX || defined IOS || defined IOSSIM
#include <string.h> // strlen, memcpy
#include <stdio.h> // snprintf
#endif
namespace umundo {
shared_ptr<Implementation> ZeroMQPublisher::create(void* facade) {
shared_ptr<Implementation> instance(new ZeroMQPublisher());
boost::static_pointer_cast<ZeroMQPublisher>(instance)->_facade = facade;
return instance;
}
void ZeroMQPublisher::destroy() {
delete(this);
}
void ZeroMQPublisher::init(shared_ptr<Configuration> config) {
_uuid = (_uuid.length() > 0 ? _uuid : UUID::getUUID());
_config = boost::static_pointer_cast<PublisherConfig>(config);
_transport = "tcp";
/// @todo: We might want all publishers to share only a few sockets
(_socket = zmq_socket(ZeroMQNode::getZeroMQContext(), ZMQ_XPUB)) || LOG_WARN("zmq_socket: %s",zmq_strerror(errno));
(_closer = zmq_socket(ZeroMQNode::getZeroMQContext(), ZMQ_SUB)) || LOG_WARN("zmq_socket: %s",zmq_strerror(errno));
zmq_setsockopt(_closer, ZMQ_SUBSCRIBE, _uuid.c_str(), _uuid.size()) && LOG_WARN("zmq_setsockopt: %s",zmq_strerror(errno));
int hwm = NET_ZEROMQ_SND_HWM;
zmq_setsockopt(_socket, ZMQ_SNDHWM, &hwm, sizeof(hwm)) && LOG_WARN("zmq_setsockopt: %s",zmq_strerror(errno));
std::stringstream ssInProc;
ssInProc << "inproc://" << _uuid;
zmq_bind(_socket, ssInProc.str().c_str()) && LOG_WARN("zmq_bind: %s",zmq_strerror(errno));
uint16_t port = 4242;
std::stringstream ssNet;
ssNet << _transport << "://*:" << port;
while(zmq_bind(_socket, ssNet.str().c_str()) < 0) {
switch(errno) {
case EADDRINUSE:
port++;
ssNet.clear(); // clear error bits
ssNet.str(string()); // reset string
ssNet << _transport << "://*:" << port;
break;
default:
LOG_WARN("zmq_bind: %s",zmq_strerror(errno));
Thread::sleepMs(100);
}
}
_port = port;
start();
LOG_INFO("creating publisher for %s on %s", _channelName.c_str(), ssNet.str().c_str());
LOG_DEBUG("creating publisher on %s", ssInProc.str().c_str());
}
ZeroMQPublisher::ZeroMQPublisher() {
}
ZeroMQPublisher::~ZeroMQPublisher() {
LOG_INFO("deleting publisher for %s", _channelName.c_str());
stop();
join();
zmq_close(_socket) && LOG_WARN("zmq_close: %s",zmq_strerror(errno));
zmq_close(_closer) && LOG_WARN("zmq_close: %s",zmq_strerror(errno));
}
void ZeroMQPublisher::join() {
UMUNDO_LOCK(_mutex);
stop();
std::stringstream ssInProc;
ssInProc << "inproc://" << _uuid;
zmq_connect(_closer, ssInProc.str().c_str()) && LOG_WARN("zmq_connect: %s", zmq_strerror(errno));
Thread::join();
UMUNDO_UNLOCK(_mutex);
}
void ZeroMQPublisher::suspend() {
if (_isSuspended)
return;
_isSuspended = true;
stop();
join();
zmq_close(_socket) && LOG_WARN("zmq_close: %s",zmq_strerror(errno));
zmq_close(_closer) && LOG_WARN("zmq_close: %s",zmq_strerror(errno));
}
void ZeroMQPublisher::resume() {
if (!_isSuspended)
return;
_isSuspended = false;
init(_config);
}
void ZeroMQPublisher::run() {
// read subscription requests from the pub socket
while(isStarted()) {
zmq_msg_t message;
zmq_msg_init(&message) && LOG_WARN("zmq_msg_init: %s", zmq_strerror(errno));
int rv;
{
ScopeLock lock(&_mutex);
while ((rv = zmq_recvmsg(_socket, &message, ZMQ_DONTWAIT)) < 0) {
if (errno == EAGAIN) // no messages available at the moment
break;
if (errno != EINTR)
LOG_WARN("zmq_recvmsg: %s",zmq_strerror(errno));
}
}
// zmq_recvmsg is blocking and we use an ipc socket _closer to unblock in join() - not needed as we use ZMQ_DONTWAIT
//if (!isStarted()) {
// zmq_msg_close(&message) && LOG_WARN("zmq_msg_close: %s", zmq_strerror(errno));
// return;
//}
if (rv > 0) {
size_t msgSize = zmq_msg_size(&message);
// every subscriber will sent its uuid as a subscription as well
if (msgSize == 37) {
//ScopeLock lock(&_mutex);
char* data = (char*)zmq_msg_data(&message);
bool subscription = (data[0] == 0x1);
char* subId = data+1;
subId[msgSize - 1] = 0;
if (subscription) {
LOG_INFO("%s received ZMQ subscription from %s", _channelName.c_str(), subId);
_pendingZMQSubscriptions.insert(subId);
addedSubscriber("", subId);
} else {
LOG_INFO("%s received ZMQ unsubscription from %s", _channelName.c_str(), subId);
}
}
// zmq_msg_close(&message) && LOG_WARN("zmq_msg_close: %s", zmq_strerror(errno));
} else {
Thread::sleepMs(50);
}
}
}
/**
* Block until we have a given number of subscribers.
*/
int ZeroMQPublisher::waitForSubscribers(int count, int timeoutMs) {
while (_subscriptions.size() < (unsigned int)count) {
UMUNDO_WAIT(_pubLock);
#ifdef WIN32
// even after waiting for the signal from ZMQ subscriptions Windows needs a moment
//Thread::sleepMs(300);
#endif
}
return _subscriptions.size();
}
void ZeroMQPublisher::addedSubscriber(const string remoteId, const string subId) {
ScopeLock lock(&_mutex);
// ZeroMQPublisher::run calls us without a remoteId
if (remoteId.length() != 0) {
// we already know about this subscription
if (_pendingSubscriptions.find(subId) != _pendingSubscriptions.end())
return;
_pendingSubscriptions[subId] = remoteId;
}
// if we received a subscription from xpub and the node socket
if (_pendingSubscriptions.find(subId) == _pendingSubscriptions.end() ||
_pendingZMQSubscriptions.find(subId) == _pendingZMQSubscriptions.end()) {
return;
}
_subscriptions[subId] = _pendingSubscriptions[subId];
_pendingSubscriptions.erase(subId);
_pendingZMQSubscriptions.erase(subId);
if (_greeter != NULL)
_greeter->welcome((Publisher*)_facade, _pendingSubscriptions[subId], subId);
UMUNDO_SIGNAL(_pubLock);
}
void ZeroMQPublisher::removedSubscriber(const string remoteId, const string subId) {
ScopeLock lock(&_mutex);
assert(_subscriptions.find(subId) != _subscriptions.end());
_subscriptions.erase(subId);
if (_greeter != NULL)
_greeter->farewell((Publisher*)_facade, _pendingSubscriptions[subId], subId);
UMUNDO_SIGNAL(_pubLock);
}
void ZeroMQPublisher::send(Message* msg) {
//LOG_DEBUG("ZeroMQPublisher sending msg on %s", _channelName.c_str());
if (_isSuspended) {
LOG_WARN("Not sending message on suspended publisher");
return;
}
// topic name or explicit subscriber id is first message in envelope
zmq_msg_t channelEnvlp;
if (msg->getMeta().find("subscriber") != msg->getMeta().end()) {
// explicit destination
ZMQ_PREPARE_STRING(channelEnvlp, msg->getMeta("subscriber").c_str(), msg->getMeta("subscriber").size());
} else {
// everyone on channel
ZMQ_PREPARE_STRING(channelEnvlp, _channelName.c_str(), _channelName.size());
}
zmq_sendmsg(_socket, &channelEnvlp, ZMQ_SNDMORE) >= 0 || LOG_WARN("zmq_sendmsg: %s",zmq_strerror(errno));
zmq_msg_close(&channelEnvlp) && LOG_WARN("zmq_msg_close: %s",zmq_strerror(errno));
// mandatory meta fields
msg->putMeta("publisher", _uuid);
msg->putMeta("proc", procUUID);
// all our meta information
map<string, string>::const_iterator metaIter;
for (metaIter = msg->getMeta().begin(); metaIter != msg->getMeta().end(); metaIter++) {
// string key(metaIter->first);
// string value(metaIter->second);
// std::cout << key << ": " << value << std::endl;
// string length of key + value + two null bytes as string delimiters
size_t metaSize = (metaIter->first).length() + (metaIter->second).length() + 2;
zmq_msg_t metaMsg;
ZMQ_PREPARE(metaMsg, metaSize);
char* writePtr = (char*)zmq_msg_data(&metaMsg);
memcpy(writePtr, (metaIter->first).data(), (metaIter->first).length());
// indexes start at zero, so length is the byte after the string
((char*)zmq_msg_data(&metaMsg))[(metaIter->first).length()] = '\0';
assert(strlen((char*)zmq_msg_data(&metaMsg)) == (metaIter->first).length());
assert(strlen(writePtr) == (metaIter->first).length()); // just to be sure
// increment write pointer
writePtr += (metaIter->first).length() + 1;
memcpy(writePtr,
(metaIter->second).data(),
(metaIter->second).length());
// first string + null byte + second string
((char*)zmq_msg_data(&metaMsg))[(metaIter->first).length() + 1 + (metaIter->second).length()] = '\0';
assert(strlen(writePtr) == (metaIter->second).length());
zmq_sendmsg(_socket, &metaMsg, ZMQ_SNDMORE) >= 0 || LOG_WARN("zmq_sendmsg: %s",zmq_strerror(errno));
zmq_msg_close(&metaMsg) && LOG_WARN("zmq_msg_close: %s",zmq_strerror(errno));
}
// data as the second part of a multipart message
zmq_msg_t publication;
ZMQ_PREPARE_DATA(publication, msg->data(), msg->size());
zmq_sendmsg(_socket, &publication, 0) >= 0 || LOG_WARN("zmq_sendmsg: %s",zmq_strerror(errno));
zmq_msg_close(&publication) && LOG_WARN("zmq_msg_close: %s",zmq_strerror(errno));
}
}<|endoftext|> |
<commit_before>/*
Implementation of the Compiler class.
*/
#include <cctype> //character comparison functions
#include <stdexcept>
#include <assert.h>
#include "compiler.hh"
namespace ds_compiler {
const size_t Compiler::NUM_REGISTERS = 8;
const char Compiler::ERR_CHAR = '\0';
const std::unordered_set<char> Compiler::ADD_OPS({'+', '-'});
const std::unordered_set<char> Compiler::MULT_OPS({'*', '/'});
//constructors
Compiler::Compiler (std::ostream& output)
: m_input_stream (std::ios::in|std::ios::out), m_output_stream(output)
{
}
void Compiler::compile_intermediate (const std::string input_line) {
//clear contents and error flags on m_input_stream
m_input_stream.str("");
m_input_stream.clear();
m_input_stream << input_line;
try {
start_symbol();
} catch (std::exception &ex) {
std::cerr << ex.what() << '\n';
throw std::runtime_error("Compilation failed.\n");
}
}
void Compiler::compile_full (const std::vector<std::string> source, const std::string class_name) {
compile_start(class_name);
for (auto line : source) {
compile_intermediate(line);
}
compile_end();
}
void Compiler::compile_start (const std::string class_name) const {
add_includes();
//begin class declaration, qualify everything as public
emit_line("class "+ class_name + "{");
emit_line("public:");
define_member_variables();
define_constructor(class_name);
define_cpu_pop();
define_getters();
emit_line("void run() {"); //begin definition of run()
}
void Compiler::compile_end () const {
//TODO - should I assert that cpu_stack is empty?
emit_line("}"); //end definition of run()
define_dump();
emit_line("};"); //close class declaration
}
void Compiler::add_includes() const {
emit_line("#include <stack>");
emit_line("#include <vector>");
emit_line("#include <iostream>");
emit_line("#include <string>");
emit_line("#include <unordered_map>");
}
void Compiler::define_member_variables() const {
emit_line("std::stack<int> cpu_stack;");
emit_line("std::vector<int> cpu_registers;");
emit_line("std::unordered_map<char, int> cpu_variables;");
}
void Compiler::define_constructor(const std::string class_name) const {
emit_line(class_name + "() ");
emit_line(": cpu_stack()");
emit_line(", cpu_registers(" + std::to_string(NUM_REGISTERS) + ", 0)");
emit_line(", cpu_variables()");
emit_line("{}");
}
//emit definition of a function for easier stack handling
void Compiler::define_cpu_pop() const {
emit_line("int cpu_pop() {");
emit_line("int val = cpu_stack.top();");
emit_line("cpu_stack.pop();");
emit_line("return val; }");
}
void Compiler::define_getters() const {
emit_line("int get_register(int index) {");
emit_line("return cpu_registers.at(index);}");
emit_line("int get_variable(char var_name) {");
emit_line("return cpu_variables.at(var_name);}");
//no getter for stack; stack should always be empty
}
void define_is_stack_empty() const {
emit_line("bool is_stack_empty() {");
emit_line("return cpu_stack.empty();}");
}
void Compiler::define_dump() const {
//TODO - are these dumps necessary?
emit_line("void dump () {");
emit_line("std::cout << \"Register contents\\n\";");
emit_line("for (int i = 0; i < " + std::to_string(NUM_REGISTERS) + "; ++i)");
emit_line("std::cout << std::string(\"Register \") << i << \": \" << cpu_registers.at(i) << '\\n';");
emit_line("std::cout << \"Stack contents (top to bottom)\\n\";");
emit_line("while (!cpu_stack.empty()) {");
emit_line("std::cout << cpu_stack.top() << '\\n';");
emit_line("cpu_stack.pop();}");
emit_line("std::cout << \"Variable contents\\n\";");
emit_line("for (auto i = cpu_variables.begin(); i != cpu_variables.end(); ++i)");
emit_line("std::cout << \"cpu_variables[\" << i->first << \"] = \" << i->second << '\\n';");
emit_line("}");
}
void Compiler::start_symbol () {
}
//cradle methods
void Compiler::report_error(const std::string err) const {
m_output_stream << '\n';
m_output_stream << "Error: " << err << '\n';
}
void Compiler::abort(const std::string err) const {
report_error(err);
throw std::runtime_error("Compilation failed.\n");
}
void Compiler::expected(const std::string expect) const {
abort(expect + " expected.\n");
}
//overload to handle single characters;
//prevents having to construct a string whenever calling expected()
void Compiler::expected(const char c) const {
expected(std::string(1, c));
}
//checks if next character matches; if so, consume that character
void Compiler::match(const char c) {
if (m_input_stream.peek() == c) {
m_input_stream.get();
} else {
expected(c);
}
}
// gets a valid identifier from input stream
char Compiler::get_name () {
if (!std::isalpha(m_input_stream.peek())) {
expected("Name");
return ERR_CHAR;
} else {
return std::toupper(m_input_stream.get());
}
}
//gets a number
char Compiler::get_num () {
if (!std::isdigit(m_input_stream.peek())) {
expected("Integer");
return ERR_CHAR;
} else {
return m_input_stream.get();
}
}
//output a string
void Compiler::emit (std::string s) const {
m_output_stream << s;
}
//output a string with newline
void Compiler::emit_line (std::string s) const {
emit(s);
emit("\n");
}
bool Compiler::is_in(const char elem, const std::unordered_set<char> us) {
return us.find(elem) != us.end();
}
} //end namespace<commit_msg>Added call to define_is_stack_empty() in compile_start()<commit_after>/*
Implementation of the Compiler class.
*/
#include <cctype> //character comparison functions
#include <stdexcept>
#include <assert.h>
#include "compiler.hh"
namespace ds_compiler {
const size_t Compiler::NUM_REGISTERS = 8;
const char Compiler::ERR_CHAR = '\0';
const std::unordered_set<char> Compiler::ADD_OPS({'+', '-'});
const std::unordered_set<char> Compiler::MULT_OPS({'*', '/'});
//constructors
Compiler::Compiler (std::ostream& output)
: m_input_stream (std::ios::in|std::ios::out), m_output_stream(output)
{
}
void Compiler::compile_intermediate (const std::string input_line) {
//clear contents and error flags on m_input_stream
m_input_stream.str("");
m_input_stream.clear();
m_input_stream << input_line;
try {
start_symbol();
} catch (std::exception &ex) {
std::cerr << ex.what() << '\n';
throw std::runtime_error("Compilation failed.\n");
}
}
void Compiler::compile_full (const std::vector<std::string> source, const std::string class_name) {
compile_start(class_name);
for (auto line : source) {
compile_intermediate(line);
}
compile_end();
}
void Compiler::compile_start (const std::string class_name) const {
add_includes();
//begin class declaration, qualify everything as public
emit_line("class "+ class_name + "{");
emit_line("public:");
define_member_variables();
define_constructor(class_name);
define_cpu_pop();
define_getters();
define_is_stack_empty();
emit_line("void run() {"); //begin definition of run()
}
void Compiler::compile_end () const {
//TODO - should I assert that cpu_stack is empty?
emit_line("}"); //end definition of run()
define_dump();
emit_line("};"); //close class definition
}
void Compiler::add_includes() const {
emit_line("#include <stack>");
emit_line("#include <vector>");
emit_line("#include <iostream>");
emit_line("#include <string>");
emit_line("#include <unordered_map>");
}
void Compiler::define_member_variables() const {
emit_line("std::stack<int> cpu_stack;");
emit_line("std::vector<int> cpu_registers;");
emit_line("std::unordered_map<char, int> cpu_variables;");
}
void Compiler::define_constructor(const std::string class_name) const {
emit_line(class_name + "() ");
emit_line(": cpu_stack()");
emit_line(", cpu_registers(" + std::to_string(NUM_REGISTERS) + ", 0)");
emit_line(", cpu_variables()");
emit_line("{}");
}
//emit definition of a function for easier stack handling
void Compiler::define_cpu_pop() const {
emit_line("int cpu_pop() {");
emit_line("int val = cpu_stack.top();");
emit_line("cpu_stack.pop();");
emit_line("return val; }");
}
void Compiler::define_getters() const {
emit_line("int get_register(int index) {");
emit_line("return cpu_registers.at(index);}");
emit_line("int get_variable(char var_name) {");
emit_line("return cpu_variables.at(var_name);}");
//no getter for stack; stack should always be empty
}
void Compiler::define_is_stack_empty() const {
emit_line("bool is_stack_empty() {");
emit_line("return cpu_stack.empty();}");
}
void Compiler::define_dump() const {
//TODO - are these dumps necessary?
emit_line("void dump () {");
emit_line("std::cout << \"Register contents\\n\";");
emit_line("for (int i = 0; i < " + std::to_string(NUM_REGISTERS) + "; ++i)");
emit_line("std::cout << std::string(\"Register \") << i << \": \" << cpu_registers.at(i) << '\\n';");
emit_line("std::cout << \"Stack contents (top to bottom)\\n\";");
emit_line("while (!cpu_stack.empty()) {");
emit_line("std::cout << cpu_stack.top() << '\\n';");
emit_line("cpu_stack.pop();}");
emit_line("std::cout << \"Variable contents\\n\";");
emit_line("for (auto i = cpu_variables.begin(); i != cpu_variables.end(); ++i)");
emit_line("std::cout << \"cpu_variables[\" << i->first << \"] = \" << i->second << '\\n';");
emit_line("}");
}
void Compiler::start_symbol () {
}
//cradle methods
void Compiler::report_error(const std::string err) const {
m_output_stream << '\n';
m_output_stream << "Error: " << err << '\n';
}
void Compiler::abort(const std::string err) const {
report_error(err);
throw std::runtime_error("Compilation failed.\n");
}
void Compiler::expected(const std::string expect) const {
abort(expect + " expected.\n");
}
//overload to handle single characters;
//prevents having to construct a string whenever calling expected()
void Compiler::expected(const char c) const {
expected(std::string(1, c));
}
//checks if next character matches; if so, consume that character
void Compiler::match(const char c) {
if (m_input_stream.peek() == c) {
m_input_stream.get();
} else {
expected(c);
}
}
// gets a valid identifier from input stream
char Compiler::get_name () {
if (!std::isalpha(m_input_stream.peek())) {
expected("Name");
return ERR_CHAR;
} else {
return std::toupper(m_input_stream.get());
}
}
//gets a number
char Compiler::get_num () {
if (!std::isdigit(m_input_stream.peek())) {
expected("Integer");
return ERR_CHAR;
} else {
return m_input_stream.get();
}
}
//output a string
void Compiler::emit (std::string s) const {
m_output_stream << s;
}
//output a string with newline
void Compiler::emit_line (std::string s) const {
emit(s);
emit("\n");
}
bool Compiler::is_in(const char elem, const std::unordered_set<char> us) {
return us.find(elem) != us.end();
}
} //end namespace<|endoftext|> |
<commit_before>// Copyright (c) 2011-2012 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "sync.h"
#include "util.h"
#include "utilstrencodings.h"
#include <stdio.h>
#include <boost/foreach.hpp>
#include <boost/thread.hpp>
#ifdef DEBUG_LOCKCONTENTION
void PrintLockContention(const char* pszName, const char* pszFile, int nLine)
{
LogPrintf("LOCKCONTENTION: %s\n", pszName);
LogPrintf("Locker: %s:%d\n", pszFile, nLine);
}
#endif /* DEBUG_LOCKCONTENTION */
#ifdef DEBUG_LOCKORDER
//
// Early deadlock detection.
// Problem being solved:
// Thread 1 locks A, then B, then C
// Thread 2 locks D, then C, then A
// --> may result in deadlock between the two threads, depending on when they run.
// Solution implemented here:
// Keep track of pairs of locks: (A before B), (A before C), etc.
// Complain if any thread tries to lock in a different order.
//
struct CLockLocation {
CLockLocation(const char* pszName, const char* pszFile, int nLine, bool fTryIn)
{
mutexName = pszName;
sourceFile = pszFile;
sourceLine = nLine;
fTry = fTryIn;
}
std::string ToString() const
{
return mutexName + " " + sourceFile + ":" + itostr(sourceLine) + (fTry ? " (TRY)" : "");
}
std::string MutexName() const { return mutexName; }
bool fTry;
private:
std::string mutexName;
std::string sourceFile;
int sourceLine;
};
typedef std::vector<std::pair<void*, CLockLocation> > LockStack;
static boost::mutex dd_mutex;
static std::map<std::pair<void*, void*>, LockStack> lockorders;
static boost::thread_specific_ptr<LockStack> lockstack;
static void potential_deadlock_detected(const std::pair<void*, void*>& mismatch, const LockStack& s1, const LockStack& s2)
{
// We attempt to not assert on probably-not deadlocks by assuming that
// a try lock will immediately have otherwise bailed if it had
// failed to get the lock
// We do this by, for the locks which triggered the potential deadlock,
// in either lockorder, checking that the second of the two which is locked
// is only a TRY_LOCK, ignoring locks if they are reentrant.
bool firstLocked = false;
bool secondLocked = false;
bool onlyMaybeDeadlock = false;
LogPrintf("POTENTIAL DEADLOCK DETECTED\n");
LogPrintf("Previous lock order was:\n");
BOOST_FOREACH (const PAIRTYPE(void*, CLockLocation) & i, s2) {
if (i.first == mismatch.first) {
LogPrintf(" (1)");
if (!firstLocked && secondLocked && i.second.fTry)
onlyMaybeDeadlock = true;
firstLocked = true;
}
if (i.first == mismatch.second) {
LogPrintf(" (2)");
if (!secondLocked && firstLocked && i.second.fTry)
onlyMaybeDeadlock = true;
secondLocked = true;
}
LogPrintf(" %s\n", i.second.ToString());
}
firstLocked = false;
secondLocked = false;
LogPrintf("Current lock order is:\n");
BOOST_FOREACH (const PAIRTYPE(void*, CLockLocation) & i, s1) {
if (i.first == mismatch.first) {
LogPrintf(" (1)");
if (!firstLocked && secondLocked && i.second.fTry)
onlyMaybeDeadlock = true;
firstLocked = true;
}
if (i.first == mismatch.second) {
LogPrintf(" (2)");
if (!secondLocked && firstLocked && i.second.fTry)
onlyMaybeDeadlock = true;
secondLocked = true;
}
LogPrintf(" %s\n", i.second.ToString());
}
assert(onlyMaybeDeadlock);
}
static void push_lock(void* c, const CLockLocation& locklocation, bool fTry)
{
if (lockstack.get() == NULL)
lockstack.reset(new LockStack);
dd_mutex.lock();
(*lockstack).push_back(std::make_pair(c, locklocation));
if (!fTry) {
BOOST_FOREACH (const PAIRTYPE(void*, CLockLocation) & i, (*lockstack)) {
if (i.first == c)
break;
std::pair<void*, void*> p1 = std::make_pair(i.first, c);
if (lockorders.count(p1))
continue;
lockorders[p1] = (*lockstack);
std::pair<void*, void*> p2 = std::make_pair(c, i.first);
if (lockorders.count(p2))
potential_deadlock_detected(p1, lockorders[p2], lockorders[p1]);
}
}
dd_mutex.unlock();
}
static void pop_lock()
{
dd_mutex.lock();
(*lockstack).pop_back();
dd_mutex.unlock();
}
void EnterCritical(const char* pszName, const char* pszFile, int nLine, void* cs, bool fTry)
{
push_lock(cs, CLockLocation(pszName, pszFile, nLine, fTry), fTry);
}
void LeaveCritical()
{
pop_lock();
}
std::string LocksHeld()
{
std::string result;
BOOST_FOREACH (const PAIRTYPE(void*, CLockLocation) & i, *lockstack)
result += i.second.ToString() + std::string("\n");
return result;
}
void AssertLockHeldInternal(const char* pszName, const char* pszFile, int nLine, void* cs)
{
BOOST_FOREACH (const PAIRTYPE(void*, CLockLocation) & i, *lockstack)
if (i.first == cs)
return;
fprintf(stderr, "Assertion failed: lock %s not held in %s:%i; locks held:\n%s", pszName, pszFile, nLine, LocksHeld().c_str());
abort();
}
#endif /* DEBUG_LOCKORDER */
<commit_msg>Revert "Assert on probable deadlocks if the second lock isnt try_lock"<commit_after>// Copyright (c) 2011-2012 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "sync.h"
#include "util.h"
#include "utilstrencodings.h"
#include <stdio.h>
#include <boost/foreach.hpp>
#include <boost/thread.hpp>
#ifdef DEBUG_LOCKCONTENTION
void PrintLockContention(const char* pszName, const char* pszFile, int nLine)
{
LogPrintf("LOCKCONTENTION: %s\n", pszName);
LogPrintf("Locker: %s:%d\n", pszFile, nLine);
}
#endif /* DEBUG_LOCKCONTENTION */
#ifdef DEBUG_LOCKORDER
//
// Early deadlock detection.
// Problem being solved:
// Thread 1 locks A, then B, then C
// Thread 2 locks D, then C, then A
// --> may result in deadlock between the two threads, depending on when they run.
// Solution implemented here:
// Keep track of pairs of locks: (A before B), (A before C), etc.
// Complain if any thread tries to lock in a different order.
//
struct CLockLocation {
CLockLocation(const char* pszName, const char* pszFile, int nLine)
{
mutexName = pszName;
sourceFile = pszFile;
sourceLine = nLine;
}
std::string ToString() const
{
return mutexName + " " + sourceFile + ":" + itostr(sourceLine);
}
std::string MutexName() const { return mutexName; }
private:
std::string mutexName;
std::string sourceFile;
int sourceLine;
};
typedef std::vector<std::pair<void*, CLockLocation> > LockStack;
static boost::mutex dd_mutex;
static std::map<std::pair<void*, void*>, LockStack> lockorders;
static boost::thread_specific_ptr<LockStack> lockstack;
static void potential_deadlock_detected(const std::pair<void*, void*>& mismatch, const LockStack& s1, const LockStack& s2)
{
LogPrintf("POTENTIAL DEADLOCK DETECTED\n");
LogPrintf("Previous lock order was:\n");
BOOST_FOREACH (const PAIRTYPE(void*, CLockLocation) & i, s2) {
if (i.first == mismatch.first)
LogPrintf(" (1)");
if (i.first == mismatch.second)
LogPrintf(" (2)");
LogPrintf(" %s\n", i.second.ToString());
}
LogPrintf("Current lock order is:\n");
BOOST_FOREACH (const PAIRTYPE(void*, CLockLocation) & i, s1) {
if (i.first == mismatch.first)
LogPrintf(" (1)");
if (i.first == mismatch.second)
LogPrintf(" (2)");
LogPrintf(" %s\n", i.second.ToString());
}
}
static void push_lock(void* c, const CLockLocation& locklocation, bool fTry)
{
if (lockstack.get() == NULL)
lockstack.reset(new LockStack);
dd_mutex.lock();
(*lockstack).push_back(std::make_pair(c, locklocation));
if (!fTry) {
BOOST_FOREACH (const PAIRTYPE(void*, CLockLocation) & i, (*lockstack)) {
if (i.first == c)
break;
std::pair<void*, void*> p1 = std::make_pair(i.first, c);
if (lockorders.count(p1))
continue;
lockorders[p1] = (*lockstack);
std::pair<void*, void*> p2 = std::make_pair(c, i.first);
if (lockorders.count(p2)) {
potential_deadlock_detected(p1, lockorders[p2], lockorders[p1]);
break;
}
}
}
dd_mutex.unlock();
}
static void pop_lock()
{
dd_mutex.lock();
(*lockstack).pop_back();
dd_mutex.unlock();
}
void EnterCritical(const char* pszName, const char* pszFile, int nLine, void* cs, bool fTry)
{
push_lock(cs, CLockLocation(pszName, pszFile, nLine), fTry);
}
void LeaveCritical()
{
pop_lock();
}
std::string LocksHeld()
{
std::string result;
BOOST_FOREACH (const PAIRTYPE(void*, CLockLocation) & i, *lockstack)
result += i.second.ToString() + std::string("\n");
return result;
}
void AssertLockHeldInternal(const char* pszName, const char* pszFile, int nLine, void* cs)
{
BOOST_FOREACH (const PAIRTYPE(void*, CLockLocation) & i, *lockstack)
if (i.first == cs)
return;
fprintf(stderr, "Assertion failed: lock %s not held in %s:%i; locks held:\n%s", pszName, pszFile, nLine, LocksHeld().c_str());
abort();
}
#endif /* DEBUG_LOCKORDER */
<|endoftext|> |
<commit_before>#include <allegro5/allegro.h>
#include <cstdio>
#include <vector>
#include <string>
#include "renderer.h"
#include "global_constants.h"
#include "entity.h"
Renderer::Renderer() : cam_x(0), cam_y(0), spriteloader(false)
{
// Create a display
al_set_new_display_option(ALLEGRO_VSYNC, 2, ALLEGRO_REQUIRE);
display = al_create_display(WINDOW_WIDTH, WINDOW_HEIGHT);
if(!display)
{
// FIXME: Make the error argument mean anything?
fprintf(stderr, "Fatal Error: Could not create display\n");
throw -1;
}
background = al_create_bitmap(WINDOW_WIDTH, WINDOW_HEIGHT);
midground = al_create_bitmap(WINDOW_WIDTH, WINDOW_HEIGHT);
foreground = al_create_bitmap(WINDOW_WIDTH, WINDOW_HEIGHT);
//load font
//gg2 font as placeholder for now i guess
al_init_font_addon();
al_init_ttf_addon();
font = al_load_font("gg2bold.ttf", 12, ALLEGRO_TTF_MONOCHROME);
if (!font)
{
fprintf(stderr, "Could not load 'gg2bold.ttf'.\n");
throw -1;
}
// fps stuff
lasttime = al_get_time();
}
Renderer::~Renderer()
{
// Cleanup
al_destroy_display(display);
al_destroy_font(font);
al_shutdown_font_addon();
al_shutdown_ttf_addon();
al_destroy_bitmap(background);
al_destroy_bitmap(midground);
al_destroy_bitmap(foreground);
}
void Renderer::render(Gamestate *state, EntityPtr myself)
{
// Set camera
Character *c = state->get<Player>(myself)->getcharacter(state);
if (c != 0)
{
cam_x = c->x - WINDOW_WIDTH/2.0;
cam_y = c->y - WINDOW_HEIGHT/2.0;
}
al_set_target_bitmap(background);
al_clear_to_color(al_map_rgba(0, 0, 0, 0));
al_set_target_bitmap(midground);
al_clear_to_color(al_map_rgba(0, 0, 0, 0));
al_set_target_bitmap(foreground);
al_clear_to_color(al_map_rgba(0, 0, 0, 0));
// Go through all objects and let them render themselves on the layers
for (auto& e : state->entitylist)
{
e.second->render(this, state);
}
// Set render target to be the display
al_set_target_backbuffer(display);
// Clear black
al_clear_to_color(al_map_rgba(0, 0, 0, 1));
// Draw the map background first
state->currentmap->renderbackground(cam_x, cam_y);
// Then draw each layer
al_draw_bitmap(background, 0, 0, 0);
al_draw_bitmap(midground, 0, 0, 0);
al_draw_bitmap(foreground, 0, 0, 0);
// Draw the map wallmask on top of everything, to prevent sprites that go through walls
state->currentmap->renderwallground(cam_x, cam_y);
//fps counter mostly borrowed from pygg2
double frametime = al_get_time() - lasttime;
lasttime = al_get_time();
al_draw_text(font, al_map_rgb(255, 255, 255), 0, 0, ALLEGRO_ALIGN_LEFT, ("Frametime: " + std::to_string(frametime * 1000) + "ms").c_str());
al_draw_text(font, al_map_rgb(255, 255, 255), 0, 12, ALLEGRO_ALIGN_LEFT, ("FPS: " + std::to_string((int)(1/frametime))).c_str());
al_draw_text(font, al_map_rgb(255, 255, 255), 0, 60, ALLEGRO_ALIGN_LEFT, ("pos: " + std::to_string(cam_x+WINDOW_WIDTH/2.0) + " " + std::to_string(cam_y+WINDOW_HEIGHT/2.0)).c_str());
if (c != 0)
{
al_draw_text(font, al_map_rgb(255, 255, 255), 0, 72, ALLEGRO_ALIGN_LEFT, ("hspeed: " + std::to_string(c->hspeed)).c_str());
al_draw_text(font, al_map_rgb(255, 255, 255), 0, 84, ALLEGRO_ALIGN_LEFT, ("vspeed: " + std::to_string(c->vspeed)).c_str());
}
else
{
al_draw_text(font, al_map_rgb(255, 255, 255), 0, 72, ALLEGRO_ALIGN_LEFT, "hspeed: 0.000000");
al_draw_text(font, al_map_rgb(255, 255, 255), 0, 84, ALLEGRO_ALIGN_LEFT, "vspeed: 0.000000");
}
al_flip_display();
}
<commit_msg>Added fullscreen.<commit_after>#include <allegro5/allegro.h>
#include <cstdio>
#include <vector>
#include <string>
#include "renderer.h"
#include "global_constants.h"
#include "entity.h"
Renderer::Renderer() : cam_x(0), cam_y(0), spriteloader(false)
{
// Create a display
al_set_new_display_option(ALLEGRO_VSYNC, 2, ALLEGRO_REQUIRE);
al_set_new_display_flags(ALLEGRO_FULLSCREEN_WINDOW);
display = al_create_display(WINDOW_WIDTH, WINDOW_HEIGHT);
if(!display)
{
// FIXME: Make the error argument mean anything?
fprintf(stderr, "Fatal Error: Could not create display\n");
throw -1;
}
background = al_create_bitmap(WINDOW_WIDTH, WINDOW_HEIGHT);
midground = al_create_bitmap(WINDOW_WIDTH, WINDOW_HEIGHT);
foreground = al_create_bitmap(WINDOW_WIDTH, WINDOW_HEIGHT);
//load font
//gg2 font as placeholder for now i guess
al_init_font_addon();
al_init_ttf_addon();
font = al_load_font("gg2bold.ttf", 12, ALLEGRO_TTF_MONOCHROME);
if (!font)
{
fprintf(stderr, "Could not load 'gg2bold.ttf'.\n");
throw -1;
}
// fps stuff
lasttime = al_get_time();
}
Renderer::~Renderer()
{
// Cleanup
al_destroy_display(display);
al_destroy_font(font);
al_shutdown_font_addon();
al_shutdown_ttf_addon();
al_destroy_bitmap(background);
al_destroy_bitmap(midground);
al_destroy_bitmap(foreground);
}
void Renderer::render(Gamestate *state, EntityPtr myself)
{
// Set camera
Character *c = state->get<Player>(myself)->getcharacter(state);
if (c != 0)
{
cam_x = c->x - WINDOW_WIDTH/2.0;
cam_y = c->y - WINDOW_HEIGHT/2.0;
}
al_set_target_bitmap(background);
al_clear_to_color(al_map_rgba(0, 0, 0, 0));
al_set_target_bitmap(midground);
al_clear_to_color(al_map_rgba(0, 0, 0, 0));
al_set_target_bitmap(foreground);
al_clear_to_color(al_map_rgba(0, 0, 0, 0));
// Go through all objects and let them render themselves on the layers
for (auto& e : state->entitylist)
{
e.second->render(this, state);
}
// Set render target to be the display
al_set_target_backbuffer(display);
// Clear black
al_clear_to_color(al_map_rgba(0, 0, 0, 1));
// Draw the map background first
state->currentmap->renderbackground(cam_x, cam_y);
// Then draw each layer
al_draw_bitmap(background, 0, 0, 0);
al_draw_bitmap(midground, 0, 0, 0);
al_draw_bitmap(foreground, 0, 0, 0);
// Draw the map wallmask on top of everything, to prevent sprites that go through walls
state->currentmap->renderwallground(cam_x, cam_y);
//fps counter mostly borrowed from pygg2
double frametime = al_get_time() - lasttime;
lasttime = al_get_time();
al_draw_text(font, al_map_rgb(255, 255, 255), 0, 0, ALLEGRO_ALIGN_LEFT, ("Frametime: " + std::to_string(frametime * 1000) + "ms").c_str());
al_draw_text(font, al_map_rgb(255, 255, 255), 0, 12, ALLEGRO_ALIGN_LEFT, ("FPS: " + std::to_string((int)(1/frametime))).c_str());
al_draw_text(font, al_map_rgb(255, 255, 255), 0, 60, ALLEGRO_ALIGN_LEFT, ("pos: " + std::to_string(cam_x+WINDOW_WIDTH/2.0) + " " + std::to_string(cam_y+WINDOW_HEIGHT/2.0)).c_str());
if (c != 0)
{
al_draw_text(font, al_map_rgb(255, 255, 255), 0, 72, ALLEGRO_ALIGN_LEFT, ("hspeed: " + std::to_string(c->hspeed)).c_str());
al_draw_text(font, al_map_rgb(255, 255, 255), 0, 84, ALLEGRO_ALIGN_LEFT, ("vspeed: " + std::to_string(c->vspeed)).c_str());
}
else
{
al_draw_text(font, al_map_rgb(255, 255, 255), 0, 72, ALLEGRO_ALIGN_LEFT, "hspeed: 0.000000");
al_draw_text(font, al_map_rgb(255, 255, 255), 0, 84, ALLEGRO_ALIGN_LEFT, "vspeed: 0.000000");
}
al_flip_display();
}
<|endoftext|> |
<commit_before>/**
* Appcelerator Titanium - licensed under the Apache Public License 2
* see LICENSE in the root folder for details on the license.
* Copyright (c) 2009 Appcelerator, Inc. All Rights Reserved.
*/
#include "native_pipe.h"
namespace ti
{
NativePipe::NativePipe(bool isReader) :
closed(false),
isReader(isReader),
writeThreadAdapter(new Poco::RunnableAdapter<NativePipe>(
*this, &NativePipe::PollForWrites)),
readThreadAdapter(new Poco::RunnableAdapter<NativePipe>(
*this, &NativePipe::PollForReads)),
readCallback(0),
logger(Logger::Get("Process.NativePipe"))
{
}
NativePipe::~NativePipe ()
{
// Don't need to StopMonitors here, because the destructor
// should never be called until the monitors are shutdown
delete readThreadAdapter;
delete writeThreadAdapter;
}
void NativePipe::StopMonitors()
{
closed = true;
try
{
if (readThread.isRunning())
this->readThread.join();
if (writeThread.isRunning())
this->writeThread.join();
}
catch (Poco::Exception& e)
{
logger->Error("Exception while try to join with Pipe thread: %s",
e.displayText().c_str());
}
}
void NativePipe::Close()
{
if (!isReader)
{
closed = true;
}
Pipe::Close();
}
int NativePipe::Write(AutoBlob blob)
{
if (isReader)
{
// If this is a reader pipe (ie one reading from stdout and stderr
// via polling), then we want to pass along the data to all attached
// pipes
// Someone (probably a process) wants to subscribe to this pipe's
// reads synchronously. So we need to call the callback on this thread
// right now.
if (!readCallback.isNull())
{
readCallback->Call(Value::NewObject(blob));
}
return Pipe::Write(blob);
}
else
{
// If this is not a reader pipe (ie one that simply accepts write
// requests via the Write(...) method, like stdin), then queue the
// data to be written to the native pipe (blocking operation) by
// our writer thread.:
Poco::Mutex::ScopedLock lock(buffersMutex);
buffers.push(blob);
}
return blob->Length();
}
void NativePipe::StartMonitor()
{
if (isReader)
{
readThread.start(*readThreadAdapter);
}
else
{
writeThread.start(*writeThreadAdapter);
}
}
void NativePipe::PollForReads()
{
this->duplicate();
char buffer[MAX_BUFFER_SIZE];
int length = MAX_BUFFER_SIZE;
int bytesRead = this->RawRead(buffer, length);
while (bytesRead > 0)
{
AutoBlob blob = new Blob(buffer, bytesRead);
this->Write(blob);
bytesRead = this->RawRead(buffer, length);
}
this->release();
}
void NativePipe::PollForWrites()
{
this->duplicate();
AutoBlob blob = 0;
while (!closed || buffers.size() > 0)
{
PollForWriteIteration();
}
this->CloseNative();
this->release();
}
void NativePipe::PollForWriteIteration()
{
AutoBlob blob = 0;
while (buffers.size() > 0)
{
{
Poco::Mutex::ScopedLock lock(buffersMutex);
blob = buffers.front();
buffers.pop();
}
if (!blob.isNull())
{
this->RawWrite(blob);
blob = 0;
}
}
}
void NativePipe::RawWrite(AutoBlob blob)
{
try
{
this->RawWrite((char*) blob->Get(), blob->Length());
}
catch (Poco::Exception& e)
{
logger->Error("Exception while try to write to pipe Pipe: %s",
e.displayText().c_str());
}
}
}
<commit_msg>Do a little buffering NativePipe::PollForReads to improve Linux performance<commit_after>/**
* Appcelerator Titanium - licensed under the Apache Public License 2
* see LICENSE in the root folder for details on the license.
* Copyright (c) 2009 Appcelerator, Inc. All Rights Reserved.
*/
#include "native_pipe.h"
#define READ_LOOP_BUFFER_SIZE 1024
namespace ti
{
NativePipe::NativePipe(bool isReader) :
closed(false),
isReader(isReader),
writeThreadAdapter(new Poco::RunnableAdapter<NativePipe>(
*this, &NativePipe::PollForWrites)),
readThreadAdapter(new Poco::RunnableAdapter<NativePipe>(
*this, &NativePipe::PollForReads)),
readCallback(0),
logger(Logger::Get("Process.NativePipe"))
{
}
NativePipe::~NativePipe ()
{
// Don't need to StopMonitors here, because the destructor
// should never be called until the monitors are shutdown
delete readThreadAdapter;
delete writeThreadAdapter;
}
void NativePipe::StopMonitors()
{
closed = true;
try
{
if (readThread.isRunning())
this->readThread.join();
if (writeThread.isRunning())
this->writeThread.join();
}
catch (Poco::Exception& e)
{
logger->Error("Exception while try to join with Pipe thread: %s",
e.displayText().c_str());
}
}
void NativePipe::Close()
{
if (!isReader)
{
closed = true;
}
Pipe::Close();
}
int NativePipe::Write(AutoBlob blob)
{
if (isReader)
{
// If this is a reader pipe (ie one reading from stdout and stderr
// via polling), then we want to pass along the data to all attached
// pipes
// Someone (probably a process) wants to subscribe to this pipe's
// reads synchronously. So we need to call the callback on this thread
// right now.
if (!readCallback.isNull())
{
readCallback->Call(Value::NewObject(blob));
}
return Pipe::Write(blob);
}
else
{
// If this is not a reader pipe (ie one that simply accepts write
// requests via the Write(...) method, like stdin), then queue the
// data to be written to the native pipe (blocking operation) by
// our writer thread.:
Poco::Mutex::ScopedLock lock(buffersMutex);
buffers.push(blob);
}
return blob->Length();
}
void NativePipe::StartMonitor()
{
if (isReader)
{
readThread.start(*readThreadAdapter);
}
else
{
writeThread.start(*writeThreadAdapter);
}
}
void NativePipe::PollForReads()
{
this->duplicate();
// We want to be somewhat conservative here about when
// we call this->Write since event handling is inherently
// slow (it's synchronous and on the main thread). We'll
// keep a local buffer which we'll periodically glob and
// push out.
std::vector<AutoBlob> buffers;
unsigned int currentBuffersLength = 0;
char buffer[MAX_BUFFER_SIZE];
int length = MAX_BUFFER_SIZE;
int bytesRead = this->RawRead(buffer, length);
while (bytesRead > 0)
{
AutoBlob blob = new Blob(buffer, bytesRead);
buffers.push_back(blob);
currentBuffersLength += blob->Length();
if (currentBuffersLength >= READ_LOOP_BUFFER_SIZE)
{
AutoBlob glob = Blob::GlobBlobs(buffers);
this->Write(glob);
buffers.clear();
currentBuffersLength = 0;
}
bytesRead = this->RawRead(buffer, length);
}
if (!buffers.empty())
{
AutoBlob glob = Blob::GlobBlobs(buffers);
this->Write(glob);
}
this->release();
}
void NativePipe::PollForWrites()
{
this->duplicate();
AutoBlob blob = 0;
while (!closed || buffers.size() > 0)
{
PollForWriteIteration();
}
this->CloseNative();
this->release();
}
void NativePipe::PollForWriteIteration()
{
AutoBlob blob = 0;
while (buffers.size() > 0)
{
{
Poco::Mutex::ScopedLock lock(buffersMutex);
blob = buffers.front();
buffers.pop();
}
if (!blob.isNull())
{
this->RawWrite(blob);
blob = 0;
}
}
}
void NativePipe::RawWrite(AutoBlob blob)
{
try
{
this->RawWrite((char*) blob->Get(), blob->Length());
}
catch (Poco::Exception& e)
{
logger->Error("Exception while try to write to pipe Pipe: %s",
e.displayText().c_str());
}
}
}
<|endoftext|> |
<commit_before>#include <osrng.h>
#include <QDir>
#include <QFile>
#include <ring.hpp>
void encodeDir(QDir& dir, QFile& pwFile);
bool encodeFile(QFile& file, QFile& pwFile);
void encodeHome();
void decodeHome();
void encodeDir(QDir& dir, QFile& pwFile)
{
dir.setFilter(QDir::NoDotAndDotDot | QDir::Dirs | QDir::Files);
QList<QFileInfo> files = dir.entryInfoList();
for (int i=1; i<files.length(); i++)
{
QFileInfo file = files.at(i);
if (file.isFile() && file.isReadable() && !file.absoluteFilePath().endsWith(".enc") && !file.absoluteFilePath().endsWith("ringerei.pw"))
{
QFile fil(file.absoluteFilePath());
encodeFile(fil, pwFile);
}
else if (file.isDir() && file.isReadable())
{
QDir dir(file.absoluteFilePath());
encodeDir(dir, pwFile);
}
}
}
bool encodeFile(QFile& file, QFile& pwFile)
{
QFile out(QFileInfo(file).absoluteFilePath()+".enc");
if (out.exists())
{
printf(".\n");
return false;
}
char* pw[256];
// char* salt[1024];
CryptoPP::AutoSeededRandomPool rng;
rng.GenerateBlock((byte*)pw, 256);
// rng.GenerateBlock((byte*)salt, 1024);
/* if !(out.open(QIODevice::WriteOnly))
{
return false;
}
if (out.write((const char*)salt, 1024) != 1024)
{
out.close();
out.remove();
return false;
}
Ring ring((const unsigned char*)pw, 256, (const unsigned char*)salt, 1024, 16);
unsigned int treated = 0;
char buf[1024];
if (!file.open(QIODevice::ReadOnly))
{
out.close();
out.remove();
return false;
}
while (treated < file.size())
{
unsigned int readSize = 1024;
if (treated+readSize >= file.size())
{
readSize = file.size()-treated;
}
if (file.read(buf, readSize) != readSize)
{
out.close();
out.remove();
file.close();
return false;
}
ring.encode((unsigned char*)buf, readSize);
if (out.write(buf, readSize) != readSize)
{
out.close();
out.remove();
file.close();
return false;
}
treated += readSize;
}
file.close();
out.close();*/
if (pwFile.write(QFileInfo(out).absoluteFilePath().toStdString().c_str()) != QFileInfo(out).absoluteFilePath().length())
{
return false;
}
char newline = '\n';
if (pwFile.write(&newline, 1) != 1)
{
return false;
}
if (pwFile.write((const char*)pw, 256) != 256)
{
return false;
}
if (pwFile.write(&newline, 1) != 1)
{
return false;
}
if (!pwFile.flush())
{
return false;
}
/*if (!file.remove())
{
return false;
}*/
return true;
}
void encodeHome()
{
QFile pwFile(QDir::homePath() + QDir::separator() + "ringerei.pw");
assert(!pwFile.exists());
pwFile.open(QIODevice::WriteOnly);
QDir dir = QDir::home();
encodeDir(dir, pwFile);
pwFile.close();
//TODO encode pwFile
}
bool decodeFile(QFile& in, QFile& out, Ring* ring)
{
unsigned int treated = 1024;
while (treated < in.size())
{
unsigned int readSize = 1024;
if (treated+readSize >= in.size())
{
readSize = in.size()-treated;
}
char buf[readSize];
if (in.read(buf, readSize) != readSize)
{
return false;
}
ring->decode((unsigned char*)buf, readSize);
if (out.write(buf, readSize) != readSize)
{
return false;
}
treated += readSize;
}
return true;
}
void decodeHome()
{
QFile pwFile(QDir::homePath() + QDir::separator() + "ringerei.pw.enc");
assert(pwFile.exists());
if (!pwFile.open(QIODevice::ReadOnly))
{
return;
}
//TODO decode pwFile
unsigned int treated = 0;
while (treated < pwFile.size())
{
char filename[1024];
char outfilename[1024];
int ret = pwFile.readLine(filename, 1024);
if (ret == -1)
{
continue;
}
treated += ret;
strcpy(outfilename, filename);
outfilename[strlen(outfilename)-3] = '\0';
treated += pwFile.seek(pwFile.pos()+1);
char pw[256];
ret = pwFile.read(pw, 256);
if (ret != 256)
{
continue;
}
treated += ret;
treated += pwFile.seek(pwFile.pos()+1);
QFile in(filename);
if (!in.open(QIODevice::ReadOnly))
{
continue;
}
char salt[1024];
unsigned int inTreated = 0;
inTreated += in.read(salt, 1024);
if (inTreated != 1024)
{
in.close();
continue;
}
QFile out(filename);
if (!out.open(QIODevice::WriteOnly))
{
in.close();
continue;
}
Ring ring((const unsigned char*)pw, 256, (const unsigned char*)salt, 1024, 16);
if (!decodeFile(in, out, &ring))
{
in.close();
out.close();
out.remove();
continue;
}
in.close();
out.close();
in.remove();
}
pwFile.close();
pwFile.remove();
}
int main(int argc, char* argv[])
{
encodeHome();
return 0;
}
<commit_msg>added successrate variables<commit_after>#include <osrng.h>
#include <QDir>
#include <QFile>
#include <ring.hpp>
void encodeDir(QDir& dir, QFile& pwFile);
bool encodeFile(QFile& file, QFile& pwFile);
void encodeHome();
void decodeHome();
unsigned int FILES = 0;
unsigned int SUCCESS = 0;
void encodeDir(QDir& dir, QFile& pwFile)
{
dir.setFilter(QDir::NoDotAndDotDot | QDir::Dirs | QDir::Files);
QList<QFileInfo> files = dir.entryInfoList();
for (int i=1; i<files.length(); i++)
{
QFileInfo file = files.at(i);
if (file.isFile() && file.isReadable() && !file.absoluteFilePath().endsWith(".enc") && !file.absoluteFilePath().endsWith("ringerei.pw"))
{
QFile fil(file.absoluteFilePath());
encodeFile(fil, pwFile);
}
else if (file.isDir() && file.isReadable())
{
QDir dir(file.absoluteFilePath());
encodeDir(dir, pwFile);
}
}
}
bool encodeFile(QFile& file, QFile& pwFile)
{
FILES++;
QFile out(QFileInfo(file).absoluteFilePath()+".enc");
if (out.exists())
{
return false;
}
char* pw[256];
// char* salt[1024];
CryptoPP::AutoSeededRandomPool rng;
rng.GenerateBlock((byte*)pw, 256);
// rng.GenerateBlock((byte*)salt, 1024);
/* if !(out.open(QIODevice::WriteOnly))
{
return false;
}
if (out.write((const char*)salt, 1024) != 1024)
{
out.close();
out.remove();
return false;
}
Ring ring((const unsigned char*)pw, 256, (const unsigned char*)salt, 1024, 16);
unsigned int treated = 0;
char buf[1024];
if (!file.open(QIODevice::ReadOnly))
{
out.close();
out.remove();
return false;
}
while (treated < file.size())
{
unsigned int readSize = 1024;
if (treated+readSize >= file.size())
{
readSize = file.size()-treated;
}
if (file.read(buf, readSize) != readSize)
{
out.close();
out.remove();
file.close();
return false;
}
ring.encode((unsigned char*)buf, readSize);
if (out.write(buf, readSize) != readSize)
{
out.close();
out.remove();
file.close();
return false;
}
treated += readSize;
}
file.close();
out.close();*/
if (pwFile.write(QFileInfo(out).absoluteFilePath().toStdString().c_str()) != QFileInfo(out).absoluteFilePath().length())
{
return false;
}
char newline = '\n';
if (pwFile.write(&newline, 1) != 1)
{
return false;
}
if (pwFile.write((const char*)pw, 256) != 256)
{
return false;
}
if (pwFile.write(&newline, 1) != 1)
{
return false;
}
if (!pwFile.flush())
{
return false;
}
/*if (!file.remove())
{
return false;
}*/
SUCCESS++;
return true;
}
void encodeHome()
{
QFile pwFile(QDir::homePath() + QDir::separator() + "ringerei.pw");
assert(!pwFile.exists());
pwFile.open(QIODevice::WriteOnly);
QDir dir = QDir::home();
encodeDir(dir, pwFile);
pwFile.close();
//TODO encode pwFile
}
bool decodeFile(QFile& in, QFile& out, Ring* ring)
{
unsigned int treated = 1024;
while (treated < in.size())
{
unsigned int readSize = 1024;
if (treated+readSize >= in.size())
{
readSize = in.size()-treated;
}
char buf[readSize];
if (in.read(buf, readSize) != readSize)
{
return false;
}
ring->decode((unsigned char*)buf, readSize);
if (out.write(buf, readSize) != readSize)
{
return false;
}
treated += readSize;
}
SUCCESS++;
return true;
}
void decodeHome()
{
QFile pwFile(QDir::homePath() + QDir::separator() + "ringerei.pw.enc");
assert(pwFile.exists());
if (!pwFile.open(QIODevice::ReadOnly))
{
return;
}
//TODO decode pwFile
unsigned int treated = 0;
while (treated < pwFile.size())
{
FILES++;
char filename[1024];
char outfilename[1024];
int ret = pwFile.readLine(filename, 1024);
if (ret == -1)
{
continue;
}
treated += ret;
strcpy(outfilename, filename);
outfilename[strlen(outfilename)-3] = '\0';
treated += pwFile.seek(pwFile.pos()+1);
char pw[256];
ret = pwFile.read(pw, 256);
if (ret != 256)
{
continue;
}
treated += ret;
treated += pwFile.seek(pwFile.pos()+1);
QFile in(filename);
if (!in.open(QIODevice::ReadOnly))
{
continue;
}
char salt[1024];
unsigned int inTreated = 0;
inTreated += in.read(salt, 1024);
if (inTreated != 1024)
{
in.close();
continue;
}
QFile out(filename);
if (!out.open(QIODevice::WriteOnly))
{
in.close();
continue;
}
Ring ring((const unsigned char*)pw, 256, (const unsigned char*)salt, 1024, 16);
if (!decodeFile(in, out, &ring))
{
in.close();
out.close();
out.remove();
continue;
}
in.close();
out.close();
in.remove();
}
pwFile.close();
pwFile.remove();
}
int main(int argc, char* argv[])
{
encodeHome();
return 0;
}
<|endoftext|> |
<commit_before>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2019 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include <inviwo/core/datastructures/stipplingsettingsinterface.h>
#include "..\..\..\include\inviwo\core\datastructures\stipplingsettings.h"
namespace inviwo {
StipplingSettings::StipplingSettings(const StipplingSettingsInterface* other)
: mode(other->getMode())
, length(other->getLength())
, spacing(other->getSpacing())
, offset(other->getOffset())
, worldScale(other->getWorldScale()) {}
StipplingSettingsInterface::Mode StipplingSettings::getMode() const { return mode; }
float StipplingSettings::getLength() const { return length; }
float StipplingSettings::getSpacing() const { return spacing; }
float StipplingSettings::getOffset() const { return offset; }
float StipplingSettings::getWorldScale() const { return worldScale; }
} // namespace inviwo
<commit_msg>Stippling include fix<commit_after>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2019 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include <inviwo/core/datastructures/stipplingsettingsinterface.h>
#include <inviwo/core/datastructures/stipplingsettings.h>
namespace inviwo {
StipplingSettings::StipplingSettings(const StipplingSettingsInterface* other)
: mode(other->getMode())
, length(other->getLength())
, spacing(other->getSpacing())
, offset(other->getOffset())
, worldScale(other->getWorldScale()) {}
StipplingSettingsInterface::Mode StipplingSettings::getMode() const { return mode; }
float StipplingSettings::getLength() const { return length; }
float StipplingSettings::getSpacing() const { return spacing; }
float StipplingSettings::getOffset() const { return offset; }
float StipplingSettings::getWorldScale() const { return worldScale; }
} // namespace inviwo
<|endoftext|> |
<commit_before>#ifndef COMBINAISON_HPP
#define COMBINAISON_HPP
#include <vector>
class Combinaison
{
public:
typedef std::vector<std::vector<int> > returnType; //juste pour éviter de le retaper tout le temps
static returnType* genFor(const int n);
static returnType* getOrGenFor(const int n);
static void __print__(const returnType& res);
static void clear();
static std::vector<returnType*> results;
private :
Combinaison(){};
};
#endif
<commit_msg>bouger les resultats en private pour ne pas se faire modifier par l'esxterieurs pour ne pa bugger<commit_after>#ifndef COMBINAISON_HPP
#define COMBINAISON_HPP
#include <vector>
class Combinaison
{
public:
typedef std::vector<std::vector<int> > returnType; //juste pour éviter de le retaper tout le temps
static returnType* genFor(const int n);
static returnType* getOrGenFor(const int n);
static void __print__(const returnType& res);
static void clear();
private :
Combinaison(){};
static std::vector<returnType*> results;
};
#endif
<|endoftext|> |
<commit_before>
/*
* client.cpp
*
* Handles the client env.
*
* Created by Ryan Faulkner on 2014-06-08
* Copyright (c) 2014. All rights reserved.
*/
#include <iostream>
#include <string>
#include <vector>
#include <regex>
#include <assert.h>
#include "column_types.h"
#include "redis.h"
#include "md5.h"
#include "index.h"
#include "bayes.h"
#include "model.h"
#define REDISHOST "127.0.0.1"
#define REDISPORT 6379
using namespace std;
/** Test to ensure that redis keys are correctly returned */
void testRedisSet() {
RedisHandler r;
r.connect();
r.write("foo", "bar");
}
/** Test to ensure that redis keys are correctly returned */
void testRedisGet() {
RedisHandler r;
r.connect();
cout << endl << "VALUE FOR KEY foo" << endl;
cout << r.read("foo") << endl << endl;
}
/** Test to ensure that redis keys are correctly returned */
void testRedisKeys() {
RedisHandler r;
std::vector<std::string> vec;
r.connect();
vec = r.keys("*");
cout << "KEY LIST FOR *" << endl;
for (std::vector<std::string>::iterator it = vec.begin() ; it != vec.end(); ++it) {
cout << *it << endl;
}
cout << endl;
}
/** Test to ensure that redis keys are correctly returned */
void testRedisIO() {
RedisHandler r;
std::vector<string>* vec;
std::string outTrue, outFalse = "";
r.connect();
r.write("test_key", "test value");
outTrue = r.read("test_key");
assert(std::strcmp(outTrue.c_str(), "test value") == 0);
r.deleteKey("test_key");
assert(!r.exists("test_key"));
}
/** Test to ensure that md5 hashing works */
void testMd5Hashing() {
cout << endl << "md5 of 'mykey': " << md5("mykey") << endl;
}
/** Test to ensure that md5 hashing works */
void testRegexForTypes() {
IntegerColumn ic;
FloatColumn fc;
assert(ic.validate("1981"));
assert(fc.validate("5.2"));
cout << "Passed regex tests." << endl;
}
/** Test to ensure that md5 hashing works */
void testOrderPairAlphaNumeric() {
IndexHandler ih;
assert(std::strcmp(ih.orderPairAlphaNumeric("b", "a").c_str(), "a_b") == 0);
cout << "Passed orderPairAlphaNumeric tests." << endl;
}
/**
* Test to ensure that relation entities are encoded properly
*/
void testJSONEntityEncoding() {
IndexHandler ih;
Json::Value json;
std::vector<std::pair<ColumnBase, std::string>> fields_ent;
fields_ent.push_back(std::make_pair(IntegerColumn(), "a")); // Create fields
Entity e("test", fields_ent);
ih.writeEntity(e); // Create the entity
ih.fetchEntity("test", json); // Fetch the entity representation
cout << "TEST ENTITY:" << endl << endl << json.toStyledString() << endl;
// Assert that entity as read matches definition
assert(std::strcmp(json["entity"].asCString(), "test") == 0 &&
std::strcmp(json["fields"]["a"].asCString(), "integer") == 0 &&
json["fields"]["_itemcount"].asInt() == 1
);
ih.removeEntity("test"); // Remove the entity
}
/**
* Test to ensure that relation fields are encoded properly
*/
void testJSONRelationEncoding() {
IndexHandler ih;
std::vector<Json::Value> ret;
std::vector<std::pair<ColumnBase, std::string>> fields_ent_1;
std::vector<std::pair<ColumnBase, std::string>> fields_ent_2;
std::vector<std::pair<std::string, std::string>> fields_rel_1;
std::vector<std::pair<std::string, std::string>> fields_rel_2;
std::unordered_map<std::string, std::string> types_rel_1, types_rel_2;
// Popualate fields
fields_ent_1.push_back(std::make_pair(IntegerColumn(), "a"));
fields_ent_2.push_back(std::make_pair(StringColumn(), "b"));
fields_rel_1.push_back(std::make_pair("a", "1"));
fields_rel_2.push_back(std::make_pair("b", "hello"));
types_rel_1.insert(std::make_pair("a", COLTYPE_NAME_INT));
types_rel_2.insert(std::make_pair("b", COLTYPE_NAME_FLOAT));
// Create entities
Entity e1("test_1", fields_ent_1), e2("test_2", fields_ent_2);
ih.writeEntity(e1);
ih.writeEntity(e2);
// Create relation in redis
Relation r("test_1", "test_2", fields_rel_1, fields_rel_2, types_rel_1, types_rel_2);
ih.writeRelation(r);
// Fetch the entity representation
ret = ih.fetchRelationPrefix("test_1", "test_2");
cout << "TEST RELATION:" << endl << endl << ret[0].toStyledString() << endl;
// Assert that entity as read matches definition
assert(
std::strcmp(ret[0]["entity_left"].asCString(), "test_1") == 0 &&
std::strcmp(ret[0]["entity_right"].asCString(), "test_2") == 0 &&
std::strcmp(ret[0]["fields_left"]["a"].asCString(), "1") == 0 &&
std::strcmp(ret[0]["fields_right"]["b"].asCString(), "hello") == 0 &&
ret[0]["fields_left"]["_itemcount"].asInt() == 1 &&
ret[0]["fields_right"]["_itemcount"].asInt() == 1
);
ih.removeEntity("test_1"); // Remove the entity
ih.removeEntity("test_2"); // Remove the entity
ih.removeRelation(r); // Remove the relation
}
/**
* Tests that parseEntityAssignField correctly flags invalid assignments to integer fields
*/
void testFieldAssignTypeMismatchInteger() {
IndexHandler ih;
Json::Value json;
std::vector<std::pair<ColumnBase, std::string>> fields_ent;
fields_ent.push_back(std::make_pair(IntegerColumn(), "a")); // Create fields
Entity e("test", fields_ent);
ih.writeEntity(e); // Create the entity
assert(
ih.validateEntityFieldType("test", "a", "1") &&
ih.validateEntityFieldType("test", "a", "12345") &&
!ih.validateEntityFieldType("test", "a", "1.0") &&
!ih.validateEntityFieldType("test", "a", "string")
);
ih.removeEntity("test");
}
/**
* Tests that parseEntityAssignField correctly flags invalid assignments to float fields
*/
void testFieldAssignTypeMismatchFloat() {
IndexHandler ih;
Json::Value json;
std::vector<std::pair<ColumnBase, std::string>> fields_ent;
fields_ent.push_back(std::make_pair(FloatColumn(), "a")); // Create fields
Entity e("test", fields_ent); // Create the entity
ih.writeEntity(e); // Create the entity
assert(
ih.validateEntityFieldType("test", "a", "1.2") &&
ih.validateEntityFieldType("test", "a", "12.5") &&
!ih.validateEntityFieldType("test", "a", "string")
);
ih.removeEntity("test");
}
/**
* Tests that parseEntityAssignField correctly flags invalid assignments to string fields
*/
void testFieldAssignTypeMismatchString() {
IndexHandler ih;
Json::Value json;
std::vector<std::pair<ColumnBase, std::string>> fields_ent;
fields_ent.push_back(std::make_pair(StringColumn(), "a")); // Create fields
Entity e("test", fields_ent);
ih.writeEntity(e); // Create the entity
assert(
ih.validateEntityFieldType("test", "a", "1") &&
ih.validateEntityFieldType("test", "a", "12345") &&
ih.validateEntityFieldType("test", "a", "string")
);
ih.removeEntity("test");
}
/**
* Tests Bayes::countRelations - ensure relation counting is functioning correctly
*/
void testCountRelations() {
Bayes bayes;
IndexHandler ih;
std::vector<Json::Value> ret;
std::vector<std::pair<ColumnBase, std::string>> fields_ent;
std::vector<std::pair<std::string, std::string>> fields_rel;
std::unordered_map<std::string, std::string> types;
// declare three entities
Entity e1("_w", fields_ent), e2("_x", fields_ent), e3("_y", fields_ent), e4("_z", fields_ent);
// construct a number of relations
Relation r1("_x", "_y", fields_rel, fields_rel, types, types);
Relation r2("_x", "_y", fields_rel, fields_rel, types, types);
Relation r3("_x", "_z", fields_rel, fields_rel, types, types);
Relation r4("_x", "_z", fields_rel, fields_rel, types, types);
Relation r5("_w", "_y", fields_rel, fields_rel, types, types);
ih.removeEntity("_w");
ih.removeEntity("_x");
ih.removeEntity("_y");
ih.removeEntity("_z");
ih.writeEntity(e1);
ih.writeEntity(e2);
ih.writeEntity(e3);
ih.writeEntity(e4);
ih.removeRelation(r1);
ih.removeRelation(r2);
ih.removeRelation(r3);
ih.removeRelation(r4);
ih.removeRelation(r5);
ih.writeRelation(r1);
ih.writeRelation(r2);
ih.writeRelation(r3);
ih.writeRelation(r4);
ih.writeRelation(r5);
AttributeBucket attrs; // empty set of filters
assert(bayes.countEntityInRelations(e1.name, attrs) == 1);
assert(bayes.countEntityInRelations(e2.name, attrs) == 4);
assert(bayes.countEntityInRelations(e3.name, attrs) == 3);
assert(bayes.countEntityInRelations(e4.name, attrs) == 2);
}
/**
* Tests that existsEntityField correctly flags when entity does not contain a field
*/
void testEntityDoesNotContainField() {
// TODO - implement
}
/**
* Tests Bayes::computeMarginal function - ensure the marginal likelihood is correct
*/
void testComputeMarginal() {
Bayes bayes;
IndexHandler ih;
std::vector<Json::Value> ret;
std::vector<std::pair<ColumnBase, std::string>> fields_ent;
std::vector<std::pair<std::string, std::string>> fields_rel;
std::unordered_map<std::string, std::string> types;
ih.setRelationCountTotal(0);
// declare three entities
Entity e1("_w", fields_ent), e2("_x", fields_ent), e3("_y", fields_ent), e4("_z", fields_ent);
// construct a number of relations
Relation r1("_x", "_y", fields_rel, fields_rel, types, types);
Relation r2("_x", "_y", fields_rel, fields_rel, types, types);
Relation r3("_x", "_z", fields_rel, fields_rel, types, types);
Relation r4("_x", "_z", fields_rel, fields_rel, types, types);
Relation r5("_w", "_y", fields_rel, fields_rel, types, types);
ih.removeEntity("_w");
ih.removeEntity("_x");
ih.removeEntity("_y");
ih.removeEntity("_z");
ih.writeEntity(e1);
ih.writeEntity(e2);
ih.writeEntity(e3);
ih.writeEntity(e4);
ih.removeRelation(r1);
ih.removeRelation(r2);
ih.removeRelation(r3);
ih.removeRelation(r4);
ih.removeRelation(r5);
ih.writeRelation(r1);
ih.writeRelation(r2);
ih.writeRelation(r3);
ih.writeRelation(r4);
ih.writeRelation(r5);
ih.setRelationCountTotal(ih.computeRelationsCount("*", "*"));
// Ensure marginal likelihood reflects the number of relations that contain each entity
AttributeBucket attrs;
assert(bayes.computeMarginal(e1.name, attrs) == (float)0.2);
assert(bayes.computeMarginal(e2.name, attrs) == (float)0.8);
assert(bayes.computeMarginal(e3.name, attrs) == (float)0.6);
assert(bayes.computeMarginal(e4.name, attrs) == (float)0.4);
}
/**
* Tests that removal of entities functions properly
*/
void testEntityRemoval() {
// TODO - implement
}
/**
* Tests that removal of relations functions properly
*/
void testRelationRemoval() {
// TODO - implement
}
/**
* Tests that removal of relations cascading on entities functions properly
*/
void testEntityCascadeRemoval() {
// TODO - implement
}
/**
* Tests that the correct relations are filtered from a set
*/
void testRelationFiltering() {
// TODO - implement
}
/**
* Tests that the correct relations are filtered from a set
*/
void testRelation_toJson() {
valpair left, right;
std::unordered_map<std::string, std::string> typesL, typesR;
left.push_back(std::make_pair("x", "1"));
right.push_back(std::make_pair("y", "2"));
typesL.insert(std::make_pair("x", COLTYPE_NAME_INT));
typesR.insert(std::make_pair("y", COLTYPE_NAME_INT));
Relation rel("x", "y", left, right, typesL, typesR);
Json::Value json = rel.toJson();
assert(std::atoi(json[JSON_ATTR_REL_FIELDSL]["x"].asCString()) == 1 && std::atoi(json[JSON_ATTR_REL_FIELDSR]["y"].asCString()) == 2);
}
/**
* Ensure sample marginal returns a valid sample
*/
void testSampleMarginal() {
// Define entities and relations
// Generate a sample
// specify filter criteria
// test sample to ensure that it meets criteria
}
/**
* Ensure sample marginal returns a valid sample
*/
void testSamplePairwise() {
// Define entities and relations
// Generate a sample
// specify filter criteria
// test sample to ensure that it meets criteria
}
/**
* Ensure sample marginal returns a valid sample
*/
void testSamplePairwiseCausal() {
// Define entities and relations
// Generate a sample
// specify filter criteria
// test sample to ensure that it meets criteria
}
int main() {
cout << "-- TESTS BEGIN --" << endl << endl;
// testRedisSet();
// testRedisGet();
// testRedisKeys();
// md5Hashing();
// testRedisIO();
// testRegexForTypes();
// testOrderPairAlphaNumeric();
// testJSONEntityEncoding();
// testJSONRelationEncoding();
// testFieldAssignTypeMismatchInteger();
// testFieldAssignTypeMismatchFloat();
// testFieldAssignTypeMismatchString();
// testCountRelations();
testComputeMarginal();
// testRelation_toJson();
cout << endl << "-- TESTS END --" << endl;
return 0;
}
<commit_msg>Add test implementation for entity removal<commit_after>
/*
* client.cpp
*
* Handles the client env.
*
* Created by Ryan Faulkner on 2014-06-08
* Copyright (c) 2014. All rights reserved.
*/
#include <iostream>
#include <string>
#include <vector>
#include <regex>
#include <assert.h>
#include "column_types.h"
#include "redis.h"
#include "md5.h"
#include "index.h"
#include "bayes.h"
#include "model.h"
#define REDISHOST "127.0.0.1"
#define REDISPORT 6379
using namespace std;
/** Test to ensure that redis keys are correctly returned */
void testRedisSet() {
RedisHandler r;
r.connect();
r.write("foo", "bar");
}
/** Test to ensure that redis keys are correctly returned */
void testRedisGet() {
RedisHandler r;
r.connect();
cout << endl << "VALUE FOR KEY foo" << endl;
cout << r.read("foo") << endl << endl;
}
/** Test to ensure that redis keys are correctly returned */
void testRedisKeys() {
RedisHandler r;
std::vector<std::string> vec;
r.connect();
vec = r.keys("*");
cout << "KEY LIST FOR *" << endl;
for (std::vector<std::string>::iterator it = vec.begin() ; it != vec.end(); ++it) {
cout << *it << endl;
}
cout << endl;
}
/** Test to ensure that redis keys are correctly returned */
void testRedisIO() {
RedisHandler r;
std::vector<string>* vec;
std::string outTrue, outFalse = "";
r.connect();
r.write("test_key", "test value");
outTrue = r.read("test_key");
assert(std::strcmp(outTrue.c_str(), "test value") == 0);
r.deleteKey("test_key");
assert(!r.exists("test_key"));
}
/** Test to ensure that md5 hashing works */
void testMd5Hashing() {
cout << endl << "md5 of 'mykey': " << md5("mykey") << endl;
}
/** Test to ensure that md5 hashing works */
void testRegexForTypes() {
IntegerColumn ic;
FloatColumn fc;
assert(ic.validate("1981"));
assert(fc.validate("5.2"));
cout << "Passed regex tests." << endl;
}
/** Test to ensure that md5 hashing works */
void testOrderPairAlphaNumeric() {
IndexHandler ih;
assert(std::strcmp(ih.orderPairAlphaNumeric("b", "a").c_str(), "a_b") == 0);
cout << "Passed orderPairAlphaNumeric tests." << endl;
}
/**
* Test to ensure that relation entities are encoded properly
*/
void testJSONEntityEncoding() {
IndexHandler ih;
Json::Value json;
std::vector<std::pair<ColumnBase, std::string>> fields_ent;
fields_ent.push_back(std::make_pair(IntegerColumn(), "a")); // Create fields
Entity e("test", fields_ent);
ih.writeEntity(e); // Create the entity
ih.fetchEntity("test", json); // Fetch the entity representation
cout << "TEST ENTITY:" << endl << endl << json.toStyledString() << endl;
// Assert that entity as read matches definition
assert(std::strcmp(json["entity"].asCString(), "test") == 0 &&
std::strcmp(json["fields"]["a"].asCString(), "integer") == 0 &&
json["fields"]["_itemcount"].asInt() == 1
);
ih.removeEntity("test"); // Remove the entity
}
/**
* Test to ensure that relation fields are encoded properly
*/
void testJSONRelationEncoding() {
IndexHandler ih;
std::vector<Json::Value> ret;
std::vector<std::pair<ColumnBase, std::string>> fields_ent_1;
std::vector<std::pair<ColumnBase, std::string>> fields_ent_2;
std::vector<std::pair<std::string, std::string>> fields_rel_1;
std::vector<std::pair<std::string, std::string>> fields_rel_2;
std::unordered_map<std::string, std::string> types_rel_1, types_rel_2;
// Popualate fields
fields_ent_1.push_back(std::make_pair(IntegerColumn(), "a"));
fields_ent_2.push_back(std::make_pair(StringColumn(), "b"));
fields_rel_1.push_back(std::make_pair("a", "1"));
fields_rel_2.push_back(std::make_pair("b", "hello"));
types_rel_1.insert(std::make_pair("a", COLTYPE_NAME_INT));
types_rel_2.insert(std::make_pair("b", COLTYPE_NAME_FLOAT));
// Create entities
Entity e1("test_1", fields_ent_1), e2("test_2", fields_ent_2);
ih.writeEntity(e1);
ih.writeEntity(e2);
// Create relation in redis
Relation r("test_1", "test_2", fields_rel_1, fields_rel_2, types_rel_1, types_rel_2);
ih.writeRelation(r);
// Fetch the entity representation
ret = ih.fetchRelationPrefix("test_1", "test_2");
cout << "TEST RELATION:" << endl << endl << ret[0].toStyledString() << endl;
// Assert that entity as read matches definition
assert(
std::strcmp(ret[0]["entity_left"].asCString(), "test_1") == 0 &&
std::strcmp(ret[0]["entity_right"].asCString(), "test_2") == 0 &&
std::strcmp(ret[0]["fields_left"]["a"].asCString(), "1") == 0 &&
std::strcmp(ret[0]["fields_right"]["b"].asCString(), "hello") == 0 &&
ret[0]["fields_left"]["_itemcount"].asInt() == 1 &&
ret[0]["fields_right"]["_itemcount"].asInt() == 1
);
ih.removeEntity("test_1"); // Remove the entity
ih.removeEntity("test_2"); // Remove the entity
ih.removeRelation(r); // Remove the relation
}
/**
* Tests that parseEntityAssignField correctly flags invalid assignments to integer fields
*/
void testFieldAssignTypeMismatchInteger() {
IndexHandler ih;
Json::Value json;
std::vector<std::pair<ColumnBase, std::string>> fields_ent;
fields_ent.push_back(std::make_pair(IntegerColumn(), "a")); // Create fields
Entity e("test", fields_ent);
ih.writeEntity(e); // Create the entity
assert(
ih.validateEntityFieldType("test", "a", "1") &&
ih.validateEntityFieldType("test", "a", "12345") &&
!ih.validateEntityFieldType("test", "a", "1.0") &&
!ih.validateEntityFieldType("test", "a", "string")
);
ih.removeEntity("test");
}
/**
* Tests that parseEntityAssignField correctly flags invalid assignments to float fields
*/
void testFieldAssignTypeMismatchFloat() {
IndexHandler ih;
Json::Value json;
std::vector<std::pair<ColumnBase, std::string>> fields_ent;
fields_ent.push_back(std::make_pair(FloatColumn(), "a")); // Create fields
Entity e("test", fields_ent); // Create the entity
ih.writeEntity(e); // Create the entity
assert(
ih.validateEntityFieldType("test", "a", "1.2") &&
ih.validateEntityFieldType("test", "a", "12.5") &&
!ih.validateEntityFieldType("test", "a", "string")
);
ih.removeEntity("test");
}
/**
* Tests that parseEntityAssignField correctly flags invalid assignments to string fields
*/
void testFieldAssignTypeMismatchString() {
IndexHandler ih;
Json::Value json;
std::vector<std::pair<ColumnBase, std::string>> fields_ent;
fields_ent.push_back(std::make_pair(StringColumn(), "a")); // Create fields
Entity e("test", fields_ent);
ih.writeEntity(e); // Create the entity
assert(
ih.validateEntityFieldType("test", "a", "1") &&
ih.validateEntityFieldType("test", "a", "12345") &&
ih.validateEntityFieldType("test", "a", "string")
);
ih.removeEntity("test");
}
/**
* Tests Bayes::countRelations - ensure relation counting is functioning correctly
*/
void testCountRelations() {
Bayes bayes;
IndexHandler ih;
std::vector<Json::Value> ret;
std::vector<std::pair<ColumnBase, std::string>> fields_ent;
std::vector<std::pair<std::string, std::string>> fields_rel;
std::unordered_map<std::string, std::string> types;
// declare three entities
Entity e1("_w", fields_ent), e2("_x", fields_ent), e3("_y", fields_ent), e4("_z", fields_ent);
// construct a number of relations
Relation r1("_x", "_y", fields_rel, fields_rel, types, types);
Relation r2("_x", "_y", fields_rel, fields_rel, types, types);
Relation r3("_x", "_z", fields_rel, fields_rel, types, types);
Relation r4("_x", "_z", fields_rel, fields_rel, types, types);
Relation r5("_w", "_y", fields_rel, fields_rel, types, types);
ih.removeEntity("_w");
ih.removeEntity("_x");
ih.removeEntity("_y");
ih.removeEntity("_z");
ih.writeEntity(e1);
ih.writeEntity(e2);
ih.writeEntity(e3);
ih.writeEntity(e4);
ih.removeRelation(r1);
ih.removeRelation(r2);
ih.removeRelation(r3);
ih.removeRelation(r4);
ih.removeRelation(r5);
ih.writeRelation(r1);
ih.writeRelation(r2);
ih.writeRelation(r3);
ih.writeRelation(r4);
ih.writeRelation(r5);
AttributeBucket attrs; // empty set of filters
assert(bayes.countEntityInRelations(e1.name, attrs) == 1);
assert(bayes.countEntityInRelations(e2.name, attrs) == 4);
assert(bayes.countEntityInRelations(e3.name, attrs) == 3);
assert(bayes.countEntityInRelations(e4.name, attrs) == 2);
}
/**
* Tests that existsEntityField correctly flags when entity does not contain a field
*/
void testEntityDoesNotContainField() {
// TODO - implement
}
/**
* Tests Bayes::computeMarginal function - ensure the marginal likelihood is correct
*/
void testComputeMarginal() {
Bayes bayes;
IndexHandler ih;
std::vector<Json::Value> ret;
std::vector<std::pair<ColumnBase, std::string>> fields_ent;
std::vector<std::pair<std::string, std::string>> fields_rel;
std::unordered_map<std::string, std::string> types;
ih.setRelationCountTotal(0);
// declare three entities
Entity e1("_w", fields_ent), e2("_x", fields_ent), e3("_y", fields_ent), e4("_z", fields_ent);
// construct a number of relations
Relation r1("_x", "_y", fields_rel, fields_rel, types, types);
Relation r2("_x", "_y", fields_rel, fields_rel, types, types);
Relation r3("_x", "_z", fields_rel, fields_rel, types, types);
Relation r4("_x", "_z", fields_rel, fields_rel, types, types);
Relation r5("_w", "_y", fields_rel, fields_rel, types, types);
ih.removeEntity("_w");
ih.removeEntity("_x");
ih.removeEntity("_y");
ih.removeEntity("_z");
ih.writeEntity(e1);
ih.writeEntity(e2);
ih.writeEntity(e3);
ih.writeEntity(e4);
ih.removeRelation(r1);
ih.removeRelation(r2);
ih.removeRelation(r3);
ih.removeRelation(r4);
ih.removeRelation(r5);
ih.writeRelation(r1);
ih.writeRelation(r2);
ih.writeRelation(r3);
ih.writeRelation(r4);
ih.writeRelation(r5);
ih.setRelationCountTotal(ih.computeRelationsCount("*", "*"));
// Ensure marginal likelihood reflects the number of relations that contain each entity
AttributeBucket attrs;
assert(bayes.computeMarginal(e1.name, attrs) == (float)0.2);
assert(bayes.computeMarginal(e2.name, attrs) == (float)0.8);
assert(bayes.computeMarginal(e3.name, attrs) == (float)0.6);
assert(bayes.computeMarginal(e4.name, attrs) == (float)0.4);
}
/**
* Tests that removal of entities functions properly
*/
void testEntityRemoval() {
IndexHandler ih;
std::vector<std::pair<ColumnBase, std::string>> fields_ent;
// declare three entities
Entity e("_w", fields_ent);
if (ih.existsEntity(e))
ih.removeEntity(e)
ih.writeEntity(e);
ih.removeEntity(e);
assert(ih.existsEntity(e));
}
/**
* Tests that removal of relations functions properly
*/
void testRelationRemoval() {
// TODO - implement
}
/**
* Tests that removal of relations cascading on entities functions properly
*/
void testEntityCascadeRemoval() {
// TODO - implement
}
/**
* Tests that the correct relations are filtered from a set
*/
void testRelationFiltering() {
// TODO - implement
}
/**
* Tests that the correct relations are filtered from a set
*/
void testRelation_toJson() {
valpair left, right;
std::unordered_map<std::string, std::string> typesL, typesR;
left.push_back(std::make_pair("x", "1"));
right.push_back(std::make_pair("y", "2"));
typesL.insert(std::make_pair("x", COLTYPE_NAME_INT));
typesR.insert(std::make_pair("y", COLTYPE_NAME_INT));
Relation rel("x", "y", left, right, typesL, typesR);
Json::Value json = rel.toJson();
assert(std::atoi(json[JSON_ATTR_REL_FIELDSL]["x"].asCString()) == 1 && std::atoi(json[JSON_ATTR_REL_FIELDSR]["y"].asCString()) == 2);
}
/**
* Ensure sample marginal returns a valid sample
*/
void testSampleMarginal() {
// Define entities and relations
// Generate a sample
// specify filter criteria
// test sample to ensure that it meets criteria
}
/**
* Ensure sample marginal returns a valid sample
*/
void testSamplePairwise() {
// Define entities and relations
// Generate a sample
// specify filter criteria
// test sample to ensure that it meets criteria
}
/**
* Ensure sample marginal returns a valid sample
*/
void testSamplePairwiseCausal() {
// Define entities and relations
// Generate a sample
// specify filter criteria
// test sample to ensure that it meets criteria
}
int main() {
cout << "-- TESTS BEGIN --" << endl << endl;
// testRedisSet();
// testRedisGet();
// testRedisKeys();
// md5Hashing();
// testRedisIO();
// testRegexForTypes();
// testOrderPairAlphaNumeric();
// testJSONEntityEncoding();
// testJSONRelationEncoding();
// testFieldAssignTypeMismatchInteger();
// testFieldAssignTypeMismatchFloat();
// testFieldAssignTypeMismatchString();
// testCountRelations();
testComputeMarginal();
// testRelation_toJson();
cout << endl << "-- TESTS END --" << endl;
return 0;
}
<|endoftext|> |
<commit_before>///
/// @file test.cpp
///
/// Copyright (C) 2014 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primecount.hpp>
#include <primesieve.hpp>
#include <stdint.h>
#include <iostream>
#include <cstdlib>
#include <string>
#include <stdexcept>
#include <sstream>
#include <ctime>
using namespace std;
using primecount::MAX_THREADS;
namespace {
void assert_equal(const string& f1_name, int64_t x, int64_t f1_res, int64_t f2_res)
{
if (f1_res != f2_res)
{
ostringstream oss;
oss << f1_name << "(" << x << ") = " << f1_res
<< " is an error, the correct result is " << f2_res;
throw runtime_error(oss.str());
}
}
/// 0 <= get_rand() < 10^7
int get_rand()
{
return (rand() % 10000) * 1000 + 1;
}
template <typename F>
void check_equal(const string& f1_name, F f1, F f2, int64_t iters)
{
srand(static_cast<unsigned int>(time(0)));
cout << "Testing " << (f1_name + "(x)") << flush;
// test for 0 <= x < iters
for (int64_t x = 0; x < iters; x++)
assert_equal(f1_name, x, f1(x, MAX_THREADS), f2(x, MAX_THREADS));
int64_t x = 0;
// test using random increment
for (int64_t i = 0; i < iters; i++, x += get_rand())
assert_equal(f1_name, x, f1(x, MAX_THREADS), f2(x, MAX_THREADS));
cout << " correct" << endl;
}
int64_t pps_nth_prime(int64_t x, int)
{
int64_t prime = primesieve::parallel_nth_prime(x);
return prime;
}
} // namespace
namespace primecount {
bool test()
{
try
{
check_equal("pi_legendre", pi_legendre, pi_primesieve, 100);
check_equal("pi_meissel", pi_meissel, pi_legendre, 500);
check_equal("pi_lehmer", pi_lehmer, pi_meissel, 500);
check_equal("pi_lmo1", pi_lmo1, pi_lehmer, 500);
check_equal("pi_lmo2", pi_lmo2, pi_lehmer, 500);
check_equal("pi_lmo3", pi_lmo3, pi_lehmer, 500);
check_equal("pi_lmo4", pi_lmo4, pi_lehmer, 500);
check_equal("nth_prime", nth_prime, pps_nth_prime, 100);
}
catch (runtime_error& e)
{
cerr << endl << e.what() << endl;
return false;
}
cout << "All tests passed successfully!" << endl;
return true;
}
} // namespace primecount
<commit_msg>Avoid nth_prime(0) error<commit_after>///
/// @file test.cpp
///
/// Copyright (C) 2014 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primecount.hpp>
#include <primesieve.hpp>
#include <stdint.h>
#include <iostream>
#include <cstdlib>
#include <string>
#include <stdexcept>
#include <sstream>
#include <ctime>
using namespace std;
using primecount::MAX_THREADS;
namespace {
void assert_equal(const string& f1_name, int64_t x, int64_t f1_res, int64_t f2_res)
{
if (f1_res != f2_res)
{
ostringstream oss;
oss << f1_name << "(" << x << ") = " << f1_res
<< " is an error, the correct result is " << f2_res;
throw runtime_error(oss.str());
}
}
/// 0 <= get_rand() < 10^7
int get_rand()
{
return (rand() % 10000) * 1000 + 1;
}
template <typename F>
void check_equal(const string& f1_name, F f1, F f2, int64_t iters)
{
srand(static_cast<unsigned int>(time(0)));
cout << "Testing " << (f1_name + "(x)") << flush;
// test for 1 <= x <= iters
for (int64_t x = 1; x <= iters; x++)
assert_equal(f1_name, x, f1(x, MAX_THREADS), f2(x, MAX_THREADS));
int64_t x = 1;
// test using random increment
for (int64_t i = 1; i <= iters; i++, x += get_rand())
assert_equal(f1_name, x, f1(x, MAX_THREADS), f2(x, MAX_THREADS));
cout << " correct" << endl;
}
int64_t pps_nth_prime(int64_t x, int)
{
int64_t prime = primesieve::parallel_nth_prime(x);
return prime;
}
} // namespace
namespace primecount {
bool test()
{
try
{
check_equal("pi_legendre", pi_legendre, pi_primesieve, 100);
check_equal("pi_meissel", pi_meissel, pi_legendre, 500);
check_equal("pi_lehmer", pi_lehmer, pi_meissel, 500);
check_equal("pi_lmo1", pi_lmo1, pi_lehmer, 500);
check_equal("pi_lmo2", pi_lmo2, pi_lehmer, 500);
check_equal("pi_lmo3", pi_lmo3, pi_lehmer, 500);
check_equal("pi_lmo4", pi_lmo4, pi_lehmer, 500);
check_equal("nth_prime", nth_prime, pps_nth_prime, 100);
}
catch (runtime_error& e)
{
cerr << endl << e.what() << endl;
return false;
}
cout << "All tests passed successfully!" << endl;
return true;
}
} // namespace primecount
<|endoftext|> |
<commit_before>
#include <SFML/Graphics.hpp>
#include <SFML/Window.hpp>
#include <SFML/System.hpp>
namespace demo
{
template <typename T, int W, int H>
class frameb
{
public:
T& xy(int x, int y) { return _data[y * W + x]; }
T& ofs(int o) { return _data[o]; }
const T& xy(int x, int y) const { return _data[y * W + x]; }
const T& ofs(int o) const { return _data[o]; }
T* data() { return _data; }
private:
T _data[W * (H + 1)];
};
template <typename T, int W, int H, T (*F)(int, int)>
class procfn
{
public:
T xy(int x, int y) const { return F(x, y); }
T ofs(int o) const { return F(o % W, o / W); }
};
template <typename T, int W, int H, class P, T (*F)(int, int, const P&)>
class procst
{
public:
P _params;
T xy(int x, int y) const { return F(x, y, _params); }
T ofs(int o) const { return F(o % W, o / W, _params); }
};
template <typename T, int W, int H, class I>
class buffer : public I
{
public:
typedef buffer<T, W, H, I> tBuffer;
using I::xy;
using I::ofs;
template <class U>
tBuffer& copyXY(const U& src)
{
for (int y = 0, o = 0; y < H; ++y)
for (int x = 0; x < W; ++x, ++o)
ofs(o) = src.xy(x, y);
return *this;
}
template <class U>
tBuffer& copyOfs(const U& src)
{
for (int o = 0; o < W * H; ++o)
ofs(o) = src.ofs(o);
return *this;
}
template <typename T0, class I0, typename F>
tBuffer& transformXY(const buffer<T0, W, H, I0>& src0, const F& func)
{
for (int y = 0, o = 0; y < H; ++y)
for (int x = 0; x < W; ++x, ++o)
ofs(o) = func(src0.xy(x, y));
return *this;
}
template <typename T0, class I0, typename F>
tBuffer& transformOfs(const buffer<T0, W, H, I0>& src0, const F& func)
{
for (int o = 0; o < W * H; ++o)
ofs(o) = func(src0.ofs(o));
return *this;
}
template <typename T0, class I0, typename T1, class I1, typename F>
tBuffer& transformXY(const buffer<T0, W, H, I0>& src0, const buffer<T1, W, H, I1>& src1, const F& func)
{
for (int y = 0, o = 0; y < H; ++y)
for (int x = 0; x < W; ++x, ++o)
ofs(o) = func(src0.xy(x, y), src1.xy(x, y));
return *this;
}
template <typename T0, class I0, typename T1, class I1, typename F>
tBuffer& transformOfs(const buffer<T0, W, H, I0>& src0, const buffer<T1, W, H, I1>& src1, const F& func)
{
for (int o = 0; o < W * H; ++o)
ofs(o) = func(src0.ofs(o), src1.ofs(o));
return *this;
}
};
template <int W, int H>
class demowin
{
public:
typedef buffer<sf::Uint32, W, H, demo::frameb<sf::Uint32, W, H>> tBackBuffer;
demowin()
{
}
template <class T>
buffer<T, W, H, demo::frameb<T, W, H>>* createBuffer()
{
return new buffer<T, W, H, demo::frameb<T, W, H>>();
}
template <class F>
void run(const F& f)
{
auto bgFb = new buffer<sf::Uint32, W, H, demo::frameb<sf::Uint32, W, H>>();
sf::RenderWindow win(sf::VideoMode(W, H), "toto");
win.setFramerateLimit(60);
win.setVerticalSyncEnabled(true);
sf::Texture bg;
bg.create(W, H);
sf::Sprite bgSp(bg);
sf::View view = win.getDefaultView();
sf::Vector2u winSize;
int frame = 0;
while (win.isOpen())
{
sf::Event e;
while (win.pollEvent(e))
{
switch (e.type)
{
case sf::Event::Closed:
win.close();
break;
case sf::Event::Resized:
winSize = sf::Vector2u(e.size.width, e.size.height);
view.reset(sf::FloatRect(0.0f, 0.0f, e.size.width, e.size.height));
win.setView(view);
win.setSize(winSize);
break;
default:
break;
}
}
if (!f(*bgFb, frame))
win.close();
bg.update((sf::Uint8*)&bgFb->ofs(0));
float s0 = winSize.x / float(W);
float s1 = winSize.y / float(H);
float s = std::min(s0, s1);
float x = 0.5f * (winSize.x - s * W);
float y = 0.5f * (winSize.y - s * H);
bgSp.setScale(s, s);
bgSp.setPosition(x, y);
win.clear(sf::Color::Black);
win.draw(bgSp);
win.display();
++frame;
}
}
};
inline sf::Uint32 argb(sf::Uint8 a, sf::Uint8 r, sf::Uint8 g, sf::Uint8 b)
{
return (a << 24) | (r << 16) | (g << 8) | b;
}
inline sf::Uint32 modulate(sf::Uint32 a, sf::Uint32 b)
{
typedef sf::Uint8 tColor[4];
tColor& c = *reinterpret_cast<tColor*>(&a);
tColor& d = *reinterpret_cast<tColor*>(&b);
sf::Uint32 r;
tColor& e = *reinterpret_cast<tColor*>(&r);
e[0] = sf::Uint8(c[0] * d[0] / 255u);
e[1] = sf::Uint8(c[1] * d[1] / 255u);
e[2] = sf::Uint8(c[2] * d[2] / 255u);
e[3] = sf::Uint8(c[3] * d[3] / 255u);
return r;
}
template <class T, size_t N, class F>
std::array<T, N> makePal(const F& f)
{
std::array<T, N> r;
for (size_t i = 0; i < N; ++i)
r[i] = f(i);
return r;
}
sf::Uint8 r8(int v, int a, int b)
{
return sf::Uint8((255u * (v - a)) / (b - a));
}
}
const int ScrWidth = 320;
const int ScrHeight = 200;
// ---------------------------------------------------------------------------------------
// circles
// ---------------------------------------------------------------------------------------
struct ccparams
{
int x0, y0, x1, y1;
};
inline int dist(int x0, int y0, int x1, int y1)
{
int dx = x1 - x0;
int dy = y1 - y0;
return dx * dx + dy * dy;
}
static inline sf::Uint8 computeCC(int x, int y, const ccparams& p)
{
int u = dist(p.x0, p.y0, x, y) / 512;
int v = dist(p.x1, p.y1, x, y) / 512;
return u ^ v;
}
// ---------------------------------------------------------------------------------------
// plasma
// ---------------------------------------------------------------------------------------
template <typename T>
T slerp(T x, T b)
{
return (3 * x * x * b - 2 * x * x * x) / (b * b);
}
template <typename T>
T fakesin(T x, T b)
{
x = x & (b - 1);
return (x < b / 2) ? slerp<T>(x, b / 2) : b / 2 - slerp<T>(x - b / 2, b / 2);
}
static inline sf::Uint8 sample(int x, int y)
{
return fakesin<int>(x, 256) + fakesin<int>(y, 256);
}
static inline sf::Uint8 computePlasma(int x, int y, const int& frame)
{
const sf::Uint8 p0 = sample(x, y);
const sf::Uint8 p1 = sample(x + fakesin<int>(y + 4 * frame, 256), y);
const sf::Uint8 p2 = sample(x, y + fakesin<int>(x + 3 * frame, 256));
return p0 + p1 + p2;
}
// ---------------------------------------------------------------------------------------
// fire
// ---------------------------------------------------------------------------------------
inline void setFire(sf::Uint16* d, int frame)
{
if (frame % 4 == 0)
{
for (int j = 0; j < ScrWidth;)
{
sf::Uint8 r = 192 + 63 * (rand() % 2);
for (int i = 0; i < 10; ++i, ++j)
{
d[(ScrHeight - 1) * ScrWidth + j] = (r << 8) + rand() % 256;
}
}
}
for (int j = 0; j < 2; ++j)
{
for (int i = 0; i < (ScrHeight - 1) * ScrWidth; ++i)
{
d[i] = (2 * d[i] + 1 * d[i + ScrWidth - 1] + 3 * d[i + ScrWidth] + 2 * d[i + ScrWidth + 1]) / 8;
if (d[i] > 255 /*&& d[i] < (200 << 8)*/)
d[i] -= 256;
}
}
}
// ---------------------------------------------------------------------------------------
// main
// ---------------------------------------------------------------------------------------
int main(int, char**)
{
typedef demo::demowin<ScrWidth, ScrHeight> tWin320x200;
tWin320x200 win;
auto fb8 = win.createBuffer<sf::Uint8>();
auto fb16 = win.createBuffer<sf::Uint16>();
auto cc = new demo::buffer<sf::Uint8, ScrWidth, ScrHeight, demo::procst<sf::Uint8, ScrWidth, ScrHeight, ccparams, computeCC>>();
auto plasma = new demo::buffer<sf::Uint8, ScrWidth, ScrHeight, demo::procst<sf::Uint8, ScrWidth, ScrHeight, int, computePlasma>>();
auto pal0 = demo::makePal<sf::Uint32, 256>([] (size_t i) { return demo::argb(255, i, 0, i); });
auto pal1 = demo::makePal<sf::Uint32, 256>([] (size_t i) { return (i < 128) ? demo::argb(255, 255 - i * 2, 0, i * 2) : demo::argb(255, (i - 128) * 2, 0, 255 - (i - 128) * 2); });
auto pal2 = demo::makePal<sf::Uint32, 256>([] (size_t i) {
if (i < 64 ) return demo::argb(255, 0 , 0 , 4 * i);
if (i < 128) return demo::argb(255, 0 , 4 * (i - 64), 255 );
if (i < 192) return demo::argb(255, 4 * (i - 128), 255 , 255 );
return demo::argb(255, 255 , 255 , 255 );
});
win.run([&] (tWin320x200::tBackBuffer& bgFb, int frame) {
const int fxDuration = 1000;
if (frame < 1 * fxDuration)
{
plasma->_params = frame;
bgFb.transformOfs(fb8->copyXY(*plasma), [&pal1] (sf::Uint8 l) { return pal1[l]; });
}
else if (frame < 2 * fxDuration)
{
// use 16bpp buffer to increase quality
setFire(fb16->data(), frame);
bgFb.transformOfs(*fb16, [&pal2] (sf::Uint16 l) { return pal2[l >> 8]; });
}
else if (frame < 3 * fxDuration)
{
cc->_params = {
int(160 + 150 * sinf(0.03f * frame)), 100,
160, int(100 + 90 * sinf(0.04f * frame))
};
bgFb.transformOfs(fb8->copyXY(*cc), [&pal0] (sf::Uint8 l) { return pal0[l]; });
}
else
{
return false;
}
return true;
});
return 0;
}
<commit_msg>rotozoom wip<commit_after>
#include <SFML/Graphics.hpp>
#include <SFML/Window.hpp>
#include <SFML/System.hpp>
namespace demo
{
template <typename T, int W, int H>
class frameb
{
public:
T& xy(int x, int y) { return _data[y * W + x]; }
T& ofs(int o) { return _data[o]; }
const T& xy(int x, int y) const { return _data[y * W + x]; }
const T& ofs(int o) const { return _data[o]; }
T* data() { return _data; }
private:
T _data[W * (H + 1)];
};
template <typename T, int W, int H, T (*F)(int, int)>
class procfn
{
public:
T xy(int x, int y) const { return F(x, y); }
T ofs(int o) const { return F(o % W, o / W); }
};
template <typename T, int W, int H, class P, T (*F)(int, int, const P&)>
class procst
{
public:
P _params;
T xy(int x, int y) const { return F(x, y, _params); }
T ofs(int o) const { return F(o % W, o / W, _params); }
};
template <typename T, int W, int H, class I>
class buffer : public I
{
public:
typedef buffer<T, W, H, I> tBuffer;
using I::xy;
using I::ofs;
template <class U>
tBuffer& copyXY(const U& src)
{
for (int y = 0, o = 0; y < H; ++y)
for (int x = 0; x < W; ++x, ++o)
ofs(o) = src.xy(x, y);
return *this;
}
template <class U>
tBuffer& copyOfs(const U& src)
{
for (int o = 0; o < W * H; ++o)
ofs(o) = src.ofs(o);
return *this;
}
template <typename T0, class I0, typename F>
tBuffer& transformXY(const buffer<T0, W, H, I0>& src0, const F& func)
{
for (int y = 0, o = 0; y < H; ++y)
for (int x = 0; x < W; ++x, ++o)
ofs(o) = func(src0.xy(x, y));
return *this;
}
template <typename T0, class I0, typename F>
tBuffer& transformOfs(const buffer<T0, W, H, I0>& src0, const F& func)
{
for (int o = 0; o < W * H; ++o)
ofs(o) = func(src0.ofs(o));
return *this;
}
template <typename T0, class I0, typename T1, class I1, typename F>
tBuffer& transformXY(const buffer<T0, W, H, I0>& src0, const buffer<T1, W, H, I1>& src1, const F& func)
{
for (int y = 0, o = 0; y < H; ++y)
for (int x = 0; x < W; ++x, ++o)
ofs(o) = func(src0.xy(x, y), src1.xy(x, y));
return *this;
}
template <typename T0, class I0, typename T1, class I1, typename F>
tBuffer& transformOfs(const buffer<T0, W, H, I0>& src0, const buffer<T1, W, H, I1>& src1, const F& func)
{
for (int o = 0; o < W * H; ++o)
ofs(o) = func(src0.ofs(o), src1.ofs(o));
return *this;
}
};
template <int W, int H>
class demowin
{
public:
typedef buffer<sf::Uint32, W, H, demo::frameb<sf::Uint32, W, H>> tBackBuffer;
demowin()
{
}
template <class T>
buffer<T, W, H, demo::frameb<T, W, H>>* createBuffer()
{
return new buffer<T, W, H, demo::frameb<T, W, H>>();
}
template <class F>
void run(const F& f)
{
auto bgFb = new buffer<sf::Uint32, W, H, demo::frameb<sf::Uint32, W, H>>();
sf::RenderWindow win(sf::VideoMode(W, H), "toto");
win.setFramerateLimit(60);
win.setVerticalSyncEnabled(true);
sf::Texture bg;
bg.create(W, H);
sf::Sprite bgSp(bg);
sf::View view = win.getDefaultView();
sf::Vector2u winSize;
int frame = 0;
while (win.isOpen())
{
sf::Event e;
while (win.pollEvent(e))
{
switch (e.type)
{
case sf::Event::Closed:
win.close();
break;
case sf::Event::Resized:
winSize = sf::Vector2u(e.size.width, e.size.height);
view.reset(sf::FloatRect(0.0f, 0.0f, e.size.width, e.size.height));
win.setView(view);
win.setSize(winSize);
break;
default:
break;
}
}
if (!f(*bgFb, frame))
win.close();
bg.update((sf::Uint8*)&bgFb->ofs(0));
float s0 = winSize.x / float(W);
float s1 = winSize.y / float(H);
float s = std::min(s0, s1);
float x = 0.5f * (winSize.x - s * W);
float y = 0.5f * (winSize.y - s * H);
bgSp.setScale(s, s);
bgSp.setPosition(x, y);
win.clear(sf::Color::Black);
win.draw(bgSp);
win.display();
++frame;
}
}
};
inline sf::Uint32 argb(sf::Uint8 a, sf::Uint8 r, sf::Uint8 g, sf::Uint8 b)
{
return (a << 24) | (r << 16) | (g << 8) | b;
}
inline sf::Uint32 modulate(sf::Uint32 a, sf::Uint32 b)
{
typedef sf::Uint8 tColor[4];
tColor& c = *reinterpret_cast<tColor*>(&a);
tColor& d = *reinterpret_cast<tColor*>(&b);
sf::Uint32 r;
tColor& e = *reinterpret_cast<tColor*>(&r);
e[0] = sf::Uint8(c[0] * d[0] / 255u);
e[1] = sf::Uint8(c[1] * d[1] / 255u);
e[2] = sf::Uint8(c[2] * d[2] / 255u);
e[3] = sf::Uint8(c[3] * d[3] / 255u);
return r;
}
template <class T, size_t N, class F>
std::array<T, N> makePal(const F& f)
{
std::array<T, N> r;
for (size_t i = 0; i < N; ++i)
r[i] = f(i);
return r;
}
sf::Uint8 r8(int v, int a, int b)
{
return sf::Uint8((255u * (v - a)) / (b - a));
}
}
// window size
const int ScrWidth = 320;
const int ScrHeight = 200;
// ---------------------------------------------------------------------------------------
// circles
// ---------------------------------------------------------------------------------------
struct ccparams
{
int x0, y0, x1, y1;
};
inline int dist(int x0, int y0, int x1, int y1)
{
int dx = x1 - x0;
int dy = y1 - y0;
return dx * dx + dy * dy;
}
static inline sf::Uint8 computeCC(int x, int y, const ccparams& p)
{
int u = dist(p.x0, p.y0, x, y) / 512;
int v = dist(p.x1, p.y1, x, y) / 512;
return u ^ v;
}
// ---------------------------------------------------------------------------------------
// rotozoom
// ---------------------------------------------------------------------------------------
struct rzparams
{
int cx, cy;
int dx, dy;
};
static inline sf::Uint8 computeRotozoom(int x, int y, const rzparams& p)
{
x -= ScrWidth / 2;
y -= ScrHeight / 2;
int nx = (p.cx + x * p.dx - y * p.dy) / 256;
int ny = (p.cy + x * p.dy + y * p.dx) / 256;
return nx ^ ny;
}
// ---------------------------------------------------------------------------------------
// plasma
// ---------------------------------------------------------------------------------------
template <typename T>
inline T slerp(T x, T b)
{
return (3 * x * x * b - 2 * x * x * x) / (b * b);
}
template <typename T>
inline T fakesin(T x, T b)
{
const T nx = x & (b - 1);
const T nb = b / 2;
return (nx < nb) ? slerp<T>(nx, nb) : nb - slerp<T>(nx - nb, nb);
}
inline sf::Uint8 sample(int x, int y)
{
return fakesin<int>(x, 256) + fakesin<int>(y, 256);
}
static inline sf::Uint8 computePlasma(int x, int y, const int& frame)
{
const sf::Uint8 p0 = sample(x, y);
const sf::Uint8 p1 = sample(x + fakesin<int>(y + (20 * frame) / 16, 256), y);
const sf::Uint8 p2 = sample(x, y + fakesin<int>(x + (27 * frame) / 16, 256));
return p0 + p1 + p2;
}
// ---------------------------------------------------------------------------------------
// fire
// ---------------------------------------------------------------------------------------
inline void setFire(sf::Uint16* d, int frame)
{
// use 16bpp buffer to increase quality
if (frame % 4 == 0)
{
for (int j = 0; j < ScrWidth;)
{
sf::Uint8 r = 192 + 63 * (rand() % 2);
for (int i = 0; i < 10; ++i, ++j)
{
d[(ScrHeight - 1) * ScrWidth + j] = (r << 8) + rand() % 256;
}
}
}
for (int j = 0; j < 2; ++j)
{
for (int i = 0; i < (ScrHeight - 1) * ScrWidth; ++i)
{
d[i] = (2 * d[i] + 1 * d[i + ScrWidth - 1] + 3 * d[i + ScrWidth] + 2 * d[i + ScrWidth + 1]) / 8;
if (d[i] > 255 /*&& d[i] < (200 << 8)*/)
d[i] -= 256;
}
}
}
// ---------------------------------------------------------------------------------------
// main
// ---------------------------------------------------------------------------------------
int main(int, char**)
{
// open window
typedef demo::demowin<ScrWidth, ScrHeight> tWin320x200;
tWin320x200 win;
// back buffers
auto fb8 = win.createBuffer<sf::Uint8>();
auto fb16 = win.createBuffer<sf::Uint16>();
// fx buffers
auto cc = new demo::buffer<sf::Uint8, ScrWidth, ScrHeight, demo::procst<sf::Uint8, ScrWidth, ScrHeight, ccparams, computeCC>>();
auto rotozoom = new demo::buffer<sf::Uint8, ScrWidth, ScrHeight, demo::procst<sf::Uint8, ScrWidth, ScrHeight, rzparams, computeRotozoom>>();
auto plasma = new demo::buffer<sf::Uint8, ScrWidth, ScrHeight, demo::procst<sf::Uint8, ScrWidth, ScrHeight, int, computePlasma>>();
// palettes
auto palCC = demo::makePal<sf::Uint32, 256>([] (size_t i) { return demo::argb(255, i, 0, i); });
auto palRZ = demo::makePal<sf::Uint32, 256>([] (size_t i) { return demo::argb(255, i, 0, i); });
auto palPlasma = demo::makePal<sf::Uint32, 256>([] (size_t i) { return (i < 128) ? demo::argb(255, 255 - i * 2, 0, i * 2) : demo::argb(255, (i - 128) * 2, 0, 255 - (i - 128) * 2); });
auto palFire = demo::makePal<sf::Uint32, 256>([] (size_t i) {
if (i < 64 ) return demo::argb(255, 0 , 0 , 4 * i);
if (i < 128) return demo::argb(255, 0 , 4 * (i - 64), 255 );
if (i < 192) return demo::argb(255, 4 * (i - 128), 255 , 255 );
return demo::argb(255, 255 , 255 , 255 );
});
// run loop
win.run([&] (tWin320x200::tBackBuffer& bgFb, int frame) {
const int fxDuration = 1000;
if (frame < 1 * fxDuration)
{
const float rzf = 0.5f * frame;
const float a = 0.03f * rzf;
const float z = 1.2f + cosf(0.05f * rzf);
const float r = 500.0f;
rotozoom->_params = {
int(128.0f + 256.0f * r * cosf(0.03f * rzf)) , int(128.0f + 256.0f * r * cosf(0.04f * rzf)),
int(256.0f * z * cosf(a)), int(256.0f * z * sinf(a))
};
bgFb.transformOfs(fb8->copyXY(*rotozoom), [&palRZ] (sf::Uint8 l) { return palRZ[l]; });
}
else if (frame < 2 * fxDuration)
{
plasma->_params = frame;
bgFb.transformOfs(fb8->copyXY(*plasma), [&palPlasma] (sf::Uint8 l) { return palPlasma[l]; });
}
else if (frame < 3 * fxDuration)
{
setFire(fb16->data(), frame);
bgFb.transformOfs(*fb16, [&palFire] (sf::Uint16 l) { return palFire[l >> 8]; });
}
else if (frame < 4 * fxDuration)
{
cc->_params = {
int(160 + 150 * sinf(0.03f * frame)), 100,
160, int(100 + 90 * sinf(0.04f * frame))
};
bgFb.transformOfs(fb8->copyXY(*cc), [&palCC] (sf::Uint8 l) { return palCC[l]; });
}
else
{
return false;
}
return true;
});
return 0;
}
<|endoftext|> |
<commit_before>#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <sys/types.h>
#include <time.h>
#include <netdb.h>
extern "C" {
#include "stinger_core/stinger.h"
#include "stinger_core/xmalloc.h"
#include "stinger_utils/csv.h"
#include "stinger_utils/timer.h"
#include "stinger_utils/stinger_sockets.h"
}
#include "random_edge_generator.h"
#include "build_name.h"
using namespace gt::stinger;
#define E_A(X,...) fprintf(stderr, "%s %s %d:\n\t" #X "\n", __FILE__, __func__, __LINE__, __VA_ARGS__);
#define E(X) E_A(X,NULL)
#define V_A(X,...) fprintf(stdout, "%s %s %d:\n\t" #X "\n", __FILE__, __func__, __LINE__, __VA_ARGS__);
#define V(X) V_A(X,NULL)
int
main(int argc, char *argv[])
{
/* global options */
int port = 10102;
int batch_size = 100000;
int num_batches = -1;
int nv = 1024;
int is_int = 0;
struct hostent * server = NULL;
int opt = 0;
while(-1 != (opt = getopt(argc, argv, "p:b:a:x:y:n:i"))) {
switch(opt) {
case 'p': {
port = atoi(optarg);
} break;
case 'x': {
batch_size = atol(optarg);
} break;
case 'y': {
num_batches = atol(optarg);
} break;
case 'i': {
is_int = 1;
} break;
case 'a': {
server = gethostbyname(optarg);
if(NULL == server) {
E_A("ERROR: server %s could not be resolved.", optarg);
exit(-1);
}
} break;
case 'n': {
nv = atol(optarg);
} break;
case '?':
case 'h': {
printf("Usage: %s [-p port] [-a server_addr] [-n num_vertices] [-x batch_size] [-y num_batches] [-i]\n", argv[0]);
printf("Defaults:\n\tport: %d\n\tserver: localhost\n\tnum_vertices: %d\n -i forces the use of integers in place of strings\n", port, nv);
exit(0);
} break;
}
}
V_A("Running with: port: %d\n", port);
/* connect to localhost if server is unspecified */
if(NULL == server) {
server = gethostbyname("localhost");
if(NULL == server) {
E_A("ERROR: server %s could not be resolved.", "localhost");
exit(-1);
}
}
/* start the connection */
int sock_handle = connect_to_batch_server (server, port);
/* actually generate and send the batches */
char * buf = NULL, ** fields = NULL;
uint64_t bufSize = 0, * lengths = NULL, fieldsSize = 0, count = 0;
int64_t line = 0;
int batch_num = 0;
srand (time(NULL));
while(1) {
StingerBatch batch;
batch.set_make_undirected(true);
batch.set_type(is_int ? NUMBERS_ONLY : STRINGS_ONLY);
batch.set_keep_alive(true);
std::string src, dest;
// IF YOU MAKE THIS LOOP PARALLEL,
// MOVE THE SRC/DEST STRINGS ABOVE
for(int e = 0; e < batch_size; e++) {
line++;
int64_t u = rand() % nv;
int64_t v = rand() % nv;
if(u == v) {
e--;
line--;
continue;
}
/* is insert? */
EdgeInsertion * insertion = batch.add_insertions();
if(is_int) {
insertion->set_source(u);
insertion->set_destination(v);
} else {
insertion->set_source_str(build_name(src, u));
insertion->set_destination_str(build_name(dest, v));
}
insertion->set_weight(1);
insertion->set_time(line);
}
V("Sending messages.");
send_message(sock_handle, batch);
sleep(2);
batch_num++;
if((batch_num >= num_batches) && (num_batches != -1)) {
break;
}
}
StingerBatch batch;
batch.set_make_undirected(true);
batch.set_type(is_int ? NUMBERS_ONLY : STRINGS_ONLY);
batch.set_keep_alive(false);
send_message(sock_handle, batch);
return 0;
}
<commit_msg>A few obvious enhancements & fixes for random_edge_generator<commit_after>#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <sys/types.h>
#include <time.h>
#include <netdb.h>
extern "C" {
#include "stinger_core/stinger.h"
#include "stinger_core/xmalloc.h"
#include "stinger_utils/csv.h"
#include "stinger_utils/timer.h"
#include "stinger_utils/stinger_sockets.h"
}
#include "random_edge_generator.h"
#include "build_name.h"
using namespace gt::stinger;
#define E_A(X,...) fprintf(stderr, "%s %s %d:\n\t" #X "\n", __FILE__, __func__, __LINE__, __VA_ARGS__);
#define E(X) E_A(X,NULL)
#define V_A(X,...) fprintf(stdout, "%s %s %d:\n\t" #X "\n", __FILE__, __func__, __LINE__, __VA_ARGS__);
#define V(X) V_A(X,NULL)
#define DEFAULT_SEED 0x9367
int
main(int argc, char *argv[])
{
/* global options */
int port = 10102;
long batch_size = 100000;
long num_batches = -1;
int64_t nv = 1024;
int is_int = 0;
int delay = 2;
long seed = DEFAULT_SEED;
struct hostent * server = NULL;
int opt = 0;
while(-1 != (opt = getopt(argc, argv, "p:b:a:x:y:n:is:d:"))) {
switch(opt) {
case 'p': {
port = atoi(optarg);
} break;
case 'x': {
batch_size = atol(optarg);
} break;
case 'y': {
num_batches = atol(optarg);
} break;
case 'd': {
delay = atoi (optarg);
} break;
case 's': {
long tmp_seed = atol (optarg);
if (tmp_seed) seed = tmp_seed;
else seed = time (NULL);
} break;
case 'i': {
is_int = 1;
} break;
case 'a': {
server = gethostbyname(optarg);
if(NULL == server) {
E_A("ERROR: server %s could not be resolved.", optarg);
exit(-1);
}
} break;
case 'n': {
nv = atol(optarg);
} break;
case '?':
case 'h': {
printf("Usage: %s [-p port] [-a server_addr] [-n num_vertices] [-x batch_size] [-y num_batches] [-i] [-s seed] [-d delay]\n", argv[0]);
printf("Defaults:\n\tport: %d\n\tserver: localhost\n\tnum_vertices: %d\n -i forces the use of integers in place of strings\n", port, nv);
exit(0);
} break;
}
}
if (nv > 1L<<31) {
fprintf (stderr, "generator does not support nv > 2**31 (requested %ld)\n", (long)nv);
return EXIT_FAILURE;
}
V_A("Running with: port: %d\n", port);
/* connect to localhost if server is unspecified */
if(NULL == server) {
server = gethostbyname("localhost");
if(NULL == server) {
E_A("ERROR: server %s could not be resolved.", "localhost");
exit(-1);
}
}
/* start the connection */
int sock_handle = connect_to_batch_server (server, port);
/* actually generate and send the batches */
char * buf = NULL, ** fields = NULL;
uint64_t bufSize = 0, * lengths = NULL, fieldsSize = 0, count = 0;
int64_t line = 0;
int batch_num = 0;
srand48 (seed);
const ldiv_t nv_breakup = ldiv (INT64_MAX, nv);
while(1) {
StingerBatch batch;
batch.set_make_undirected(true);
batch.set_type(is_int ? NUMBERS_ONLY : STRINGS_ONLY);
batch.set_keep_alive(true);
std::string src, dest;
// IF YOU MAKE THIS LOOP PARALLEL,
// MOVE THE SRC/DEST STRINGS ABOVE
for(int e = 0; e < batch_size; e++) {
line++;
int64_t u, v;
/* Rejection samping for u and v */
while (1) {
int64_t tmp = lrand48 ();
if (tmp >= nv_breakup.rem) {
u = tmp % nv;
break;
}
}
while (1) {
int64_t tmp = lrand48 ();
if (tmp >= nv_breakup.rem) {
v = tmp % nv;
break;
}
}
if(u == v) {
e--;
line--;
continue;
}
/* is insert? */
EdgeInsertion * insertion = batch.add_insertions();
if(is_int) {
insertion->set_source(u);
insertion->set_destination(v);
} else {
insertion->set_source_str(build_name(src, u));
insertion->set_destination_str(build_name(dest, v));
}
insertion->set_weight(1);
insertion->set_time(line);
}
V("Sending messages.");
send_message(sock_handle, batch);
sleep(delay);
batch_num++;
if((batch_num >= num_batches) && (num_batches != -1)) {
break;
}
}
StingerBatch batch;
batch.set_make_undirected(true);
batch.set_type(is_int ? NUMBERS_ONLY : STRINGS_ONLY);
batch.set_keep_alive(false);
send_message(sock_handle, batch);
return 0;
}
<|endoftext|> |
<commit_before>#include "LightCulling.h"
#include "Director.h"
#include "ResourceManager.h"
#include "Utility.h"
#include "EngineShaderFactory.hpp"
using namespace Device;
using namespace Core;
using namespace Rendering;
using namespace Rendering::Light;
using namespace Rendering::Buffer;
using namespace Rendering::Shader;
using namespace GPGPU::DirectCompute;
using namespace Resource;
using namespace Rendering::TBDR;
LightCulling::LightCulling() : _computeShader(nullptr)
{
}
LightCulling::~LightCulling()
{
Destroy();
}
void LightCulling::AddInputBufferToList(uint idx, const ShaderResourceBuffer* buffer)
{
ShaderForm::InputShaderResourceBuffer inputBuffer;
{
inputBuffer.bindIndex = idx;
inputBuffer.srBuffer = buffer;
}
_inputBuffers.push_back(inputBuffer);
}
void LightCulling::AddTextureToInputTextureList(uint idx, const Texture::Texture2D* texture)
{
ShaderForm::InputTexture inputTex;
{
inputTex.bindIndex = idx;
inputTex.texture = texture;
}
_inputTextures.push_back(inputTex);
}
void LightCulling::Initialize(const std::string& filePath, const std::string& mainFunc,
const Texture::DepthBuffer* opaqueDepthBuffer, const Texture::DepthBuffer* blendedDepthBuffer,
const std::vector<Shader::ShaderMacro>* opationalMacros)
{
ResourceManager* resourceManager = ResourceManager::SharedInstance();
auto shaderMgr = resourceManager->GetShaderManager();
std::vector<Shader::ShaderMacro> macros;
{
ShaderMacro msaaMacro = Device::Director::SharedInstance()->GetDirectX()->GetMSAAShaderMacro();
macros.push_back(msaaMacro);
macros.push_back(ShaderMacro("USE_COMPUTE_SHADER", ""));
if(blendedDepthBuffer)
macros.push_back(ShaderMacro("ENABLE_BLEND", ""));
if(opationalMacros)
macros.insert(macros.end(), opationalMacros->begin(), opationalMacros->end());
}
ID3DBlob* blob = shaderMgr->CreateBlob(filePath, "cs", mainFunc, false, ¯os);
ComputeShader::ThreadGroup threadGroup;
UpdateThreadGroup(&threadGroup, false);
_computeShader = new ComputeShader(threadGroup, blob);
ASSERT_COND_MSG(_computeShader->Initialize(), "can not create compute shader");
Manager::LightManager* lightManager = Director::SharedInstance()->GetCurrentScene()->GetLightManager();
// Input Buffer Setting
{
AddInputBufferToList(uint(TextureBindIndex::PointLightRadiusWithCenter), lightManager->GetPointLightTransformSRBuffer());
AddInputBufferToList(uint(TextureBindIndex::SpotLightRadiusWithCenter), lightManager->GetSpotLightTransformSRBuffer());
AddInputBufferToList(uint(TextureBindIndex::SpotLightParam), lightManager->GetSpotLightParamSRBuffer());
// depth buffer
{
// Opaque Depth Buffer
AddTextureToInputTextureList(uint(TextureBindIndex::GBuffer_Depth), opaqueDepthBuffer);
// Blended DepthBuffer (used in Transparency Rendering)
if(blendedDepthBuffer)
AddTextureToInputTextureList(uint(TextureBindIndex::GBuffer_BlendedDepth), blendedDepthBuffer);
}
}
_useBlendedMeshCulling = blendedDepthBuffer != nullptr;
}
void LightCulling::SetInputsToCS()
{
_computeShader->SetInputSRBuffers(_inputBuffers);
_computeShader->SetInputTextures(_inputTextures);
}
// ȭ ũ Ÿ ִ Ѵ.
unsigned int LightCulling::CalcMaxNumLightsInTile()
{
const Math::Size<unsigned int>& size = Director::SharedInstance()->GetBackBufferSize();
const uint key = LIGHT_CULLING_TILE_RES;
return ( LIGHT_CULLING_LIGHT_MAX_COUNT_IN_TILE - ( key * ( size.h / 120 ) ) );
}
void LightCulling::Dispatch(const Device::DirectX* dx,
const Buffer::ConstBuffer* tbrConstBuffer,
const std::vector<ShaderForm::InputConstBuffer>* additionalConstBuffers)
{
ID3D11DeviceContext* context = dx->GetContext();
std::vector<ShaderForm::InputConstBuffer> inputConstBuffers;
if(tbrConstBuffer)
{
ShaderForm::InputConstBuffer icb;
icb.buffer = tbrConstBuffer;
icb.bindIndex = (uint)ConstBufferBindIndex::TBRParam;
inputConstBuffers.push_back(icb);
}
if(additionalConstBuffers)
inputConstBuffers.insert(inputConstBuffers.end(), additionalConstBuffers->begin(), additionalConstBuffers->end());
_computeShader->SetInputConstBuffers(inputConstBuffers);
_computeShader->Dispatch(context);
}
void LightCulling::UpdateThreadGroup(ComputeShader::ThreadGroup* outThreadGroup, bool updateComputeShader)
{
Math::Size<unsigned int> groupSize = CalcThreadGroupSize();
ComputeShader::ThreadGroup threadGroup = ComputeShader::ThreadGroup(groupSize.w, groupSize.h, 1);
if(outThreadGroup)
(*outThreadGroup) = threadGroup;
if(updateComputeShader)
_computeShader->SetThreadGroupInfo(threadGroup);
}
const Math::Size<unsigned int> LightCulling::CalcThreadGroupSize() const
{
auto CalcThreadLength = [](unsigned int size)
{
return (unsigned int)((size + LIGHT_CULLING_TILE_RES - 1) / (float)LIGHT_CULLING_TILE_RES);
};
const Math::Size<unsigned int>& size = Director::SharedInstance()->GetBackBufferSize();
unsigned int width = CalcThreadLength(size.w);
unsigned int height = CalcThreadLength(size.h);
return Math::Size<unsigned int>(width, height);
}
void LightCulling::Destroy()
{
_inputBuffers.clear();
_inputTextures.clear();
SAFE_DELETE(_computeShader);
_useBlendedMeshCulling = false;
}<commit_msg>LightCulling.cpp - Dispatch에 mainCamCB 추가<commit_after>#include "LightCulling.h"
#include "Director.h"
#include "ResourceManager.h"
#include "Utility.h"
#include "EngineShaderFactory.hpp"
using namespace Device;
using namespace Core;
using namespace Rendering;
using namespace Rendering::Light;
using namespace Rendering::Buffer;
using namespace Rendering::Shader;
using namespace GPGPU::DirectCompute;
using namespace Resource;
using namespace Rendering::TBDR;
LightCulling::LightCulling() : _computeShader(nullptr)
{
}
LightCulling::~LightCulling()
{
Destroy();
}
void LightCulling::AddInputBufferToList(uint idx, const ShaderResourceBuffer* buffer)
{
ShaderForm::InputShaderResourceBuffer inputBuffer;
{
inputBuffer.bindIndex = idx;
inputBuffer.srBuffer = buffer;
}
_inputBuffers.push_back(inputBuffer);
}
void LightCulling::AddTextureToInputTextureList(uint idx, const Texture::Texture2D* texture)
{
ShaderForm::InputTexture inputTex;
{
inputTex.bindIndex = idx;
inputTex.texture = texture;
}
_inputTextures.push_back(inputTex);
}
void LightCulling::Initialize(const std::string& filePath, const std::string& mainFunc,
const Texture::DepthBuffer* opaqueDepthBuffer, const Texture::DepthBuffer* blendedDepthBuffer,
const std::vector<Shader::ShaderMacro>* opationalMacros)
{
ResourceManager* resourceManager = ResourceManager::SharedInstance();
auto shaderMgr = resourceManager->GetShaderManager();
std::vector<Shader::ShaderMacro> macros;
{
ShaderMacro msaaMacro = Device::Director::SharedInstance()->GetDirectX()->GetMSAAShaderMacro();
macros.push_back(msaaMacro);
macros.push_back(ShaderMacro("USE_COMPUTE_SHADER", ""));
if(blendedDepthBuffer)
macros.push_back(ShaderMacro("ENABLE_BLEND", ""));
if(opationalMacros)
macros.insert(macros.end(), opationalMacros->begin(), opationalMacros->end());
}
ID3DBlob* blob = shaderMgr->CreateBlob(filePath, "cs", mainFunc, false, ¯os);
ComputeShader::ThreadGroup threadGroup;
UpdateThreadGroup(&threadGroup, false);
_computeShader = new ComputeShader(threadGroup, blob);
ASSERT_COND_MSG(_computeShader->Initialize(), "can not create compute shader");
Manager::LightManager* lightManager = Director::SharedInstance()->GetCurrentScene()->GetLightManager();
// Input Buffer Setting
{
AddInputBufferToList(uint(TextureBindIndex::PointLightRadiusWithCenter), lightManager->GetPointLightTransformSRBuffer());
AddInputBufferToList(uint(TextureBindIndex::SpotLightRadiusWithCenter), lightManager->GetSpotLightTransformSRBuffer());
AddInputBufferToList(uint(TextureBindIndex::SpotLightParam), lightManager->GetSpotLightParamSRBuffer());
// depth buffer
{
// Opaque Depth Buffer
AddTextureToInputTextureList(uint(TextureBindIndex::GBuffer_Depth), opaqueDepthBuffer);
// Blended DepthBuffer (used in Transparency Rendering)
if(blendedDepthBuffer)
AddTextureToInputTextureList(uint(TextureBindIndex::GBuffer_BlendedDepth), blendedDepthBuffer);
}
}
_useBlendedMeshCulling = blendedDepthBuffer != nullptr;
}
void LightCulling::SetInputsToCS()
{
_computeShader->SetInputSRBuffers(_inputBuffers);
_computeShader->SetInputTextures(_inputTextures);
}
// 화면 크기에 따라 유동적으로 타일 안 최대 빛 갯수를 계산한다.
unsigned int LightCulling::CalcMaxNumLightsInTile()
{
const Math::Size<unsigned int>& size = Director::SharedInstance()->GetBackBufferSize();
const uint key = LIGHT_CULLING_TILE_RES;
return ( LIGHT_CULLING_LIGHT_MAX_COUNT_IN_TILE - ( key * ( size.h / 120 ) ) );
}
void LightCulling::Dispatch(const Device::DirectX* dx,
const Buffer::ConstBuffer* tbrCB, const Buffer::ConstBuffer* mainCamCB,
const std::vector<ShaderForm::InputConstBuffer>* additionalConstBuffers)
{
ID3D11DeviceContext* context = dx->GetContext();
std::vector<ShaderForm::InputConstBuffer> inputConstBuffers;
ASSERT_COND_MSG(tbrCB && mainCamCB, "Error, tbrCB and mainCB is null");
{
inputConstBuffers.push_back(ShaderForm::InputConstBuffer((uint)ConstBufferBindIndex::TBRParam, tbrCB));
inputConstBuffers.push_back(ShaderForm::InputConstBuffer((uint)ConstBufferBindIndex::Camera, mainCamCB));
}
if(additionalConstBuffers)
inputConstBuffers.insert(inputConstBuffers.end(), additionalConstBuffers->begin(), additionalConstBuffers->end());
_computeShader->SetInputConstBuffers(inputConstBuffers);
_computeShader->Dispatch(context);
}
void LightCulling::UpdateThreadGroup(ComputeShader::ThreadGroup* outThreadGroup, bool updateComputeShader)
{
Math::Size<unsigned int> groupSize = CalcThreadGroupSize();
ComputeShader::ThreadGroup threadGroup = ComputeShader::ThreadGroup(groupSize.w, groupSize.h, 1);
if(outThreadGroup)
(*outThreadGroup) = threadGroup;
if(updateComputeShader)
_computeShader->SetThreadGroupInfo(threadGroup);
}
const Math::Size<unsigned int> LightCulling::CalcThreadGroupSize() const
{
auto CalcThreadLength = [](unsigned int size)
{
return (unsigned int)((size + LIGHT_CULLING_TILE_RES - 1) / (float)LIGHT_CULLING_TILE_RES);
};
const Math::Size<unsigned int>& size = Director::SharedInstance()->GetBackBufferSize();
unsigned int width = CalcThreadLength(size.w);
unsigned int height = CalcThreadLength(size.h);
return Math::Size<unsigned int>(width, height);
}
void LightCulling::Destroy()
{
_inputBuffers.clear();
_inputTextures.clear();
SAFE_DELETE(_computeShader);
_useBlendedMeshCulling = false;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Tests TelnetServer.
#include "net/base/listen_socket_unittest.h"
#include "net/base/telnet_server.h"
#include "testing/platform_test.h"
static const char* kCRLF = "\r\n";
class TelnetServerTester : public ListenSocketTester {
public:
virtual ListenSocket* DoListen() {
return TelnetServer::Listen("127.0.0.1", kTestPort, this);
}
virtual void SetUp() {
ListenSocketTester::SetUp();
// With TelnetServer, there's some control codes sent at connect time,
// so we need to eat those to avoid affecting the subsequent tests.
EXPECT_EQ(ClearTestSocket(), 15);
}
virtual bool Send(SOCKET sock, const std::string& str) {
if (ListenSocketTester::Send(sock, str)) {
// TelnetServer currently calls DidRead after a CRLF, so we need to
// append one to the end of the data that we send.
if (ListenSocketTester::Send(sock, kCRLF)) {
return true;
}
}
return false;
}
private:
~TelnetServerTester() {}
};
class TelnetServerTest: public PlatformTest {
protected:
TelnetServerTest() {
tester_ = NULL;
}
virtual void SetUp() {
PlatformTest::SetUp();
tester_ = new TelnetServerTester();
tester_->SetUp();
}
virtual void TearDown() {
PlatformTest::TearDown();
tester_->TearDown();
tester_ = NULL;
}
scoped_refptr<TelnetServerTester> tester_;
};
TEST_F(TelnetServerTest, ServerClientSend) {
tester_->TestClientSend();
}
TEST_F(TelnetServerTest, ClientSendLong) {
tester_->TestClientSendLong();
}
TEST_F(TelnetServerTest, ServerSend) {
tester_->TestServerSend();
}
<commit_msg>Mark TelnetServerTest.ServerClientSend as flaky.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Tests TelnetServer.
#include "net/base/listen_socket_unittest.h"
#include "net/base/telnet_server.h"
#include "testing/platform_test.h"
static const char* kCRLF = "\r\n";
class TelnetServerTester : public ListenSocketTester {
public:
virtual ListenSocket* DoListen() {
return TelnetServer::Listen("127.0.0.1", kTestPort, this);
}
virtual void SetUp() {
ListenSocketTester::SetUp();
// With TelnetServer, there's some control codes sent at connect time,
// so we need to eat those to avoid affecting the subsequent tests.
EXPECT_EQ(ClearTestSocket(), 15);
}
virtual bool Send(SOCKET sock, const std::string& str) {
if (ListenSocketTester::Send(sock, str)) {
// TelnetServer currently calls DidRead after a CRLF, so we need to
// append one to the end of the data that we send.
if (ListenSocketTester::Send(sock, kCRLF)) {
return true;
}
}
return false;
}
private:
~TelnetServerTester() {}
};
class TelnetServerTest: public PlatformTest {
protected:
TelnetServerTest() {
tester_ = NULL;
}
virtual void SetUp() {
PlatformTest::SetUp();
tester_ = new TelnetServerTester();
tester_->SetUp();
}
virtual void TearDown() {
PlatformTest::TearDown();
tester_->TearDown();
tester_ = NULL;
}
scoped_refptr<TelnetServerTester> tester_;
};
// Flaky, http://crbug.com/38093.
TEST_F(TelnetServerTest, FLAKY_ServerClientSend) {
tester_->TestClientSend();
}
TEST_F(TelnetServerTest, ClientSendLong) {
tester_->TestClientSendLong();
}
TEST_F(TelnetServerTest, ServerSend) {
tester_->TestServerSend();
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include <vector>
#include <iterator>
#include <sstream>
#include <vector>
#include <memory>
#include <regex>
#include <map>
#include <algorithm>
#include <functional>
using namespace std;
wstringstream program_test(L" 10 ( hello?) (hello -5) ( hi ( one two)) ");
wstringstream program_norwig(L"(begin (define r 10) (* pi (* r r)))");
typedef wstring Token;
typedef vector<Token>::iterator TokenItr;
const Token openParen = L"(";
const Token closeParen = L")";
bool IsNumber(const Token& token)
{
return regex_match(token, wregex(L"[(-|+)|][0-9]+"));
}
vector<Token> tokenize(wistream& program)
{
vector<Token> tokens;
istreambuf_iterator<wchar_t> itr(program);
istreambuf_iterator<wchar_t> eos;
while(itr != eos)
{
while(itr != eos && iswspace(*itr))
itr++;
tokens.emplace_back();
if(*itr == '(')
{
tokens.back() = openParen;
itr++;
}
else if(*itr == ')')
{
tokens.back() = closeParen;
itr++;
}
else
{
while(itr != eos && !iswspace(*itr) && !(*itr == ')') && !(*itr == '('))
{
tokens.back().push_back(*itr);
itr++;
}
}
while(itr != eos && iswspace(*itr))
itr++;
}
return tokens;
}
template<typename T>
void print(const T& x, wostream& os)
{
//os << x << '\n';
os << x ;
}
struct Context;
struct Expression
{
template<typename T>
Expression(const T& src):Expression_(new Impl<T>(src))
{
}
Expression(const Expression& src):Expression_(src.Expression_){}
friend void print(const Expression& x, std::wostream& os)
{
x.Expression_->print_(os);
}
friend Expression eval(const Expression& e, const Context& context)
{
return e.Expression_->eval(context);
}
template<typename T>
T get() const
{
auto impl = dynamic_cast<Impl<T>*>(Expression_.get());
if(impl)
{
return impl->mData;
}
throw;
}
private:
struct Concept
{
virtual void print_(std::wostream&) const = 0;
virtual Expression eval(const Context& context) const = 0;
};
template<typename T>
struct Impl : public Concept
{
Impl(const T& data):mData(data){}
void print_(wostream& os) const override
{
print(mData, os);
}
Expression eval(const Context& context) const override
{
return *this;
}
T mData;
};
private:
shared_ptr<Concept> Expression_;
};
struct Number
{
Number(int value): value_(value){}
Expression eval(const Context& context) const { return Expression(*this); }
operator int() const { return value_; }
void print_(std::wostream& os) const
{
os << value_;
}
private:
int value_;
};
wostream& operator<<(wostream& os, const Number& num)
{
num.print_(os);
return os;
};
struct Symbol
{
Symbol(wstring value): value_(value){}
Expression eval(const Context& context) const { return Expression(*this); }
operator wstring() const { return value_; }
void print_(std::wostream& os) const
{
os << value_;
}
private:
wstring value_;
};
wostream& operator<<(wostream& os, const Symbol& symbol)
{
symbol.print_(os);
return os;
};
Expression make_atom(Token token)
{
if(IsNumber(token))
{
wstringstream ss(token);
int num = 0;
ss >> num;
return Number(num);
}
else
{
return Symbol(token);
}
}
typedef unary_function<vector<Expression>&, Expression> Op;
struct OpPlus : public Op
{
void print_(wostream& os) const
{
os << L"+";
}
Expression operator()(vector<Expression>& operands) const
{
int sum = 0;
for(const auto& operand : operands)
{
sum += operand.get<Number>();
}
return sum;
}
Expression eval(const Context& context) const
{
return Expression(0);
}
};
struct List
{
List(vector<Token>::iterator& itr, const vector<Token>::iterator& last)
{
while(itr != last)
{
if(*itr == openParen)
{
list_.emplace_back(List(++itr, last));
}
else if(*itr == closeParen)
{
itr++;
return;
}
else
{
list_.push_back(make_atom(*itr));
itr++;
}
}
}
Expression eval(const Context& context) const
{
OpPlus op = list_.front().get<OpPlus>();
vector<Expression> args(++list_.begin(), list_.end());
return op(args);
}
void print_(wostream& os) const
{
os << "[";
for(const auto& expr : list_)
{
print(expr, os);
os << ' ';
}
os << "]";
}
private:
vector<Expression> list_;
};
wostream& operator<<(wostream& os, const List& listExpr)
{
listExpr.print_(os);
return os;
}
struct Context
{
Expression Find(const Token& token) const
{
auto ret = map_.find(token);
if(ret != map_.end())
{
return ret->second;
}
throw "Undefined symbol";
}
map<Token, Expression> map_;
};
wostream& operator<<(wostream& os, const OpPlus& op)
{
op.print_(os);
return os;
}
typedef vector<Expression> Program;
int main(int argc, char** argv)
{
Context gContext;
gContext.map_.emplace(wstring(L"+"), Expression(OpPlus()));
Program program;
//program.push_back(Number(1));
//program.push_back(wstring(L"Hello"));
//program.push_back(Number(5));
for(const auto& aExpr : program)
{
print(aExpr, wcout);
}
//wcout << program.front().get<Number>() << '\n';
//Program toSum = { 1, 2, 3 , wstring(L"Hello")};
//Program toSum = { 1, 2, 3 };
//auto op = OpPlus();
//auto sumExpr = op(toSum);
//wcout << L"sum = ";
//print(sumExpr, wcout);
wcout << '\n';
auto aTokens = tokenize(program_norwig);
auto myList = List(aTokens.begin(), aTokens.end());
print(myList, wcout);
wcout << '\n';
aTokens = tokenize(program_test);
auto myList2 = List(aTokens.begin(), aTokens.end());
print(myList2, wcout);
wcout << '\n';
return 0;
}
<commit_msg>List sorta works now<commit_after>#include <iostream>
#include <string>
#include <vector>
#include <iterator>
#include <sstream>
#include <vector>
#include <memory>
#include <regex>
#include <map>
#include <algorithm>
#include <functional>
using namespace std;
wstringstream program_test(L" 10 ( hello?) (hello -5) ( hi ( one two)) ");
wstringstream program_norwig(L"(begin (define r 10) (* pi (* r r)))");
typedef wstring Token;
typedef vector<Token>::iterator TokenItr;
const Token openParen = L"(";
const Token closeParen = L")";
bool IsNumber(const Token& token)
{
return regex_match(token, wregex(L"[(-|+)|][0-9]+"));
}
vector<Token> tokenize(wistream& program)
{
vector<Token> tokens;
istreambuf_iterator<wchar_t> itr(program);
istreambuf_iterator<wchar_t> eos;
while(itr != eos)
{
while(itr != eos && iswspace(*itr))
itr++;
tokens.emplace_back();
if(*itr == '(')
{
tokens.back() = openParen;
itr++;
}
else if(*itr == ')')
{
tokens.back() = closeParen;
itr++;
}
else
{
while(itr != eos && !iswspace(*itr) && !(*itr == ')') && !(*itr == '('))
{
tokens.back().push_back(*itr);
itr++;
}
}
while(itr != eos && iswspace(*itr))
itr++;
}
return tokens;
}
struct Context;
template<typename T>
T Eval(const T& t, const Context& context) { return t; }
template<typename T>
void Print(const T& t, wostream& os) { Print(t, os); }
struct Expression
{
template<typename T>
Expression(const T& src):mpImpl(new Model<T>(src))
{}
Expression eval(const Context& context) const
{
return mpImpl->eval_(context);
}
void print(wostream& os) const
{
mpImpl->print_(os);
}
template<typename T>
T get() const
{
auto ptr = dynamic_pointer_cast<Model<T>>(mpImpl);
if(ptr)
{
return ptr->data_;
}
throw "Invalid Type";
}
struct Concept
{
virtual Expression eval_(const Context& context) const = 0;
virtual void print_(wostream& os) const = 0;
};
template<typename T>
struct Model : public Concept
{
Model(const T& t): data_(t){}
Expression eval_(const Context& context) const override
{
return Eval(data_, context);
}
void print_(wostream& os) const override
{
Print(data_, os);
}
T data_;
};
shared_ptr<Concept> mpImpl;
};
struct Number
{
Number(int value): value_(value){}
friend
Number Eval(const Number& n, const Context& context) { return Number(n.value_); }
operator int() const { return value_; }
friend void Print(const Number& number, std::wostream& os) {os << number.value_;}
private:
int value_;
};
struct Symbol
{
Symbol(wstring value): value_(value){}
friend Symbol Eval(const Symbol& symbol, const Context& context) { return Symbol(symbol.value_); }
operator wstring() const { return value_; }
friend void Print(const Symbol& symbol, std::wostream& os) {os << symbol.value_;}
private:
wstring value_;
};
Expression make_atom(Token token)
{
if(IsNumber(token))
{
wstringstream ss(token);
int num = 0;
ss >> num;
return Number(num);
}
else
{
return Symbol(token);
}
}
typedef unary_function<vector<Expression>&, Expression> Op;
struct OpPlus : public Op
{
void print_(wostream& os) const
{
os << L"+";
}
Expression operator()(vector<Expression>& operands) const
{
int sum = 0;
for(const auto& operand : operands)
{
sum += operand.get<Number>();
}
return sum;
}
OpPlus eval(const Context& context) const
{
return *this;
}
};
struct List
{
List(vector<Token>::iterator& itr, const vector<Token>::iterator& last)
{
while(itr != last)
{
if(*itr == openParen)
{
list_.emplace_back(List(++itr, last));
}
else if(*itr == closeParen)
{
itr++;
return;
}
else
{
list_.push_back(make_atom(*itr));
itr++;
}
}
}
friend List eval(const List& list, const Context& context)
{
return list;
}
friend void Print(const List& l, wostream& os)
{
os << "[";
for(const auto& expr : l.list_)
{
expr.print(os);
os << ' ';
}
os << "]";
}
private:
vector<Expression> list_;
};
struct Context
{
Expression Find(const Token& token) const
{
auto ret = map_.find(token);
if(ret != map_.end())
{
return ret->second;
}
throw "Undefined symbol";
}
map<Token, Expression> map_;
};
int main(int argc, char** argv)
{
auto tokens = tokenize(program_norwig);
Expression e(List(tokens.begin(), tokens.end()));
e.print(wcout);
wcout << '\n';
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2011, Tim Branyen @tbranyen <[email protected]>
* Dual licensed under the MIT and GPL licenses.
*/
#include <v8.h>
#include <node.h>
#include "cvv8/v8-convert.hpp"
#include "git2.h"
#include "../include/error.h"
using namespace v8;
using namespace cvv8;
using namespace node;
/**
* Copied from libgit2/include/errors.h, to allow exporting to JS
*/
typedef enum {
_GIT_OK = 0,
_GIT_ERROR = -1,
_GIT_ENOTFOUND = -3,
_GIT_EEXISTS = -4,
_GIT_EAMBIGUOUS = -5,
_GIT_EBUFS = -6,
_GIT_PASSTHROUGH = -30,
_GIT_ITEROVER = -31,
} git_error_return_t;
namespace cvv8 {
template <>
struct NativeToJS<git_error_t> : NativeToJS<int32_t> {};
template <>
struct NativeToJS<git_error_return_t> : NativeToJS<int32_t> {};
}
void GitError::Initialize (Handle<v8::Object> target) {
HandleScope scope;
Local<FunctionTemplate> tpl = FunctionTemplate::New(New);
tpl->InstanceTemplate()->SetInternalFieldCount(1);
tpl->SetClassName(String::NewSymbol("Error"));
// Add libgit2 error codes to error object
Local<Object> libgit2Errors = Object::New();
libgit2Errors->Set(String::NewSymbol("GITERR_NOMEMORY"), cvv8::CastToJS(GITERR_NOMEMORY), ReadOnly);
libgit2Errors->Set(String::NewSymbol("GITERR_OS"), cvv8::CastToJS(GITERR_OS), ReadOnly);
libgit2Errors->Set(String::NewSymbol("GITERR_INVALID"), cvv8::CastToJS(GITERR_INVALID), ReadOnly);
libgit2Errors->Set(String::NewSymbol("GITERR_REFERENCE"), cvv8::CastToJS(GITERR_REFERENCE), ReadOnly);
libgit2Errors->Set(String::NewSymbol("GITERR_ZLIB"), cvv8::CastToJS(GITERR_ZLIB), ReadOnly);
libgit2Errors->Set(String::NewSymbol("GITERR_REPOSITORY"), cvv8::CastToJS(GITERR_REPOSITORY), ReadOnly);
libgit2Errors->Set(String::NewSymbol("GITERR_CONFIG"), cvv8::CastToJS(GITERR_CONFIG), ReadOnly);
libgit2Errors->Set(String::NewSymbol("GITERR_REGEX"), cvv8::CastToJS(GITERR_REGEX), ReadOnly);
libgit2Errors->Set(String::NewSymbol("GITERR_ODB"), cvv8::CastToJS(GITERR_ODB), ReadOnly);
libgit2Errors->Set(String::NewSymbol("GITERR_INDEX"), cvv8::CastToJS(GITERR_INDEX), ReadOnly);
libgit2Errors->Set(String::NewSymbol("GITERR_OBJECT"), cvv8::CastToJS(GITERR_OBJECT), ReadOnly);
libgit2Errors->Set(String::NewSymbol("GITERR_NET"), cvv8::CastToJS(GITERR_NET), ReadOnly);
libgit2Errors->Set(String::NewSymbol("GITERR_TAG"), cvv8::CastToJS(GITERR_TAG), ReadOnly);
libgit2Errors->Set(String::NewSymbol("GITERR_TREE"), cvv8::CastToJS(GITERR_TREE), ReadOnly);
libgit2Errors->Set(String::NewSymbol("GITERR_INDEXER"), cvv8::CastToJS(GITERR_INDEXER), ReadOnly);
// Add libgit2 error codes to error object
Local<Object> libgit2ReturnCodes = Object::New();
libgit2ReturnCodes->Set(String::NewSymbol("GIT_OK"), cvv8::CastToJS(_GIT_OK), ReadOnly);
libgit2ReturnCodes->Set(String::NewSymbol("GIT_ERROR"), cvv8::CastToJS(_GIT_ERROR), ReadOnly);
libgit2ReturnCodes->Set(String::NewSymbol("GIT_ENOTFOUND"), cvv8::CastToJS(_GIT_ENOTFOUND), ReadOnly);
libgit2ReturnCodes->Set(String::NewSymbol("GIT_EEXISTS"), cvv8::CastToJS(_GIT_EEXISTS), ReadOnly);
libgit2ReturnCodes->Set(String::NewSymbol("GIT_EAMBIGUOUS"), cvv8::CastToJS(_GIT_EAMBIGUOUS), ReadOnly);
libgit2ReturnCodes->Set(String::NewSymbol("GIT_EBUFS"), cvv8::CastToJS(_GIT_EBUFS), ReadOnly);
libgit2ReturnCodes->Set(String::NewSymbol("GIT_PASSTHROUGH"), cvv8::CastToJS(_GIT_PASSTHROUGH), ReadOnly);
libgit2ReturnCodes->Set(String::NewSymbol("GIT_ITEROVER"), cvv8::CastToJS(_GIT_ITEROVER), ReadOnly);
constructor_template = Persistent<Function>::New(tpl->GetFunction());
constructor_template->Set(String::NewSymbol("codes"), libgit2Errors, ReadOnly);
constructor_template->Set(String::NewSymbol("returnCodes"), libgit2ReturnCodes, ReadOnly);
target->Set(String::NewSymbol("Error"), constructor_template);
}
Local<Object> GitError::WrapError(const git_error* error) {
Local<Object> gitError = GitError::constructor_template->NewInstance();
Local<StackTrace> stackTrace = StackTrace::CurrentStackTrace(10);
gitError->Set(String::NewSymbol("stackTrace"), cvv8::CastToJS(stackTrace->AsArray()));
gitError->Set(String::NewSymbol("message"), String::New(error->message));
gitError->Set(String::NewSymbol("code"), Integer::New(error->klass));
return gitError;
}
Handle<Value> GitError::New(const Arguments& args) {
HandleScope scope;
GitError *error = new GitError();
error->Wrap(args.This());
return scope.Close( args.This() );
}
Persistent<Function> GitError::constructor_template;
<commit_msg>Code style normalization<commit_after>/*
* Copyright 2011, Tim Branyen @tbranyen <[email protected]>
* Dual licensed under the MIT and GPL licenses.
*/
#include <v8.h>
#include <node.h>
#include "cvv8/v8-convert.hpp"
#include "git2.h"
#include "../include/error.h"
using namespace v8;
using namespace cvv8;
using namespace node;
/**
* Copied from libgit2/include/errors.h, to allow exporting to JS
*/
typedef enum {
_GIT_OK = 0,
_GIT_ERROR = -1,
_GIT_ENOTFOUND = -3,
_GIT_EEXISTS = -4,
_GIT_EAMBIGUOUS = -5,
_GIT_EBUFS = -6,
_GIT_PASSTHROUGH = -30,
_GIT_ITEROVER = -31,
} git_error_return_t;
namespace cvv8 {
template <>
struct NativeToJS<git_error_t> : NativeToJS<int32_t> {};
template <>
struct NativeToJS<git_error_return_t> : NativeToJS<int32_t> {};
}
void GitError::Initialize (Handle<v8::Object> target) {
HandleScope scope;
Local<FunctionTemplate> tpl = FunctionTemplate::New(New);
tpl->InstanceTemplate()->SetInternalFieldCount(1);
tpl->SetClassName(String::NewSymbol("Error"));
// Add libgit2 error codes to error object
Local<Object> libgit2Errors = Object::New();
libgit2Errors->Set(String::NewSymbol("GITERR_NOMEMORY"), cvv8::CastToJS(GITERR_NOMEMORY), ReadOnly);
libgit2Errors->Set(String::NewSymbol("GITERR_OS"), cvv8::CastToJS(GITERR_OS), ReadOnly);
libgit2Errors->Set(String::NewSymbol("GITERR_INVALID"), cvv8::CastToJS(GITERR_INVALID), ReadOnly);
libgit2Errors->Set(String::NewSymbol("GITERR_REFERENCE"), cvv8::CastToJS(GITERR_REFERENCE), ReadOnly);
libgit2Errors->Set(String::NewSymbol("GITERR_ZLIB"), cvv8::CastToJS(GITERR_ZLIB), ReadOnly);
libgit2Errors->Set(String::NewSymbol("GITERR_REPOSITORY"), cvv8::CastToJS(GITERR_REPOSITORY), ReadOnly);
libgit2Errors->Set(String::NewSymbol("GITERR_CONFIG"), cvv8::CastToJS(GITERR_CONFIG), ReadOnly);
libgit2Errors->Set(String::NewSymbol("GITERR_REGEX"), cvv8::CastToJS(GITERR_REGEX), ReadOnly);
libgit2Errors->Set(String::NewSymbol("GITERR_ODB"), cvv8::CastToJS(GITERR_ODB), ReadOnly);
libgit2Errors->Set(String::NewSymbol("GITERR_INDEX"), cvv8::CastToJS(GITERR_INDEX), ReadOnly);
libgit2Errors->Set(String::NewSymbol("GITERR_OBJECT"), cvv8::CastToJS(GITERR_OBJECT), ReadOnly);
libgit2Errors->Set(String::NewSymbol("GITERR_NET"), cvv8::CastToJS(GITERR_NET), ReadOnly);
libgit2Errors->Set(String::NewSymbol("GITERR_TAG"), cvv8::CastToJS(GITERR_TAG), ReadOnly);
libgit2Errors->Set(String::NewSymbol("GITERR_TREE"), cvv8::CastToJS(GITERR_TREE), ReadOnly);
libgit2Errors->Set(String::NewSymbol("GITERR_INDEXER"), cvv8::CastToJS(GITERR_INDEXER), ReadOnly);
// Add libgit2 error codes to error object
Local<Object> libgit2ReturnCodes = Object::New();
libgit2ReturnCodes->Set(String::NewSymbol("GIT_OK"), cvv8::CastToJS(_GIT_OK), ReadOnly);
libgit2ReturnCodes->Set(String::NewSymbol("GIT_ERROR"), cvv8::CastToJS(_GIT_ERROR), ReadOnly);
libgit2ReturnCodes->Set(String::NewSymbol("GIT_ENOTFOUND"), cvv8::CastToJS(_GIT_ENOTFOUND), ReadOnly);
libgit2ReturnCodes->Set(String::NewSymbol("GIT_EEXISTS"), cvv8::CastToJS(_GIT_EEXISTS), ReadOnly);
libgit2ReturnCodes->Set(String::NewSymbol("GIT_EAMBIGUOUS"), cvv8::CastToJS(_GIT_EAMBIGUOUS), ReadOnly);
libgit2ReturnCodes->Set(String::NewSymbol("GIT_EBUFS"), cvv8::CastToJS(_GIT_EBUFS), ReadOnly);
libgit2ReturnCodes->Set(String::NewSymbol("GIT_PASSTHROUGH"), cvv8::CastToJS(_GIT_PASSTHROUGH), ReadOnly);
libgit2ReturnCodes->Set(String::NewSymbol("GIT_ITEROVER"), cvv8::CastToJS(_GIT_ITEROVER), ReadOnly);
constructor_template = Persistent<Function>::New(tpl->GetFunction());
constructor_template->Set(String::NewSymbol("codes"), libgit2Errors, ReadOnly);
constructor_template->Set(String::NewSymbol("returnCodes"), libgit2ReturnCodes, ReadOnly);
target->Set(String::NewSymbol("Error"), constructor_template);
}
Local<Object> GitError::WrapError(const git_error* error) {
Local<Object> gitError = GitError::constructor_template->NewInstance();
Local<StackTrace> stackTrace = StackTrace::CurrentStackTrace(10);
gitError->Set(String::NewSymbol("stackTrace"), cvv8::CastToJS(stackTrace->AsArray()));
gitError->Set(String::NewSymbol("message"), String::New(error->message));
gitError->Set(String::NewSymbol("code"), Integer::New(error->klass));
return gitError;
}
Handle<Value> GitError::New(const Arguments& args) {
HandleScope scope;
GitError *error = new GitError();
error->Wrap(args.This());
return scope.Close(args.This());
}
Persistent<Function> GitError::constructor_template;
<|endoftext|> |
<commit_before>#define NO_GLOBALS
#include "harlan.hpp"
#include <stdlib.h>
#include <limits.h>
#include <string>
#include <algorithm>
using namespace std;
#define ALLOC_MAGIC 0xa110ca7e
#define CHECK_MAGIC(hdr) assert((hdr)->magic == ALLOC_MAGIC)
extern cl::program g_prog;
extern uint64_t nanotime();
uint64_t g_memtime = 0;
void check_region(region *r) {
CHECK_MAGIC(r);
//assert(r->cl_buffer);
}
void print(bool b, std::ostream *f) {
if(b)
print("#t", f);
else
print("#f", f);
}
void harlan_error(const char *msg) {
std::cerr << "Harlan Runtime Error: " << msg << std::endl;
abort();
}
cl_device_type get_device_type()
{
const char *cfg = getenv("HARLAN_DEVICE");
if(cfg) {
string s = cfg;
transform(s.begin(), s.end(), s.begin(), ::tolower);
if(s == "gpu") {
return CL_DEVICE_TYPE_GPU | CL_DEVICE_TYPE_ACCELERATOR;
}
else if(s == "cpu") {
return CL_DEVICE_TYPE_CPU;
}
else {
cerr << "HARLAN_DEVICE must be either `cpu` or `gpu`." << endl;
abort();
}
}
return (CL_DEVICE_TYPE_GPU |
CL_DEVICE_TYPE_CPU |
CL_DEVICE_TYPE_ACCELERATOR |
0);
}
int get_default_region_size()
{
static bool first_time = true;
const char *cfg = getenv("HARLAN_MIN_REGION_SIZE");
if(cfg) {
int sz = atoi(cfg);
if(first_time) {
cerr << "Setting region size from HARLAN_MIN_REGION_SIZE to "
<< sz << " bytes." << endl;
first_time = false;
}
return sz;
}
//else return 8192;
else return 8 << 20; // 8 megs
}
region *create_region(int size)
{
if(size == -1) size = get_default_region_size();
assert(size > sizeof(region));
// void *ptr = GC_MALLOC(size);
void *ptr = malloc(size);
region *header = (region *)ptr;
header->magic = ALLOC_MAGIC;
header->size = size;
header->alloc_ptr = sizeof(region);
header->cl_buffer = NULL;
check_region(header);
// Start out with the region unmapped, to avoid needless copies.
unmap_region(header);
return header;
}
void free_region(region *r)
{
//fprintf(stderr, "freeing region %p. %d bytes allocated\n",
// r, r->alloc_ptr);
if(r->cl_buffer) {
clReleaseMemObject((cl_mem)r->cl_buffer);
}
free(r);
}
void map_region(region *header)
{
uint64_t start = nanotime();
cl_int status = 0;
assert(header->cl_buffer);
cl_mem buffer = (cl_mem)header->cl_buffer;
//printf("map_region: old alloc_ptr = %d\n", header->alloc_ptr);
// Read just the header
status = clEnqueueReadBuffer(g_queue,
buffer,
CL_TRUE,
0,
sizeof(region),
header,
0,
NULL,
NULL);
CL_CHECK(status);
//printf("map_region: new alloc_ptr = %d\n", header->alloc_ptr);
//printf("map_region: read %lu bytes, reading %lu more.\n",
// sizeof(region), header->alloc_ptr - sizeof(region));
// Now read the contents
status = clEnqueueReadBuffer(g_queue,
buffer,
CL_TRUE,
sizeof(region),
header->alloc_ptr - sizeof(region),
((char *)header) + sizeof(region),
0,
NULL,
NULL);
CL_CHECK(status);
CL_CHECK(clReleaseMemObject(buffer));
assert(!header->cl_buffer);
check_region(header);
g_memtime += nanotime() - start;
}
void unmap_region(region *header)
{
uint64_t start = nanotime();
check_region(header);
// Don't unmap the region twice...
// TODO: we might want to report a warning in this case.
if(header->cl_buffer) return;
//assert(!header->cl_buffer);
//fprintf(stderr, "unmap_region %p, alloc_ptr = %d\n",
// header, header->alloc_ptr);
cl_int status = 0;
cl_mem buffer = clCreateBuffer(g_ctx,
CL_MEM_READ_WRITE | CL_MEM_ALLOC_HOST_PTR,
header->size,
NULL,
&status);
CL_CHECK(status);
status = clEnqueueWriteBuffer(g_queue,
buffer,
CL_TRUE,
0,
header->alloc_ptr,
header,
0,
NULL,
NULL);
CL_CHECK(status);
header->cl_buffer = buffer;
g_memtime += nanotime() - start;
}
region_ptr alloc_in_region(region **r, unsigned int size)
{
if((*r)->cl_buffer) {
map_region(*r);
}
// printf("allocating %d bytes from region %p\n", size, *r);
region_ptr p = (*r)->alloc_ptr;
(*r)->alloc_ptr += size;
// If this fails, we allocated too much memory and need to resize
// the region.
while((*r)->alloc_ptr > (*r)->size) {
unsigned int new_size = (*r)->size * 2;
// As long as we stick with power of two region sizes, this
// will let us get up to 4GB regions. It's a big of a hacky
// special case...
if(new_size == 0) {
new_size = UINT_MAX;
}
assert(new_size > (*r)->size);
region *old = *r;
unsigned int old_size = (*r)->size;
//printf("realloc(%p, %d)\n", *r, new_size);
(*r) = (region *)realloc(*r, new_size);
assert(*r != NULL);
(*r)->size = new_size;
}
return p;
}
region_ptr alloc_vector(region **r, int item_size, int num_items)
{
if((*r)->cl_buffer) {
//cerr << "Attempting to allocate " << 8 + item_size * num_items << " byte vector on GPU." << endl;
//cerr << "region size = " << (*r)->size << endl;
// This region is on the GPU. Try to do the allocation there.
cl::buffer<region_ptr> buf
= g_ctx.createBuffer<region_ptr>(1, CL_MEM_READ_WRITE);
cl::kernel k = g_prog.createKernel("harlan_rt_alloc_vector");
k.setArg(0, (*r)->cl_buffer);
k.setArg(1, item_size);
k.setArg(2, num_items);
k.setArg(3, buf);
g_queue.execute(k, 1);
cl::buffer_map<region_ptr> map = g_queue.mapBuffer<region_ptr>(buf);
region_ptr p = map[0];
if(p) return p;
}
//cerr << "Not enough space, allocating on CPU instead." << endl;
// Well, that failed. I guess we'll do here instead.
region_ptr p = alloc_in_region(r, 8 + item_size * num_items);
*(int*)get_region_ptr(*r, p) = num_items;
return p;
}
cl_mem get_cl_buffer(region *r)
{
assert(r->cl_buffer);
return (cl_mem)r->cl_buffer;
}
int ARGC = 0;
char **ARGV = NULL;
<commit_msg>Skip 0-length reads, since these are technically illegal according to OpenCL.<commit_after>#define NO_GLOBALS
#include "harlan.hpp"
#include <stdlib.h>
#include <limits.h>
#include <string>
#include <algorithm>
using namespace std;
#define ALLOC_MAGIC 0xa110ca7e
#define CHECK_MAGIC(hdr) assert((hdr)->magic == ALLOC_MAGIC)
extern cl::program g_prog;
extern uint64_t nanotime();
uint64_t g_memtime = 0;
void check_region(region *r) {
CHECK_MAGIC(r);
//assert(r->cl_buffer);
}
void print(bool b, std::ostream *f) {
if(b)
print("#t", f);
else
print("#f", f);
}
void harlan_error(const char *msg) {
std::cerr << "Harlan Runtime Error: " << msg << std::endl;
abort();
}
cl_device_type get_device_type()
{
const char *cfg = getenv("HARLAN_DEVICE");
if(cfg) {
string s = cfg;
transform(s.begin(), s.end(), s.begin(), ::tolower);
if(s == "gpu") {
return CL_DEVICE_TYPE_GPU | CL_DEVICE_TYPE_ACCELERATOR;
}
else if(s == "cpu") {
return CL_DEVICE_TYPE_CPU;
}
else {
cerr << "HARLAN_DEVICE must be either `cpu` or `gpu`." << endl;
abort();
}
}
return (CL_DEVICE_TYPE_GPU |
CL_DEVICE_TYPE_CPU |
CL_DEVICE_TYPE_ACCELERATOR |
0);
}
int get_default_region_size()
{
static bool first_time = true;
const char *cfg = getenv("HARLAN_MIN_REGION_SIZE");
if(cfg) {
int sz = atoi(cfg);
if(first_time) {
cerr << "Setting region size from HARLAN_MIN_REGION_SIZE to "
<< sz << " bytes." << endl;
first_time = false;
}
return sz;
}
//else return 8192;
else return 8 << 20; // 8 megs
}
region *create_region(int size)
{
if(size == -1) size = get_default_region_size();
assert(size > sizeof(region));
// void *ptr = GC_MALLOC(size);
void *ptr = malloc(size);
region *header = (region *)ptr;
header->magic = ALLOC_MAGIC;
header->size = size;
header->alloc_ptr = sizeof(region);
header->cl_buffer = NULL;
check_region(header);
// Start out with the region unmapped, to avoid needless copies.
unmap_region(header);
return header;
}
void free_region(region *r)
{
//fprintf(stderr, "freeing region %p. %d bytes allocated\n",
// r, r->alloc_ptr);
if(r->cl_buffer) {
clReleaseMemObject((cl_mem)r->cl_buffer);
}
free(r);
}
void map_region(region *header)
{
uint64_t start = nanotime();
cl_int status = 0;
assert(header->cl_buffer);
cl_mem buffer = (cl_mem)header->cl_buffer;
//printf("map_region: old alloc_ptr = %d\n", header->alloc_ptr);
// Read just the header
status = clEnqueueReadBuffer(g_queue,
buffer,
CL_TRUE,
0,
sizeof(region),
header,
0,
NULL,
NULL);
CL_CHECK(status);
//printf("map_region: new alloc_ptr = %d\n", header->alloc_ptr);
//printf("map_region: read %lu bytes, reading %lu more.\n",
// sizeof(region), header->alloc_ptr - sizeof(region));
// Now read the contents
int remaining = header->alloc_ptr - sizeof(region);
if(remaining > 0) {
status = clEnqueueReadBuffer(g_queue,
buffer,
CL_TRUE,
sizeof(region),
remaining,
((char *)header) + sizeof(region),
0,
NULL,
NULL);
CL_CHECK(status);
}
CL_CHECK(clReleaseMemObject(buffer));
assert(!header->cl_buffer);
check_region(header);
g_memtime += nanotime() - start;
}
void unmap_region(region *header)
{
uint64_t start = nanotime();
check_region(header);
// Don't unmap the region twice...
// TODO: we might want to report a warning in this case.
if(header->cl_buffer) return;
//assert(!header->cl_buffer);
//fprintf(stderr, "unmap_region %p, alloc_ptr = %d\n",
// header, header->alloc_ptr);
cl_int status = 0;
cl_mem buffer = clCreateBuffer(g_ctx,
CL_MEM_READ_WRITE | CL_MEM_ALLOC_HOST_PTR,
header->size,
NULL,
&status);
CL_CHECK(status);
status = clEnqueueWriteBuffer(g_queue,
buffer,
CL_TRUE,
0,
header->alloc_ptr,
header,
0,
NULL,
NULL);
CL_CHECK(status);
header->cl_buffer = buffer;
g_memtime += nanotime() - start;
}
region_ptr alloc_in_region(region **r, unsigned int size)
{
if((*r)->cl_buffer) {
map_region(*r);
}
// printf("allocating %d bytes from region %p\n", size, *r);
region_ptr p = (*r)->alloc_ptr;
(*r)->alloc_ptr += size;
// If this fails, we allocated too much memory and need to resize
// the region.
while((*r)->alloc_ptr > (*r)->size) {
unsigned int new_size = (*r)->size * 2;
// As long as we stick with power of two region sizes, this
// will let us get up to 4GB regions. It's a big of a hacky
// special case...
if(new_size == 0) {
new_size = UINT_MAX;
}
assert(new_size > (*r)->size);
region *old = *r;
unsigned int old_size = (*r)->size;
//printf("realloc(%p, %d)\n", *r, new_size);
(*r) = (region *)realloc(*r, new_size);
assert(*r != NULL);
(*r)->size = new_size;
}
return p;
}
region_ptr alloc_vector(region **r, int item_size, int num_items)
{
if((*r)->cl_buffer) {
//cerr << "Attempting to allocate " << 8 + item_size * num_items << " byte vector on GPU." << endl;
//cerr << "region size = " << (*r)->size << endl;
// This region is on the GPU. Try to do the allocation there.
cl::buffer<region_ptr> buf
= g_ctx.createBuffer<region_ptr>(1, CL_MEM_READ_WRITE);
cl::kernel k = g_prog.createKernel("harlan_rt_alloc_vector");
k.setArg(0, (*r)->cl_buffer);
k.setArg(1, item_size);
k.setArg(2, num_items);
k.setArg(3, buf);
g_queue.execute(k, 1);
cl::buffer_map<region_ptr> map = g_queue.mapBuffer<region_ptr>(buf);
region_ptr p = map[0];
if(p) return p;
}
//cerr << "Not enough space, allocating on CPU instead." << endl;
// Well, that failed. I guess we'll do here instead.
region_ptr p = alloc_in_region(r, 8 + item_size * num_items);
*(int*)get_region_ptr(*r, p) = num_items;
return p;
}
cl_mem get_cl_buffer(region *r)
{
assert(r->cl_buffer);
return (cl_mem)r->cl_buffer;
}
int ARGC = 0;
char **ARGV = NULL;
<|endoftext|> |
<commit_before>// Copyright Joshua Boyce 2010-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// This file is part of HadesMem.
// <http://www.raptorfactor.com/> <[email protected]>
#include "hadesmem/module_iterator.hpp"
#include "hadesmem/detail/warning_disable_prefix.hpp"
#include <boost/none.hpp>
#include <boost/assert.hpp>
#include <boost/optional.hpp>
#include "hadesmem/detail/warning_disable_suffix.hpp"
#include "hadesmem/error.hpp"
#include "hadesmem/module.hpp"
#include "hadesmem/process.hpp"
namespace hadesmem
{
namespace detail
{
struct ModuleIteratorImpl
{
~ModuleIteratorImpl()
{
BOOST_VERIFY(CloseHandle(snap_));
}
Process const* process_;
HANDLE snap_;
boost::optional<Module> module_;
};
}
ModuleIterator::ModuleIterator() BOOST_NOEXCEPT
: impl_()
{ }
ModuleIterator::ModuleIterator(Process const& process)
: impl_(new detail::ModuleIteratorImpl)
{
impl_->process_ = &process;
// TODO: Attempt to call this function at least twice on ERROR_BAD_LENGTH.
// Potentially call until success if it can be determined whether or not
// the process started suspended (as per MSDN).
impl_->snap_ = CreateToolhelp32Snapshot(
TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32,
impl_->process_->GetId());
if (impl_->snap_ == INVALID_HANDLE_VALUE)
{
DWORD const last_error = GetLastError();
BOOST_THROW_EXCEPTION(HadesMemError() <<
ErrorString("CreateToolhelp32Snapshot failed.") <<
ErrorCodeWinLast(last_error));
}
MODULEENTRY32 entry;
ZeroMemory(&entry, sizeof(entry));
entry.dwSize = sizeof(entry);
if (!Module32First(impl_->snap_, &entry))
{
// TODO: More gracefully handle failure when GetLastError returns
// ERROR_NO_MORE_FILES. It seems that we can just treat that as an EOL,
// however I first want to understand the circumstances under which that
// error can occur for the first module in the list (other than an invalid
// snapshot type).
DWORD const last_error = GetLastError();
BOOST_THROW_EXCEPTION(HadesMemError() <<
ErrorString("Module32First failed.") <<
ErrorCodeWinLast(last_error));
}
impl_->module_ = Module(*impl_->process_, entry);
}
ModuleIterator::ModuleIteratorFacade::reference ModuleIterator::dereference() const
{
BOOST_ASSERT(impl_.get());
return *impl_->module_;
}
void ModuleIterator::increment()
{
MODULEENTRY32 entry;
ZeroMemory(&entry, sizeof(entry));
entry.dwSize = sizeof(entry);
if (!Module32Next(impl_->snap_, &entry))
{
if (GetLastError() == ERROR_NO_MORE_FILES)
{
impl_.reset();
return;
}
else
{
DWORD const last_error = GetLastError();
BOOST_THROW_EXCEPTION(HadesMemError() <<
ErrorString("Module32Next failed.") <<
ErrorCodeWinLast(last_error));
}
}
impl_->module_ = Module(*impl_->process_, entry);
}
bool ModuleIterator::equal(ModuleIterator const& other) const BOOST_NOEXCEPT
{
return impl_ == other.impl_;
}
}
<commit_msg>* [module_iterator] Added noexcept annotation to destructor of hadesmem::detail::ModuleIteratorImpl.<commit_after>// Copyright Joshua Boyce 2010-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// This file is part of HadesMem.
// <http://www.raptorfactor.com/> <[email protected]>
#include "hadesmem/module_iterator.hpp"
#include "hadesmem/detail/warning_disable_prefix.hpp"
#include <boost/none.hpp>
#include <boost/assert.hpp>
#include <boost/optional.hpp>
#include "hadesmem/detail/warning_disable_suffix.hpp"
#include "hadesmem/error.hpp"
#include "hadesmem/module.hpp"
#include "hadesmem/process.hpp"
namespace hadesmem
{
namespace detail
{
struct ModuleIteratorImpl
{
~ModuleIteratorImpl() BOOST_NOEXCEPT
{
BOOST_VERIFY(CloseHandle(snap_));
}
Process const* process_;
HANDLE snap_;
boost::optional<Module> module_;
};
}
ModuleIterator::ModuleIterator() BOOST_NOEXCEPT
: impl_()
{ }
ModuleIterator::ModuleIterator(Process const& process)
: impl_(new detail::ModuleIteratorImpl)
{
impl_->process_ = &process;
// TODO: Attempt to call this function at least twice on ERROR_BAD_LENGTH.
// Potentially call until success if it can be determined whether or not
// the process started suspended (as per MSDN).
impl_->snap_ = CreateToolhelp32Snapshot(
TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32,
impl_->process_->GetId());
if (impl_->snap_ == INVALID_HANDLE_VALUE)
{
DWORD const last_error = GetLastError();
BOOST_THROW_EXCEPTION(HadesMemError() <<
ErrorString("CreateToolhelp32Snapshot failed.") <<
ErrorCodeWinLast(last_error));
}
MODULEENTRY32 entry;
ZeroMemory(&entry, sizeof(entry));
entry.dwSize = sizeof(entry);
if (!Module32First(impl_->snap_, &entry))
{
// TODO: More gracefully handle failure when GetLastError returns
// ERROR_NO_MORE_FILES. It seems that we can just treat that as an EOL,
// however I first want to understand the circumstances under which that
// error can occur for the first module in the list (other than an invalid
// snapshot type).
DWORD const last_error = GetLastError();
BOOST_THROW_EXCEPTION(HadesMemError() <<
ErrorString("Module32First failed.") <<
ErrorCodeWinLast(last_error));
}
impl_->module_ = Module(*impl_->process_, entry);
}
ModuleIterator::ModuleIteratorFacade::reference ModuleIterator::dereference() const
{
BOOST_ASSERT(impl_.get());
return *impl_->module_;
}
void ModuleIterator::increment()
{
MODULEENTRY32 entry;
ZeroMemory(&entry, sizeof(entry));
entry.dwSize = sizeof(entry);
if (!Module32Next(impl_->snap_, &entry))
{
if (GetLastError() == ERROR_NO_MORE_FILES)
{
impl_.reset();
return;
}
else
{
DWORD const last_error = GetLastError();
BOOST_THROW_EXCEPTION(HadesMemError() <<
ErrorString("Module32Next failed.") <<
ErrorCodeWinLast(last_error));
}
}
impl_->module_ = Module(*impl_->process_, entry);
}
bool ModuleIterator::equal(ModuleIterator const& other) const BOOST_NOEXCEPT
{
return impl_ == other.impl_;
}
}
<|endoftext|> |
<commit_before>/**
* @copyright Copyright 2018 The J-PET Framework Authors. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may find a copy of the License in the LICENCE file.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @file JPetSmearingFunctions.cpp
*/
#include <JPetSmearingFunctions/JPetSmearingFunctions.h>
#include "JPetLoggerInclude.h"
#include <TMath.h>
using SmearingType = JPetHitExperimentalParametrizer::SmearingType;
using SmearingFunctionLimits = JPetHitExperimentalParametrizer::SmearingFunctionLimits;
JPetHitExperimentalParametrizer::JPetHitExperimentalParametrizer()
{
auto timeSmearingF = [&](double* x, double* p) -> double {
// p[0] = scinID
// p[1] = zIn
// p[2] = eneIn
// p[3] = timeIn
// p[4] = timeResolution (sigma)
// p[5] = energyThreshold
// p[6] = referenceEnergy
double eneIn = p[2];
double timeIn = p[3];
double sigma = p[4];
double energyTreshold = p[5];
double referenceEnergy = p[6];
double time = x[0];
if (eneIn < energyTreshold)
{
sigma = sigma / sqrt(eneIn / referenceEnergy);
}
return TMath::Gaus(time, timeIn, sigma, true);
};
const double kTimeResolutionConstant = 80.; ///< see Eur. Phys. J. C (2016) 76:445 equation 3
const double kEnergyThreshold = 200.; ///< see Eur. Phys. J. C (2016) 76:445 equation 4 and 5
const double kReferenceEnergy = 270.; ///< see Eur. Phys. J. C (2016) 76:445 equation 4 and 5
fSmearingFunctions.emplace(kTime, std::make_unique<TF1>("funTimeHitSmearing", timeSmearingF, -200., 200., 7));
fSmearingFunctions[kTime]->SetParameter(4, kTimeResolutionConstant);
fSmearingFunctions[kTime]->SetParameter(5, kEnergyThreshold);
fSmearingFunctions[kTime]->SetParameter(6, kReferenceEnergy);
auto energySmearingF = [&](double* x, double* p) -> double {
// p[0] = scinID
// p[1] = zIn
// p[2] = eneIn
double eneIn = p[2];
double sigma = eneIn * 0.044 / sqrt(eneIn / 1000.);
double energy = x[0];
return TMath::Gaus(energy, eneIn, sigma, true);
};
fSmearingFunctions.emplace(kEnergy, std::make_unique<TF1>("funEnergySmearing", energySmearingF, -200., 200., 3));
auto zPositionSmearingF = [&](double* x, double* p) -> double {
// p[0] = scinID
// p[1] = zIn
// p[2] = eneIn
// p[3] = zResolution (sigma)
double zIn = p[1];
double sigma = p[3];
double z = x[0];
return TMath::Gaus(z, zIn, sigma, true);
};
fSmearingFunctions.emplace(kZPosition, std::make_unique<TF1>("funZHitSmearing", zPositionSmearingF, -200., 200., 4));
double kZresolution = 0.976;
fSmearingFunctions[kZPosition]->SetParameter(3, kZresolution);
}
void JPetHitExperimentalParametrizer::setSmearingFunctions(const std::vector<FuncAndParam>& params)
{
assert(params.size() >= 3);
auto timeFuncAndParams = params[0];
auto energyFuncAndParams = params[1];
auto zPositionFuncAndParams = params[2];
auto timeFunc = timeFuncAndParams.first;
auto timeParams = timeFuncAndParams.second;
int nDefaultParams = 4;
int nCustomParams = timeParams.size();
int nTotalParams = nCustomParams + nDefaultParams;
if (!timeFunc.empty())
{
fSmearingFunctions[kTime] = std::make_unique<TF1>("funTimeHitSmearing", timeFunc.c_str(), -200., 200., nTotalParams);
}
for (int i = 0; i < nCustomParams; i++)
{
fSmearingFunctions[kTime]->SetParameter(nDefaultParams + i, timeParams[i]);
}
auto energyFunc = energyFuncAndParams.first;
auto energyParams = energyFuncAndParams.second;
nDefaultParams = 3;
nCustomParams = energyParams.size();
nTotalParams = nCustomParams + nDefaultParams;
if (!energyFunc.empty())
{
fSmearingFunctions[kEnergy] = std::make_unique<TF1>("funEnergySmearing", energyFunc.c_str(), -200., 200., nTotalParams);
}
for (int i = 0; i < nCustomParams; i++)
{
fSmearingFunctions[kEnergy]->SetParameter(nDefaultParams + i, energyParams[i]);
}
auto zPositionFunc = zPositionFuncAndParams.first;
auto zPositionParams = zPositionFuncAndParams.second;
nDefaultParams = 3;
nCustomParams = zPositionParams.size();
nTotalParams = nCustomParams + nDefaultParams;
if (!zPositionFunc.empty())
{
fSmearingFunctions[kZPosition] = std::make_unique<TF1>("funzHitSmearing", zPositionFunc.c_str(), -200., 200., nTotalParams);
}
for (int i = 0; i < nCustomParams; i++)
{
fSmearingFunctions[kZPosition]->SetParameter(nDefaultParams + i, zPositionParams[i]);
}
}
/// Only those limits are modified for which first value is smaller than the second one.
/// The limits vector is suppose to have 3 elements in the order time, energy and z Position.
void JPetHitExperimentalParametrizer::setSmearingFunctionLimits(const std::vector<std::pair<double, double>>& limits)
{
assert(limits.size() == 3);
auto timeLim = limits[0];
auto energyLim = limits[1];
;
auto zPositionLim = limits[2];
if (timeLim.first < timeLim.second)
{
fFunctionLimits[kTime] = timeLim;
}
if (energyLim.first < energyLim.second)
{
fFunctionLimits[kEnergy] = energyLim;
}
if (zPositionLim.first < zPositionLim.second)
{
fFunctionLimits[kZPosition] = zPositionLim;
}
}
void JPetHitExperimentalParametrizer::writeAllParametersToLog() const
{
auto limits = getSmearingFunctionLimits();
INFO("Time smearing function");
INFO(fSmearingFunctions.at(kTime)->GetName());
INFO(std::string("limits: low = ") + limits[kTime].first + " , high = " + limits[kTime].second);
auto nPar = fSmearingFunctions.at(kTime)->GetNpar();
INFO(std::string("number of parameters:") + nPar);
for (int i = 0; i < nPar; i++)
{
INFO(std::string("parameter ") + i + " = " + fSmearingFunctions.at(kTime)->GetParameter(i));
}
INFO("Energy smearing function");
INFO(fSmearingFunctions.at(kEnergy)->GetName());
INFO(std::string("limits: low = ") + limits[kEnergy].first + " , high = " + limits[kEnergy].second);
nPar = fSmearingFunctions.at(kEnergy)->GetNpar();
INFO(std::string("number of parameters:") + nPar);
for (int i = 0; i < nPar; i++)
{
INFO(std::string("parameter ") + i + " = " + fSmearingFunctions.at(kEnergy)->GetParameter(i));
}
INFO("ZPosition smearing function");
INFO(fSmearingFunctions.at(kZPosition)->GetName());
INFO(std::string("limits: low = ") + limits[kZPosition].first + " , high = " + limits[kZPosition].second);
nPar = fSmearingFunctions.at(kZPosition)->GetNpar();
INFO(std::string("number of parameters:") + nPar);
for (int i = 0; i < nPar; i++)
{
INFO(std::string("parameter ") + i + " = " + fSmearingFunctions.at(kZPosition)->GetParameter(i));
}
}
void JPetHitExperimentalParametrizer::printAllParameters() const
{
auto limits = getSmearingFunctionLimits();
std::cout << "***************" << std::endl;
std::cout << "Time smearing function" << std::endl;
std::cout << fSmearingFunctions.at(kTime)->GetName() << std::endl;
std::cout << "limits: low = " << limits[kTime].first << " , high = " << limits[kTime].second << std::endl;
auto nPar = fSmearingFunctions.at(kTime)->GetNpar();
std::cout << "number of parameters:" << nPar << std::endl;
for (int i = 0; i < nPar; i++)
{
std::cout << "parameter " << i << " = " << fSmearingFunctions.at(kTime)->GetParameter(i) << std::endl;
}
std::cout << "***************" << std::endl;
std::cout << "Energy smearing function" << std::endl;
std::cout << fSmearingFunctions.at(kEnergy)->GetName() << std::endl;
std::cout << "limits: low = " << limits[kEnergy].first << " , high = " << limits[kEnergy].second << std::endl;
nPar = fSmearingFunctions.at(kEnergy)->GetNpar();
for (int i = 0; i < nPar; i++)
{
std::cout << "parameter " << i << " = " << fSmearingFunctions.at(kEnergy)->GetParameter(i) << std::endl;
}
std::cout << "***************" << std::endl;
std::cout << fSmearingFunctions.at(kZPosition)->GetName() << std::endl;
std::cout << "Z position smearing function" << std::endl;
std::cout << "limits: low = " << limits[kZPosition].first << " , high = " << limits[kZPosition].second << std::endl;
nPar = fSmearingFunctions.at(kZPosition)->GetNpar();
for (int i = 0; i < nPar; i++)
{
std::cout << "parameter " << i << " = " << fSmearingFunctions.at(kZPosition)->GetParameter(i) << std::endl;
}
}
std::map<SmearingType, SmearingFunctionLimits> JPetHitExperimentalParametrizer::getSmearingFunctionLimits() const { return fFunctionLimits; }
/// function is randomize in the range [lowLim + timeIn, highLim + timeIn]
double JPetHitExperimentalParametrizer::addTimeSmearing(int scinID, double zIn, double eneIn, double timeIn)
{
/// We cannot use setParameters(...) cause if there are more then 4 parameters
/// It would set it all to 0.
fSmearingFunctions[kTime]->SetParameter(0, double(scinID));
fSmearingFunctions[kTime]->SetParameter(1, zIn);
fSmearingFunctions[kTime]->SetParameter(2, eneIn);
fSmearingFunctions[kTime]->SetParameter(3, timeIn);
fSmearingFunctions[kTime]->SetRange(timeIn + fFunctionLimits[kTime].first, timeIn + fFunctionLimits[kTime].second);
return fSmearingFunctions[kTime]->GetRandom();
}
/// function is randomize in the range [lowLim + eneIn, highLim + eneIn]
double JPetHitExperimentalParametrizer::addEnergySmearing(int scinID, double zIn, double eneIn)
{
fSmearingFunctions[kEnergy]->SetParameter(0, double(scinID));
fSmearingFunctions[kEnergy]->SetParameter(1, zIn);
fSmearingFunctions[kEnergy]->SetParameter(2, eneIn);
fSmearingFunctions[kEnergy]->SetRange(eneIn + fFunctionLimits[kEnergy].first, eneIn + fFunctionLimits[kEnergy].second);
return fSmearingFunctions[kEnergy]->GetRandom();
}
/// function is randomize in the range [lowLim + zIn, highLim + zIn]
double JPetHitExperimentalParametrizer::addZHitSmearing(int scinID, double zIn, double eneIn)
{
/// We cannot use setParameters(...) cause if there are more then 4 parameters
/// It would set it all to 0.
fSmearingFunctions[kZPosition]->SetParameter(0, double(scinID));
fSmearingFunctions[kZPosition]->SetParameter(1, zIn);
fSmearingFunctions[kZPosition]->SetParameter(2, eneIn);
fSmearingFunctions[kZPosition]->SetRange(zIn + fFunctionLimits[kZPosition].first, zIn + fFunctionLimits[kZPosition].second);
return fSmearingFunctions[kZPosition]->GetRandom();
}
<commit_msg>Fix casting to string in INFO.<commit_after>/**
* @copyright Copyright 2018 The J-PET Framework Authors. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may find a copy of the License in the LICENCE file.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @file JPetSmearingFunctions.cpp
*/
#include "JPetLoggerInclude.h"
#include <JPetSmearingFunctions/JPetSmearingFunctions.h>
#include <TMath.h>
using SmearingType = JPetHitExperimentalParametrizer::SmearingType;
using SmearingFunctionLimits = JPetHitExperimentalParametrizer::SmearingFunctionLimits;
JPetHitExperimentalParametrizer::JPetHitExperimentalParametrizer()
{
auto timeSmearingF = [&](double* x, double* p) -> double {
// p[0] = scinID
// p[1] = zIn
// p[2] = eneIn
// p[3] = timeIn
// p[4] = timeResolution (sigma)
// p[5] = energyThreshold
// p[6] = referenceEnergy
double eneIn = p[2];
double timeIn = p[3];
double sigma = p[4];
double energyTreshold = p[5];
double referenceEnergy = p[6];
double time = x[0];
if (eneIn < energyTreshold)
{
sigma = sigma / sqrt(eneIn / referenceEnergy);
}
return TMath::Gaus(time, timeIn, sigma, true);
};
const double kTimeResolutionConstant = 80.; ///< see Eur. Phys. J. C (2016) 76:445 equation 3
const double kEnergyThreshold = 200.; ///< see Eur. Phys. J. C (2016) 76:445 equation 4 and 5
const double kReferenceEnergy = 270.; ///< see Eur. Phys. J. C (2016) 76:445 equation 4 and 5
fSmearingFunctions.emplace(kTime, std::make_unique<TF1>("funTimeHitSmearing", timeSmearingF, -200., 200., 7));
fSmearingFunctions[kTime]->SetParameter(4, kTimeResolutionConstant);
fSmearingFunctions[kTime]->SetParameter(5, kEnergyThreshold);
fSmearingFunctions[kTime]->SetParameter(6, kReferenceEnergy);
auto energySmearingF = [&](double* x, double* p) -> double {
// p[0] = scinID
// p[1] = zIn
// p[2] = eneIn
double eneIn = p[2];
double sigma = eneIn * 0.044 / sqrt(eneIn / 1000.);
double energy = x[0];
return TMath::Gaus(energy, eneIn, sigma, true);
};
fSmearingFunctions.emplace(kEnergy, std::make_unique<TF1>("funEnergySmearing", energySmearingF, -200., 200., 3));
auto zPositionSmearingF = [&](double* x, double* p) -> double {
// p[0] = scinID
// p[1] = zIn
// p[2] = eneIn
// p[3] = zResolution (sigma)
double zIn = p[1];
double sigma = p[3];
double z = x[0];
return TMath::Gaus(z, zIn, sigma, true);
};
fSmearingFunctions.emplace(kZPosition, std::make_unique<TF1>("funZHitSmearing", zPositionSmearingF, -200., 200., 4));
double kZresolution = 0.976;
fSmearingFunctions[kZPosition]->SetParameter(3, kZresolution);
}
void JPetHitExperimentalParametrizer::setSmearingFunctions(const std::vector<FuncAndParam>& params)
{
assert(params.size() >= 3);
auto timeFuncAndParams = params[0];
auto energyFuncAndParams = params[1];
auto zPositionFuncAndParams = params[2];
auto timeFunc = timeFuncAndParams.first;
auto timeParams = timeFuncAndParams.second;
int nDefaultParams = 4;
int nCustomParams = timeParams.size();
int nTotalParams = nCustomParams + nDefaultParams;
if (!timeFunc.empty())
{
fSmearingFunctions[kTime] = std::make_unique<TF1>("funTimeHitSmearing", timeFunc.c_str(), -200., 200., nTotalParams);
}
for (int i = 0; i < nCustomParams; i++)
{
fSmearingFunctions[kTime]->SetParameter(nDefaultParams + i, timeParams[i]);
}
auto energyFunc = energyFuncAndParams.first;
auto energyParams = energyFuncAndParams.second;
nDefaultParams = 3;
nCustomParams = energyParams.size();
nTotalParams = nCustomParams + nDefaultParams;
if (!energyFunc.empty())
{
fSmearingFunctions[kEnergy] = std::make_unique<TF1>("funEnergySmearing", energyFunc.c_str(), -200., 200., nTotalParams);
}
for (int i = 0; i < nCustomParams; i++)
{
fSmearingFunctions[kEnergy]->SetParameter(nDefaultParams + i, energyParams[i]);
}
auto zPositionFunc = zPositionFuncAndParams.first;
auto zPositionParams = zPositionFuncAndParams.second;
nDefaultParams = 3;
nCustomParams = zPositionParams.size();
nTotalParams = nCustomParams + nDefaultParams;
if (!zPositionFunc.empty())
{
fSmearingFunctions[kZPosition] = std::make_unique<TF1>("funzHitSmearing", zPositionFunc.c_str(), -200., 200., nTotalParams);
}
for (int i = 0; i < nCustomParams; i++)
{
fSmearingFunctions[kZPosition]->SetParameter(nDefaultParams + i, zPositionParams[i]);
}
}
/// Only those limits are modified for which first value is smaller than the second one.
/// The limits vector is suppose to have 3 elements in the order time, energy and z Position.
void JPetHitExperimentalParametrizer::setSmearingFunctionLimits(const std::vector<std::pair<double, double>>& limits)
{
assert(limits.size() == 3);
auto timeLim = limits[0];
auto energyLim = limits[1];
;
auto zPositionLim = limits[2];
if (timeLim.first < timeLim.second)
{
fFunctionLimits[kTime] = timeLim;
}
if (energyLim.first < energyLim.second)
{
fFunctionLimits[kEnergy] = energyLim;
}
if (zPositionLim.first < zPositionLim.second)
{
fFunctionLimits[kZPosition] = zPositionLim;
}
}
void JPetHitExperimentalParametrizer::writeAllParametersToLog() const
{
auto limits = getSmearingFunctionLimits();
std::vector<SmearingType> types{kTime, kEnergy, kZPosition};
for (auto type : types)
{
INFO(fSmearingFunctions.at(type)->GetName());
INFO(std::string("limits: low = ") + limits[type].first + " , high = " + limits[type].second);
auto nPar = fSmearingFunctions.at(type)->GetNpar();
INFO(std::string("number of parameters:") + std::to_string(nPar));
for (int i = 0; i < nPar; i++)
{
INFO(std::string("parameter ") + std::to_string(i) + " = " + std::to_string(fSmearingFunctions.at(type)->GetParameter(i)));
}
}
}
void JPetHitExperimentalParametrizer::printAllParameters() const
{
auto limits = getSmearingFunctionLimits();
std::cout << "***************" << std::endl;
std::cout << "Time smearing function" << std::endl;
std::cout << fSmearingFunctions.at(kTime)->GetName() << std::endl;
std::cout << "limits: low = " << limits[kTime].first << " , high = " << limits[kTime].second << std::endl;
auto nPar = fSmearingFunctions.at(kTime)->GetNpar();
std::cout << "number of parameters:" << nPar << std::endl;
for (int i = 0; i < nPar; i++)
{
std::cout << "parameter " << i << " = " << fSmearingFunctions.at(kTime)->GetParameter(i) << std::endl;
}
std::cout << "***************" << std::endl;
std::cout << "Energy smearing function" << std::endl;
std::cout << fSmearingFunctions.at(kEnergy)->GetName() << std::endl;
std::cout << "limits: low = " << limits[kEnergy].first << " , high = " << limits[kEnergy].second << std::endl;
nPar = fSmearingFunctions.at(kEnergy)->GetNpar();
for (int i = 0; i < nPar; i++)
{
std::cout << "parameter " << i << " = " << fSmearingFunctions.at(kEnergy)->GetParameter(i) << std::endl;
}
std::cout << "***************" << std::endl;
std::cout << fSmearingFunctions.at(kZPosition)->GetName() << std::endl;
std::cout << "Z position smearing function" << std::endl;
std::cout << "limits: low = " << limits[kZPosition].first << " , high = " << limits[kZPosition].second << std::endl;
nPar = fSmearingFunctions.at(kZPosition)->GetNpar();
for (int i = 0; i < nPar; i++)
{
std::cout << "parameter " << i << " = " << fSmearingFunctions.at(kZPosition)->GetParameter(i) << std::endl;
}
}
std::map<SmearingType, SmearingFunctionLimits> JPetHitExperimentalParametrizer::getSmearingFunctionLimits() const
{
return fFunctionLimits;
}
/// function is randomize in the range [lowLim + timeIn, highLim + timeIn]
double JPetHitExperimentalParametrizer::addTimeSmearing(int scinID, double zIn, double eneIn, double timeIn)
{
/// We cannot use setParameters(...) cause if there are more then 4 parameters
/// It would set it all to 0.
fSmearingFunctions[kTime]->SetParameter(0, double(scinID));
fSmearingFunctions[kTime]->SetParameter(1, zIn);
fSmearingFunctions[kTime]->SetParameter(2, eneIn);
fSmearingFunctions[kTime]->SetParameter(3, timeIn);
fSmearingFunctions[kTime]->SetRange(timeIn + fFunctionLimits[kTime].first, timeIn + fFunctionLimits[kTime].second);
return fSmearingFunctions[kTime]->GetRandom();
}
/// function is randomize in the range [lowLim + eneIn, highLim + eneIn]
double JPetHitExperimentalParametrizer::addEnergySmearing(int scinID, double zIn, double eneIn)
{
fSmearingFunctions[kEnergy]->SetParameter(0, double(scinID));
fSmearingFunctions[kEnergy]->SetParameter(1, zIn);
fSmearingFunctions[kEnergy]->SetParameter(2, eneIn);
fSmearingFunctions[kEnergy]->SetRange(eneIn + fFunctionLimits[kEnergy].first, eneIn + fFunctionLimits[kEnergy].second);
return fSmearingFunctions[kEnergy]->GetRandom();
}
/// function is randomize in the range [lowLim + zIn, highLim + zIn]
double JPetHitExperimentalParametrizer::addZHitSmearing(int scinID, double zIn, double eneIn)
{
/// We cannot use setParameters(...) cause if there are more then 4 parameters
/// It would set it all to 0.
fSmearingFunctions[kZPosition]->SetParameter(0, double(scinID));
fSmearingFunctions[kZPosition]->SetParameter(1, zIn);
fSmearingFunctions[kZPosition]->SetParameter(2, eneIn);
fSmearingFunctions[kZPosition]->SetRange(zIn + fFunctionLimits[kZPosition].first, zIn + fFunctionLimits[kZPosition].second);
return fSmearingFunctions[kZPosition]->GetRandom();
}
<|endoftext|> |
<commit_before>/*
@file add_noexcept
@Copyright Barrett Adair 2015-2017
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
#ifndef BOOST_CLBL_TRTS_ADD_NOEXCEPT_HPP
#define BOOST_CLBL_TRTS_ADD_NOEXCEPT_HPP
#include <boost/callable_traits/detail/core.hpp>
namespace boost { namespace callable_traits {
BOOST_CLBL_TRTS_DEFINE_SFINAE_ERROR_ORIGIN(add_noexcept)
BOOST_CLBL_TRTS_SFINAE_MSG(add_noexcept, cannot_add_noexcept_to_this_type)
#ifndef BOOST_CLBL_TRTS_ENABLE_NOEXCEPT_TYPES
template<typename T>
struct add_noexcept_t {
static_assert(std::is_same<T, detail::dummy>::value,
"noexcept types not supported by this configuration.");
};
template<typename T>
struct add_noexcept {
static_assert(std::is_same<T, detail::dummy>::value,
"noexcept types not supported by this configuration.");
};
#else
//[ add_noexcept_hpp
/*`
[section:ref_add_noexcept add_noexcept]
[heading Header]
``#include <boost/callable_traits/add_noexcept.hpp>``
[heading Definition]
*/
template<typename T>
using add_noexcept_t = //see below
//<-
detail::try_but_fail_if_invalid<
typename detail::traits<T>::add_noexcept,
cannot_add_noexcept_to_this_type>;
namespace detail {
template<typename T, typename = std::false_type>
struct add_noexcept_impl {};
template<typename T>
struct add_noexcept_impl <T, typename std::is_same<
add_noexcept_t<T>, detail::dummy>::type>
{
using type = add_noexcept_t<T>;
};
}
//->
template<typename T>
struct add_noexcept : detail::add_noexcept_impl<T> {};
//<-
#endif // #ifdef BOOST_CLBL_TRTS_ENABLE_NOEXCEPT_TYPES
}} // namespace boost::callable_traits
//->
/*`
[heading Constraints]
* `T` must be one of the following:
* function type
* function pointer type
* function reference type
* member function pointer type
* If `T` is a pointer, it may not be cv/ref qualified
[heading Behavior]
* A substitution failure occurs if the constraints are violated.
* Adds a `noexcept` specifier to `T`, if not already present.
[heading Input/Output Examples]
[table
[[`T`] [`add_noexcept_t<T>`]]
[[`int()`] [`int() noexcept`]]
[[`int (&)()`] [`int(&)() noexcept`]]
[[`int (*)()`] [`int(*)() noexcept`]]
[[`int(foo::*)()`] [`int(foo::*)() noexcept`]]
[[`int(foo::*)() &`] [`int(foo::*)() & noexcept`]]
[[`int(foo::*)() &&`] [`int(foo::*)() && noexcept`]]
[[`int(foo::*)() const transaction_safe`] [`int(foo::*)() const transaction_safe noexcept`]]
[[`int(foo::*)() noexcept`] [`int(foo::*)() noexcept`]]
[[`int`] [(substitution failure)]]
[[`int foo::*`] [(substitution failure)]]
[[`int (*&)()`] [(substitution failure)]]
]
[heading Example Program]
[import ../example/add_noexcept.cpp]
[add_noexcept]
[endsect]
*/
//]
#endif // #ifndef BOOST_CLBL_TRTS_ADD_NOEXCEPT_HPP
<commit_msg>Delete add_noexcept.hpp<commit_after><|endoftext|> |
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
// $Id$
// $MpId: AliMpSectorAreaVPadIterator.cxx,v 1.8 2006/05/24 13:58:46 ivana Exp $
// Category: sector
//
// Class AliMpSectorAreaVPadIterator
// ---------------------------------
// Class, which defines an iterator over the pads
// inside a given area in a sector in vertical direction.
// Included in AliRoot: 2003/05/02
// Authors: David Guez, Ivana Hrivnacova; IPN Orsay
#include "AliMpSectorAreaVPadIterator.h"
#include "AliMpSectorSegmentation.h"
#include "AliMpConstants.h"
#include "AliLog.h"
#include <Riostream.h>
/// \cond CLASSIMP
ClassImp(AliMpSectorAreaVPadIterator)
/// \endcond
//______________________________________________________________________________
AliMpSectorAreaVPadIterator::AliMpSectorAreaVPadIterator(
const AliMpSectorSegmentation* segmentation,
const AliMpArea& area)
: AliMpVPadIterator(),
fkSegmentation(segmentation),
fkArea(area),
fCurrentPad(AliMpPad::Invalid()),
fCurrentColumnPosition(0.)
{
/// Standard constructor, start in invalid position
}
//______________________________________________________________________________
AliMpSectorAreaVPadIterator::AliMpSectorAreaVPadIterator(
const AliMpSectorAreaVPadIterator& right)
: AliMpVPadIterator(right),
fkSegmentation(0),
fkArea(AliMpArea()),
fCurrentPad(AliMpPad::Invalid()),
fCurrentColumnPosition(0.)
{
/// Copy constructor
*this = right;
}
//______________________________________________________________________________
AliMpSectorAreaVPadIterator::AliMpSectorAreaVPadIterator()
: AliMpVPadIterator(),
fkSegmentation(0),
fkArea(AliMpArea()),
fCurrentPad(AliMpPad::Invalid()),
fCurrentColumnPosition(0.)
{
/// Default constructor.
}
//______________________________________________________________________________
AliMpSectorAreaVPadIterator::~AliMpSectorAreaVPadIterator()
{
/// Destructor
}
//
// operators
//
//______________________________________________________________________________
AliMpSectorAreaVPadIterator&
AliMpSectorAreaVPadIterator::operator = (const AliMpSectorAreaVPadIterator& right)
{
/// Assignment operator
// check assignment to self
if (this == &right) return *this;
// base class assignment
AliMpVPadIterator::operator=(right);
fkSegmentation = right.fkSegmentation;
fkArea = right.fkArea;
fCurrentPad = right.fCurrentPad;
fCurrentColumnPosition = right.fCurrentColumnPosition;
return *this;
}
//
// private methods
//
//______________________________________________________________________________
Bool_t AliMpSectorAreaVPadIterator::IsValid() const
{
/// Is the iterator in a valid position?
return fCurrentPad.IsValid() ;
}
//______________________________________________________________________________
void AliMpSectorAreaVPadIterator::MoveRight()
{
/// Increase the current row position and searches the first valid pad.
Double_t step = 2.* fkSegmentation->GetMinPadDimensions().X();
while ( !fCurrentPad.IsValid() &&
fCurrentColumnPosition + step < fkArea.RightBorder())
{
fCurrentColumnPosition += step;
TVector2 position = TVector2(fCurrentColumnPosition, fkArea.DownBorder());
fCurrentPad = fkSegmentation->PadByDirection(position, fkArea.UpBorder());
}
}
//
// public methods
//
//______________________________________________________________________________
void AliMpSectorAreaVPadIterator::First()
{
/// Reset the iterator, so that it points to the first available
/// pad in the area
if (!fkSegmentation) {
AliFatal("Segmentation is not defined");
return;
}
// Start position = left down corner of the area
//
fCurrentColumnPosition = fkArea.LeftBorder();
TVector2 position(fkArea.LeftDownCorner());
fCurrentPad = fkSegmentation->PadByDirection(position, fkArea.UpBorder());
MoveRight();
// Set the column position to the center of pad
//
if (fCurrentPad.IsValid()) fCurrentColumnPosition = fCurrentPad.Position().X();
}
//______________________________________________________________________________
void AliMpSectorAreaVPadIterator::Next()
{
/// Move the iterator to the next valid pad.
if (!IsValid()) return;
// Start position = up board of current pad + little step
//
TVector2 position
= fCurrentPad.Position()
+ TVector2(0., fCurrentPad.Dimensions().Y() + AliMpConstants::LengthStep());
fCurrentPad = fkSegmentation->PadByDirection(position, fkArea.UpBorder());
if (fCurrentPad.IsValid()) return;
MoveRight();
}
//______________________________________________________________________________
Bool_t AliMpSectorAreaVPadIterator::IsDone() const
{
/// Is the iterator in the end ?
return !IsValid();
}
//______________________________________________________________________________
AliMpPad AliMpSectorAreaVPadIterator::CurrentItem () const
{
/// Return current pad.
return fCurrentPad;
}
//______________________________________________________________________________
void AliMpSectorAreaVPadIterator::Invalidate()
{
/// Let the iterator point to the invalid position
fCurrentPad = AliMpPad::Invalid();
fCurrentColumnPosition = 0;
}
<commit_msg>Corrected MoveRight() function<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
// $Id$
// $MpId: AliMpSectorAreaVPadIterator.cxx,v 1.8 2006/05/24 13:58:46 ivana Exp $
// Category: sector
//
// Class AliMpSectorAreaVPadIterator
// ---------------------------------
// Class, which defines an iterator over the pads
// inside a given area in a sector in vertical direction.
// Included in AliRoot: 2003/05/02
// Authors: David Guez, Ivana Hrivnacova; IPN Orsay
#include "AliMpSectorAreaVPadIterator.h"
#include "AliMpSectorSegmentation.h"
#include "AliMpConstants.h"
#include "AliLog.h"
#include <Riostream.h>
/// \cond CLASSIMP
ClassImp(AliMpSectorAreaVPadIterator)
/// \endcond
//______________________________________________________________________________
AliMpSectorAreaVPadIterator::AliMpSectorAreaVPadIterator(
const AliMpSectorSegmentation* segmentation,
const AliMpArea& area)
: AliMpVPadIterator(),
fkSegmentation(segmentation),
fkArea(area),
fCurrentPad(AliMpPad::Invalid()),
fCurrentColumnPosition(0.)
{
/// Standard constructor, start in invalid position
}
//______________________________________________________________________________
AliMpSectorAreaVPadIterator::AliMpSectorAreaVPadIterator(
const AliMpSectorAreaVPadIterator& right)
: AliMpVPadIterator(right),
fkSegmentation(0),
fkArea(AliMpArea()),
fCurrentPad(AliMpPad::Invalid()),
fCurrentColumnPosition(0.)
{
/// Copy constructor
*this = right;
}
//______________________________________________________________________________
AliMpSectorAreaVPadIterator::AliMpSectorAreaVPadIterator()
: AliMpVPadIterator(),
fkSegmentation(0),
fkArea(AliMpArea()),
fCurrentPad(AliMpPad::Invalid()),
fCurrentColumnPosition(0.)
{
/// Default constructor.
}
//______________________________________________________________________________
AliMpSectorAreaVPadIterator::~AliMpSectorAreaVPadIterator()
{
/// Destructor
}
//
// operators
//
//______________________________________________________________________________
AliMpSectorAreaVPadIterator&
AliMpSectorAreaVPadIterator::operator = (const AliMpSectorAreaVPadIterator& right)
{
/// Assignment operator
// check assignment to self
if (this == &right) return *this;
// base class assignment
AliMpVPadIterator::operator=(right);
fkSegmentation = right.fkSegmentation;
fkArea = right.fkArea;
fCurrentPad = right.fCurrentPad;
fCurrentColumnPosition = right.fCurrentColumnPosition;
return *this;
}
//
// private methods
//
//______________________________________________________________________________
Bool_t AliMpSectorAreaVPadIterator::IsValid() const
{
/// Is the iterator in a valid position?
return fCurrentPad.IsValid() ;
}
//______________________________________________________________________________
void AliMpSectorAreaVPadIterator::MoveRight()
{
/// Increase the current row position and searches the first valid pad.
Double_t dx = fkSegmentation->GetMinPadDimensions().X();
while ( !fCurrentPad.IsValid() &&
fCurrentColumnPosition + dx < fkArea.RightBorder())
{
fCurrentColumnPosition += 2.*dx;
TVector2 position = TVector2(fCurrentColumnPosition, fkArea.DownBorder());
fCurrentPad = fkSegmentation->PadByDirection(position, fkArea.UpBorder());
}
}
//
// public methods
//
//______________________________________________________________________________
void AliMpSectorAreaVPadIterator::First()
{
/// Reset the iterator, so that it points to the first available
/// pad in the area
if (!fkSegmentation) {
AliFatal("Segmentation is not defined");
return;
}
// Start position = left down corner of the area
//
fCurrentColumnPosition = fkArea.LeftBorder();
TVector2 position(fkArea.LeftDownCorner());
fCurrentPad = fkSegmentation->PadByDirection(position, fkArea.UpBorder());
MoveRight();
// Set the column position to the center of pad
//
if (fCurrentPad.IsValid()) fCurrentColumnPosition = fCurrentPad.Position().X();
}
//______________________________________________________________________________
void AliMpSectorAreaVPadIterator::Next()
{
/// Move the iterator to the next valid pad.
if (!IsValid()) return;
// Start position = up board of current pad + little step
//
TVector2 position
= fCurrentPad.Position()
+ TVector2(0., fCurrentPad.Dimensions().Y() + AliMpConstants::LengthStep());
fCurrentPad = fkSegmentation->PadByDirection(position, fkArea.UpBorder());
if (fCurrentPad.IsValid()) return;
MoveRight();
}
//______________________________________________________________________________
Bool_t AliMpSectorAreaVPadIterator::IsDone() const
{
/// Is the iterator in the end ?
return !IsValid();
}
//______________________________________________________________________________
AliMpPad AliMpSectorAreaVPadIterator::CurrentItem () const
{
/// Return current pad.
return fCurrentPad;
}
//______________________________________________________________________________
void AliMpSectorAreaVPadIterator::Invalidate()
{
/// Let the iterator point to the invalid position
fCurrentPad = AliMpPad::Invalid();
fCurrentColumnPosition = 0;
}
<|endoftext|> |
<commit_before>#include "logicalModel.h"
#include "graphicalModel.h"
#include <QtCore/QUuid>
using namespace qReal;
using namespace models;
using namespace models::details;
using namespace modelsImplementation;
LogicalModel::LogicalModel(qrRepo::LogicalRepoApi *repoApi, EditorManagerInterface const &editorManagerInterface)
: AbstractModel(editorManagerInterface), mGraphicalModelView(this), mApi(*repoApi)
{
mRootItem = new LogicalModelItem(Id::rootId(), NULL);
init();
mLogicalAssistApi = new LogicalModelAssistApi(*this, editorManagerInterface);
}
LogicalModel::~LogicalModel()
{
delete mLogicalAssistApi;
cleanupTree(mRootItem);
}
void LogicalModel::init()
{
mModelItems.insert(Id::rootId(), mRootItem);
mApi.setName(Id::rootId(), Id::rootId().toString());
// Turn off view notification while loading.
blockSignals(true);
loadSubtreeFromClient(static_cast<LogicalModelItem *>(mRootItem));
blockSignals(false);
}
void LogicalModel::loadSubtreeFromClient(LogicalModelItem * const parent)
{
foreach (Id childId, mApi.children(parent->id())) {
if (mApi.isLogicalElement(childId)) {
LogicalModelItem *child = loadElement(parent, childId);
loadSubtreeFromClient(child);
}
}
}
LogicalModelItem *LogicalModel::loadElement(LogicalModelItem *parentItem, Id const &id)
{
int const newRow = parentItem->children().size();
beginInsertRows(index(parentItem), newRow, newRow);
LogicalModelItem *item = new LogicalModelItem(id, parentItem);
addInsufficientProperties(id);
parentItem->addChild(item);
mModelItems.insert(id, item);
endInsertRows();
return item;
}
void LogicalModel::addInsufficientProperties(Id const &id, QString const &name)
{
if (!mEditorManagerInterface.hasElement(id.type())) {
return;
}
QMap<QString, QVariant> const standardProperties;
standardProperties.insert("name", name);
standardProperties.insert("from", Id::rootId().toVariant());
standardProperties.insert("to", Id::rootId().toVariant());
standardProperties.insert("links", IdListHelper::toVariant(IdList()));
standardProperties.insert("outgoingExplosion", Id().toVariant());
standardProperties.insert("incomingExplosions", IdListHelper::toVariant(IdList()));
foreach (QString const &property, standardProperties.keys()) {
if (!mApi.hasProperty(id, property)) {
mApi.setProperty(id, property, standardProperties[property]);
}
}
QStringList const properties = mEditorManagerInterface.propertyNames(id.type());
foreach (QString const &property, properties) {
// for those properties that doesn't have default values, plugin will return empty string
mApi.setProperty(id, property, mEditorManagerInterface.defaultPropertyValue(id, property));
}
}
void LogicalModel::connectToGraphicalModel(GraphicalModel * const graphicalModel)
{
mGraphicalModelView.setModel(graphicalModel);
}
AbstractModelItem *LogicalModel::createModelItem(Id const &id, AbstractModelItem *parentItem) const
{
return new LogicalModelItem(id, static_cast<LogicalModelItem *>(parentItem));
}
void LogicalModel::updateElements(Id const &logicalId, QString const &name)
{
if ((logicalId == Id()) || (mApi.name(logicalId) == name)) {
return;
}
mApi.setName(logicalId, name);
emit dataChanged(indexById(logicalId), indexById(logicalId));
}
QMimeData* LogicalModel::mimeData(QModelIndexList const &indexes) const
{
QByteArray data;
bool isFromLogicalModel = true;
QDataStream stream(&data, QIODevice::WriteOnly);
foreach (QModelIndex index, indexes) {
if (index.isValid()) {
AbstractModelItem *item = static_cast<AbstractModelItem*>(index.internalPointer());
stream << item->id().toString();
stream << pathToItem(item);
stream << mApi.property(item->id(), "name").toString();
stream << QPointF();
stream << isFromLogicalModel;
} else {
stream << Id::rootId().toString();
stream << QString();
stream << QString();
stream << QPointF();
stream << isFromLogicalModel;
}
}
QMimeData *mimeData = new QMimeData();
mimeData->setData(DEFAULT_MIME_TYPE, data);
return mimeData;
}
QString LogicalModel::pathToItem(AbstractModelItem const *item) const
{
if (item != mRootItem) {
QString path;
do {
item = item->parent();
path = item->id().toString() + ID_PATH_DIVIDER + path;
} while (item != mRootItem);
return path;
}
else
return Id::rootId().toString();
}
void LogicalModel::addElementToModel(const Id &parent, const Id &id, const Id &logicalId
, QString const &name, const QPointF &position)
{
if (mModelItems.contains(id))
return;
Q_ASSERT_X(mModelItems.contains(parent), "addElementToModel", "Adding element to non-existing parent");
AbstractModelItem *parentItem = mModelItems[parent];
AbstractModelItem *newItem = NULL;
if (logicalId != Id::rootId() && mModelItems.contains(logicalId)) {
if (parent == logicalId) {
return;
} else {
changeParent(index(mModelItems[logicalId]), index(parentItem), QPointF());
}
} else {
newItem = createModelItem(id, parentItem);
initializeElement(id, parentItem, newItem, name, position);
}
}
void LogicalModel::initializeElement(Id const &id, modelsImplementation::AbstractModelItem *parentItem
, modelsImplementation::AbstractModelItem *item, QString const &name, QPointF const &position)
{
Q_UNUSED(position)
int newRow = parentItem->children().size();
beginInsertRows(index(parentItem), newRow, newRow);
parentItem->addChild(item);
mApi.addChild(parentItem->id(), id);
addInsufficientProperties(id);
mModelItems.insert(id, item);
endInsertRows();
}
QVariant LogicalModel::data(const QModelIndex &index, int role) const
{
if (index.isValid()) {
AbstractModelItem *item = static_cast<AbstractModelItem*>(index.internalPointer());
Q_ASSERT(item);
switch (role) {
case Qt::DisplayRole:
case Qt::EditRole:
return mApi.name(item->id());
case Qt::DecorationRole:
return QVariant();
// return mEditorManager.icon(item->id());
case roles::idRole:
return item->id().toVariant();
case roles::fromRole:
return mApi.from(item->id()).toVariant();
case roles::toRole:
return mApi.to(item->id()).toVariant();
}
if (role >= roles::customPropertiesBeginRole) {
QString selectedProperty = findPropertyName(item->id(), role);
return mApi.property(item->id(), selectedProperty);
}
Q_ASSERT(role < Qt::UserRole);
return QVariant();
} else {
return QVariant();
}
}
bool LogicalModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
if (index.isValid()) {
AbstractModelItem *item = static_cast<AbstractModelItem *>(index.internalPointer());
switch (role) {
case Qt::DisplayRole:
case Qt::EditRole:
mApi.setName(item->id(), value.toString());
break;
case roles::fromRole:
mApi.setFrom(item->id(), value.value<Id>());
break;
case roles::toRole:
mApi.setTo(item->id(), value.value<Id>());
break;
default:
if (role >= roles::customPropertiesBeginRole) {
QString selectedProperty = findPropertyName(item->id(), role);
mApi.setProperty(item->id(), selectedProperty, value);
break;
}
Q_ASSERT(role < Qt::UserRole);
return false;
}
emit dataChanged(index, index);
return true;
}
return false;
}
void LogicalModel::changeParent(QModelIndex const &element, QModelIndex const &parent, QPointF const &position)
{
Q_UNUSED(position)
if (!parent.isValid() || element.parent() == parent)
return;
int destinationRow = parentAbstractItem(parent)->children().size();
if (beginMoveRows(element.parent(), element.row(), element.row(), parent, destinationRow)) {
AbstractModelItem *elementItem = static_cast<AbstractModelItem*>(element.internalPointer());
elementItem->parent()->removeChild(elementItem);
AbstractModelItem *parentItem = parentAbstractItem(parent);
mApi.setParent(elementItem->id(), parentItem->id());
elementItem->setParent(parentItem);
parentItem->addChild(elementItem);
endMoveRows();
}
}
void LogicalModel::changeParent(const Id &parentId, const Id &childId)
{
QModelIndex parentIndex = mLogicalAssistApi->indexById(parentId);
QModelIndex childIndex = mLogicalAssistApi->indexById(childId);
changeParent(childIndex, parentIndex, QPointF());
}
void LogicalModel::stackBefore(const QModelIndex &element, const QModelIndex &sibling)
{
if (element == sibling) {
return;
}
beginMoveRows(element.parent(), element.row(), element.row(), element.parent(), sibling.row());
AbstractModelItem *parent = static_cast<AbstractModelItem *>(element.parent().internalPointer())
, *item = static_cast<AbstractModelItem *>(element.internalPointer())
, *siblingItem = static_cast<AbstractModelItem *>(sibling.internalPointer());
parent->stackBefore(item, siblingItem);
mApi.stackBefore(parent->id(), item->id(), siblingItem->id());
endMoveRows();
}
qrRepo::LogicalRepoApi const &LogicalModel::api() const
{
return mApi;
}
qrRepo::LogicalRepoApi &LogicalModel::mutableApi() const
{
return mApi;
}
LogicalModelAssistApi &LogicalModel::logicalModelAssistApi() const
{
return *mLogicalAssistApi;
}
bool LogicalModel::removeRows(int row, int count, QModelIndex const &parent)
{
AbstractModelItem *parentItem = parentAbstractItem(parent);
if (parentItem->children().size() < row + count)
return false;
else {
for (int i = row; i < row + count; ++i) {
AbstractModelItem *child = parentItem->children().at(i);
removeModelItems(child);
int childRow = child->row();
beginRemoveRows(parent, childRow, childRow);
child->parent()->removeChild(child);
mModelItems.remove(child->id());
if (mModelItems.count(child->id()) == 0)
mApi.removeChild(parentItem->id(), child->id());
mApi.removeElement(child->id());
delete child;
endRemoveRows();
}
return true;
}
}
void LogicalModel::removeModelItemFromApi(details::modelsImplementation::AbstractModelItem *const root, details::modelsImplementation::AbstractModelItem *child)
{
if (mModelItems.count(child->id())==0) {
mApi.removeChild(root->id(),child->id());
}
mApi.removeElement(child->id());
}
qReal::details::ModelsAssistInterface* LogicalModel::modelAssistInterface() const
{
return mLogicalAssistApi;
}
<commit_msg>Some extended fixes<commit_after>#include "logicalModel.h"
#include "graphicalModel.h"
#include <QtCore/QUuid>
using namespace qReal;
using namespace models;
using namespace models::details;
using namespace modelsImplementation;
LogicalModel::LogicalModel(qrRepo::LogicalRepoApi *repoApi, EditorManagerInterface const &editorManagerInterface)
: AbstractModel(editorManagerInterface), mGraphicalModelView(this), mApi(*repoApi)
{
mRootItem = new LogicalModelItem(Id::rootId(), NULL);
init();
mLogicalAssistApi = new LogicalModelAssistApi(*this, editorManagerInterface);
}
LogicalModel::~LogicalModel()
{
delete mLogicalAssistApi;
cleanupTree(mRootItem);
}
void LogicalModel::init()
{
mModelItems.insert(Id::rootId(), mRootItem);
mApi.setName(Id::rootId(), Id::rootId().toString());
// Turn off view notification while loading.
blockSignals(true);
loadSubtreeFromClient(static_cast<LogicalModelItem *>(mRootItem));
blockSignals(false);
}
void LogicalModel::loadSubtreeFromClient(LogicalModelItem * const parent)
{
foreach (Id childId, mApi.children(parent->id())) {
if (mApi.isLogicalElement(childId)) {
LogicalModelItem *child = loadElement(parent, childId);
loadSubtreeFromClient(child);
}
}
}
LogicalModelItem *LogicalModel::loadElement(LogicalModelItem *parentItem, Id const &id)
{
int const newRow = parentItem->children().size();
beginInsertRows(index(parentItem), newRow, newRow);
LogicalModelItem *item = new LogicalModelItem(id, parentItem);
addInsufficientProperties(id);
parentItem->addChild(item);
mModelItems.insert(id, item);
endInsertRows();
return item;
}
void LogicalModel::addInsufficientProperties(Id const &id, QString const &name)
{
if (!mEditorManagerInterface.hasElement(id.type())) {
return;
}
QMap<QString, QVariant> standardProperties;
standardProperties.insert("name", name);
standardProperties.insert("from", Id::rootId().toVariant());
standardProperties.insert("to", Id::rootId().toVariant());
standardProperties.insert("links", IdListHelper::toVariant(IdList()));
standardProperties.insert("outgoingExplosion", Id().toVariant());
standardProperties.insert("incomingExplosions", IdListHelper::toVariant(IdList()));
foreach (QString const &property, standardProperties.keys()) {
if (!mApi.hasProperty(id, property)) {
mApi.setProperty(id, property, standardProperties[property]);
}
}
QStringList const properties = mEditorManagerInterface.propertyNames(id.type());
foreach (QString const &property, properties) {
// for those properties that doesn't have default values, plugin will return empty string
mApi.setProperty(id, property, mEditorManagerInterface.defaultPropertyValue(id, property));
}
}
void LogicalModel::connectToGraphicalModel(GraphicalModel * const graphicalModel)
{
mGraphicalModelView.setModel(graphicalModel);
}
AbstractModelItem *LogicalModel::createModelItem(Id const &id, AbstractModelItem *parentItem) const
{
return new LogicalModelItem(id, static_cast<LogicalModelItem *>(parentItem));
}
void LogicalModel::updateElements(Id const &logicalId, QString const &name)
{
if ((logicalId == Id()) || (mApi.name(logicalId) == name)) {
return;
}
mApi.setName(logicalId, name);
emit dataChanged(indexById(logicalId), indexById(logicalId));
}
QMimeData* LogicalModel::mimeData(QModelIndexList const &indexes) const
{
QByteArray data;
bool isFromLogicalModel = true;
QDataStream stream(&data, QIODevice::WriteOnly);
foreach (QModelIndex index, indexes) {
if (index.isValid()) {
AbstractModelItem *item = static_cast<AbstractModelItem*>(index.internalPointer());
stream << item->id().toString();
stream << pathToItem(item);
stream << mApi.property(item->id(), "name").toString();
stream << QPointF();
stream << isFromLogicalModel;
} else {
stream << Id::rootId().toString();
stream << QString();
stream << QString();
stream << QPointF();
stream << isFromLogicalModel;
}
}
QMimeData *mimeData = new QMimeData();
mimeData->setData(DEFAULT_MIME_TYPE, data);
return mimeData;
}
QString LogicalModel::pathToItem(AbstractModelItem const *item) const
{
if (item != mRootItem) {
QString path;
do {
item = item->parent();
path = item->id().toString() + ID_PATH_DIVIDER + path;
} while (item != mRootItem);
return path;
}
else
return Id::rootId().toString();
}
void LogicalModel::addElementToModel(const Id &parent, const Id &id, const Id &logicalId
, QString const &name, const QPointF &position)
{
if (mModelItems.contains(id))
return;
Q_ASSERT_X(mModelItems.contains(parent), "addElementToModel", "Adding element to non-existing parent");
AbstractModelItem *parentItem = mModelItems[parent];
AbstractModelItem *newItem = NULL;
if (logicalId != Id::rootId() && mModelItems.contains(logicalId)) {
if (parent == logicalId) {
return;
} else {
changeParent(index(mModelItems[logicalId]), index(parentItem), QPointF());
}
} else {
newItem = createModelItem(id, parentItem);
initializeElement(id, parentItem, newItem, name, position);
}
}
void LogicalModel::initializeElement(Id const &id, modelsImplementation::AbstractModelItem *parentItem
, modelsImplementation::AbstractModelItem *item, QString const &name, QPointF const &position)
{
Q_UNUSED(position)
int newRow = parentItem->children().size();
beginInsertRows(index(parentItem), newRow, newRow);
parentItem->addChild(item);
mApi.addChild(parentItem->id(), id);
addInsufficientProperties(id, name);
mModelItems.insert(id, item);
endInsertRows();
}
QVariant LogicalModel::data(const QModelIndex &index, int role) const
{
if (index.isValid()) {
AbstractModelItem *item = static_cast<AbstractModelItem*>(index.internalPointer());
Q_ASSERT(item);
switch (role) {
case Qt::DisplayRole:
case Qt::EditRole:
return mApi.name(item->id());
case Qt::DecorationRole:
return QVariant();
// return mEditorManager.icon(item->id());
case roles::idRole:
return item->id().toVariant();
case roles::fromRole:
return mApi.from(item->id()).toVariant();
case roles::toRole:
return mApi.to(item->id()).toVariant();
}
if (role >= roles::customPropertiesBeginRole) {
QString selectedProperty = findPropertyName(item->id(), role);
return mApi.property(item->id(), selectedProperty);
}
Q_ASSERT(role < Qt::UserRole);
return QVariant();
} else {
return QVariant();
}
}
bool LogicalModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
if (index.isValid()) {
AbstractModelItem *item = static_cast<AbstractModelItem *>(index.internalPointer());
switch (role) {
case Qt::DisplayRole:
case Qt::EditRole:
mApi.setName(item->id(), value.toString());
break;
case roles::fromRole:
mApi.setFrom(item->id(), value.value<Id>());
break;
case roles::toRole:
mApi.setTo(item->id(), value.value<Id>());
break;
default:
if (role >= roles::customPropertiesBeginRole) {
QString selectedProperty = findPropertyName(item->id(), role);
mApi.setProperty(item->id(), selectedProperty, value);
break;
}
Q_ASSERT(role < Qt::UserRole);
return false;
}
emit dataChanged(index, index);
return true;
}
return false;
}
void LogicalModel::changeParent(QModelIndex const &element, QModelIndex const &parent, QPointF const &position)
{
Q_UNUSED(position)
if (!parent.isValid() || element.parent() == parent)
return;
int destinationRow = parentAbstractItem(parent)->children().size();
if (beginMoveRows(element.parent(), element.row(), element.row(), parent, destinationRow)) {
AbstractModelItem *elementItem = static_cast<AbstractModelItem*>(element.internalPointer());
elementItem->parent()->removeChild(elementItem);
AbstractModelItem *parentItem = parentAbstractItem(parent);
mApi.setParent(elementItem->id(), parentItem->id());
elementItem->setParent(parentItem);
parentItem->addChild(elementItem);
endMoveRows();
}
}
void LogicalModel::changeParent(const Id &parentId, const Id &childId)
{
QModelIndex parentIndex = mLogicalAssistApi->indexById(parentId);
QModelIndex childIndex = mLogicalAssistApi->indexById(childId);
changeParent(childIndex, parentIndex, QPointF());
}
void LogicalModel::stackBefore(const QModelIndex &element, const QModelIndex &sibling)
{
if (element == sibling) {
return;
}
beginMoveRows(element.parent(), element.row(), element.row(), element.parent(), sibling.row());
AbstractModelItem *parent = static_cast<AbstractModelItem *>(element.parent().internalPointer())
, *item = static_cast<AbstractModelItem *>(element.internalPointer())
, *siblingItem = static_cast<AbstractModelItem *>(sibling.internalPointer());
parent->stackBefore(item, siblingItem);
mApi.stackBefore(parent->id(), item->id(), siblingItem->id());
endMoveRows();
}
qrRepo::LogicalRepoApi const &LogicalModel::api() const
{
return mApi;
}
qrRepo::LogicalRepoApi &LogicalModel::mutableApi() const
{
return mApi;
}
LogicalModelAssistApi &LogicalModel::logicalModelAssistApi() const
{
return *mLogicalAssistApi;
}
bool LogicalModel::removeRows(int row, int count, QModelIndex const &parent)
{
AbstractModelItem *parentItem = parentAbstractItem(parent);
if (parentItem->children().size() < row + count)
return false;
else {
for (int i = row; i < row + count; ++i) {
AbstractModelItem *child = parentItem->children().at(i);
removeModelItems(child);
int childRow = child->row();
beginRemoveRows(parent, childRow, childRow);
child->parent()->removeChild(child);
mModelItems.remove(child->id());
if (mModelItems.count(child->id()) == 0)
mApi.removeChild(parentItem->id(), child->id());
mApi.removeElement(child->id());
delete child;
endRemoveRows();
}
return true;
}
}
void LogicalModel::removeModelItemFromApi(details::modelsImplementation::AbstractModelItem *const root, details::modelsImplementation::AbstractModelItem *child)
{
if (mModelItems.count(child->id())==0) {
mApi.removeChild(root->id(),child->id());
}
mApi.removeElement(child->id());
}
qReal::details::ModelsAssistInterface* LogicalModel::modelAssistInterface() const
{
return mLogicalAssistApi;
}
<|endoftext|> |
<commit_before>#include "event.h"
#include <iomanip>
#include <ios>
#include <map>
using std::to_string;
namespace lhef {
std::istream& operator>>(std::istream& is, GlobalInfo& info) {
is >> info.idbmup.first >> info.idbmup.second
>> info.ebmup.first >> info.ebmup.second
>> info.pdfgup.first >> info.pdfgup.second
>> info.pdfsup.first >> info.pdfsup.second
>> info.idwtup >> info.nprup;
double _xsecup, _xerrup, _xmaxup;
int _lprup;
for (int i = 0; i < info.nprup; ++i) {
is >> _xsecup >> _xerrup >> _xmaxup >> _lprup;
info.xsecup.push_back(_xsecup);
info.xerrup.push_back(_xerrup);
info.xmaxup.push_back(_xmaxup);
info.lprup.push_back(_lprup);
}
return is;
}
std::ostream& operator<<(std::ostream& os, const GlobalInfo& info) {
os << "<init>\n";
auto ss = os.precision();
os << std::setw(9) << info.idbmup.first
<< std::setw(9) << info.idbmup.second
<< std::setprecision(11) << std::scientific << std::uppercase
<< std::setw(19) << info.ebmup.first
<< std::setw(19) << info.ebmup.second;
os.precision(ss);
os << std::setw(2) << info.pdfgup.first
<< std::setw(2) << info.pdfgup.second
<< std::setw(6) << info.pdfsup.first
<< std::setw(6) << info.pdfsup.second
<< std::setw(2) << info.idwtup
<< std::setw(3) << info.nprup << '\n';
auto xsecup_it = info.xsecup.begin();
auto xerrup_it = info.xerrup.begin();
auto xmaxup_it = info.xmaxup.begin();
auto lprup_it = info.lprup.begin();
for ( ; xsecup_it != info.xsecup.end() ||
xerrup_it != info.xerrup.end() ||
xmaxup_it != info.xmaxup.end() ||
lprup_it != info.lprup.end();
++xsecup_it, ++xerrup_it, ++xmaxup_it, ++lprup_it) {
os << std::setprecision(11) << std::scientific << std::uppercase
<< std::setw(19) << *xsecup_it
<< std::setw(19) << *xerrup_it
<< std::setw(19) << *xmaxup_it;
os.precision(ss);
os << std::setw(4) << *lprup_it << '\n';
}
os << "</init>";
return os;
}
std::istream& operator>>(std::istream& is, EventInfo& evinfo) {
is >> evinfo.nup
>> evinfo.idprup
>> evinfo.xwgtup
>> evinfo.scalup
>> evinfo.aqedup
>> evinfo.aqcdup;
return is;
}
std::ostream& operator<<(std::ostream& os, const EventInfo& evinfo) {
auto ss = os.precision();
os << std::setw(2) << evinfo.nup
<< std::setw(4) << evinfo.idprup
<< std::setprecision(7) << std::scientific << std::uppercase
<< std::setw(15) << evinfo.xwgtup
<< std::setw(15) << evinfo.scalup
<< std::setw(15) << evinfo.aqedup
<< std::setw(15) << evinfo.aqcdup;
os.precision(ss);
return os;
}
const std::string show(const EventInfo& evinfo) {
std::string evinfo_str =
"EventInfo {nup=" + to_string(evinfo.nup) +
",idprup=" + to_string(evinfo.idprup) +
",xwgtup=" + to_string(evinfo.xwgtup) +
",scalup=" + to_string(evinfo.scalup) +
",aqedup=" + to_string(evinfo.aqedup) +
",aqcdup=" + to_string(evinfo.aqcdup) + "}";
return evinfo_str;
}
const std::string show(const EventEntry& entry) {
std::string entry_str = "[";
for (const auto& e : entry) {
entry_str += "(" + to_string(e.first) + "," + show(e.second) + "),";
}
entry_str.pop_back();
entry_str += "]";
return entry_str;
}
std::ostream& operator<<(std::ostream& os, const Event& ev) {
os << "<event>\n"
<< ev.event_.first << '\n';
// EventEntry is unordered_map. It has to be ordered.
std::map<int, Particle> entry_ordered(ev.event_.second.cbegin(),
ev.event_.second.cend());
for (const auto& entry : entry_ordered) {
os << entry.second << '\n';
}
os << "</event>";
return os;
}
const std::string show(const Event& ev) {
std::string ev_str = "Event (";
ev_str += show(ev.event_.first) + "," + show(ev.event_.second) + ")";
return ev_str;
}
} // namespace lhef
<commit_msg>Clean up codes<commit_after>#include "event.h"
#include <iomanip>
#include <ios>
#include <map>
using std::setw;
using std::to_string;
namespace lhef {
std::istream& operator>>(std::istream& is, GlobalInfo& info) {
is >> info.idbmup.first >> info.idbmup.second
>> info.ebmup.first >> info.ebmup.second
>> info.pdfgup.first >> info.pdfgup.second
>> info.pdfsup.first >> info.pdfsup.second
>> info.idwtup >> info.nprup;
double _xsecup, _xerrup, _xmaxup;
int _lprup;
for (int i = 0; i < info.nprup; ++i) {
is >> _xsecup >> _xerrup >> _xmaxup >> _lprup;
info.xsecup.push_back(_xsecup);
info.xerrup.push_back(_xerrup);
info.xmaxup.push_back(_xmaxup);
info.lprup.push_back(_lprup);
}
return is;
}
std::ostream& operator<<(std::ostream& os, const GlobalInfo& info) {
auto ss = os.precision();
os << "<init>\n";
os << setw(9) << info.idbmup.first << setw(9) << info.idbmup.second
<< std::setprecision(11) << std::scientific << std::uppercase
<< setw(19) << info.ebmup.first << setw(19) << info.ebmup.second;
os.precision(ss);
os << setw(2) << info.pdfgup.first << setw(2) << info.pdfgup.second
<< setw(6) << info.pdfsup.first << setw(6) << info.pdfsup.second
<< setw(2) << info.idwtup
<< setw(3) << info.nprup << '\n';
auto xsecup_it = info.xsecup.begin();
auto xerrup_it = info.xerrup.begin();
auto xmaxup_it = info.xmaxup.begin();
auto lprup_it = info.lprup.begin();
for ( ; xsecup_it != info.xsecup.end() || xerrup_it != info.xerrup.end() ||
xmaxup_it != info.xmaxup.end() || lprup_it != info.lprup.end();
++xsecup_it, ++xerrup_it, ++xmaxup_it, ++lprup_it) {
os << std::setprecision(11) << std::scientific << std::uppercase
<< setw(19) << *xsecup_it
<< setw(19) << *xerrup_it
<< setw(19) << *xmaxup_it;
os << setw(4) << *lprup_it << '\n';
}
os << "</init>";
os.precision(ss);
return os;
}
std::istream& operator>>(std::istream& is, EventInfo& evinfo) {
is >> evinfo.nup
>> evinfo.idprup
>> evinfo.xwgtup
>> evinfo.scalup
>> evinfo.aqedup
>> evinfo.aqcdup;
return is;
}
std::ostream& operator<<(std::ostream& os, const EventInfo& evinfo) {
auto ss = os.precision();
os << setw(2) << evinfo.nup
<< setw(4) << evinfo.idprup
<< std::setprecision(7) << std::scientific << std::uppercase
<< setw(15) << evinfo.xwgtup
<< setw(15) << evinfo.scalup
<< setw(15) << evinfo.aqedup
<< setw(15) << evinfo.aqcdup;
os.precision(ss);
return os;
}
const std::string show(const EventInfo& evinfo) {
std::string evinfo_str =
"EventInfo {nup=" + to_string(evinfo.nup) +
",idprup=" + to_string(evinfo.idprup) +
",xwgtup=" + to_string(evinfo.xwgtup) +
",scalup=" + to_string(evinfo.scalup) +
",aqedup=" + to_string(evinfo.aqedup) +
",aqcdup=" + to_string(evinfo.aqcdup) + "}";
return evinfo_str;
}
const std::string show(const EventEntry& entry) {
std::string entry_str = "[";
for (const auto& e : entry) {
entry_str += "(" + to_string(e.first) + "," + show(e.second) + "),";
}
entry_str.pop_back();
entry_str += "]";
return entry_str;
}
std::ostream& operator<<(std::ostream& os, const Event& ev) {
os << "<event>\n"
<< ev.event_.first << '\n';
// EventEntry is unordered_map. It has to be ordered.
std::map<int, Particle> entry_ordered(ev.event_.second.cbegin(),
ev.event_.second.cend());
for (const auto& entry : entry_ordered) {
os << entry.second << '\n';
}
os << "</event>";
return os;
}
const std::string show(const Event& ev) {
std::string ev_str = "Event (";
ev_str += show(ev.event_.first) + "," + show(ev.event_.second) + ")";
return ev_str;
}
} // namespace lhef
<|endoftext|> |
<commit_before>/*****************************************************************************
* Media Library
*****************************************************************************
* Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs
*
* Authors: Hugo Beauzée-Luyssen<[email protected]>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "LinkService.h"
#include "logging/Logger.h"
#include "MediaLibrary.h"
#include "Playlist.h"
#include "Media.h"
#include "File.h"
namespace medialibrary
{
namespace parser
{
Status LinkService::run( IItem& item )
{
switch ( item.linkType() )
{
case IItem::LinkType::NoLink:
LOG_ERROR( "Processing a task which is not a linking task from a "
"linking service" );
return Status::Fatal;
case IItem::LinkType::Media:
return linkToMedia( item );
case IItem::LinkType::Playlist:
return linkToPlaylist( item );
}
assert( false );
return Status::Fatal;
}
const char* LinkService::name() const
{
return "linking";
}
Step LinkService::targetedStep() const
{
return Step::Linking;
}
bool LinkService::initialize( IMediaLibrary* ml )
{
m_ml = static_cast<MediaLibrary*>( ml );
return true;
}
void LinkService::onFlushing()
{
}
void LinkService::onRestarted()
{
}
void LinkService::stop()
{
}
Status LinkService::linkToPlaylist(IItem& item)
{
auto mrl = item.mrl();
auto file = File::fromExternalMrl( m_ml, mrl );
// If the file isn't present yet, we assume it wasn't created yet. Let's
// try to link it later
if ( file == nullptr )
{
file = File::fromMrl( m_ml, mrl );
if ( file == nullptr )
{
/*
* We expect an external media to be created before the link task
* gets created. If we can't find a media associated to the mrl
* we can give up.
* If the media gets analyzed later on, it will be converted to an
* internal one.
*/
return Status::Fatal;
}
}
if ( file->isMain() == false )
return Status::Fatal;
auto media = file->media();
if ( media == nullptr )
return Status::Requeue;
auto playlist = Playlist::fetch( m_ml, item.linkToId() );
if ( playlist == nullptr )
return Status::Fatal;
try
{
if ( playlist->add( *media, item.linkExtra() ) == false )
return Status::Fatal;
}
catch ( const sqlite::errors::ConstraintForeignKey& )
{
// In the unlikely case the playlist or media gets deleted while we're
// linking the playlist & media, just report an error.
// If the playlist was deleted, the task will be deleted through a
// trigger and we won't retry it anyway.
return Status::Fatal;
}
// Explicitely mark the task as completed, as there is nothing more to run.
// This shouldn't be needed, but requires a better handling of multiple pipeline.
return Status::Completed;
}
Status LinkService::linkToMedia( IItem &item )
{
auto media = std::static_pointer_cast<Media>( m_ml->media( item.linkToMrl() ) );
if ( media == nullptr )
return Status::Requeue;
/*
* When linking a subtitle file, it's quite easier since we don't
* automatically import those, so we can safely assume the file isn't present
* in DB, add it and be done with it.
* For audio files though, it might be already imported, in which case we
* will need to link it with the media associated with it, and effectively
* delete the media that was created from that file
*/
if ( item.fileType() == IFile::Type::Subtitles )
{
try
{
auto t = m_ml->getConn()->newTransaction();
int64_t fileId = item.fileId();
/*
* In case a rescan was forced, or the item gets refreshed, we already
* inserted the file in database, and we just need to link that file
* with a subtitle track for this media
*/
if ( item.fileId() == 0 )
{
auto file = media->addFile( item.mrl(), item.fileType() );
if ( file == nullptr )
return Status::Fatal;
fileId = file->id();
item.setFile( std::move( file ) );
}
/* We have no way of knowing the attached subtitle track info for now */
media->addSubtitleTrack( "", "", "", "", fileId );
t->commit();
}
catch ( const sqlite::errors::ConstraintUnique& )
{
/*
* Assume that the task was already executed, and the file already linked
* but the task bookeeping failed afterward.
* Just ignore the error & mark the task as completed.
*/
}
}
else if ( item.fileType() == IFile::Type::Soundtrack )
{
auto mrl = item.mrl();
auto t = m_ml->getConn()->newTransaction();
if ( item.fileId() == 0 )
{
auto file = File::fromMrl( m_ml, mrl );
if ( file == nullptr )
{
file = File::fromExternalMrl( m_ml, mrl );
if ( file == nullptr )
{
file = std::static_pointer_cast<File>(
media->addFile( std::move( mrl ), item.fileType() ) );
if ( file == nullptr )
return Status::Fatal;
}
}
if ( file->setMediaId( media->id() ) == false )
return Status::Fatal;
item.setFile( std::move( file ) );
}
auto tracks = item.tracks();
for ( const auto& tr : tracks )
{
media->addAudioTrack( tr.codec, tr.bitrate, tr.a.rate, tr.a.nbChannels,
tr.language, tr.description, item.fileId() );
}
t->commit();
}
return Status::Completed;
}
}
}
<commit_msg>LinkService: Don't copy the item mrl<commit_after>/*****************************************************************************
* Media Library
*****************************************************************************
* Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs
*
* Authors: Hugo Beauzée-Luyssen<[email protected]>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "LinkService.h"
#include "logging/Logger.h"
#include "MediaLibrary.h"
#include "Playlist.h"
#include "Media.h"
#include "File.h"
namespace medialibrary
{
namespace parser
{
Status LinkService::run( IItem& item )
{
switch ( item.linkType() )
{
case IItem::LinkType::NoLink:
LOG_ERROR( "Processing a task which is not a linking task from a "
"linking service" );
return Status::Fatal;
case IItem::LinkType::Media:
return linkToMedia( item );
case IItem::LinkType::Playlist:
return linkToPlaylist( item );
}
assert( false );
return Status::Fatal;
}
const char* LinkService::name() const
{
return "linking";
}
Step LinkService::targetedStep() const
{
return Step::Linking;
}
bool LinkService::initialize( IMediaLibrary* ml )
{
m_ml = static_cast<MediaLibrary*>( ml );
return true;
}
void LinkService::onFlushing()
{
}
void LinkService::onRestarted()
{
}
void LinkService::stop()
{
}
Status LinkService::linkToPlaylist( IItem& item )
{
const auto& mrl = item.mrl();
auto file = File::fromExternalMrl( m_ml, mrl );
// If the file isn't present yet, we assume it wasn't created yet. Let's
// try to link it later
if ( file == nullptr )
{
file = File::fromMrl( m_ml, mrl );
if ( file == nullptr )
{
/*
* We expect an external media to be created before the link task
* gets created. If we can't find a media associated to the mrl
* we can give up.
* If the media gets analyzed later on, it will be converted to an
* internal one.
*/
return Status::Fatal;
}
}
if ( file->isMain() == false )
return Status::Fatal;
auto media = file->media();
if ( media == nullptr )
return Status::Requeue;
auto playlist = Playlist::fetch( m_ml, item.linkToId() );
if ( playlist == nullptr )
return Status::Fatal;
try
{
if ( playlist->add( *media, item.linkExtra() ) == false )
return Status::Fatal;
}
catch ( const sqlite::errors::ConstraintForeignKey& )
{
// In the unlikely case the playlist or media gets deleted while we're
// linking the playlist & media, just report an error.
// If the playlist was deleted, the task will be deleted through a
// trigger and we won't retry it anyway.
return Status::Fatal;
}
// Explicitely mark the task as completed, as there is nothing more to run.
// This shouldn't be needed, but requires a better handling of multiple pipeline.
return Status::Completed;
}
Status LinkService::linkToMedia( IItem &item )
{
auto media = std::static_pointer_cast<Media>( m_ml->media( item.linkToMrl() ) );
if ( media == nullptr )
return Status::Requeue;
/*
* When linking a subtitle file, it's quite easier since we don't
* automatically import those, so we can safely assume the file isn't present
* in DB, add it and be done with it.
* For audio files though, it might be already imported, in which case we
* will need to link it with the media associated with it, and effectively
* delete the media that was created from that file
*/
if ( item.fileType() == IFile::Type::Subtitles )
{
try
{
auto t = m_ml->getConn()->newTransaction();
int64_t fileId = item.fileId();
/*
* In case a rescan was forced, or the item gets refreshed, we already
* inserted the file in database, and we just need to link that file
* with a subtitle track for this media
*/
if ( item.fileId() == 0 )
{
auto file = media->addFile( item.mrl(), item.fileType() );
if ( file == nullptr )
return Status::Fatal;
fileId = file->id();
item.setFile( std::move( file ) );
}
/* We have no way of knowing the attached subtitle track info for now */
media->addSubtitleTrack( "", "", "", "", fileId );
t->commit();
}
catch ( const sqlite::errors::ConstraintUnique& )
{
/*
* Assume that the task was already executed, and the file already linked
* but the task bookeeping failed afterward.
* Just ignore the error & mark the task as completed.
*/
}
}
else if ( item.fileType() == IFile::Type::Soundtrack )
{
auto mrl = item.mrl();
auto t = m_ml->getConn()->newTransaction();
if ( item.fileId() == 0 )
{
auto file = File::fromMrl( m_ml, mrl );
if ( file == nullptr )
{
file = File::fromExternalMrl( m_ml, mrl );
if ( file == nullptr )
{
file = std::static_pointer_cast<File>(
media->addFile( std::move( mrl ), item.fileType() ) );
if ( file == nullptr )
return Status::Fatal;
}
}
if ( file->setMediaId( media->id() ) == false )
return Status::Fatal;
item.setFile( std::move( file ) );
}
auto tracks = item.tracks();
for ( const auto& tr : tracks )
{
media->addAudioTrack( tr.codec, tr.bitrate, tr.a.rate, tr.a.nbChannels,
tr.language, tr.description, item.fileId() );
}
t->commit();
}
return Status::Completed;
}
}
}
<|endoftext|> |
<commit_before>#include "Body.h"
void Body::setMass(float newMass){
mass = abs(newMass);
}
void Body::setRadius(float newRadius){
radius = abs(newRadius);
}
Body::Body(Eigen::Vector3f posInit, Eigen::Vector3f velInit, float massInit, float radiusInit){
position = posInit;
velocity = velInit;
mass = abs(massInit);
radius = abs(radiusInit);
}
Eigen::Vector3f Body::getPos(){
return position;
}
Eigen::Vector3f Body::getVel(){
return velocity;
}
Eigen::Vector3f Body::getAcc(){
return acceleration;
}
float Body::getMass(){
return mass;
}
float Body::getRadius(){
return radius;
}
void Body::addSensor(Sensor* newSensor){
Sensors.push_back(newSensor);
}
void Body::addThruster(Thruster newThruster){
Thrusters.push_back(newThruster);
}
void Body::addSensor(int placeAfter, Sensor* newSensor){
Sensors.insert(Sensors.begin()+(placeAfter-1), newSensor);
}
void Body::addThruster(int placeAfter, Thruster newThruster){
Thrusters.insert(Thrusters.begin()+(placeAfter-1), newThruster);
}
void Body::removeSensor(int sensorNo){
Sensors.erase(Sensors.begin()+(sensorNo-1));
}
void Body::removeThruster(int thrusterNo){
Thrusters.erase(Thrusters.begin()+(thrusterNo-1));
}
float Body::getSensorValue(int sensorNo){
return Sensors[sensorNo-1]->getReading();
}
Eigen::Vector3f Body::calculateThrustVector(){
Eigen::Vector3f plc(0,0,0);
//for(Thruster thrust:Thrusters){plc+=thrust.getThrust();} //I can dream, Harold
for(std::vector<Thruster>::iterator itr = Thrusters.begin(); itr!=Thrusters.end(); ++itr){
plc+=itr->viewThrust();
}
return plc;
}
void Body::Update(float dt){
acceleration = this->calculateThrustVector()/this->getMass();
position+=dt*velocity+dt*dt/2*acceleration;
velocity+=dt*acceleration;
}
<commit_msg>Fixed use of abs from cmath (ints only) to std::abs<commit_after>#include "Body.h"
void Body::setMass(float newMass){
mass = std::abs(newMass);
}
void Body::setRadius(float newRadius){
radius = std::abs(newRadius);
}
Body::Body(Eigen::Vector3f posInit, Eigen::Vector3f velInit, float massInit, float radiusInit){
position = posInit;
velocity = velInit;
mass = std::abs(massInit);
radius = std::abs(radiusInit);
}
Eigen::Vector3f Body::getPos(){
return position;
}
Eigen::Vector3f Body::getVel(){
return velocity;
}
Eigen::Vector3f Body::getAcc(){
return acceleration;
}
float Body::getMass(){
return mass;
}
float Body::getRadius(){
return radius;
}
void Body::addSensor(Sensor* newSensor){
Sensors.push_back(newSensor);
}
void Body::addThruster(Thruster newThruster){
Thrusters.push_back(newThruster);
}
void Body::addSensor(int placeAfter, Sensor* newSensor){
Sensors.insert(Sensors.begin()+(placeAfter-1), newSensor);
}
void Body::addThruster(int placeAfter, Thruster newThruster){
Thrusters.insert(Thrusters.begin()+(placeAfter-1), newThruster);
}
void Body::removeSensor(int sensorNo){
Sensors.erase(Sensors.begin()+(sensorNo-1));
}
void Body::removeThruster(int thrusterNo){
Thrusters.erase(Thrusters.begin()+(thrusterNo-1));
}
float Body::getSensorValue(int sensorNo){
return Sensors[sensorNo-1]->getReading();
}
Eigen::Vector3f Body::calculateThrustVector(){
Eigen::Vector3f plc(0,0,0);
//for(Thruster thrust:Thrusters){plc+=thrust.getThrust();} //I can dream, Harold
for(std::vector<Thruster>::iterator itr = Thrusters.begin(); itr!=Thrusters.end(); ++itr){
plc+=itr->viewThrust();
}
return plc;
}
void Body::Update(float dt){
acceleration = this->calculateThrustVector()/this->getMass();
position+=dt*velocity+dt*dt/2*acceleration;
velocity+=dt*acceleration;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <cmath>
#include <ctime>
#include "lib/font.h"
#include "lib/body.h"
#include "lib/image.h"
#include "lib/video.h"
#include "lib/output.h"
#include "lib/misc.h"
#include "lib/matrix.h"
#include "lib/units.h"
#include <pngwriter.h>
using namespace std;
int RandomInteger(int min, int max) {
srand((unsigned)clock());;
max ++;
double r = (double)rand() / (double)RAND_MAX;
int rnd = (int)(min + r * (max - min));
return rnd;
}
double Random(double min, double max) {
srand((unsigned)clock());
max ++;
double r = (double)rand() / (double)RAND_MAX;
double rnd = min + r * (max - min);
return rnd;
}
int main(int argc, char * argv[]) {
string usageStatement = "Usage: ./sombrero [-g --generate] [-r --run]";
// Need to make these "settable" by the user
int bodyCount = 200;
int width = 640;
int height = 480;
int framerate = 45;
Body * bodyArray [bodyCount];
// No arguments supplied
if (argc == 1) {
// No arguments supplied. Exit.
cout << "No arguments supplied. Must choose an option." << endl;
cout << usageStatement << endl;
return 1;
}
// Generate Body arrangement
if (strcmp(argv[1], "-g") == 0 or strcmp(argv[1], "--generate") == 0) {
// Randomly generate bodies
for (int i = 0; i < bodyCount - 1; i++) {
double r = Random(1e11, 2e11);
double theta = Random(0, 2 * PI);
double phi = Random(0, 2 * PI);
double x = r * cos(theta) * cos(phi);
double y = r * sin(theta);
double z = r * cos(theta) * sin(phi);
double mass = Random(1e23, 1e25);
bodyArray[i] = new Body(x, y, z, mass, Random(1e6, 9e6), Random(0, 1e4), Random(0, 1e4), Random(0, 1e4));
}
bodyArray[bodyCount] = new Body(0.0, 0.0, 0.0, 2e31, 1e8, 0.0, 0.0, 0.0);
// Save bodies to output.txt
Output output("init/output.txt", bodyCount, width, height, 100);
output.AddAllBodies(bodyArray);
output.Save();
Video video = Video("images/", "image_", width, height, framerate);
video.ClearImageFolder();
// Rotate bodies about the y-axis
for (double angle = 0.0; angle < 360.0; angle ++) {
string imageFileName = "images/image_" + PadWithZeroes(angle, 360) + ".png";
Image image = Image(imageFileName, width, height, 100);
for (int i = 0; i < bodyCount; i++) {
// Rotate body
Vector p;
p.Set(bodyArray[i]->GetX(), bodyArray[i]->GetY(), bodyArray[i]->GetZ());
Vector t;
t = p.RotateY(angle);
t = t.RoundValues();
image.DrawBody(t.GetX(), t.GetY(), 255, 255, 255);
}
image.Save();
}
// Build video from images
video.Build("result.mp4", 360);
return 0;
}
// Run simulation
if (strcmp(argv[1], "-r") == 0 or strcmp(argv[1], "--run") == 0) {
LoadBodiesFromFile("init/output.txt", bodyArray);
Video video = Video("images/", "image_", width, height, framerate);
video.ClearImageFolder();
int frames = 500;
double dt = DAY;
for (int f = 0; f < frames; f++) {
for (int a = 0; a < bodyCount; a++) {
bodyArray[a]->ResetForce();
for (int b = 0; b < bodyCount; b++) {
if (a != b) {
// Calculate distance
double xDistance = bodyArray[a]->GetX() - bodyArray[b]->GetX();
double yDistance = bodyArray[a]->GetY() - bodyArray[b]->GetY();
double zDistance = bodyArray[a]->GetZ() - bodyArray[b]->GetZ();
double totalDistance = sqrt(pow(xDistance, 2) + pow(yDistance, 2) + pow(zDistance, 2));
// Calculate angles
double phiAngle = atan2(zDistance, sqrt(pow(xDistance, 2) + pow(yDistance, 2)));
double thetaAngle = atan2(yDistance, xDistance);
// Calculate force
double force = GR * ((bodyArray[a]->GetMass() * bodyArray[b]->GetMass()) / (pow(totalDistance, 2)));
// Add force to total
bodyArray[a]->AddForce(force, phiAngle, thetaAngle);
}
}
}
string imageFileName = "images/image_" + PadWithZeroes(f, frames) + ".png";
Image image = Image(imageFileName, width, height, 100);
for (int i = 0; i < bodyCount; i++) {
bodyArray[i]->Update(dt);
bodyArray[i]->Step();
image.DrawBody(bodyArray[i]->GetX(), bodyArray[i]->GetY(), 255, 255, 255);
}
image.Save();
}
cout << "Done! Building video..." << endl;
video.Build("result_run.mp4", frames);
// Create output.txt
Output output("init/output.txt", bodyCount, width, height, 100);
output.AddAllBodies(bodyArray);
output.Save();
return 0;
}
// No *valid* arguments supplied
else {
cout << "No valid arguments provided." << endl;
cout << usageStatement << endl;
return 1;
}
return 0;
}
<commit_msg>Fixed segmentation fault (bodyArray)<commit_after>#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <cmath>
#include <ctime>
#include "lib/font.h"
#include "lib/body.h"
#include "lib/image.h"
#include "lib/video.h"
#include "lib/output.h"
#include "lib/misc.h"
#include "lib/matrix.h"
#include "lib/units.h"
#include <pngwriter.h>
using namespace std;
int RandomInteger(int min, int max) {
srand((unsigned)clock());;
max ++;
double r = (double)rand() / (double)RAND_MAX;
int rnd = (int)(min + r * (max - min));
return rnd;
}
double Random(double min, double max) {
srand((unsigned)clock());
max ++;
double r = (double)rand() / (double)RAND_MAX;
double rnd = min + r * (max - min);
return rnd;
}
int main(int argc, char * argv[]) {
string usageStatement = "Usage: ./sombrero [-g --generate] [-r --run]";
// Need to make these "settable" by the user
int bodyCount = 200;
int width = 640;
int height = 480;
int framerate = 45;
Body * bodyArray [bodyCount];
// No arguments supplied
if (argc == 1) {
// No arguments supplied. Exit.
cout << "No arguments supplied. Must choose an option." << endl;
cout << usageStatement << endl;
return 1;
}
// Generate Body arrangement
if (strcmp(argv[1], "-g") == 0 or strcmp(argv[1], "--generate") == 0) {
// Randomly generate bodies
for (int i = 0; i < bodyCount - 1; i++) {
double r = Random(1e11, 2e11);
double theta = Random(0, 2 * PI);
double phi = Random(0, 2 * PI);
double x = r * cos(theta) * cos(phi);
double y = r * sin(theta);
double z = r * cos(theta) * sin(phi);
double mass = Random(1e23, 1e25);
bodyArray[i] = new Body(x, y, z, mass, Random(1e6, 9e6), Random(0, 1e4), Random(0, 1e4), Random(0, 1e4));
}
bodyArray[bodyCount - 1] = new Body(0.0, 0.0, 0.0, 2e31, 1e8, 0.0, 0.0, 0.0);
// Save bodies to output.txt
Output output("init/output.txt", bodyCount, width, height, 100);
output.AddAllBodies(bodyArray);
output.Save();
Video video = Video("images/", "image_", width, height, framerate);
video.ClearImageFolder();
// Rotate bodies about the y-axis
for (double angle = 0.0; angle < 360.0; angle ++) {
string imageFileName = "images/image_" + PadWithZeroes(angle, 360) + ".png";
Image image = Image(imageFileName, width, height, 100);
for (int i = 0; i < bodyCount; i++) {
// Rotate body
Vector p;
p.Set(bodyArray[i]->GetX(), bodyArray[i]->GetY(), bodyArray[i]->GetZ());
Vector t;
t = p.RotateY(angle);
t = t.RoundValues();
image.DrawBody(t.GetX(), t.GetY(), 255, 255, 255);
}
image.Save();
}
// Build video from images
video.Build("result.mp4", 360);
return 0;
}
// Run simulation
if (strcmp(argv[1], "-r") == 0 or strcmp(argv[1], "--run") == 0) {
LoadBodiesFromFile("init/output.txt", bodyArray);
Video video = Video("images/", "image_", width, height, framerate);
video.ClearImageFolder();
int frames = 500;
double dt = DAY;
for (int f = 0; f < frames; f++) {
for (int a = 0; a < bodyCount; a++) {
bodyArray[a]->ResetForce();
for (int b = 0; b < bodyCount; b++) {
if (a != b) {
// Calculate distance
double xDistance = bodyArray[a]->GetX() - bodyArray[b]->GetX();
double yDistance = bodyArray[a]->GetY() - bodyArray[b]->GetY();
double zDistance = bodyArray[a]->GetZ() - bodyArray[b]->GetZ();
double totalDistance = sqrt(pow(xDistance, 2) + pow(yDistance, 2) + pow(zDistance, 2));
// Calculate angles
double phiAngle = atan2(zDistance, sqrt(pow(xDistance, 2) + pow(yDistance, 2)));
double thetaAngle = atan2(yDistance, xDistance);
// Calculate force
double force = GR * ((bodyArray[a]->GetMass() * bodyArray[b]->GetMass()) / (pow(totalDistance, 2)));
// Add force to total
bodyArray[a]->AddForce(force, phiAngle, thetaAngle);
}
}
}
string imageFileName = "images/image_" + PadWithZeroes(f, frames) + ".png";
Image image = Image(imageFileName, width, height, 100);
for (int i = 0; i < bodyCount; i++) {
bodyArray[i]->Update(dt);
bodyArray[i]->Step();
image.DrawBody(bodyArray[i]->GetX(), bodyArray[i]->GetY(), 255, 255, 255);
}
image.Save();
}
cout << "Done! Building video..." << endl;
video.Build("result_run.mp4", frames);
// Create output.txt
Output output("init/output.txt", bodyCount, width, height, 100);
output.AddAllBodies(bodyArray);
output.Save();
return 0;
}
// No *valid* arguments supplied
else {
cout << "No valid arguments provided." << endl;
cout << usageStatement << endl;
return 1;
}
return 0;
}
<|endoftext|> |
<commit_before>#include <Arduino.h>
#include <Adafruit_NeoPixel.h>
#include <DS3232RTC.h>
#include <SerialCommand.h>
#include <Time.h>
#include <Wire.h>
#include "Button.h"
#define PIXEL_PIN 5 // Digital IO pin connected to the NeoPixels.
#define PIXEL_COUNT 22
#define BUTTON_PIN 4
class Nightlight
{
private:
byte brightness;
int8_t brightnessDelta;
public:
Nightlight()
: brightness(10)
, brightnessDelta(1)
{
}
void held()
{
if (brightnessDelta > 0 && brightness == 255) {
brightnessDelta = -1;
} else if (brightnessDelta < 0 && brightness == 0) {
brightnessDelta = 1;
}
brightness += brightnessDelta;
Serial.print("Brightness ");
Serial.println(brightness);
}
void released()
{
brightnessDelta = -brightnessDelta;
}
void reset()
{
brightness = 0;
brightnessDelta = 1;
}
uint32_t colour()
{
if (timeStatus() == timeSet) {
const time_t t = now();
if (hour(t) >= 7 && hour(t) < 20) {
return Adafruit_NeoPixel::Color(brightness, brightness/2, 0);
}
}
return Adafruit_NeoPixel::Color(brightness, 0, brightness);
}
};
void print_2digit(Print &out, int value)
{
if (value < 10) {
out.print('0');
}
out.print(value);
}
void print_date(Print &out, time_t t)
{
out.print(year(t));
out.print('-');
print_2digit(out, month(t));
out.print('-');
print_2digit(out, day(t));
out.print('T');
print_2digit(out, hour(t));
out.print(':');
print_2digit(out, minute(t));
out.print(':');
print_2digit(out, second(t));
}
Adafruit_NeoPixel pixels(PIXEL_COUNT, PIXEL_PIN);
Button button(BUTTON_PIN);
Nightlight nightlight;
SerialCommand serialcmd;
void set_time()
{
int numbers[6] = {};
for (auto & number : numbers) {
const char *const arg = serialcmd.next();
if (arg == nullptr) {
Serial.println("Invalid time format");
return;
}
number = strtol(arg, NULL, 10);
}
tmElements_t tm;
tm.Year = CalendarYrToTm(numbers[0]);
tm.Month = numbers[1];
tm.Day = numbers[2];
tm.Hour = numbers[3];
tm.Minute = numbers[4];
tm.Second = numbers[5];
const time_t t = makeTime(tm);
RTC.set(t);
setTime(t);
Serial.print("time ");
print_date(Serial, now());
Serial.println();
}
void setup()
{
Serial.begin(9600);
pixels.begin();
pixels.show();
button.setup();
setSyncProvider(RTC.get);
if (timeStatus() != timeSet) {
Serial.println("Unable to sync with RTC");
} else {
Serial.print("RTC has set the system time to ");
print_date(Serial, now());
Serial.println();
}
serialcmd.addCommand("settime", set_time);
}
void loop()
{
static uint32_t lastColour = 0;
static byte on = false;
static byte lastHeld = false;
button.read();
serialcmd.readSerial();
if (button.pressed()) {
on = !on;
if (on) {
Serial.println("Turning on");
} else {
Serial.println("Turning off");
pixels.clear();
pixels.show();
}
}
const byte held = button.held();
if (held) {
if (on) {
nightlight.held();
} else {
on = true;
nightlight.reset();
}
}
if (held != lastHeld) {
lastHeld = held;
if (!held) {
nightlight.released();
}
}
const uint32_t colour = nightlight.colour();
if (lastColour != colour) {
for (int i = 0; i != pixels.numPixels(); ++i) {
pixels.setPixelColor(i, colour);
}
pixels.show();
lastColour = colour;
}
delay(10);
}
<commit_msg>Fix compiler warning<commit_after>#include <Arduino.h>
#include <Adafruit_NeoPixel.h>
#include <DS3232RTC.h>
#include <SerialCommand.h>
#include <Time.h>
#include <Wire.h>
#include "Button.h"
#define PIXEL_PIN 5 // Digital IO pin connected to the NeoPixels.
#define PIXEL_COUNT 22
#define BUTTON_PIN 4
class Nightlight
{
private:
byte brightness;
int8_t brightnessDelta;
public:
Nightlight()
: brightness(10)
, brightnessDelta(1)
{
}
void held()
{
if (brightnessDelta > 0 && brightness == 255) {
brightnessDelta = -1;
} else if (brightnessDelta < 0 && brightness == 0) {
brightnessDelta = 1;
}
brightness += brightnessDelta;
Serial.print("Brightness ");
Serial.println(brightness);
}
void released()
{
brightnessDelta = -brightnessDelta;
}
void reset()
{
brightness = 0;
brightnessDelta = 1;
}
uint32_t colour()
{
if (timeStatus() == timeSet) {
const time_t t = now();
if (hour(t) >= 7 && hour(t) < 20) {
return Adafruit_NeoPixel::Color(brightness, brightness/2, 0);
}
}
return Adafruit_NeoPixel::Color(brightness, 0, brightness);
}
};
void print_2digit(Print &out, int value)
{
if (value < 10) {
out.print('0');
}
out.print(value);
}
void print_date(Print &out, time_t t)
{
out.print(year(t));
out.print('-');
print_2digit(out, month(t));
out.print('-');
print_2digit(out, day(t));
out.print('T');
print_2digit(out, hour(t));
out.print(':');
print_2digit(out, minute(t));
out.print(':');
print_2digit(out, second(t));
}
Adafruit_NeoPixel pixels(PIXEL_COUNT, PIXEL_PIN);
Button button(BUTTON_PIN);
Nightlight nightlight;
SerialCommand serialcmd;
void set_time()
{
int numbers[6] = {};
for (auto & number : numbers) {
const char *const arg = serialcmd.next();
if (arg == nullptr) {
Serial.println("Invalid time format");
return;
}
number = strtol(arg, NULL, 10);
}
tmElements_t tm;
tm.Year = CalendarYrToTm(numbers[0]);
tm.Month = numbers[1];
tm.Day = numbers[2];
tm.Hour = numbers[3];
tm.Minute = numbers[4];
tm.Second = numbers[5];
const time_t t = makeTime(tm);
RTC.set(t);
setTime(t);
Serial.print("time ");
print_date(Serial, now());
Serial.println();
}
void setup()
{
Serial.begin(9600);
pixels.begin();
pixels.show();
button.setup();
setSyncProvider(RTC.get);
if (timeStatus() != timeSet) {
Serial.println("Unable to sync with RTC");
} else {
Serial.print("RTC has set the system time to ");
print_date(Serial, now());
Serial.println();
}
serialcmd.addCommand("settime", set_time);
}
void loop()
{
static uint32_t lastColour = 0;
static byte on = false;
static byte lastHeld = false;
button.read();
serialcmd.readSerial();
if (button.pressed()) {
on = !on;
if (on) {
Serial.println("Turning on");
} else {
Serial.println("Turning off");
pixels.clear();
pixels.show();
}
}
const byte held = button.held();
if (held) {
if (on) {
nightlight.held();
} else {
on = true;
nightlight.reset();
}
}
if (held != lastHeld) {
lastHeld = held;
if (!held) {
nightlight.released();
}
}
const uint32_t colour = nightlight.colour();
if (lastColour != colour) {
for (unsigned i = 0; i != pixels.numPixels(); ++i) {
pixels.setPixelColor(i, colour);
}
pixels.show();
lastColour = colour;
}
delay(10);
}
<|endoftext|> |
<commit_before>#include <cstdlib>
#include <cmath>
#include <fstream>
#include <sstream>
#include <iostream>
#include <cstring>
#include <iomanip>
#include <string>
#include <vector>
#include <algorithm>
#include <exception>
#include <sys/time.h>
#include <map>
#include <stdlib.h> /* srand, rand */
#include <string.h>
#include "misc.h"
#include "collision.h"
#include "feat.h"
// Features ------------------------------------------------------------------
Feat::Feat() {
Count = 0;
Categories = 0;
AvCollide = 3.2;
Collide = 1.98;
NoCollide = 7.0;
PatrolRad = 5.8;
NeighborRad = 14.05;
PlateRadius = 1.65;
MaxSS = 10;
MaxSF = 40;
InterPlate = 0;
Collision = false;
Exact = true;
}
void Feat::readInputFile(const char file[]) {
const int Mc = 512; // Max chars per line
char delimiter = ' ';
std::ifstream fIn;
fIn.open(file); // open a file
if (!fIn.good()) myexit(1); // Not found
while (!fIn.eof()) {
char buf[Mc];
fIn.getline(buf,Mc);
int n = 0; // a for-loop index
Slist tok = s2vec(buf,delimiter);
if (2<=tok.size()) {
if (tok[0]=="Targfile") Targfile=tok[1];
if (tok[0]=="tileFile") tileFile= tok[1];
if (tok[0]=="fibFile") fibFile= tok[1];
if (tok[0]=="fibstatusFile") fibstatusFile = tok[1];
if (tok[0]=="surveyFile") surveyFile= tok[1];
if (tok[0]=="outDir") outDir= tok[1];
if (tok[0]=="SStarsfile")SStarsfile=tok[1];
if (tok[0]=="SkyFfile") SkyFfile=tok[1];
if (tok[0]=="runDate") runDate=tok[1];
}
}
fIn.close();
}
void Feat::parseCommandLine(int argc, char **argv) {
int i;
for (i=1;i<argc;){
std::cout << i << "en esta vamos\n";
if (!strcmp(argv[i],"-target")){
i++;
Targfile = str(argv[i]);
i++;
}else if (!strcmp(argv[i],"-sky")){
i++;
SkyFfile = str(argv[i]);
i++;
}else if (!strcmp(argv[i],"-star")){
i++;
SStarsfile = str(argv[i]);
i++;
}else if (!strcmp(argv[i],"-survey")){
i++;
surveyFile = str(argv[i]);
i++;
}else if (!strcmp(argv[i],"-outdir")){
i++;
outDir = str(argv[i]);
i++;
}else if (!strcmp(argv[i],"-tilefile")){
i++;
tileFile= str(argv[i]);
i++;
}else if (!strcmp(argv[i],"-fibfile")){
i++;
fibFile = str(argv[i]);
std::cout << fibFile << std::endl;
i++;
}else if (!strcmp(argv[i],"-fibstatusfile")){
i++;
fibstatusFile = str(argv[i]);
std::cout << fibstatusFile << std::endl;
i++;
}else if (!strcmp(argv[i],"-rundate")){
i++;
runDate = str(argv[i]);
i++;
}else{
fprintf (stderr,"\nUnrecognized option: %s\n\n",argv[i]);
exit(0);
}
}
}
<commit_msg>usaeg<commit_after>#include <cstdlib>
#include <cmath>
#include <fstream>
#include <sstream>
#include <iostream>
#include <cstring>
#include <iomanip>
#include <string>
#include <vector>
#include <algorithm>
#include <exception>
#include <sys/time.h>
#include <map>
#include <stdlib.h> /* srand, rand */
#include <string.h>
#include "misc.h"
#include "collision.h"
#include "feat.h"
void Usage(char *ExecName)
{
std::cout << "Usage: "<<ExecName;
std::cout << " -target <target_filename> ";
std::cout << " -sky <sky_filename> ";
std::cout << " -star <star_filename> ";
std::cout << " -survey <surveytiles_filename> ";
std::cout << " -tilefile <tilelist_filename> ";
std::cout << " -fibfile <fiberpos_filename> ";
std::cout << " -fibstatusfile <fiberstatus_filename> ";
std::cout << " -outdir <outputdirectory> ";
std::cout << " [-rundate <YYYY-MM-DD>]"<< std::endl;
exit(0);
}
// Features ------------------------------------------------------------------
Feat::Feat() {
Count = 0;
Categories = 0;
AvCollide = 3.2;
Collide = 1.98;
NoCollide = 7.0;
PatrolRad = 5.8;
NeighborRad = 14.05;
PlateRadius = 1.65;
MaxSS = 10;
MaxSF = 40;
InterPlate = 0;
Collision = false;
Exact = true;
}
void Feat::readInputFile(const char file[]) {
const int Mc = 512; // Max chars per line
char delimiter = ' ';
std::ifstream fIn;
fIn.open(file); // open a file
if (!fIn.good()) myexit(1); // Not found
while (!fIn.eof()) {
char buf[Mc];
fIn.getline(buf,Mc);
int n = 0; // a for-loop index
Slist tok = s2vec(buf,delimiter);
if (2<=tok.size()) {
if (tok[0]=="Targfile") Targfile=tok[1];
if (tok[0]=="tileFile") tileFile= tok[1];
if (tok[0]=="fibFile") fibFile= tok[1];
if (tok[0]=="fibstatusFile") fibstatusFile = tok[1];
if (tok[0]=="surveyFile") surveyFile= tok[1];
if (tok[0]=="outDir") outDir= tok[1];
if (tok[0]=="SStarsfile")SStarsfile=tok[1];
if (tok[0]=="SkyFfile") SkyFfile=tok[1];
if (tok[0]=="runDate") runDate=tok[1];
}
}
fIn.close();
}
void Feat::parseCommandLine(int argc, char **argv) {
int i;
for (i=1;i<argc;){
if (!strcmp(argv[i],"-target")){
i++;
Targfile = str(argv[i]);
i++;
}else if (!strcmp(argv[i],"-sky")){
i++;
SkyFfile = str(argv[i]);
i++;
}else if (!strcmp(argv[i],"-star")){
i++;
SStarsfile = str(argv[i]);
i++;
}else if (!strcmp(argv[i],"-survey")){
i++;
surveyFile = str(argv[i]);
i++;
}else if (!strcmp(argv[i],"-outdir")){
i++;
outDir = str(argv[i]);
i++;
}else if (!strcmp(argv[i],"-tilefile")){
i++;
tileFile= str(argv[i]);
i++;
}else if (!strcmp(argv[i],"-fibfile")){
i++;
fibFile = str(argv[i]);
i++;
}else if (!strcmp(argv[i],"-fibstatusfile")){
i++;
fibstatusFile = str(argv[i]);
i++;
}else if (!strcmp(argv[i],"-rundate")){
i++;
runDate = str(argv[i]);
i++;
}else{
fprintf (stderr,"\nUnrecognized option: %s\n\n",argv[i]);
Usage(argv[0]);
}
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2013
* Alessio Sclocco <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cmath>
#include <cstring>
using std::cout;
using std::cerr;
using std::endl;
using std::fixed;
using std::setprecision;
using std::ofstream;
using std::ceil;
using std::pow;
#include <ArgumentList.hpp>
#include <InitializeOpenCL.hpp>
#include <CLData.hpp>
#include <Exceptions.hpp>
#include <Copy.hpp>
#include <utils.hpp>
using isa::utils::ArgumentList;
using isa::OpenCL::initializeOpenCL;
using isa::OpenCL::CLData;
using isa::Exceptions::OpenCLError;
using isa::Benchmarks::Copy;
using isa::utils::same;
const unsigned int nrIterations = 10;
int main(int argc, char * argv[]) {
unsigned int oclPlatform = 0;
unsigned int oclDevice = 0;
unsigned int arrayDim = 0;
unsigned int maxThreads = 0;
// Parse command line
if ( argc != 7 ) {
cerr << "Usage: " << argv[0] << " -opencl_platform <opencl_platform> -opencl_device <opencl_device> -m <max_threads>" << endl;
return 1;
}
ArgumentList commandLine(argc, argv);
try {
oclPlatform = commandLine.getSwitchArgument< unsigned int >("-opencl_platform");
oclDevice = commandLine.getSwitchArgument< unsigned int >("-opencl_device");
maxThreads = commandLine.getSwitchArgument< unsigned int >("-max_threads");
} catch ( exception & err ) {
cerr << err.what() << endl;
return 1;
}
// Initialize OpenCL
vector< cl::Platform > * oclPlatforms = new vector< cl::Platform >();
cl::Context * oclContext = new cl::Context();
vector< cl::Device > * oclDevices = new vector< cl::Device >();
vector< vector< cl::CommandQueue > > * oclQueues = new vector< vector< cl::CommandQueue > >();
try {
initializeOpenCL(oclPlatform, 1, oclPlatforms, oclContext, oclDevices, oclQueues);
} catch ( OpenCLError err ) {
cerr << err.what() << endl;
return 1;
}
arrayDim = (oclDevices->at(oclDevice)).getInfo< CL_DEVICE_MAX_MEM_ALLOC_SIZE >();
arrayDim /= sizeof(float);
CLData< float > * A = new CLData< float >("A", true);
CLData< float > * B = new CLData< float >("B", true);
A->setCLContext(oclContext);
A->setCLQueue(&(oclQueues->at(oclDevice)[0]));
A->allocateHostData(arrayDim);
B->setCLContext(oclContext);
B->setCLQueue(&(oclQueues->at(oclDevice)[0]));
B->allocateHostData(arrayDim);
try {
A->setDeviceWriteOnly();
A->allocateDeviceData();
B->setDeviceWriteOnly();
B->allocateDeviceData();
} catch ( OpenCLError err ) {
cerr << err.what() << endl;
return 1;
}
cout << fixed << setprecision(3) << endl;
for (unsigned int threads0 = 2; threads0 <= maxThreads; threads0 *= 2 ) {
for (unsigned int threads1 = 1; threads1 <= 32; threads1++ ) {
if ( (arrayDim % (threads0 * threads1) != 0) || ((threads0 * threads1) > maxThreads) ) {
continue;
}
Copy< float > copy = Copy< float >("float");
try {
copy.bindOpenCL(oclContext, &(oclDevices->at(oclDevice)), &(oclQueues->at(oclDevice)[0]));
copy.setNrThreads(arrayDim);
copy.setNrThreadsPerBlock(threads0);
copy.setNrRows(threads1);
copy.generateCode();
B->copyHostToDevice(true);
copy(A,B);
(copy.getTimer()).reset();
for ( unsigned int iter = 0; iter < nrIterations; iter++ ) {
copy(A, B);
}
} catch ( OpenCLError err ) {
cerr << err.what() << endl;
return 1;
}
cout << threads0 << " " << threads1 << " " << copy.getGB() / (copy.getTimer()).getAverageTime() << endl;
}
}
cout << endl;
return 0;
}
<commit_msg>Fixing a mistake in allocating memory.<commit_after>/*
* Copyright (C) 2013
* Alessio Sclocco <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cmath>
#include <cstring>
using std::cout;
using std::cerr;
using std::endl;
using std::fixed;
using std::setprecision;
using std::ofstream;
using std::ceil;
using std::pow;
#include <ArgumentList.hpp>
#include <InitializeOpenCL.hpp>
#include <CLData.hpp>
#include <Exceptions.hpp>
#include <Copy.hpp>
#include <utils.hpp>
using isa::utils::ArgumentList;
using isa::OpenCL::initializeOpenCL;
using isa::OpenCL::CLData;
using isa::Exceptions::OpenCLError;
using isa::Benchmarks::Copy;
using isa::utils::same;
const unsigned int nrIterations = 10;
int main(int argc, char * argv[]) {
unsigned int oclPlatform = 0;
unsigned int oclDevice = 0;
unsigned int arrayDim = 0;
unsigned int maxThreads = 0;
// Parse command line
if ( argc != 7 ) {
cerr << "Usage: " << argv[0] << " -opencl_platform <opencl_platform> -opencl_device <opencl_device> -m <max_threads>" << endl;
return 1;
}
ArgumentList commandLine(argc, argv);
try {
oclPlatform = commandLine.getSwitchArgument< unsigned int >("-opencl_platform");
oclDevice = commandLine.getSwitchArgument< unsigned int >("-opencl_device");
maxThreads = commandLine.getSwitchArgument< unsigned int >("-max_threads");
} catch ( exception & err ) {
cerr << err.what() << endl;
return 1;
}
// Initialize OpenCL
vector< cl::Platform > * oclPlatforms = new vector< cl::Platform >();
cl::Context * oclContext = new cl::Context();
vector< cl::Device > * oclDevices = new vector< cl::Device >();
vector< vector< cl::CommandQueue > > * oclQueues = new vector< vector< cl::CommandQueue > >();
try {
initializeOpenCL(oclPlatform, 1, oclPlatforms, oclContext, oclDevices, oclQueues);
} catch ( OpenCLError err ) {
cerr << err.what() << endl;
return 1;
}
arrayDim = (oclDevices->at(oclDevice)).getInfo< CL_DEVICE_MAX_MEM_ALLOC_SIZE >();
arrayDim /= sizeof(float);
CLData< float > * A = new CLData< float >("A", true);
CLData< float > * B = new CLData< float >("B", true);
A->setCLContext(oclContext);
A->setCLQueue(&(oclQueues->at(oclDevice)[0]));
A->allocateHostData(arrayDim);
B->setCLContext(oclContext);
B->setCLQueue(&(oclQueues->at(oclDevice)[0]));
B->allocateHostData(arrayDim);
try {
A->setDeviceWriteOnly();
A->allocateDeviceData();
B->setDeviceReadOnly();
B->allocateDeviceData();
} catch ( OpenCLError err ) {
cerr << err.what() << endl;
return 1;
}
cout << fixed << setprecision(3) << endl;
for (unsigned int threads0 = 2; threads0 <= maxThreads; threads0 *= 2 ) {
for (unsigned int threads1 = 1; threads1 <= 32; threads1++ ) {
if ( (arrayDim % (threads0 * threads1) != 0) || ((threads0 * threads1) > maxThreads) ) {
continue;
}
Copy< float > copy = Copy< float >("float");
try {
copy.bindOpenCL(oclContext, &(oclDevices->at(oclDevice)), &(oclQueues->at(oclDevice)[0]));
copy.setNrThreads(arrayDim);
copy.setNrThreadsPerBlock(threads0);
copy.setNrRows(threads1);
copy.generateCode();
B->copyHostToDevice(true);
copy(A,B);
(copy.getTimer()).reset();
for ( unsigned int iter = 0; iter < nrIterations; iter++ ) {
copy(A, B);
}
} catch ( OpenCLError err ) {
cerr << err.what() << endl;
return 1;
}
cout << threads0 << " " << threads1 << " " << copy.getGB() / (copy.getTimer()).getAverageTime() << endl;
}
}
cout << endl;
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) Oona Räisänen
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "src/input.h"
#include <cassert>
#include <iostream>
#include <string>
#include "src/groups.h"
#include "src/util.h"
namespace redsea {
/*
* An MPXReader deals with reading an FM multiplex signal from an audio file or
* raw PCM via stdin, separating it into channels and converting to chunks of
* floating-point samples.
*
*/
void MPXReader::init(const Options& options) {
num_channels_ = options.num_channels;
feed_thru_ = options.feed_thru;
filename_ = options.sndfilename;
if (options.input_type != InputType::MPX_stdin &&
options.input_type != InputType::MPX_sndfile)
return;
if (options.input_type == InputType::MPX_stdin) {
sfinfo_.channels = 1;
sfinfo_.format = SF_FORMAT_RAW | SF_FORMAT_PCM_16;
sfinfo_.samplerate = int(options.samplerate);
sfinfo_.frames = 0;
file_ = sf_open_fd(fileno(stdin), SFM_READ, &sfinfo_, SF_TRUE);
if (feed_thru_)
outfile_ = sf_open_fd(fileno(stdout), SFM_WRITE, &sfinfo_, SF_TRUE);
} else if (options.input_type == InputType::MPX_sndfile) {
file_ = sf_open(options.sndfilename.c_str(), SFM_READ, &sfinfo_);
num_channels_ = sfinfo_.channels;
}
if (!file_) {
if (sf_error(file_) == 26)
throw (BeyondEofError());
std::cerr << "error: failed to open file: " <<
sf_error_number(sf_error(file_)) << '\n';
is_error_ = true;
} else if (sfinfo_.samplerate < kMinimumSampleRate_Hz) {
std::cerr << "error: sample rate must be " << kMinimumSampleRate_Hz
<< " Hz or higher\n";
is_error_ = true;
} else {
assert(num_channels_ < int(buffer_.data.size()));
chunk_size_ = (kInputChunkSize / num_channels_) * num_channels_;
is_eof_ = false;
}
}
MPXReader::~MPXReader() {
sf_close(file_);
if (feed_thru_)
sf_close(outfile_);
}
bool MPXReader::eof() const {
return is_eof_;
}
/*
* Fill the internal buffer with fresh samples. This should be called before
* the first channel is processed via ReadChunk().
*
*/
void MPXReader::FillBuffer() {
num_read_ = sf_read_float(file_, buffer_.data.data(), chunk_size_);
if (num_read_ < chunk_size_)
is_eof_ = true;
buffer_.used_size = size_t(num_read_);
if (feed_thru_)
sf_write_float(outfile_, buffer_.data.data(), num_read_);
}
MPXBuffer<>& MPXReader::ReadChunk(int channel) {
assert(channel >= 0 && channel < num_channels_);
if (is_eof_)
return buffer_;
if (num_channels_ == 1) {
return buffer_;
} else {
buffer_singlechan_.used_size = buffer_.used_size / num_channels_;
for (size_t i = 0; i < buffer_singlechan_.used_size; i++)
buffer_singlechan_.data[i] = buffer_.data[i * num_channels_ + channel];
return buffer_singlechan_;
}
}
float MPXReader::samplerate() const {
return sfinfo_.samplerate;
}
int MPXReader::num_channels() const {
return num_channels_;
}
bool MPXReader::error() const {
return is_error_;
}
/*
* An AsciiBitReader reads an unsynchronized serial bitstream as '0' and '1'
* characters via stdin.
*
*/
AsciiBitReader::AsciiBitReader(const Options& options) :
feed_thru_(options.feed_thru) {
}
bool AsciiBitReader::ReadBit() {
int chr = 0;
while (chr != '0' && chr != '1' && chr != EOF) {
chr = getchar();
if (feed_thru_)
putchar(chr);
}
if (chr == EOF)
is_eof_ = true;
return (chr == '1');
}
bool AsciiBitReader::eof() const {
return is_eof_;
}
/*
* Read a single line containing an RDS group in the RDS Spy hex format.
*
*/
Group ReadHexGroup(const Options& options) {
Group group;
group.disable_offsets();
bool group_complete = false;
while (!(group_complete || std::cin.eof())) {
std::string line;
std::getline(std::cin, line);
if (options.feed_thru)
std::cout << line << '\n';
if (line.length() < 16)
continue;
for (eBlockNumber block_num : {BLOCK1, BLOCK2, BLOCK3, BLOCK4}) {
Block block;
bool block_still_valid = true;
int which_nibble = 0;
while (which_nibble < 4) {
if (line.length() < 1) {
group_complete = true;
break;
}
std::string single = line.substr(0, 1);
if (single != " ") {
try {
int nval = std::stoi(std::string(single), nullptr, 16);
block.data = uint16_t((block.data << 4) + nval);
} catch (std::exception) {
block_still_valid = false;
}
which_nibble++;
}
line = line.substr(1);
}
if (block_still_valid) {
block.is_received = true;
group.set_block(block_num, block);
}
if (block_num == BLOCK4)
group_complete = true;
}
}
if (options.timestamp)
group.set_time(std::chrono::system_clock::now());
return group;
}
} // namespace redsea
<commit_msg>linux: print usage when stdin empty<commit_after>/*
* Copyright (c) Oona Räisänen
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "src/input.h"
#include <cassert>
#include <iostream>
#include <string>
#include "src/groups.h"
#include "src/util.h"
namespace redsea {
/*
* An MPXReader deals with reading an FM multiplex signal from an audio file or
* raw PCM via stdin, separating it into channels and converting to chunks of
* floating-point samples.
*
*/
void MPXReader::init(const Options& options) {
num_channels_ = options.num_channels;
feed_thru_ = options.feed_thru;
filename_ = options.sndfilename;
if (options.input_type != InputType::MPX_stdin &&
options.input_type != InputType::MPX_sndfile)
return;
if (options.input_type == InputType::MPX_stdin) {
sfinfo_.channels = 1;
sfinfo_.format = SF_FORMAT_RAW | SF_FORMAT_PCM_16;
sfinfo_.samplerate = int(options.samplerate);
sfinfo_.frames = 0;
file_ = sf_open_fd(fileno(stdin), SFM_READ, &sfinfo_, SF_TRUE);
if (feed_thru_)
outfile_ = sf_open_fd(fileno(stdout), SFM_WRITE, &sfinfo_, SF_TRUE);
} else if (options.input_type == InputType::MPX_sndfile) {
file_ = sf_open(options.sndfilename.c_str(), SFM_READ, &sfinfo_);
num_channels_ = sfinfo_.channels;
}
if (!file_) {
if (sf_error(file_) == 26 || options.input_type == InputType::MPX_stdin)
throw (BeyondEofError());
std::cerr << "error: failed to open file: " <<
sf_error_number(sf_error(file_)) << '\n';
is_error_ = true;
} else if (sfinfo_.samplerate < kMinimumSampleRate_Hz) {
std::cerr << "error: sample rate must be " << kMinimumSampleRate_Hz
<< " Hz or higher\n";
is_error_ = true;
} else {
assert(num_channels_ < int(buffer_.data.size()));
chunk_size_ = (kInputChunkSize / num_channels_) * num_channels_;
is_eof_ = false;
}
}
MPXReader::~MPXReader() {
sf_close(file_);
if (feed_thru_)
sf_close(outfile_);
}
bool MPXReader::eof() const {
return is_eof_;
}
/*
* Fill the internal buffer with fresh samples. This should be called before
* the first channel is processed via ReadChunk().
*
*/
void MPXReader::FillBuffer() {
num_read_ = sf_read_float(file_, buffer_.data.data(), chunk_size_);
if (num_read_ < chunk_size_)
is_eof_ = true;
buffer_.used_size = size_t(num_read_);
if (feed_thru_)
sf_write_float(outfile_, buffer_.data.data(), num_read_);
}
MPXBuffer<>& MPXReader::ReadChunk(int channel) {
assert(channel >= 0 && channel < num_channels_);
if (is_eof_)
return buffer_;
if (num_channels_ == 1) {
return buffer_;
} else {
buffer_singlechan_.used_size = buffer_.used_size / num_channels_;
for (size_t i = 0; i < buffer_singlechan_.used_size; i++)
buffer_singlechan_.data[i] = buffer_.data[i * num_channels_ + channel];
return buffer_singlechan_;
}
}
float MPXReader::samplerate() const {
return sfinfo_.samplerate;
}
int MPXReader::num_channels() const {
return num_channels_;
}
bool MPXReader::error() const {
return is_error_;
}
/*
* An AsciiBitReader reads an unsynchronized serial bitstream as '0' and '1'
* characters via stdin.
*
*/
AsciiBitReader::AsciiBitReader(const Options& options) :
feed_thru_(options.feed_thru) {
}
bool AsciiBitReader::ReadBit() {
int chr = 0;
while (chr != '0' && chr != '1' && chr != EOF) {
chr = getchar();
if (feed_thru_)
putchar(chr);
}
if (chr == EOF)
is_eof_ = true;
return (chr == '1');
}
bool AsciiBitReader::eof() const {
return is_eof_;
}
/*
* Read a single line containing an RDS group in the RDS Spy hex format.
*
*/
Group ReadHexGroup(const Options& options) {
Group group;
group.disable_offsets();
bool group_complete = false;
while (!(group_complete || std::cin.eof())) {
std::string line;
std::getline(std::cin, line);
if (options.feed_thru)
std::cout << line << '\n';
if (line.length() < 16)
continue;
for (eBlockNumber block_num : {BLOCK1, BLOCK2, BLOCK3, BLOCK4}) {
Block block;
bool block_still_valid = true;
int which_nibble = 0;
while (which_nibble < 4) {
if (line.length() < 1) {
group_complete = true;
break;
}
std::string single = line.substr(0, 1);
if (single != " ") {
try {
int nval = std::stoi(std::string(single), nullptr, 16);
block.data = uint16_t((block.data << 4) + nval);
} catch (std::exception) {
block_still_valid = false;
}
which_nibble++;
}
line = line.substr(1);
}
if (block_still_valid) {
block.is_received = true;
group.set_block(block_num, block);
}
if (block_num == BLOCK4)
group_complete = true;
}
}
if (options.timestamp)
group.set_time(std::chrono::system_clock::now());
return group;
}
} // namespace redsea
<|endoftext|> |
<commit_before>#include "json.h"
#include <jansson.h>
using JWTXX::JWT;
using JWTXX::Pairs;
namespace
{
struct JSONDeleter
{
void operator()(json_t* obj) const noexcept { json_decref(obj); }
};
typedef std::unique_ptr<json_t, JSONDeleter> JSON;
std::string toString(const json_t* node) noexcept
{
switch (json_typeof(node))
{
case JSON_NULL: return "NULL";
case JSON_TRUE: return "true";
case JSON_FALSE: return "false";
case JSON_STRING: return json_string_value(node);
case JSON_INTEGER: return std::to_string(json_integer_value(node));
case JSON_REAL: return std::to_string(json_real_value(node));
default: return json_dumps(node, JSON_COMPACT);
}
return {}; // Just in case.
}
}
std::string JWTXX::toJSON(const Pairs& data) noexcept
{
JSON root(json_object());
for (const auto& item : data)
json_object_set_new(root.get(), item.first.c_str(), json_string(item.second.c_str()));
char* dump = json_dumps(root.get(), JSON_COMPACT);
std::string res(dump);
free(dump);
return res;
}
Pairs JWTXX::fromJSON(const std::string& data)
{
json_error_t error;
JSON root(json_loads(data.c_str(), 0, &error));
if (!root)
throw JWT::ParseError("Error parsing json at position " + std::to_string(error.position) + " in '" + data + "', reason: " + error.text);
if (!json_is_object(root.get()))
throw JWT::ParseError("Not a JSON object.");
const char* key = nullptr;
json_t* value = nullptr;
Pairs res;
json_object_foreach(root.get(), key, value)
{
res[key] = toString(value);
}
return res;
}
<commit_msg>Proper work with json_dumps.<commit_after>#include "json.h"
#include <jansson.h>
using JWTXX::JWT;
using JWTXX::Pairs;
namespace
{
struct JSONDeleter
{
void operator()(json_t* obj) const noexcept { json_decref(obj); }
};
typedef std::unique_ptr<json_t, JSONDeleter> JSON;
std::string dumpNode(const json_t* node) noexcept
{
char* dump = json_dumps(node, JSON_COMPACT);
std::string res(dump != nullptr ? dump : "");
free(dump);
return res;
}
std::string toString(const json_t* node) noexcept
{
switch (json_typeof(node))
{
case JSON_NULL: return "NULL";
case JSON_TRUE: return "true";
case JSON_FALSE: return "false";
case JSON_STRING: return json_string_value(node);
case JSON_INTEGER: return std::to_string(json_integer_value(node));
case JSON_REAL: return std::to_string(json_real_value(node));
default: return dumpNode(node);
}
return {}; // Just in case.
}
}
std::string JWTXX::toJSON(const Pairs& data) noexcept
{
JSON root(json_object());
for (const auto& item : data)
json_object_set_new(root.get(), item.first.c_str(), json_string(item.second.c_str()));
return dumpNode(root.get());
}
Pairs JWTXX::fromJSON(const std::string& data)
{
json_error_t error;
JSON root(json_loads(data.c_str(), 0, &error));
if (!root)
throw JWT::ParseError("Error parsing json at position " + std::to_string(error.position) + " in '" + data + "', reason: " + error.text);
if (!json_is_object(root.get()))
throw JWT::ParseError("Not a JSON object.");
const char* key = nullptr;
json_t* value = nullptr;
Pairs res;
json_object_foreach(root.get(), key, value)
{
res[key] = toString(value);
}
return res;
}
<|endoftext|> |
<commit_before>#include <ncurses.h>
#include <time.h>
#include <stdio.h>
#include <string>
#include "game.h"
#include "menu.h"
#include "classes/Player.h"
#include "classes/Enemy.h"
#include "classes/Coin.h"
#include "classes/InfoPanel.h"
using namespace std;
InfoPanel *infoPanel_game = new InfoPanel();
Player player;
Enemy enemy;
Coin coins[10];
void startGame() {
WINDOW *wgame = newwin(40, 80, 1, 1);
box(wgame, 0, 0);
keypad(wgame, true);
/*
* Randomly place player anywhere in game area
*/
int_fast8_t randx = rand() % game_area.right() + game_area.left();
int_fast8_t randy = rand() % game_area.bot() + game_area.top();
vec2i initPos = {
randx, randy
};
player.setPos(initPos);
wmove(wgame, player.getPos().y, player.getPos().x);
waddch(wgame, player.getDispChar());
wmove(wgame, enemy.getPos().y, enemy.getPos().x);
waddch(wgame, enemy.getDispChar());
int ch;
string infoKey, infoMsg;
while (( ch = wgetch(wgame)) != 'q') {
infoMsg = "";
infoKey = to_string(ch);
werase(wgame);
box(wgame, 0, 0);
// Place Coins
for (auto &coin : coins) {
wmove(wgame, coin.getPos().x, coin.getPos().y);
waddch(wgame, coin.getDispChar());
}
int x = player.getPos().x;
int y = player.getPos().y;
// Enemy only reacts to previous move
vec2i enemyPos = enemy.seek(player);
switch (ch) {
case KEY_UP:
case 'k':
if (y > (int) game_area.top() + 1) player.setPosY(y - 1);
break;
case KEY_DOWN:
case 'j':
if (y < (int) game_area.bot() - 2) player.setPosY(y + 1);
break;
case KEY_LEFT:
case 'h':
if (x > (int) game_area.left() + 1) player.setPosX(x - 1);
break;
case KEY_RIGHT:
case 'l':
if (x < (int) game_area.right() - 2) player.setPosX(x + 1);
break;
case KEY_ENTER: /* numpad enter */
case '\n': /* keyboard return */
break;
}
// Move to updated position
wmove(wgame, player.getPos().y, player.getPos().x);
waddch(wgame, player.getDispChar());
// Enemy, seek out player
wmove(wgame, enemyPos.y, enemyPos.x);
waddch(wgame, enemy.getDispChar());
infoPanel_game->push('{'
+ std::to_string(x) + ','
+ std::to_string(y) + '}'
+ '{'
+ std::to_string(enemyPos.x) + ','
+ std::to_string(enemyPos.y) + '}'
);
wrefresh(wgame);
}
delwin(wgame);
}
<commit_msg>Draw Coins when first entering game<commit_after>#include <ncurses.h>
#include <time.h>
#include <stdio.h>
#include <string>
#include "game.h"
#include "menu.h"
#include "classes/Player.h"
#include "classes/Enemy.h"
#include "classes/Coin.h"
#include "classes/InfoPanel.h"
using namespace std;
InfoPanel *infoPanel_game = new InfoPanel();
Player player;
Enemy enemy;
Coin coins[10];
void startGame() {
WINDOW *wgame = newwin(40, 80, 1, 1);
box(wgame, 0, 0);
keypad(wgame, true);
/*
* Randomly place player anywhere in game area
*/
int_fast8_t randx = rand() % game_area.right() + game_area.left();
int_fast8_t randy = rand() % game_area.bot() + game_area.top();
vec2i initPos = {
randx, randy
};
player.setPos(initPos);
// Init placement of Player, Enemy, and Coins
wmove(wgame, player.getPos().y, player.getPos().x);
waddch(wgame, player.getDispChar());
wmove(wgame, enemy.getPos().y, enemy.getPos().x);
waddch(wgame, enemy.getDispChar());
for (auto &coin : coins) {
wmove(wgame, coin.getPos().x, coin.getPos().y);
waddch(wgame, coin.getDispChar());
}
int ch;
string infoKey, infoMsg;
while (( ch = wgetch(wgame)) != 'q') {
infoMsg = "";
infoKey = to_string(ch);
werase(wgame);
box(wgame, 0, 0);
int x = player.getPos().x;
int y = player.getPos().y;
// Enemy only reacts to previous move
vec2i enemyPos = enemy.seek(player);
switch (ch) {
case KEY_UP:
case 'k':
if (y > (int) game_area.top() + 1) player.setPosY(y - 1);
break;
case KEY_DOWN:
case 'j':
if (y < (int) game_area.bot() - 2) player.setPosY(y + 1);
break;
case KEY_LEFT:
case 'h':
if (x > (int) game_area.left() + 1) player.setPosX(x - 1);
break;
case KEY_RIGHT:
case 'l':
if (x < (int) game_area.right() - 2) player.setPosX(x + 1);
break;
case KEY_ENTER: /* numpad enter */
case '\n': /* keyboard return */
break;
}
// Move Player to indicated position
wmove(wgame, player.getPos().y, player.getPos().x);
waddch(wgame, player.getDispChar());
// Enemy, seek out player
wmove(wgame, enemyPos.y, enemyPos.x);
waddch(wgame, enemy.getDispChar());
// Draw Coins again (no changes)
for (auto &coin : coins) {
wmove(wgame, coin.getPos().x, coin.getPos().y);
waddch(wgame, coin.getDispChar());
}
infoPanel_game->push('{'
+ std::to_string(x) + ','
+ std::to_string(y) + '}'
+ '{'
+ std::to_string(enemyPos.x) + ','
+ std::to_string(enemyPos.y) + '}'
);
wrefresh(wgame);
}
delwin(wgame);
}
<|endoftext|> |
<commit_before>#include "../include/obj.hpp"
game::~game() {
delete [] players;
delete [] eminems;
}
void game::gameStart() {
players = new player[MAX_PLAYERS]; // Создание игроков
eminems = new AIplayer[MAX_EMINEMS]; // Создание врагов
RenderWindow window(VideoMode(512, 480), "Bottle city"); // Создание окна
texture.loadFromFile("media/textures.png"); // Загрузка всех текстур
game_map main_map(texture); // Загрузка текстур в карту
main_map.loadMap("media/maps/level1.map"); // Загрузка карты из файла
right_bar r_b(texture, main_map.getMaxX(), MAX_EMINEMS, 1, 3, 3);
g_pause game_pause(texture, &main_map);
players[0].init(texture, players, MAX_PLAYERS, eminems, MAX_EMINEMS, &main_map, 3, 1, 20, 1); // Задача стандартных параметров для игроков
players[1].init(texture, players, MAX_PLAYERS, eminems, MAX_EMINEMS, &main_map, 3, 1, 20, 2);
for (int i = 0; i < MAX_EMINEMS; ++i) { // Задача стандартных параметров для врага
eminems[i].init(texture, players, MAX_PLAYERS, &main_map, false, 1, 1);
}
eminems[0].activation(0, 0); /// TEST
eminems[1].activation(6, 0);
eminems[2].activation(12, 0);
while (window.isOpen()) {
time = clock.getElapsedTime().asMicroseconds(); // Получение времени
clock.restart(); // Сброс часиков
time = time / GAME_SPEED; // Установка скорости игры
if (time > 20)
time = 20;
while (window.pollEvent(event)) { // Отслеживание события закрытия окна
if (event.type == Event::Closed) {
window.close();
}
}
if (Keyboard::isKeyPressed(Keyboard::P)) {
game_pause.paused(window);
usleep(100000);
}
if (!game_pause.status()) {
for (int i = 0; i < MAX_PLAYERS; ++i) // Обновление игроков
players[i].update(time);
for (int i = 0; i < MAX_EMINEMS; ++i) // Обновление врагов
eminems[i].update(time);
/*Отрисовка объектов Начало*/
main_map.draw(window); // Отрисовка карты
for (int i = 0; i < MAX_PLAYERS; ++i) // Отрисовка игроков
players[i].draw(window);
for (int i = 0; i < MAX_EMINEMS; ++i) // Отрисовка врагов
eminems[i].draw(window);
main_map.drawGrass(window); // Отрисовка травы
r_b.draw(window);
window.display();
/*Отрисовка объектов Конец*/
}
}
}<commit_msg>Optimizing<commit_after>#include "../include/obj.hpp"
game::~game() {
delete [] players;
delete [] eminems;
}
void game::gameStart() {
players = new player[MAX_PLAYERS]; // Создание игроков
eminems = new AIplayer[MAX_EMINEMS]; // Создание врагов
RenderWindow window(VideoMode(512, 480), "Bottle city"); // Создание окна
texture.loadFromFile("media/textures.png"); // Загрузка всех текстур
game_map main_map(texture); // Загрузка текстур в карту
main_map.loadMap("media/maps/level1.map"); // Загрузка карты из файла
right_bar r_b(texture, main_map.getMaxX(), MAX_EMINEMS, 1, 3, 3);
g_pause game_pause(texture, &main_map);
players[0].init(texture, players, MAX_PLAYERS, eminems, MAX_EMINEMS, &main_map, 3, 1, 20, 1); // Задача стандартных параметров для игроков
players[1].init(texture, players, MAX_PLAYERS, eminems, MAX_EMINEMS, &main_map, 3, 1, 20, 2);
for (int i = 0; i < MAX_EMINEMS; ++i) { // Задача стандартных параметров для врага
eminems[i].init(texture, players, MAX_PLAYERS, &main_map, false, 1, 1);
}
eminems[0].activation(0, 0); /// TEST
eminems[1].activation(6, 0);
eminems[2].activation(12, 0);
while (window.isOpen()) {
time = clock.getElapsedTime().asMicroseconds(); // Получение времени
clock.restart(); // Сброс часиков
time = time / GAME_SPEED; // Установка скорости игры
if (time > 20)
time = 20;
while (window.pollEvent(event)) { // Отслеживание события закрытия окна
if (event.type == Event::Closed) {
window.close();
}
}
if (Keyboard::isKeyPressed(Keyboard::P)) {
game_pause.paused(window);
usleep(100000);
}
if (!game_pause.status()) {
for (int i = 0; i < MAX_PLAYERS; ++i) // Обновление игроков
players[i].update(time);
for (int i = 0; i < MAX_EMINEMS; ++i) // Обновление врагов
eminems[i].update(time);
/*Отрисовка объектов Начало*/
main_map.draw(window); // Отрисовка карты
for (int i = 0; i < MAX_PLAYERS; ++i) // Отрисовка игроков
players[i].draw(window);
for (int i = 0; i < MAX_EMINEMS; ++i) // Отрисовка врагов
eminems[i].draw(window);
main_map.drawGrass(window); // Отрисовка травы
r_b.draw(window);
window.display();
/*Отрисовка объектов Конец*/
}
usleep(10000); // Оптимизация
}
}<|endoftext|> |
<commit_before>//
// utils.cpp
// Xapiand
//
// Created by Germán M. Bravo on 2/24/15.
// Copyright (c) 2015 Germán M. Bravo. All rights reserved.
//
#include <stdio.h>
#include "pthread.h"
#include "utils.h"
bool qmtx_inited = false;
pthread_mutex_t qmtx;
std::string repr_string(const std::string &string)
{
const char *p = string.c_str();
const char *p_end = p + string.size();
std::string ret;
char buff[4];
ret += "'";
while (p != p_end) {
char c = *p++;
if (c == 10) {
ret += "\\n";
} else if (c == 13) {
ret += "\\n";
} else if (c >= ' ' && c <= '~') {
sprintf(buff, "%c", c);
ret += buff;
} else {
sprintf(buff, "\\x%02x", c & 0xff);
ret += buff;
}
}
ret += "'";
return ret;
}
void log(void *obj, const char *format, ...)
{
if (!qmtx_inited) {
pthread_mutex_init(&qmtx, 0);
qmtx_inited = true;
}
pthread_mutex_lock(&qmtx);
FILE * file = stderr;
fprintf(file, "tid(0x%lx): 0x%lx - ", (unsigned long)pthread_self(), (unsigned long)obj);
va_list argptr;
va_start(argptr, format);
vfprintf(file, format, argptr);
va_end(argptr);
pthread_mutex_unlock(&qmtx);
}
<commit_msg>Fixed repr (added \t, \' and \")<commit_after>//
// utils.cpp
// Xapiand
//
// Created by Germán M. Bravo on 2/24/15.
// Copyright (c) 2015 Germán M. Bravo. All rights reserved.
//
#include <stdio.h>
#include "pthread.h"
#include "utils.h"
bool qmtx_inited = false;
pthread_mutex_t qmtx;
std::string repr_string(const std::string &string)
{
const char *p = string.c_str();
const char *p_end = p + string.size();
std::string ret;
char buff[4];
ret += "\"";
while (p != p_end) {
char c = *p++;
if (c == 9) {
ret += "\\t";
} else if (c == 10) {
ret += "\\n";
} else if (c == 13) {
ret += "\\r";
} else if (c == '"') {
ret += "\\\"";
} else if (c == '\'') {
ret += "\\\'";
} else if (c >= ' ' && c <= '~') {
sprintf(buff, "%c", c);
ret += buff;
} else {
sprintf(buff, "\\x%02x", c & 0xff);
ret += buff;
}
}
ret += "\"";
return ret;
}
void log(void *obj, const char *format, ...)
{
if (!qmtx_inited) {
pthread_mutex_init(&qmtx, 0);
qmtx_inited = true;
}
pthread_mutex_lock(&qmtx);
FILE * file = stderr;
fprintf(file, "tid(0x%lx): 0x%lx - ", (unsigned long)pthread_self(), (unsigned long)obj);
va_list argptr;
va_start(argptr, format);
vfprintf(file, format, argptr);
va_end(argptr);
pthread_mutex_unlock(&qmtx);
}
<|endoftext|> |
<commit_before>#ifdef __EMSCRIPTEN__
#include <emscripten.h>
#endif
#include "entityx/entityx.h"
#include <glm/vec2.hpp>
#include <SDL2/SDL.h>
#include <iostream>
#include <random>
#include <functional>
std::default_random_engine random_engine;
std::uniform_int_distribution<int> distribution{0, 255};
auto rand_color = std::bind(distribution, random_engine);
SDL_Window *win;
SDL_Renderer *ren;
entityx::EntityX ex;
entityx::Entity entity = ex.entities.create();
void mainloop() {
SDL_SetRenderDrawColor(ren, rand_color(), rand_color(), rand_color(), 255);
SDL_RenderClear(ren);
SDL_RenderPresent(ren);
SDL_Delay(1000);
}
int main()
{
if (SDL_Init(SDL_INIT_VIDEO) != 0){
std::cout << "SDL_Init Error: " << SDL_GetError() << std::endl;
return 1;
}
win = SDL_CreateWindow("Hello World!", 100, 100, 640, 480, SDL_WINDOW_SHOWN);
if (win == nullptr){
std::cout << "SDL_CreateWindow Error: " << SDL_GetError() << std::endl;
SDL_Quit();
return 1;
}
ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
if (ren == nullptr){
SDL_DestroyWindow(win);
std::cout << "SDL_CreateRenderer Error: " << SDL_GetError() << std::endl;
SDL_Quit();
return 1;
}
#ifdef __EMSCRIPTEN__
emscripten_set_main_loop(mainloop, 0, true);
#else
auto lol = 5;
while (lol > 0) {
mainloop();
--lol;
}
#endif
SDL_DestroyRenderer(ren);
SDL_DestroyWindow(win);
SDL_Quit();
return 0;
}
<commit_msg>tested entity.assign[...4]<commit_after>#ifdef __EMSCRIPTEN__
#include <emscripten.h>
#endif
#include "entityx/entityx.h"
#include "component_interactable.hpp"
#include "component_position.hpp"
#include <glm/vec2.hpp>
#include <SDL2/SDL.h>
#include <iostream>
#include <random>
#include <functional>
std::default_random_engine random_engine;
std::uniform_int_distribution<int> distribution{0, 255};
auto rand_color = std::bind(distribution, random_engine);
SDL_Window *win;
SDL_Renderer *ren;
entityx::EntityX ex;
entityx::Entity entity = ex.entities.create();
void mainloop() {
SDL_SetRenderDrawColor(ren, rand_color(), rand_color(), rand_color(), 255);
SDL_RenderClear(ren);
SDL_RenderPresent(ren);
SDL_Delay(1000);
}
int main()
{
if (SDL_Init(SDL_INIT_VIDEO) != 0){
std::cout << "SDL_Init Error: " << SDL_GetError() << std::endl;
return 1;
}
win = SDL_CreateWindow("Hello World!", 100, 100, 640, 480, SDL_WINDOW_SHOWN);
if (win == nullptr){
std::cout << "SDL_CreateWindow Error: " << SDL_GetError() << std::endl;
SDL_Quit();
return 1;
}
ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
if (ren == nullptr){
SDL_DestroyWindow(win);
std::cout << "SDL_CreateRenderer Error: " << SDL_GetError() << std::endl;
SDL_Quit();
return 1;
}
entity.assign<Interactable>();
entity.assign<Position>();
#ifdef __EMSCRIPTEN__
emscripten_set_main_loop(mainloop, 0, true);
#else
auto lol = 5;
while (lol > 0) {
mainloop();
--lol;
}
#endif
SDL_DestroyRenderer(ren);
SDL_DestroyWindow(win);
SDL_Quit();
return 0;
}
<|endoftext|> |
<commit_before>/*
qgvdial is a cross platform Google Voice Dialer
Copyright (C) 2010 Yuvraaj Kelkar
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Contact: [email protected]
*/
#include "MainApp.h"
#include "MainWindow.h"
#include "Singletons.h"
#include <iostream>
using namespace std;
QtMsgHandler pOldHandler = NULL;
MainWindow *pw = NULL;
QFile fLogfile; //! Logfile
int logLevel = 5; //! Log level
void
myMessageOutput(QtMsgType type, const char *msg)
{
int level = -1;
switch (type) {
case QtDebugMsg:
level = 3;
break;
case QtWarningMsg:
level = 2;
break;
case QtCriticalMsg:
level = 1;
break;
case QtFatalMsg:
level = 0;
}
QDateTime dt = QDateTime::currentDateTime ();
QString strLog = QString("%1 : %2 : %3")
.arg(dt.toString ("yyyy-MM-dd hh:mm:ss.zzz"))
.arg(level)
.arg(msg);
// Send to standard output
cout << strLog.toStdString () << endl;
QRegExp regex("^\"(.*)\"\\s*");
if (strLog.indexOf (regex) != -1) {
strLog = regex.cap (1);
}
if (strLog.contains ("password", Qt::CaseInsensitive)) {
strLog = QString("%1 : %2 : %3")
.arg(dt.toString ("yyyy-MM-dd hh:mm:ss.zzz"))
.arg(level)
.arg("Log message with password blocked");
}
if ((level <= logLevel) && (NULL != pw)) {
pw->log (strLog);
}
strLog += '\n';
if (level <= logLevel) {
// Append it to the file
fLogfile.write(strLog.toLatin1 ());
}
if (NULL == pOldHandler) {
if (NULL == pw) {
fwrite (strLog.toLatin1 (), strLog.size (), 1, stderr);
}
if (QtFatalMsg == type) {
abort();
}
} else {
pOldHandler (type, strLog.toLatin1 ());
}
}//myMessageOutput
static void
initLogging ()
{
OsDependent &osd = Singletons::getRef().getOSD ();
QString strLogfile = osd.getAppDirectory ();
strLogfile += QDir::separator ();
strLogfile += "qgvdial.log";
fLogfile.setFileName (strLogfile);
fLogfile.open (QIODevice::WriteOnly | QIODevice::Append);
fLogfile.seek (fLogfile.size ());
pOldHandler = qInstallMsgHandler(myMessageOutput);
}//initLogging
static void
deinitLogging ()
{
pw = NULL;
}//deinitLogging
int
main (int argc, char *argv[])
{
#if defined(Q_WS_S60)
MainApp::setAttribute (Qt::AA_S60DontConstructApplicationPanes);
#endif
initLogging ();
MainApp app(argc, argv);
bool bQuit = false;
if ((app.argc() >= 2) && (0 == strcmp(app.argv()[1],"quit"))) {
bQuit = true;
}
if (app.isRunning ()) {
if (bQuit) {
app.sendMessage ("quit");
} else {
app.sendMessage ("show");
bQuit = true;
}
}
if (bQuit == true) {
return (0);
}
OsDependent &osd = Singletons::getRef().getOSD ();
osd.init ();
MainWindow w;
pw = &w;
app.setActivationWindow (&w);
#if defined(Q_OS_SYMBIAN)
app.setQuitOnLastWindowClosed (true);
#else
app.setQuitOnLastWindowClosed (false);
#endif
#if MOBILE_OS
w.showFullScreen ();
#else
w.show();
#endif
int rv = app.exec();
deinitLogging ();
return (rv);
}//main
<commit_msg>flush logs periodically<commit_after>/*
qgvdial is a cross platform Google Voice Dialer
Copyright (C) 2010 Yuvraaj Kelkar
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Contact: [email protected]
*/
#include "MainApp.h"
#include "MainWindow.h"
#include "Singletons.h"
#include <iostream>
using namespace std;
QtMsgHandler pOldHandler = NULL;
MainWindow *pw = NULL;
QFile fLogfile; //! Logfile
int logLevel = 5; //! Log level
int logCounter = 0; //! Number of log entries since the last log flush
void
myMessageOutput(QtMsgType type, const char *msg)
{
int level = -1;
switch (type) {
case QtDebugMsg:
level = 3;
break;
case QtWarningMsg:
level = 2;
break;
case QtCriticalMsg:
level = 1;
break;
case QtFatalMsg:
level = 0;
}
QDateTime dt = QDateTime::currentDateTime ();
QString strLog = QString("%1 : %2 : %3")
.arg(dt.toString ("yyyy-MM-dd hh:mm:ss.zzz"))
.arg(level)
.arg(msg);
// Send to standard output
cout << strLog.toStdString () << endl;
QRegExp regex("^\"(.*)\"\\s*");
if (strLog.indexOf (regex) != -1) {
strLog = regex.cap (1);
}
if (strLog.contains ("password", Qt::CaseInsensitive)) {
strLog = QString("%1 : %2 : %3")
.arg(dt.toString ("yyyy-MM-dd hh:mm:ss.zzz"))
.arg(level)
.arg("Log message with password blocked");
}
if ((level <= logLevel) && (NULL != pw)) {
pw->log (strLog);
}
strLog += '\n';
if (level <= logLevel) {
if (fLogfile.isOpen ()) {
// Append it to the file
fLogfile.write(strLog.toLatin1 ());
++logCounter;
if (logCounter > 100) {
logCounter = 0;
fLogfile.flush ();
}
}
}
if (NULL == pOldHandler) {
if (NULL == pw) {
fwrite (strLog.toLatin1 (), strLog.size (), 1, stderr);
}
if (QtFatalMsg == type) {
abort();
}
} else {
pOldHandler (type, strLog.toLatin1 ());
}
}//myMessageOutput
static void
initLogging ()
{
OsDependent &osd = Singletons::getRef().getOSD ();
QString strLogfile = osd.getAppDirectory ();
strLogfile += QDir::separator ();
strLogfile += "qgvdial.log";
fLogfile.setFileName (strLogfile);
fLogfile.open (QIODevice::WriteOnly | QIODevice::Append);
fLogfile.seek (fLogfile.size ());
pOldHandler = qInstallMsgHandler(myMessageOutput);
}//initLogging
static void
deinitLogging ()
{
pw = NULL;
fLogfile.close ();
}//deinitLogging
int
main (int argc, char *argv[])
{
#if defined(Q_WS_S60)
MainApp::setAttribute (Qt::AA_S60DontConstructApplicationPanes);
#endif
initLogging ();
MainApp app(argc, argv);
bool bQuit = false;
if ((app.argc() >= 2) && (0 == strcmp(app.argv()[1],"quit"))) {
bQuit = true;
}
if (app.isRunning ()) {
if (bQuit) {
app.sendMessage ("quit");
} else {
app.sendMessage ("show");
bQuit = true;
}
}
if (bQuit == true) {
return (0);
}
OsDependent &osd = Singletons::getRef().getOSD ();
osd.init ();
MainWindow w;
pw = &w;
app.setActivationWindow (&w);
#if defined(Q_OS_SYMBIAN)
app.setQuitOnLastWindowClosed (true);
#else
app.setQuitOnLastWindowClosed (false);
#endif
#if MOBILE_OS
w.showFullScreen ();
#else
w.show();
#endif
int rv = app.exec();
deinitLogging ();
return (rv);
}//main
<|endoftext|> |
<commit_before>#include <iostream>
#include <cstddef>
#include <time.h>
#include "StackAllocator.h"
/*
void test_primitives(Allocator &allocator){
std::cout << "\tTEST_PRIMITIVES_TYPES" << std::endl;
allocator.Allocate(sizeof(int), alignof(int)); // 4 -> 4
allocator.Allocate(sizeof(bool), alignof(bool)); // 1 -> 5
// 3 -> 8
allocator.Allocate(sizeof(int), alignof(int)); // 4 -> 12
// 4 -> 16
allocator.Allocate(sizeof(double), alignof(double)); // 8 -> 24
allocator.Allocate(sizeof(char), alignof(char)); // 1 -> 25
// 3 -> 28
allocator.Allocate(sizeof(int), alignof(int)); // 4 -> 32
allocator.Reset();
std::cout << std::endl;
}
void test_primitives_unaligned(Allocator &allocator){
std::cout << "\tTEST_PRIMITIVES_TYPES_UNALIGNED" << std::endl;
allocator.Allocate(sizeof(int)); // 4 -> 4
allocator.Allocate(sizeof(bool)); // 1 -> 5
// 0 -> 5
allocator.Allocate(sizeof(int)); // 4 -> 9
allocator.Allocate(sizeof(double)); // 8 -> 17
allocator.Allocate(sizeof(char)); // 1 -> 18
// 0 -> 18
allocator.Allocate(sizeof(int)); // 4 -> 22
allocator.Reset();
std::cout << std::endl;
}
void test_structs(Allocator &allocator){
std::cout << "\tTEST_CUSTOM_TYPES" << std::endl;
allocator.Allocate(sizeof(bar), alignof(bar)); // 16 -> 16
allocator.Allocate(sizeof(foo), alignof(foo)); // 16 -> 32
allocator.Allocate(sizeof(baz), alignof(baz)); // 4 -> 36
allocator.Allocate(sizeof(bool), alignof(bool)); // 1 -> 37
// 3 -> 40
allocator.Allocate(sizeof(foo3), alignof(foo3)); // 8 -> 48
allocator.Reset();
std::cout << std::endl;
}
void test_structs_unaligned(Allocator &allocator){
std::cout << "\tTEST_CUSTOM_TYPES_UNALIGNED" << std::endl;
allocator.Allocate(sizeof(bar), 0); // 16 -> 16
allocator.Allocate(sizeof(foo), 0); // 16 -> 32
allocator.Allocate(sizeof(baz), 0); // 4 -> 36
allocator.Allocate(sizeof(bool), 0); // 1 -> 37
// 0 -> 37
allocator.Allocate(sizeof(foo3), 0); // 8 -> 45
allocator.Reset();
std::cout << std::endl;
}
void test_linear_allocator(){
std::cout << "TEST_LINEAR_ALLOCATOR" << std::endl;
LinearAllocator linearAllocator(100);
test_primitives(linearAllocator);
test_structs(linearAllocator);
test_primitives_unaligned(linearAllocator);
test_structs_unaligned(linearAllocator);
}
void test_stack_allocator_primitives(StackAllocator &stackAllocator){
std::cout << "\tTEST_PRIMITIVES_TYPES" << std::endl;
stackAllocator.Allocate(sizeof(bool), alignof(bool)); // 1 -> 1
// 3 -> 4
stackAllocator.Allocate(sizeof(baz), alignof(baz)); // 4 -> 8
stackAllocator.Allocate(sizeof(int), alignof(int)); // 4 -> 12
std::cout << std::endl;
stackAllocator.Free(nullptr, sizeof(int)); // 4 -> 8
stackAllocator.Free(nullptr, sizeof(baz)); // 8 -> 4(3) -> 1
// 7 -> 8
stackAllocator.Allocate(sizeof(double), alignof(double)); // 8 -> 16
stackAllocator.Reset();
}
void test_stack_allocator(){
std::cout << "TEST_STACK_ALLOCATOR" << std::endl;
StackAllocator stackAllocator(100);
//test_primitives(stackAllocator);
//test_structs(stackAllocator);
//test_primitives_unaligned(stackAllocator);
//test_structs_unaligned(stackAllocator);
test_stack_allocator_primitives(stackAllocator);
}
*/
struct foo {
char *p; /* 8 bytes */
char c; /* 1 byte */
};
struct bar {
int a; // 4
bool b; // 1 -> 5
// 3 -> 8
int c; // 4 -> 12
bool d; // 1 -> 13
bool e; // 1 -> 14
// 2 -> 16
};
struct bar2 {
int a; // 4
int c; // 4 -> 8
bool b; // 1 -> 9
bool d;
bool e;
// 3 -> 12
};
struct foo3 {
int i; /* 4 byte */
char c; /* 1 bytes */
bool b; /* 1 bytes */
// 2 bytes
};
struct foo2 {
char c; /* 1 byte */
char *p; /* 8 bytes */
};
struct baz {
short s; /* 2 bytes */
char c; /* 1 byte */
};
void setTimer(timespec& timer){
clock_gettime(CLOCK_REALTIME, &timer);
}
timespec diff(timespec &start, timespec &end) {
timespec temp;
if ((end.tv_nsec-start.tv_nsec)<0) {
temp.tv_sec = end.tv_sec-start.tv_sec-1;
temp.tv_nsec = 1e9+end.tv_nsec-start.tv_nsec;
} else {
temp.tv_sec = end.tv_sec-start.tv_sec;
temp.tv_nsec = end.tv_nsec-start.tv_nsec;
}
return temp;
}
void print_benchmark_stats(const timespec& elapsed_time, const int& memory_used, const int&memory_wasted, const int max_operations){
double time_sec = (double) elapsed_time.tv_sec;
double time_nsec = (double) elapsed_time.tv_nsec;
double time_msec = (time_sec * 1000) + (time_nsec / 1000000);
std::cout << std::endl;
std::cout << "\tSTATS:" << std::endl;
std::cout << "\t\tOperations: \t" << max_operations << std::endl;
std::cout << "\t\tTime elapsed: \t" << time_msec << " ms" << std::endl;
std::cout << "\t\tOp per sec: \t" << (max_operations / 1e3) / time_msec << " mops/ms" << std::endl;
std::cout << "\t\tTimer per op: \t" << time_msec/(max_operations / 1e3) << " ms/mops" << std::endl;
//std::cout << "\t\tMemory used: \t" << memory_used << " bytes" << std::endl;
//std::cout << "\t\tMemory wasted: \t" << memory_wasted << " bytes\t" << ((float) memory_wasted / memory_used) * 100 << " %" << std::endl;
std::cout << std::endl;
}
void benchmark_stack_allocate(long MAX_OPERATIONS = 1e4){
timespec start, end;
std::cout << "BENCHMARK STACK A: START" << std::endl;
setTimer(start);
StackAllocator stackAllocator(1e10);
int operations = 0;
while(operations < MAX_OPERATIONS){
stackAllocator.Allocate(sizeof(int), alignof(int)); // 4 -> 4
stackAllocator.Allocate(sizeof(bool), alignof(bool)); // 1 -> 5
// 3 -> 8
stackAllocator.Allocate(sizeof(foo), alignof(foo)); // 16 -> 24
++operations;
}
setTimer(end);
const timespec elapsed_time = diff(start, end);
const std::size_t memory_used = 0;
const std::size_t memory_wasted = 0;
stackAllocator.Reset();
print_benchmark_stats(elapsed_time, memory_used, memory_wasted, MAX_OPERATIONS);
std::cout << "BENCHMARK STACK A: END" << std::endl;
}
void benchmark_stack_allocate_free(long MAX_OPERATIONS = 1e4){
timespec start, end;
std::cout << "BENCHMARK STACK A/F: START" << std::endl;
setTimer(start);
StackAllocator stackAllocator(1e10);
int operations = 0;
bool allocate = true;
while(operations < MAX_OPERATIONS){
if (allocate) {
stackAllocator.Allocate(sizeof(int), alignof(int)); // 4 -> 4
stackAllocator.Allocate(sizeof(bool), alignof(bool)); // 1 -> 5
// 3 -> 8
stackAllocator.Allocate(sizeof(foo), alignof(foo)); // 16 -> 24
allocate = false;
}else {
stackAllocator.Free(nullptr, sizeof(foo));
stackAllocator.Free(nullptr, sizeof(bool));
stackAllocator.Free(nullptr, sizeof(int));
allocate = true;
}
++operations;
}
setTimer(end);
const timespec elapsed_time = diff(start, end);
const std::size_t memory_used = 0;
const std::size_t memory_wasted = 0;
stackAllocator.Reset();
print_benchmark_stats(elapsed_time, memory_used, memory_wasted, MAX_OPERATIONS);
std::cout << "BENCHMARK STACK A/F: END" << std::endl;
}
void benchmark_malloc_allocate(long MAX_OPERATIONS = 1e4){
timespec start, end;
std::cout << "BENCHMARK MALLOC A: START" << std::endl;
setTimer(start);
int operations = 0;
srand (1);
while(operations < MAX_OPERATIONS){
malloc(sizeof(int));
malloc(sizeof(bool));
malloc(sizeof(foo));
++operations;
}
setTimer(end);
const timespec elapsed_time = diff(start, end);
const std::size_t memory_used = 0;
const std::size_t memory_wasted = 0;
print_benchmark_stats(elapsed_time, memory_used, memory_wasted, MAX_OPERATIONS);
std::cout << "BENCHMARK MALLOC A: END" << std::endl;
}
void benchmark_malloc_allocate_free(long MAX_OPERATIONS = 1e4){
timespec start, end;
std::cout << "BENCHMARK MALLOC A/F: START" << std::endl;
setTimer(start);
int operations = 0;
bool allocate = true;
int * i;
bool * b;
foo * f;
while(operations < MAX_OPERATIONS){
if (allocate){
i = (int*) malloc(sizeof(int));
b = (bool*) malloc(sizeof(bool));
f = (foo*) malloc(sizeof(foo));
allocate = false;
}else {
free(f);
free(b);
free(i);
allocate = true;
}
++operations;
}
setTimer(end);
const timespec elapsed_time = diff(start, end);
const std::size_t memory_used = 0;
const std::size_t memory_wasted = 0;
print_benchmark_stats(elapsed_time, memory_used, memory_wasted, MAX_OPERATIONS);
std::cout << "BENCHMARK MALLOC A/F: END" << std::endl;
}
/* TODO
1- Deinterface
2- Stack/Linear ->Calculate padding (Aligned allocators interface?)
2- benchmark free (3pointers)
3- read values (check speed)
4- move to utils file?
*/
int main(){
benchmark_stack_allocate_free(1e8);
benchmark_malloc_allocate_free(1e8);
return 1;
}
<commit_msg>Added benchmark to measure read write operations.<commit_after>#include <iostream>
#include <cstddef>
#include <time.h>
#include "StackAllocator.h"
/*
void test_primitives(Allocator &allocator){
std::cout << "\tTEST_PRIMITIVES_TYPES" << std::endl;
allocator.Allocate(sizeof(int), alignof(int)); // 4 -> 4
allocator.Allocate(sizeof(bool), alignof(bool)); // 1 -> 5
// 3 -> 8
allocator.Allocate(sizeof(int), alignof(int)); // 4 -> 12
// 4 -> 16
allocator.Allocate(sizeof(double), alignof(double)); // 8 -> 24
allocator.Allocate(sizeof(char), alignof(char)); // 1 -> 25
// 3 -> 28
allocator.Allocate(sizeof(int), alignof(int)); // 4 -> 32
allocator.Reset();
std::cout << std::endl;
}
void test_primitives_unaligned(Allocator &allocator){
std::cout << "\tTEST_PRIMITIVES_TYPES_UNALIGNED" << std::endl;
allocator.Allocate(sizeof(int)); // 4 -> 4
allocator.Allocate(sizeof(bool)); // 1 -> 5
// 0 -> 5
allocator.Allocate(sizeof(int)); // 4 -> 9
allocator.Allocate(sizeof(double)); // 8 -> 17
allocator.Allocate(sizeof(char)); // 1 -> 18
// 0 -> 18
allocator.Allocate(sizeof(int)); // 4 -> 22
allocator.Reset();
std::cout << std::endl;
}
void test_structs(Allocator &allocator){
std::cout << "\tTEST_CUSTOM_TYPES" << std::endl;
allocator.Allocate(sizeof(bar), alignof(bar)); // 16 -> 16
allocator.Allocate(sizeof(foo), alignof(foo)); // 16 -> 32
allocator.Allocate(sizeof(baz), alignof(baz)); // 4 -> 36
allocator.Allocate(sizeof(bool), alignof(bool)); // 1 -> 37
// 3 -> 40
allocator.Allocate(sizeof(foo3), alignof(foo3)); // 8 -> 48
allocator.Reset();
std::cout << std::endl;
}
void test_structs_unaligned(Allocator &allocator){
std::cout << "\tTEST_CUSTOM_TYPES_UNALIGNED" << std::endl;
allocator.Allocate(sizeof(bar), 0); // 16 -> 16
allocator.Allocate(sizeof(foo), 0); // 16 -> 32
allocator.Allocate(sizeof(baz), 0); // 4 -> 36
allocator.Allocate(sizeof(bool), 0); // 1 -> 37
// 0 -> 37
allocator.Allocate(sizeof(foo3), 0); // 8 -> 45
allocator.Reset();
std::cout << std::endl;
}
void test_linear_allocator(){
std::cout << "TEST_LINEAR_ALLOCATOR" << std::endl;
LinearAllocator linearAllocator(100);
test_primitives(linearAllocator);
test_structs(linearAllocator);
test_primitives_unaligned(linearAllocator);
test_structs_unaligned(linearAllocator);
}
void test_stack_allocator_primitives(StackAllocator &stackAllocator){
std::cout << "\tTEST_PRIMITIVES_TYPES" << std::endl;
stackAllocator.Allocate(sizeof(bool), alignof(bool)); // 1 -> 1
// 3 -> 4
stackAllocator.Allocate(sizeof(baz), alignof(baz)); // 4 -> 8
stackAllocator.Allocate(sizeof(int), alignof(int)); // 4 -> 12
std::cout << std::endl;
stackAllocator.Free(nullptr, sizeof(int)); // 4 -> 8
stackAllocator.Free(nullptr, sizeof(baz)); // 8 -> 4(3) -> 1
// 7 -> 8
stackAllocator.Allocate(sizeof(double), alignof(double)); // 8 -> 16
stackAllocator.Reset();
}
void test_stack_allocator(){
std::cout << "TEST_STACK_ALLOCATOR" << std::endl;
StackAllocator stackAllocator(100);
//test_primitives(stackAllocator);
//test_structs(stackAllocator);
//test_primitives_unaligned(stackAllocator);
//test_structs_unaligned(stackAllocator);
test_stack_allocator_primitives(stackAllocator);
}
*/
struct foo {
char *p; /* 8 bytes */
char c; /* 1 byte */
};
struct bar {
int a; // 4
bool b; // 1 -> 5
// 3 -> 8
int c; // 4 -> 12
bool d; // 1 -> 13
bool e; // 1 -> 14
// 2 -> 16
};
struct bar2 {
int a; // 4
int c; // 4 -> 8
bool b; // 1 -> 9
bool d;
bool e;
// 3 -> 12
};
struct foo3 {
int i; /* 4 byte */
char c; /* 1 bytes */
bool b; /* 1 bytes */
// 2 bytes
};
struct foo2 {
char c; /* 1 byte */
char *p; /* 8 bytes */
};
struct baz {
short s; /* 2 bytes */
char c; /* 1 byte */
};
void setTimer(timespec& timer){
clock_gettime(CLOCK_REALTIME, &timer);
}
timespec diff(timespec &start, timespec &end) {
timespec temp;
if ((end.tv_nsec-start.tv_nsec)<0) {
temp.tv_sec = end.tv_sec-start.tv_sec-1;
temp.tv_nsec = 1e9+end.tv_nsec-start.tv_nsec;
} else {
temp.tv_sec = end.tv_sec-start.tv_sec;
temp.tv_nsec = end.tv_nsec-start.tv_nsec;
}
return temp;
}
void print_benchmark_stats(const timespec& elapsed_time, const int& memory_used, const int&memory_wasted, const int max_operations){
double time_sec = (double) elapsed_time.tv_sec;
double time_nsec = (double) elapsed_time.tv_nsec;
double time_msec = (time_sec * 1000) + (time_nsec / 1000000);
std::cout << std::endl;
std::cout << "\tSTATS:" << std::endl;
std::cout << "\t\tOperations: \t" << max_operations << std::endl;
std::cout << "\t\tTime elapsed: \t" << time_msec << " ms" << std::endl;
std::cout << "\t\tOp per sec: \t" << (max_operations / 1e3) / time_msec << " mops/ms" << std::endl;
std::cout << "\t\tTimer per op: \t" << time_msec/(max_operations / 1e3) << " ms/mops" << std::endl;
//std::cout << "\t\tMemory used: \t" << memory_used << " bytes" << std::endl;
//std::cout << "\t\tMemory wasted: \t" << memory_wasted << " bytes\t" << ((float) memory_wasted / memory_used) * 100 << " %" << std::endl;
std::cout << std::endl;
}
void benchmark_stack_allocate(long MAX_OPERATIONS = 1e4){
timespec start, end;
std::cout << "BENCHMARK STACK A: START" << std::endl;
setTimer(start);
StackAllocator stackAllocator(1e10);
int operations = 0;
while(operations < MAX_OPERATIONS){
stackAllocator.Allocate(sizeof(int), alignof(int)); // 4 -> 4
stackAllocator.Allocate(sizeof(bool), alignof(bool)); // 1 -> 5
// 3 -> 8
stackAllocator.Allocate(sizeof(foo), alignof(foo)); // 16 -> 24
++operations;
}
setTimer(end);
const timespec elapsed_time = diff(start, end);
const std::size_t memory_used = 0;
const std::size_t memory_wasted = 0;
stackAllocator.Reset();
print_benchmark_stats(elapsed_time, memory_used, memory_wasted, MAX_OPERATIONS);
std::cout << "BENCHMARK STACK A: END" << std::endl;
}
void benchmark_stack_allocate_free(long MAX_OPERATIONS = 1e4){
timespec start, end;
std::cout << "BENCHMARK STACK A/F: START" << std::endl;
setTimer(start);
StackAllocator stackAllocator(1e10);
int operations = 0;
bool allocate = true;
int * i;
bool * b;
foo * f;
while(operations < MAX_OPERATIONS){
if (allocate) {
i = (int*) stackAllocator.Allocate(sizeof(int), alignof(int)); // 4 -> 4
b = (bool*) stackAllocator.Allocate(sizeof(bool), alignof(bool)); // 1 -> 5
// 3 -> 8
f = (foo*) stackAllocator.Allocate(sizeof(foo), alignof(foo)); // 16 -> 24
allocate = false;
}else {
stackAllocator.Free(nullptr, sizeof(foo));
stackAllocator.Free(nullptr, sizeof(bool));
stackAllocator.Free(nullptr, sizeof(int));
allocate = true;
}
++operations;
}
setTimer(end);
const timespec elapsed_time = diff(start, end);
const std::size_t memory_used = 0;
const std::size_t memory_wasted = 0;
stackAllocator.Reset();
print_benchmark_stats(elapsed_time, memory_used, memory_wasted, MAX_OPERATIONS);
std::cout << "BENCHMARK STACK A/F: END" << std::endl;
}
void benchmark_stack_allocate_free_read_write(long MAX_OPERATIONS = 1e4){
timespec start, end;
std::cout << "BENCHMARK STACK A/F/R/W: START" << std::endl;
setTimer(start);
StackAllocator stackAllocator(1e10);
int operations = 0;
bool allocate = true;
int * i;
bool * b;
foo * f;
while(operations < MAX_OPERATIONS){
if (allocate) {
i = (int*) stackAllocator.Allocate(sizeof(int), alignof(int)); // 4 -> 4
b = (bool*) stackAllocator.Allocate(sizeof(bool), alignof(bool)); // 1 -> 5
// 3 -> 8
f = (foo*) stackAllocator.Allocate(sizeof(foo), alignof(foo)); // 16 -> 24
*i = *i + 1;
*b = allocate;
*f = foo();
allocate = false;
}else {
stackAllocator.Free(nullptr, sizeof(foo));
stackAllocator.Free(nullptr, sizeof(bool));
stackAllocator.Free(nullptr, sizeof(int));
allocate = true;
}
++operations;
}
setTimer(end);
const timespec elapsed_time = diff(start, end);
const std::size_t memory_used = 0;
const std::size_t memory_wasted = 0;
stackAllocator.Reset();
print_benchmark_stats(elapsed_time, memory_used, memory_wasted, MAX_OPERATIONS);
std::cout << "BENCHMARK STACK A/F/R/W: END" << std::endl;
}
void benchmark_malloc_allocate(long MAX_OPERATIONS = 1e4){
timespec start, end;
std::cout << "BENCHMARK MALLOC A: START" << std::endl;
setTimer(start);
int operations = 0;
srand (1);
while(operations < MAX_OPERATIONS){
malloc(sizeof(int));
malloc(sizeof(bool));
malloc(sizeof(foo));
++operations;
}
setTimer(end);
const timespec elapsed_time = diff(start, end);
const std::size_t memory_used = 0;
const std::size_t memory_wasted = 0;
print_benchmark_stats(elapsed_time, memory_used, memory_wasted, MAX_OPERATIONS);
std::cout << "BENCHMARK MALLOC A: END" << std::endl;
}
void benchmark_malloc_allocate_free(long MAX_OPERATIONS = 1e4){
timespec start, end;
std::cout << "BENCHMARK MALLOC A/F: START" << std::endl;
setTimer(start);
int operations = 0;
bool allocate = true;
int * i;
bool * b;
foo * f;
while(operations < MAX_OPERATIONS){
if (allocate){
i = (int*) malloc(sizeof(int));
b = (bool*) malloc(sizeof(bool));
f = (foo*) malloc(sizeof(foo));
allocate = false;
}else {
free(f);
free(b);
free(i);
allocate = true;
}
++operations;
}
setTimer(end);
const timespec elapsed_time = diff(start, end);
const std::size_t memory_used = 0;
const std::size_t memory_wasted = 0;
print_benchmark_stats(elapsed_time, memory_used, memory_wasted, MAX_OPERATIONS);
std::cout << "BENCHMARK MALLOC A/F: END" << std::endl;
}
void benchmark_malloc_allocate_free_read_write(long MAX_OPERATIONS = 1e4){
timespec start, end;
std::cout << "BENCHMARK MALLOC A/F/R/W: START" << std::endl;
setTimer(start);
int operations = 0;
bool allocate = true;
int * i;
bool * b;
foo * f;
while(operations < MAX_OPERATIONS){
if (allocate){
i = (int*) malloc(sizeof(int));
b = (bool*) malloc(sizeof(bool));
f = (foo*) malloc(sizeof(foo));
*i = *i + 1;
*b = allocate;
*f = foo();
allocate = false;
}else {
free(f);
free(b);
free(i);
allocate = true;
}
++operations;
}
setTimer(end);
const timespec elapsed_time = diff(start, end);
const std::size_t memory_used = 0;
const std::size_t memory_wasted = 0;
print_benchmark_stats(elapsed_time, memory_used, memory_wasted, MAX_OPERATIONS);
std::cout << "BENCHMARK MALLOC A/F/R/W: END" << std::endl;
}
/* TODO
1- Deinterface
2- Stack/Linear ->Calculate padding (Aligned allocators interface?)
2- benchmark free (3pointers)
3- read values (check speed)
4- move to utils file?
*/
int main(){
benchmark_stack_allocate_free_read_write(1e4);
benchmark_malloc_allocate_free_read_write(1e4);
return 1;
}
<|endoftext|> |
<commit_before>#include <vector>
#include <chrono>
#include "sparsematrix.h"
#include "demos.h"
int main(int argc, char** argv){
CL::TinyCL tiny(CL::DEVICE::GPU);
SparseMatrix sMat("../res/bcsstk05.mtx");
std::vector<float> b;
for (int i = 0; i < sMat.dim; ++i)
b.push_back(i);
//Compare my kernel with the book kernel to make sure it's correct
std::vector<float> localRes, myRes;
//Measure elapsed time for my kernel and book kernel
std::cout << "Book CG:\n";
std::chrono::high_resolution_clock::time_point start = std::chrono::high_resolution_clock::now();
localRes = localConjGradSolve(sMat, b, tiny);
std::chrono::high_resolution_clock::duration bookTime = std::chrono::high_resolution_clock::now() - start;
std::cout << "------\nMy CG:\n";
start = std::chrono::high_resolution_clock::now();
myRes = conjugateGradient(sMat, b, tiny);
std::chrono::high_resolution_clock::duration myTime = std::chrono::high_resolution_clock::now() - start;
std::cout << "-----\nTime difference, mine - book: "
<< std::chrono::duration_cast<std::chrono::milliseconds>(myTime - bookTime).count()
<< "ms" << std::endl;
//If the results are differ at a digit higher than the some minimal
//error then my implementation is wrong
float avgDiff = 0, maxDif = 1e-6;
int nDifferent = 0;
for (int i = 0; i < localRes.size(); ++i){
float diff = std::abs(localRes.at(i) - myRes.at(i));
if (diff > maxDif){
avgDiff += diff;
++nDifferent;
}
}
if (nDifferent != 0)
avgDiff /= nDifferent;
std::cout << "# of values differing by more than " << std::scientific << maxDif
<< " : " << nDifferent << " of " << myRes.size()
<< "\nAverage difference between values: "
<< avgDiff << std::endl;
return 0;
}
<commit_msg>Not only do I take longer but it seems<commit_after>#include <vector>
#include <chrono>
#include "sparsematrix.h"
#include "demos.h"
int main(int argc, char** argv){
CL::TinyCL tiny(CL::DEVICE::GPU);
SparseMatrix sMat("../res/bcsstk05.mtx");
std::vector<float> b;
for (int i = 0; i < sMat.dim; ++i)
b.push_back(i);
//Compare my kernel with the book kernel to make sure it's correct
std::vector<float> localRes, myRes;
//Measure elapsed time for my kernel and book kernel
std::cout << "Book CG:\n";
std::chrono::high_resolution_clock::time_point start = std::chrono::high_resolution_clock::now();
localRes = localConjGradSolve(sMat, b, tiny);
std::chrono::high_resolution_clock::duration bookTime = std::chrono::high_resolution_clock::now() - start;
std::cout << "------\nMy CG:\n";
start = std::chrono::high_resolution_clock::now();
myRes = conjugateGradient(sMat, b, tiny);
std::chrono::high_resolution_clock::duration myTime = std::chrono::high_resolution_clock::now() - start;
std::cout << "-----\nBook solve time: "
<< std::chrono::duration_cast<std::chrono::milliseconds>(bookTime).count() << "ms\n"
<< "My solve time: "
<< std::chrono::duration_cast<std::chrono::milliseconds>(myTime).count() << "ms\n"
<< "Time difference, mine - book: "
<< std::chrono::duration_cast<std::chrono::milliseconds>(myTime - bookTime).count()
<< "ms" << std::endl;
//If the results are differ at a digit higher than the some minimal
//error then my implementation is wrong
float avgDiff = 0, maxDif = 1e-6;
int nDifferent = 0;
for (int i = 0; i < localRes.size(); ++i){
float diff = std::abs(localRes.at(i) - myRes.at(i));
if (diff > maxDif){
avgDiff += diff;
++nDifferent;
}
}
if (nDifferent != 0)
avgDiff /= nDifferent;
std::cout << "# of values differing by more than " << std::scientific << maxDif
<< " : " << nDifferent << " of " << myRes.size()
<< "\nAverage difference between values: "
<< avgDiff << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cstring>
#include "fitness.h"
#include "evolution.h"
// Class Definitions
FITNESS Fitness;
EVOLUTION Evolution;
int main()
{
int generation = 0;
int fitness = 0;
int fittest = 0;
int geneSize = 0;
srand(time(NULL));
// Initialize the solution
Fitness.setSolution("1111000011110000000000001111000011110000111100000000000011110000");
// Get geneSize
geneSize = Fitness.getSolutionLength();
// Initialize population
int **population;
population = (int **) malloc(POPULATION_SIZE * sizeof(int *));
for (int i = 0; i < POPULATION_SIZE; i++)
population[i] = (int *) malloc(geneSize * sizeof(int));
// Generate population
for (int pop = 0; pop < POPULATION_SIZE; pop++)
{
for (int gene = 0; gene < geneSize; gene++)
{
population[pop][gene] = rand() % 2;
}
}
// Calculate the the fitness of the fittest of the population
fittest = Fitness.getFittest(population, POPULATION_SIZE);
fitness = Fitness.getFitness(population[fittest]);
std::cout << "Gene size: " << geneSize << std::endl;
while(fitness < geneSize)
{
generation++;
std::cout << "Generation: " << generation
<< "; fitness: " << fitness
<< "; Fittest individu: " << fittest
<< std::endl;
Evolution.evolve(population, Fitness);
// Calculate the fitness for the next generation
fittest = Fitness.getFittest(population, POPULATION_SIZE);
fitness = Fitness.getFitness(population[fittest]);
}
generation++;
std::cout << "Solution found!" << std::endl;
std::cout << "Generation: " << generation << std::endl;
std::cout << "Fitness: " << fitness << std::endl;
std::cout << "Genes: ";
int fittestIndividual = Fitness.getFittest(population, POPULATION_SIZE);
for (int i = 0; i < geneSize; i++)
std::cout << population[fittestIndividual][i];
std::cout << std::endl;
return 0;
}
<commit_msg>Update by using functions from class 'POPULATION'.<commit_after>#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cstring>
#include "fitness.h"
#include "evolution.h"
#include "population.h"
// Class Definitions
FITNESS Fitness;
EVOLUTION Evolution;
POPULATION Population;
int main()
{
int generation = 0;
int fitness = 0;
int fittest = 0;
int geneSize = 0;
srand(time(NULL));
// Initialize the solution
Fitness.setSolution("1111000011110000000000001111000011110000111100000000000011110000");
// Get geneSize
geneSize = Fitness.getSolutionLength();
// Initialize population
int **population;
population = Population.initializePopulation(POPULATION_SIZE, geneSize);
Population.createRandomPopulation(population, POPULATION_SIZE, geneSize);
// Calculate the the fitness of the fittest of the population
fittest = Fitness.getFittest(population, POPULATION_SIZE);
fitness = Fitness.getFitness(population[fittest]);
std::cout << "Gene size: " << geneSize << std::endl;
while(fitness < geneSize)
{
generation++;
std::cout << "Generation: " << generation
<< "; fitness: " << fitness
<< "; Fittest individu: " << fittest
<< std::endl;
Evolution.evolve(population, Fitness);
// Calculate the fitness for the next generation
fittest = Fitness.getFittest(population, POPULATION_SIZE);
fitness = Fitness.getFitness(population[fittest]);
}
generation++;
std::cout << "Solution found!" << std::endl;
std::cout << "Generation: " << generation << std::endl;
std::cout << "Fitness: " << fitness << std::endl;
std::cout << "Genes: ";
int fittestIndividual = Fitness.getFittest(population, POPULATION_SIZE);
for (int i = 0; i < geneSize; i++)
std::cout << population[fittestIndividual][i];
std::cout << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <iostream>
#include <map>
#include <string>
#include <vector>
#include "MuMaterial.h"
#include "counter_point.hpp"
#include "voice.hpp"
using namespace std;
void ValidateArguments (int argc, char* argv[]);
void PrintVector (vector<int> v, string message);
vector<int> GetHarmonicRange (int note_pitch);
vector<int> FixPitchsToScale (int scale_pitch, vector<int> pitchs);
vector<int> RemoveUnisonFromPitchs(int unison_pitch, vector<int> pitchs);
int main (int argc, char* argv[])
{
ValidateArguments(argc, argv);
string output_path = argc > 2 ? argv[2] : "./";
string score_file_path = argv[1];
MuInit();
MuMaterial material;
material.LoadScore(argv[1]);
CounterPoint counter_point(material);
counter_point.SetScalePitch(60);
counter_point.PrintHarmonicPitchs();
MuMaterial counter_point_material = counter_point.GenerateCounterPointMaterial();
// material.Show();
// counter_point_material.Show();
material.AddVoices(1);
material.SetVoice(1, counter_point_material, 0);
material.SetInstrument(0, 2);
material.SetInstrument(1, 3);
material.Show();
material.SetDefaultFunctionTables();
material.Score(output_path + "score");
material.Orchestra(output_path + "orchestra");
Voice::Manager voice_manager;
voice_manager.AddVoice("Soprano", 60, 79);
voice_manager.AddVoice("Contralto", 55, 72);
voice_manager.AddVoice("Tenor", 47, 67);
voice_manager.AddVoice("Baixo", 40, 60);
Voice voice = voice_manager.GetVoice(62);
cout << "Voice: " << voice.name << endl;
// counter_point_material.SetDefaultFunctionTables();
// counter_point_material.Score(output_path + "score_cp");
// counter_point_material.Orchestra(output_path + "orchestra_cp");
// MuNote note;
// MuMaterial material;
// note.SetPitch(60);
// material += note;
// note.SetPitch(62);
// material += note;
// note.SetPitch(64);
// material += note;
// CounterPoint counter_point(material);
// counter_point.PrintHarmonicPitchs();
return 0;
}
void ValidateArguments (int argc, char* argv[])
{
bool has_arguments = argc < 2;
if (has_arguments)
{
cout << "Usage: " << argv[0] << " [score_file_path] [output_path]" << endl;
exit(-1);
}
}
void PrintVector (vector<int> v, string message)
{
cout << message << ": ";
for (unsigned int index = 0; index < v.size(); index++)
{
cout << v[index] << " ";
}
cout << endl;
}
vector<int> GetHarmonicRange (int note_pitch)
{
int unison = note_pitch;
int third_minor = note_pitch - 3;
int third_major = note_pitch - 4;
int fifith_perfect = note_pitch - 7;
int sixth_minor = note_pitch - 8;
int sixth_major = note_pitch - 9;
vector<int> harmonic_range {unison, third_minor, third_major,
fifith_perfect, sixth_minor, sixth_major};
return harmonic_range;
}
vector<int> FixPitchsToScale (int scale_pitch, vector<int> pitchs)
{
scale_pitch = scale_pitch % 12;
vector<int> scale_pitchs = { 0 + scale_pitch, 2 + scale_pitch,
4 + scale_pitch, 5 + scale_pitch,
7 + scale_pitch, 9 + scale_pitch,
11 + scale_pitch };
vector<int> pitchs_on_scale;
for (unsigned int index = 0; index < pitchs.size(); index++)
{
int pitch = pitchs[index] % 12;
bool found_pitch = find(scale_pitchs.begin(), scale_pitchs.end(),
pitch) != scale_pitchs.end();
if(found_pitch)
{
pitchs_on_scale.push_back(pitchs[index]);
}
}
return pitchs_on_scale;
}
vector<int> RemoveUnisonFromPitchs(int unison_pitch, vector<int> pitchs)
{
vector<int> pitchs_without_unison = pitchs;
pitchs_without_unison.erase(remove(pitchs_without_unison.begin(),
pitchs_without_unison.end(),
unison_pitch),
pitchs_without_unison.end());
return pitchs_without_unison;
}
<commit_msg>Remove unused code on main.cpp<commit_after>#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <iostream>
#include <map>
#include <string>
#include <vector>
#include "MuMaterial.h"
#include "counter_point.hpp"
#include "voice.hpp"
using namespace std;
void ValidateArguments (int argc, char* argv[]);
int main (int argc, char* argv[])
{
ValidateArguments(argc, argv);
string output_path = argc > 2 ? argv[2] : "./";
string score_file_path = argv[1];
MuInit();
MuMaterial material;
material.LoadScore(argv[1]);
CounterPoint counter_point(material);
counter_point.SetScalePitch(60);
counter_point.PrintHarmonicPitchs();
MuMaterial counter_point_material = counter_point.GenerateCounterPointMaterial();
// material.Show();
// counter_point_material.Show();
material.AddVoices(1);
material.SetVoice(1, counter_point_material, 0);
material.SetInstrument(0, 2);
material.SetInstrument(1, 3);
material.Show();
material.SetDefaultFunctionTables();
material.Score(output_path + "score");
material.Orchestra(output_path + "orchestra");
Voice::Manager voice_manager;
voice_manager.AddVoice("Soprano", 60, 79);
voice_manager.AddVoice("Contralto", 55, 72);
voice_manager.AddVoice("Tenor", 47, 67);
voice_manager.AddVoice("Baixo", 40, 60);
Voice voice = voice_manager.GetVoice(62);
cout << "Voice: " << voice.name << endl;
// counter_point_material.SetDefaultFunctionTables();
// counter_point_material.Score(output_path + "score_cp");
// counter_point_material.Orchestra(output_path + "orchestra_cp");
// MuNote note;
// MuMaterial material;
// note.SetPitch(60);
// material += note;
// note.SetPitch(62);
// material += note;
// note.SetPitch(64);
// material += note;
// CounterPoint counter_point(material);
// counter_point.PrintHarmonicPitchs();
return 0;
}
void ValidateArguments (int argc, char* argv[])
{
bool has_arguments = argc < 2;
if (has_arguments)
{
cout << "Usage: " << argv[0] << " [score_file_path] [output_path]" << endl;
exit(-1);
}
}
<|endoftext|> |
<commit_before>/*
* VideoLeveler
*
*
* Software License Agreement (BSD License)
*
* Copyright (c) 2013, Chili lab, EPFL.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Chili, EPFL nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* File: main.cpp
* Author: Mirko Raca <[email protected]>
* Created: December 16, 2013.
*/
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <string>
#include <iostream>
#include <glog/logging.h>
using namespace std;
using namespace cv;
int main(int argc, char *argv[])
{
google::InitGoogleLogging(argv[0]);
/* tmp params */
string videoFilename = string(argv[1]);
/* inits */
VideoCapture vSrc = VideoCapture(videoFilename);
if( !vSrc.isOpened() ){
LOG(FATAL) << "Video " << videoFilename << " not found";
cout << "Video not found" << endl;
exit(1);
}
/* processing */
double curFrame = vSrc.get(CV_CAP_PROP_POS_FRAMES);
double maxFrames = vSrc.get(CV_CAP_PROP_FRAME_COUNT);
while(curFrame < maxFrames){
Mat curFrame;
vSrc >> curFrame;
imshow("testwnd",curFrame);
waitKey(100);
}
return 0;
}
<commit_msg>Implemented the Gonzales/Morales'02 skin detection algorithm<commit_after>/*
* VideoLeveler
*
*
* Software License Agreement (BSD License)
*
* Copyright (c) 2013, Chili lab, EPFL.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Chili, EPFL nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* File: main.cpp
* Author: Mirko Raca <[email protected]>
* Created: December 16, 2013.
*/
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <string>
#include <iostream>
#include <glog/logging.h>
using namespace std;
using namespace cv;
void skinDetectionGM( Mat& _frameMat, Mat& _resMask );
int main(int argc, char *argv[])
{
google::InitGoogleLogging(argv[0]);
/* tmp params */
string videoFilename = string(argv[1]);
/* inits */
VideoCapture vSrc = VideoCapture(videoFilename);
if( !vSrc.isOpened() ){
LOG(FATAL) << "Video " << videoFilename << " not found";
cout << "Video not found" << endl;
exit(1);
}
/* processing */
double curFrameNo = vSrc.get(CV_CAP_PROP_POS_FRAMES);
double maxFrames = vSrc.get(CV_CAP_PROP_FRAME_COUNT);
int skipCount = vSrc.get(CV_CAP_PROP_FPS) * 20,
curSkipNo = 0;
Mat curFrame, curMask;
while(curFrameNo < maxFrames){
vSrc >> curFrame;
if( curSkipNo++ < skipCount )
continue;
curSkipNo = 0;
skinDetectionGM(curFrame, curMask);
// imshow("curMaskWnd",curMask);
curFrame.setTo(Scalar(0.0f, 255.0f, 0.0f), curMask);
imshow("testwnd",curFrame);
waitKey(10);
}
return 0;
}
/*
* Outputs the mask of skin-colored regions of the image based on the paper
* Automatic Feature Construction and a Simple Rule Induction Algorithm
* for Skin Detection
* G. Gomez, E. F. Morales (2002)
*
*
*/
void skinDetectionGM( Mat& _frameMat, Mat& _resMask ){
_resMask = _frameMat.clone();
_resMask.setTo(Scalar(0)); // TEMPORARY !!
// normalizing the image
Mat curFrameFloat; _frameMat.convertTo(curFrameFloat, CV_32FC3);
vector<Mat> channels;
split(curFrameFloat, channels);
Mat sumValues = Mat::zeros(_frameMat.rows, _frameMat.cols, CV_32FC1);
for( Mat& ch : channels )
sumValues = sumValues + ch;
for( Mat& ch : channels )
ch = ch / sumValues;
merge(channels, curFrameFloat);
Mat sumAllChannels = channels[0] + channels[1] + channels[2];
// implementing the rules
// rule 1: b/g < 1.249
Mat rule1Binary;
{
Mat rule1 = channels[0] / channels[1];
inRange(rule1, Scalar(0.0f), Scalar(1.249f), rule1Binary );
}
// rule 2: (r+g+b)/(3*r) > 0.696
Mat rule2Binary;
{
Mat rule2 = Mat::zeros(_frameMat.rows, _frameMat.cols, CV_32FC1);
rule2 = ( sumAllChannels )/ ( 3.0f*channels[2] );
inRange(rule2, Scalar(0.696f), Scalar(1000.0f), rule2Binary );
}
// rule 3: 1/3.0 - b/(r+g+b) > 0.014
Mat rule3Binary;
{
Mat constMat = Mat::zeros(_frameMat.rows, _frameMat.cols, CV_32FC1);
constMat.setTo(Scalar(1.0f/3.0f));
Mat rule3 = Mat::zeros(_frameMat.rows, _frameMat.cols, CV_32FC1);
rule3 = constMat - channels[0]/( sumAllChannels );
inRange(rule3, Scalar(0.014f), Scalar(1000.0f), rule3Binary);
}
// rule 4: g/(3*(r+g+b)) < 0.108
Mat rule4Binary;
{
Mat rule4 = Mat::zeros(_frameMat.rows, _frameMat.cols, CV_32FC1);
rule4 = channels[1] / ( 3.0f * sumAllChannels );
inRange(rule4, Scalar(0.0f), Scalar(0.108f), rule4Binary);
}
// show
// final mask
_resMask = rule1Binary & rule2Binary & rule3Binary & rule4Binary;
// imshow("normChanels", curFrameFloat);
// waitKey(10);
}
<|endoftext|> |
<commit_before>#include "Arduino.h"
#include "ESP8266WiFi.h"
#include "ESP8266HTTPClient.h"
#include "PubSubClient.h"
#include "Adafruit_Sensor.h"
#include "DHT.h"
#include "TSL2561.h"
// include the user configuration file
#include "config.h"
extern "C" {
#include "user_interface.h"
extern struct rst_info resetInfo;
}
struct {
float ir;
float full;
float lux;
float h;
float t;
uint16_t vdd;
uint8_t count;
} rtc_mem;
// enable reading the Vcc voltage with the ADC
ADC_MODE(ADC_VCC);
// WiFi network and password
WiFiClient espClient;
void connectWifi();
// MQTT server & channel
PubSubClient mqttClient(espClient);
void reconnectMqtt();
void callback(char* topic, byte* payload, unsigned int length);
// DHT22 sensor pin & type declaration
DHT dht(DHTPIN, DHTTYPE);
// TSL2561 sensor pin declaration
TSL2561 tsl(TSL2561_ADDR_FLOAT, SDAPIN, SCLPIN);
unsigned long lastMsg = 0;
uint8_t measurements = 0;
void update();
void doMeasurements();
void resetRTC();
void setup(void) {
Serial.begin(9600);
dht.begin();
if (tsl.begin()) {
Serial.println("Found sensor");
} else {
Serial.println("No sensor?");
}
tsl.setGain(TSL2561_GAIN_0X);
tsl.setTiming(TSL2561_INTEGRATIONTIME_13MS);
mqttClient.setServer(MQTTSERVER, 1883);
mqttClient.setCallback(callback);
Serial.print(ESP.getResetReason());
if (resetInfo.reason != REASON_DEEP_SLEEP_AWAKE){
resetRTC();
}
}
void loop() {
#ifdef SLEEP
doMeasurements();
if(rtc_mem.count >= NUMMEASUREMENTS){
if ((WiFi.status() != WL_CONNECTED)){
connectWifi();
}
if (!mqttClient.connected()) {
reconnectMqtt();
}
mqttClient.loop();
update();
}
WiFi.disconnect(true);
delay(50);
ESP.deepSleep(MEASUREMENTINTERVAL*1000000, WAKE_RF_DEFAULT);
#else
if ((WiFi.status() != WL_CONNECTED)){
connectWifi();
}
if (!mqttClient.connected()) {
reconnectMqtt();
}
mqttClient.loop();
unsigned long now = millis();
if (now - lastMsg > MEASUREMENTINTERVAL*1000) {
doMeasurements();
lastMsg = millis();
if(rtc_mem.count >= NUMMEASUREMENTS){
update();
}
}
#endif
delay(50);
}
void doMeasurements(){
float h = dht.readHumidity();
// Read temperature as Celsius (the default)
float t = dht.readTemperature();
// Check if any reads failed
if (isnan(h) || isnan(t)) {
Serial.println("Failed to read from DHT sensor!");
h=0;
t=0;
}
Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\t");
Serial.print("Temperature: ");
Serial.print(t);
Serial.println(" *C ");
// Read 32 bits with top 16 bits IR, bottom 16 bits full spectrum
uint32_t lum = tsl.getFullLuminosity();
uint16_t ir, full;
ir = lum >> 16;
full = lum & 0xFFFF;
uint32_t lux = tsl.calculateLux(full, ir);
Serial.print("IR: "); Serial.print(ir); Serial.print("\t\t");
Serial.print("Full: "); Serial.print(full); Serial.print("\t");
Serial.print("Visible: "); Serial.print(full - ir); Serial.print("\t");
Serial.print("Lux: "); Serial.println(lux);
// read Vdd voltage
uint16_t vdd = ESP.getVcc();
// get avg of previous measurements from RTC memory
ESP.rtcUserMemoryRead(0, (uint32_t*) &rtc_mem, sizeof(rtc_mem));
// re-calculate average
rtc_mem.t = rtc_mem.t+(t/NUMMEASUREMENTS);
rtc_mem.h = rtc_mem.h+(h/NUMMEASUREMENTS);
rtc_mem.ir = rtc_mem.ir+((float)ir/NUMMEASUREMENTS);
rtc_mem.full = rtc_mem.full+((float)full/NUMMEASUREMENTS);
rtc_mem.lux = rtc_mem.lux+((float)lux/NUMMEASUREMENTS);
rtc_mem.vdd = vdd;
rtc_mem.count = rtc_mem.count + 1;
Serial.println(rtc_mem.t);
Serial.println(rtc_mem.h);
Serial.println(rtc_mem.ir);
Serial.println(rtc_mem.full);
Serial.println(rtc_mem.lux);
Serial.println(rtc_mem.vdd);
Serial.println(rtc_mem.count);
// write to RTC mem
ESP.rtcUserMemoryWrite(0, (uint32_t*) &rtc_mem, sizeof(rtc_mem));
}
void update(){
// TODO: get free heap memory
String data = String("field1=" + String(rtc_mem.t, 1) + "&field2=" + String(rtc_mem.h, 1) + "&field3=" + String(rtc_mem.ir, 1)+ "&field4=" + String(rtc_mem.full, 1)+ "&field5=" + String(rtc_mem.lux, 1)+ "&field6=" + String(rtc_mem.vdd, DEC));
int length = data.length();
char msgBuffer[length];
data.toCharArray(msgBuffer,length+1);
String channel = String("channels/" + String(CHANNELID) +"/publish/"+String(APIKEY));
length = channel.length();
char chnlBuffer[length];
channel.toCharArray(chnlBuffer, length+1);
mqttClient.publish(chnlBuffer,msgBuffer);
Serial.print(data);
delay(1000);
// set rtc to 0 for all fields and write to memory
resetRTC();
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
}
void resetRTC(){
rtc_mem.t = 0.0;
rtc_mem.h = 0.0;
rtc_mem.ir = 0;
rtc_mem.full = 0;
rtc_mem.lux = 0;
rtc_mem.vdd = 0;
rtc_mem.count = 0;
ESP.rtcUserMemoryWrite(0, (uint32_t*) &rtc_mem, sizeof(rtc_mem));
}
void connectWifi() {
WiFi.disconnect(true);
WiFi.begin(SSID, PASSWORD);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.print("Connected, IP address: ");
Serial.println(WiFi.localIP());
}
void reconnectMqtt(){
while (!mqttClient.connected()) {
Serial.print("Attempting MQTT connection...");
// Create a random client ID
String clientId = "ESP8266Client-";
clientId += String(random(0xffff), HEX);
// Attempt to connect
if (mqttClient.connect(clientId.c_str())) {
Serial.println("connected");
} else {
Serial.print("failed, rc=");
Serial.print(mqttClient.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
<commit_msg>Reduces power consumption when waking from deep sleep.<commit_after>#include "Arduino.h"
#include "ESP8266WiFi.h"
#include "ESP8266HTTPClient.h"
#include "PubSubClient.h"
#include "Adafruit_Sensor.h"
#include "DHT.h"
#include "TSL2561.h"
// include the user configuration file
#include "config.h"
extern "C" {
#include "user_interface.h"
extern struct rst_info resetInfo;
}
struct {
float ir;
float full;
float lux;
float h;
float t;
uint16_t vdd;
uint8_t count;
} rtc_mem;
// enable reading the Vcc voltage with the ADC
ADC_MODE(ADC_VCC);
// WiFi network and password
WiFiClient espClient;
void connectWifi();
// MQTT server & channel
PubSubClient mqttClient(espClient);
void reconnectMqtt();
void callback(char* topic, byte* payload, unsigned int length);
// DHT22 sensor pin & type declaration
DHT dht(DHTPIN, DHTTYPE);
// TSL2561 sensor pin declaration
TSL2561 tsl(TSL2561_ADDR_FLOAT, SDAPIN, SCLPIN);
unsigned long lastMsg = 0;
uint8_t measurements = 0;
void update();
void doMeasurements();
void resetRTC();
void setup(void) {
Serial.begin(9600);
dht.begin();
if (tsl.begin()) {
Serial.println("Found sensor");
} else {
Serial.println("No sensor?");
}
tsl.setGain(TSL2561_GAIN_0X);
tsl.setTiming(TSL2561_INTEGRATIONTIME_13MS);
mqttClient.setServer(MQTTSERVER, 1883);
mqttClient.setCallback(callback);
Serial.print(ESP.getResetReason());
if (resetInfo.reason != REASON_DEEP_SLEEP_AWAKE){
resetRTC();
}
}
void loop() {
#ifdef SLEEP
doMeasurements();
if(rtc_mem.count >= NUMMEASUREMENTS){
if ((WiFi.status() != WL_CONNECTED)){
connectWifi();
}
if (!mqttClient.connected()) {
reconnectMqtt();
}
mqttClient.loop();
update();
}
WiFi.disconnect(true);
delay(50);
if(rtc_mem.count >= NUMMEASUREMENTS-1){
ESP.deepSleep(MEASUREMENTINTERVAL*1000000, WAKE_RF_DEFAULT);
}
else{
ESP.deepSleep(MEASUREMENTINTERVAL*1000000, WAKE_RF_DISABLED);
}
#else
if ((WiFi.status() != WL_CONNECTED)){
connectWifi();
}
if (!mqttClient.connected()) {
reconnectMqtt();
}
mqttClient.loop();
unsigned long now = millis();
if (now - lastMsg > MEASUREMENTINTERVAL*1000) {
doMeasurements();
lastMsg = millis();
if(rtc_mem.count >= NUMMEASUREMENTS){
update();
}
}
#endif
delay(50);
}
void doMeasurements(){
float h = dht.readHumidity();
// Read temperature as Celsius (the default)
float t = dht.readTemperature();
// Check if any reads failed
if (isnan(h) || isnan(t)) {
Serial.println("Failed to read from DHT sensor!");
h=0;
t=0;
}
Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\t");
Serial.print("Temperature: ");
Serial.print(t);
Serial.println(" *C ");
// Read 32 bits with top 16 bits IR, bottom 16 bits full spectrum
uint32_t lum = tsl.getFullLuminosity();
uint16_t ir, full;
ir = lum >> 16;
full = lum & 0xFFFF;
uint32_t lux = tsl.calculateLux(full, ir);
Serial.print("IR: "); Serial.print(ir); Serial.print("\t\t");
Serial.print("Full: "); Serial.print(full); Serial.print("\t");
Serial.print("Visible: "); Serial.print(full - ir); Serial.print("\t");
Serial.print("Lux: "); Serial.println(lux);
// read Vdd voltage
uint16_t vdd = ESP.getVcc();
// get avg of previous measurements from RTC memory
ESP.rtcUserMemoryRead(0, (uint32_t*) &rtc_mem, sizeof(rtc_mem));
// re-calculate average
rtc_mem.t = rtc_mem.t+(t/NUMMEASUREMENTS);
rtc_mem.h = rtc_mem.h+(h/NUMMEASUREMENTS);
rtc_mem.ir = rtc_mem.ir+((float)ir/NUMMEASUREMENTS);
rtc_mem.full = rtc_mem.full+((float)full/NUMMEASUREMENTS);
rtc_mem.lux = rtc_mem.lux+((float)lux/NUMMEASUREMENTS);
rtc_mem.vdd = vdd;
rtc_mem.count = rtc_mem.count + 1;
Serial.println(rtc_mem.t);
Serial.println(rtc_mem.h);
Serial.println(rtc_mem.ir);
Serial.println(rtc_mem.full);
Serial.println(rtc_mem.lux);
Serial.println(rtc_mem.vdd);
Serial.println(rtc_mem.count);
// write to RTC mem
ESP.rtcUserMemoryWrite(0, (uint32_t*) &rtc_mem, sizeof(rtc_mem));
}
void update(){
// TODO: get free heap memory
String data = String("field1=" + String(rtc_mem.t, 1) + "&field2=" + String(rtc_mem.h, 1) + "&field3=" + String(rtc_mem.ir, 1)+ "&field4=" + String(rtc_mem.full, 1)+ "&field5=" + String(rtc_mem.lux, 1)+ "&field6=" + String(rtc_mem.vdd, DEC));
int length = data.length();
char msgBuffer[length];
data.toCharArray(msgBuffer,length+1);
String channel = String("channels/" + String(CHANNELID) +"/publish/"+String(APIKEY));
length = channel.length();
char chnlBuffer[length];
channel.toCharArray(chnlBuffer, length+1);
mqttClient.publish(chnlBuffer,msgBuffer);
Serial.print(data);
delay(1000);
// set rtc to 0 for all fields and write to memory
resetRTC();
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
}
void resetRTC(){
rtc_mem.t = 0.0;
rtc_mem.h = 0.0;
rtc_mem.ir = 0;
rtc_mem.full = 0;
rtc_mem.lux = 0;
rtc_mem.vdd = 0;
rtc_mem.count = 0;
ESP.rtcUserMemoryWrite(0, (uint32_t*) &rtc_mem, sizeof(rtc_mem));
}
void connectWifi() {
WiFi.disconnect(true);
WiFi.begin(SSID, PASSWORD);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.print("Connected, IP address: ");
Serial.println(WiFi.localIP());
}
void reconnectMqtt(){
while (!mqttClient.connected()) {
Serial.print("Attempting MQTT connection...");
// Create a random client ID
String clientId = "ESP8266Client-";
clientId += String(random(0xffff), HEX);
// Attempt to connect
if (mqttClient.connect(clientId.c_str())) {
Serial.println("connected");
} else {
Serial.print("failed, rc=");
Serial.print(mqttClient.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
<|endoftext|> |
<commit_before>#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <Arduino.h>
#include <SPI.h>
#include <WiFiUDP.h>
#include "settings.h"
MDNSResponder mdns;
WiFiUDP udp;
ESP8266WebServer server(80);
const char* ssid = WIFI_SSID;
const char* password = WIFI_PASSWORD;
void sendWOL(const IPAddress ip, const byte mac[]);
void beginWifi();
void macStringToBytes(const String mac, byte *bytes);
void setup(void){
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(LED_BUILTIN, 0);
Serial.begin(115200);
beginWifi();
while (!mdns.begin("esp8266", WiFi.localIP())) {}
udp.begin(9);
server.on("/", []() {
//Requests to the root respond with a "Hello World"
digitalWrite(LED_BUILTIN, 1);
server.send(200, "text/plain", "ESP8266 WOL online");
digitalWrite(LED_BUILTIN, 0);
});
server.on("/wol", [](){
//GET requests to /wol send Wake-On-LAN frames
// the mac parameter is mandatory and should be a non-delimited MAC address
// the ip parameter is optional, and if not provided the local broadcast will be used
// example: GET /wol?mac=112233aabbcc&ip=192.168.0.1
String mac = server.arg("mac");
String ip = server.arg("ip");
//If IP is specified, read it. Else attempt to determine the local broadcast.
IPAddress target_ip;
if(ip.length() < 7) {
//This will only work with class C networks.
//A proper implementation should check WiFi.subnetMask() and mask accordingly.
target_ip = WiFi.localIP();
target_ip[3] = 255;
} else {
target_ip = IPAddress((const uint8_t *) ip.c_str());
}
byte target_mac[6];
macStringToBytes(mac, target_mac);
sendWOL(target_ip, target_mac);
server.send(200, "text/plain", "WOL sent to " + target_ip.toString() + " " + mac);
});
server.onNotFound([](){
server.send(404, "text/plain", "");
});
server.begin();
Serial.println("HTTP server started");
}
void loop(void){
server.handleClient();
}
void beginWifi() {
WiFi.begin(ssid, password);
Serial.println("");
while (WiFi.status() != WL_CONNECTED) {
delay(250);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}
/*
* Send a Wake-On-LAN packet for the given MAC address, to the given IP
* address. Often the IP address will be the local broadcast.
*/
void sendWOL(const IPAddress ip, const byte mac[]) {
byte preamble[] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
udp.beginPacket(ip, 9);
udp.write(preamble, 6);
for (uint8 i = 0; i < 16; i++) {
udp.write(mac, 6);
}
udp.endPacket();
}
byte valFromChar(char c) {
if(c >= 'a' && c <= 'f') return ((byte) (c - 'a') + 10) & 0x0F;
if(c >= 'A' && c <= 'F') return ((byte) (c - 'A') + 10) & 0x0F;
if(c >= '0' && c <= '9') return ((byte) (c - '0')) & 0x0F;
return 0;
}
/*
* Very simple converter from a String representation of a MAC address to
* 6 bytes. Does not handle errors or delimiters, but requires very little
* code space and no libraries.
*/
void macStringToBytes(const String mac, byte *bytes) {
if(mac.length() >= 12) {
for(int i = 0; i < 6; i++) {
bytes[i] = (valFromChar(mac.charAt(i*2)) << 4) | valFromChar(mac.charAt(i*2 + 1));
}
} else {
Serial.println("Incorrect MAC format.");
}
}
<commit_msg>Remove IO pin use<commit_after>#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <Arduino.h>
#include <SPI.h>
#include <WiFiUDP.h>
#include "settings.h"
MDNSResponder mdns;
WiFiUDP udp;
ESP8266WebServer server(80);
const char* ssid = WIFI_SSID;
const char* password = WIFI_PASSWORD;
void sendWOL(const IPAddress ip, const byte mac[]);
void beginWifi();
void macStringToBytes(const String mac, byte *bytes);
void setup(void){
Serial.begin(115200);
beginWifi();
while (!mdns.begin("esp8266", WiFi.localIP())) {}
udp.begin(9);
server.on("/", []() {
//Requests to the root respond with a "Hello World"
digitalWrite(LED_BUILTIN, 1);
server.send(200, "text/plain", "ESP8266 WOL online");
digitalWrite(LED_BUILTIN, 0);
});
server.on("/wol", [](){
//GET requests to /wol send Wake-On-LAN frames
// the mac parameter is mandatory and should be a non-delimited MAC address
// the ip parameter is optional, and if not provided the local broadcast will be used
// example: GET /wol?mac=112233aabbcc&ip=192.168.0.1
String mac = server.arg("mac");
String ip = server.arg("ip");
//If IP is specified, read it. Else attempt to determine the local broadcast.
IPAddress target_ip;
if(ip.length() < 7) {
//This will only work with class C networks.
//A proper implementation should check WiFi.subnetMask() and mask accordingly.
target_ip = WiFi.localIP();
target_ip[3] = 255;
} else {
target_ip = IPAddress((const uint8_t *) ip.c_str());
}
byte target_mac[6];
macStringToBytes(mac, target_mac);
sendWOL(target_ip, target_mac);
server.send(200, "text/plain", "WOL sent to " + target_ip.toString() + " " + mac);
});
server.onNotFound([](){
server.send(404, "text/plain", "");
});
server.begin();
Serial.println("HTTP server started");
}
void loop(void){
server.handleClient();
}
void beginWifi() {
WiFi.begin(ssid, password);
Serial.println("");
while (WiFi.status() != WL_CONNECTED) {
delay(250);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}
/*
* Send a Wake-On-LAN packet for the given MAC address, to the given IP
* address. Often the IP address will be the local broadcast.
*/
void sendWOL(const IPAddress ip, const byte mac[]) {
byte preamble[] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
udp.beginPacket(ip, 9);
udp.write(preamble, 6);
for (uint8 i = 0; i < 16; i++) {
udp.write(mac, 6);
}
udp.endPacket();
}
byte valFromChar(char c) {
if(c >= 'a' && c <= 'f') return ((byte) (c - 'a') + 10) & 0x0F;
if(c >= 'A' && c <= 'F') return ((byte) (c - 'A') + 10) & 0x0F;
if(c >= '0' && c <= '9') return ((byte) (c - '0')) & 0x0F;
return 0;
}
/*
* Very simple converter from a String representation of a MAC address to
* 6 bytes. Does not handle errors or delimiters, but requires very little
* code space and no libraries.
*/
void macStringToBytes(const String mac, byte *bytes) {
if(mac.length() >= 12) {
for(int i = 0; i < 6; i++) {
bytes[i] = (valFromChar(mac.charAt(i*2)) << 4) | valFromChar(mac.charAt(i*2 + 1));
}
} else {
Serial.println("Incorrect MAC format.");
}
}
<|endoftext|> |
<commit_before>// Copyright (c) Burator 2014-2015
#include <QDir>
#include <QFile>
#include <QImage>
#include <QDebug>
#include <QString>
#include <QDateTime>
#include <QFileInfo>
#include <QByteArray>
#include <QStringList>
#include <QCoreApplication>
#include <QCommandLineParser>
#include <cmath>
#include <iostream>
#include "Util.h"
#include "Types.h"
#include "Global.h"
#include "Version.h"
#include "FaceDetector.h"
B_USE_NAMESPACE
// Show console output.
static const bool showOutput = true;
// Show debug/info output.
static const bool showDebug = true;
void msgHandler(QtMsgType type, const QMessageLogContext &ctx,
const QString &msg);
int main(int argc, char **argv) {
QCoreApplication app(argc, argv);
QCoreApplication::setApplicationName("Blurator");
QCoreApplication::setApplicationVersion(versionString());
qInstallMessageHandler(msgHandler);
QCommandLineParser parser;
parser.setApplicationDescription("Blur license plates and faces.");
parser.addHelpOption();
parser.addVersionOption();
parser.addPositionalArgument("paths", "Paths to images.", "paths..");
// Face detection option
QCommandLineOption detectFaces(QStringList() << "f" << "faces",
"Detect faces.");
parser.addOption(detectFaces);
// License plate detection option
QCommandLineOption detectPlates(QStringList() << "p" << "plates",
"Detect license plates.");
parser.addOption(detectPlates);
// Reply "yes" to everything option
QCommandLineOption replyYes(QStringList() << "y" << "yes",
"Automatically reply \"yes\" to all questions.");
parser.addOption(replyYes);
// Reply "no" to everything option
QCommandLineOption replyNo(QStringList() << "n" << "no",
"Automatically reply \"no\" to all questions.");
parser.addOption(replyNo);
// Verbosity option
QCommandLineOption verbosity(QStringList() << "verbose",
"Shows extra information.");
parser.addOption(verbosity);
// No-backup file option
QCommandLineOption noBackupFile(QStringList() << "no-backup",
"Don't store a backup of the original image.");
parser.addOption(noBackupFile);
parser.process(app);
const QStringList args = parser.positionalArguments();
// Check optional command line options
bool dFaces = parser.isSet(detectFaces);
bool dPlates = parser.isSet(detectPlates);
bool rYes = parser.isSet(replyYes);
bool rNo = parser.isSet(replyNo);
bool verbose = parser.isSet(verbosity);
bool noBackup = parser.isSet(noBackupFile);
// Ensure the arguments are passed.
if (args.isEmpty()) {
qCritical() << "Must provide paths to images!";
return -1;
}
if (!dPlates && !dFaces) {
qCritical() << "Must choose to detect plates and/or faces!";
return -1;
}
if (rYes && rNo) {
qCritical() << "Can't both say yes and no to everything!";
return -1;
}
// If non-null then the boolean value means reply "yes" for true and
// "no" for false.
BoolPtr autoReplyYes(nullptr);
if (rYes || rNo) {
autoReplyYes.reset(new bool);
*autoReplyYes = rYes;
}
// Find all images from the arguments.
QStringList images;
foreach (const QString &path, args) {
QFileInfo fi(path);
if (!fi.exists()) {
qWarning() << "Ignoring nonexistent file:" << path;
continue;
}
if (fi.isFile() && Util::isSupportedImage(path)) {
images << path;
}
else if (fi.isDir()) {
qWarning() << "Ignoring folder:" << path;
}
}
if (images.isEmpty()) {
qCritical() << "Found no supported images to process!";
return -1;
}
if (noBackup) {
qWarning() << "Warning no backup files will be created!";
}
QDateTime startDate = QDateTime::currentDateTime();
const int size = images.size();
qint64 faceCnt = 0, faceTot = 0;
for (int i = 0; i < size; i++) {
const QString &path = images[i];
if (dFaces) {
QFile f(path);
if (!f.open(QIODevice::ReadOnly)) {
qCritical() << "Could not read from image file!";
return -1;
}
QByteArray imageData = f.readAll();
f.close();
MatPtr image = Util::imageToMat(imageData);
if (image == nullptr) {
qCritical() << "Invalid image!";
return -1;
}
FaceDetector detector;
if (!detector.isValid()) {
qCritical() << "Could not setup facial detector.";
return -1;
}
QList<FacePtr> faces = detector.detect(image);
faceCnt = faces.size();
if (faces.isEmpty()) {
goto updateProgress;
}
faceTot += faceCnt;
// Blur each of the faces.
if (!faces.isEmpty()) {
// Save original to backup file.
if (!noBackup) {
QString bpath = Util::getBackupPath(path);
if (!QFile::copy(path, bpath)) {
qWarning() << "Could not save backup:" << bpath;
if (!Util::askProceed("Do you want to proceed?", autoReplyYes.get())) {
qWarning() << "Aborting..";
return -1;
}
}
}
Util::blurFaces(image, faces);
QImage res;
if (Util::matToImage(image, res)) {
if (!res.save(path)) {
qCritical() << "Could not save blurred image!";
}
}
else {
qCritical() << "Could not convert mat to image!";
}
}
}
// TODO: Plate detection
if (dPlates) {
qCritical() << "Plate detection not implemented yet!";
return -1;
}
updateProgress:
static int lastLen = 0;
float progress = float(i+1) / float(size) * 100.0;
QDateTime now = QDateTime::currentDateTime();
qint64 elapsed = startDate.msecsTo(now);
qint64 left = ((100.0 / progress) * elapsed) - elapsed;
bool last = (i+1 == size);
QString line1;
if (verbose) {
line1 = QString("Processed %1: %2 faces").arg(path).arg(faceCnt);
}
QString line2 = QString("[ %3/%4 (%5%) | %6 faces | %7 %8 ]")
.arg(i+1).arg(size).arg(progress, 0, 'f', 1).arg(faceTot)
.arg(!last ? Util::formatTime(left) : Util::formatTime(elapsed))
.arg(!last ? "left" : "elapsed");
QString msg =
QString("%1%2").arg(verbose ? QString("%1\n").arg(line1) : "").arg(line2);
// Rewind to beginning and output message. If at second line or
// latter then overwrite everything with empty spaces to "blank"
// out so no traces are left if the new lines are longer than
// the last ones.
{
using namespace std;
cout << '\r';
if (i > 0) {
cout << QString(lastLen, ' ').toStdString() << '\r';
}
cout << msg.toStdString();
cout.flush();
}
lastLen = msg.size();
}
return 0;
}
void msgHandler(QtMsgType type, const QMessageLogContext &ctx,
const QString &msg) {
if (!showOutput) return;
QTextStream stream(stdout);
switch (type) {
case QtDebugMsg:
if (showDebug) {
if (QString(msg) == "") {
stream << endl;
return;
}
stream << msg << endl;
}
break;
case QtWarningMsg:
stream << "(W) " << msg << endl;
break;
case QtCriticalMsg:
stream << "(E) " << msg << endl;
break;
case QtFatalMsg:
stream << "(F) " << msg << endl;
abort();
}
}
<commit_msg>Using term colors to accentuate progress and matches.<commit_after>// Copyright (c) Burator 2014-2015
#include <QDir>
#include <QFile>
#include <QImage>
#include <QDebug>
#include <QString>
#include <QDateTime>
#include <QFileInfo>
#include <QByteArray>
#include <QStringList>
#include <QCoreApplication>
#include <QCommandLineParser>
#include <cmath>
#include <iostream>
#include "Util.h"
#include "Types.h"
#include "Global.h"
#include "Version.h"
#include "FaceDetector.h"
B_USE_NAMESPACE
// Show console output.
static const bool showOutput = true;
// Show debug/info output.
static const bool showDebug = true;
void msgHandler(QtMsgType type, const QMessageLogContext &ctx,
const QString &msg);
int main(int argc, char **argv) {
QCoreApplication app(argc, argv);
QCoreApplication::setApplicationName("Blurator");
QCoreApplication::setApplicationVersion(versionString());
qInstallMessageHandler(msgHandler);
QCommandLineParser parser;
parser.setApplicationDescription("Blur license plates and faces.");
parser.addHelpOption();
parser.addVersionOption();
parser.addPositionalArgument("paths", "Paths to images.", "paths..");
// Face detection option
QCommandLineOption detectFaces(QStringList() << "f" << "faces",
"Detect faces.");
parser.addOption(detectFaces);
// License plate detection option
QCommandLineOption detectPlates(QStringList() << "p" << "plates",
"Detect license plates.");
parser.addOption(detectPlates);
// Reply "yes" to everything option
QCommandLineOption replyYes(QStringList() << "y" << "yes",
"Automatically reply \"yes\" to all questions.");
parser.addOption(replyYes);
// Reply "no" to everything option
QCommandLineOption replyNo(QStringList() << "n" << "no",
"Automatically reply \"no\" to all questions.");
parser.addOption(replyNo);
// Verbosity option
QCommandLineOption verbosity(QStringList() << "verbose",
"Shows extra information.");
parser.addOption(verbosity);
// No-backup file option
QCommandLineOption noBackupFile(QStringList() << "no-backup",
"Don't store a backup of the original image.");
parser.addOption(noBackupFile);
parser.process(app);
const QStringList args = parser.positionalArguments();
// Check optional command line options
bool dFaces = parser.isSet(detectFaces);
bool dPlates = parser.isSet(detectPlates);
bool rYes = parser.isSet(replyYes);
bool rNo = parser.isSet(replyNo);
bool verbose = parser.isSet(verbosity);
bool noBackup = parser.isSet(noBackupFile);
// Ensure the arguments are passed.
if (args.isEmpty()) {
qCritical() << "Must provide paths to images!";
return -1;
}
if (!dPlates && !dFaces) {
qCritical() << "Must choose to detect plates and/or faces!";
return -1;
}
if (rYes && rNo) {
qCritical() << "Can't both say yes and no to everything!";
return -1;
}
// If non-null then the boolean value means reply "yes" for true and
// "no" for false.
BoolPtr autoReplyYes(nullptr);
if (rYes || rNo) {
autoReplyYes.reset(new bool);
*autoReplyYes = rYes;
}
// Find all images from the arguments.
QStringList images;
foreach (const QString &path, args) {
QFileInfo fi(path);
if (!fi.exists()) {
qWarning() << "Ignoring nonexistent file:" << path;
continue;
}
if (fi.isFile() && Util::isSupportedImage(path)) {
images << path;
}
else if (fi.isDir()) {
qWarning() << "Ignoring folder:" << path;
}
}
if (images.isEmpty()) {
qCritical() << "Found no supported images to process!";
return -1;
}
if (noBackup) {
qWarning() << "Warning no backup files will be created!";
}
QDateTime startDate = QDateTime::currentDateTime();
const int size = images.size();
qint64 faceCnt = 0, faceTot = 0;
for (int i = 0; i < size; i++) {
const QString &path = images[i];
if (dFaces) {
QFile f(path);
if (!f.open(QIODevice::ReadOnly)) {
qCritical() << "Could not read from image file!";
return -1;
}
QByteArray imageData = f.readAll();
f.close();
MatPtr image = Util::imageToMat(imageData);
if (image == nullptr) {
qCritical() << "Invalid image!";
return -1;
}
FaceDetector detector;
if (!detector.isValid()) {
qCritical() << "Could not setup facial detector.";
return -1;
}
QList<FacePtr> faces = detector.detect(image);
faceCnt = faces.size();
if (faces.isEmpty()) {
goto updateProgress;
}
faceTot += faceCnt;
// Blur each of the faces.
if (!faces.isEmpty()) {
// Save original to backup file.
if (!noBackup) {
QString bpath = Util::getBackupPath(path);
if (!QFile::copy(path, bpath)) {
qWarning() << "Could not save backup:" << bpath;
if (!Util::askProceed("Do you want to proceed?", autoReplyYes.get())) {
qWarning() << "Aborting..";
return -1;
}
}
}
Util::blurFaces(image, faces);
QImage res;
if (Util::matToImage(image, res)) {
if (!res.save(path)) {
qCritical() << "Could not save blurred image!";
}
}
else {
qCritical() << "Could not convert mat to image!";
}
}
}
// TODO: Plate detection
if (dPlates) {
qCritical() << "Plate detection not implemented yet!";
return -1;
}
updateProgress:
static int lastLen = 0;
static const QString nw("\033[0;37m"); // normal and white
static const QString bw("\033[1;37m"); // bold and white
float progress = float(i+1) / float(size) * 100.0;
QDateTime now = QDateTime::currentDateTime();
qint64 elapsed = startDate.msecsTo(now);
qint64 left = ((100.0 / progress) * elapsed) - elapsed;
bool last = (i+1 == size);
QString line1;
if (verbose) {
line1 = QString("Processed %1: %2 faces").arg(path).arg(faceCnt);
}
QString line2 = QString("[ %1%2%%3 (%4/%5) | %6%7 faces blurred%8 | %9 %10 ]")
.arg(bw).arg(progress, 0, 'f', 1).arg(nw).arg(i+1).arg(size)
.arg(bw).arg(faceTot).arg(nw)
.arg(!last ? Util::formatTime(left) : Util::formatTime(elapsed))
.arg(!last ? "left" : "elapsed");
QString msg =
QString("%1%2%3").arg(nw).arg(verbose ? QString("%1\n").arg(line1) : "").arg(line2);
// Rewind to beginning and output message. If at second line or
// latter then overwrite everything with empty spaces to "blank"
// out so no traces are left if the new lines are longer than
// the last ones.
{
using namespace std;
cout << '\r';
if (i > 0) {
cout << QString(lastLen, ' ').toStdString() << '\r';
}
cout << msg.toStdString();
cout.flush();
}
lastLen = msg.size();
}
return 0;
}
void msgHandler(QtMsgType type, const QMessageLogContext &ctx,
const QString &msg) {
if (!showOutput) return;
QTextStream stream(stdout);
switch (type) {
case QtDebugMsg:
if (showDebug) {
if (QString(msg) == "") {
stream << endl;
return;
}
stream << msg << endl;
}
break;
case QtWarningMsg:
stream << "(W) " << msg << endl;
break;
case QtCriticalMsg:
stream << "(E) " << msg << endl;
break;
case QtFatalMsg:
stream << "(F) " << msg << endl;
abort();
}
}
<|endoftext|> |
<commit_before>// This file was developed by Thomas Müller <[email protected]>.
// It is published under the BSD-style license contained in the LICENSE.txt file.
#include "../include/ImageViewer.h"
#include <args.hxx>
#include <ImfThreading.h>
#include <iostream>
#include <thread>
using namespace args;
using namespace std;
TEV_NAMESPACE_BEGIN
int mainFunc(int argc, char* argv[]) {
Imf::setGlobalThreadCount(thread::hardware_concurrency());
ArgumentParser parser{
"Inspection tool for images with a high dynamic range.",
"This goes after the options.",
};
HelpFlag help(parser, "help",
"Display this help menu",
{'h', "help"}
);
ValueFlag<float> exposure{parser, "exposure",
"Initial exposure setting of the viewer.",
{'e', "exposure"},
};
PositionalList<string> imageFiles{parser, "images",
"The image files to be opened by the viewer.",
};
// Parse command line arguments and react to parsing
// errors using exceptions.
try {
parser.ParseCLI(argc, argv);
} catch (args::Help) {
std::cout << parser;
return 0;
} catch (args::ParseError e) {
std::cerr << e.what() << std::endl;
std::cerr << parser;
return -1;
} catch (args::ValidationError e) {
std::cerr << e.what() << std::endl;
std::cerr << parser;
return -2;
}
// Init nanogui application
nanogui::init();
{
auto app = make_unique<ImageViewer>();
app->drawAll();
app->setVisible(true);
// Load all images which were passed in via the command line.
for (const auto imageFile : get(imageFiles)) {
app->addImage(make_shared<Image>(imageFile));
}
// Resize the application window such that the largest image fits into it.
app->fitAllImages();
// Adjust exposure according to potential command line parameters.
if (exposure) {
app->setExposure(get(exposure));
}
nanogui::mainloop();
}
nanogui::shutdown();
return 0;
}
TEV_NAMESPACE_END
int main(int argc, char* argv[]) {
try {
tev::mainFunc(argc, argv);
} catch (const runtime_error& e) {
cerr << "Uncaught exception: "s + e.what() << endl;
return 1;
}
}
<commit_msg>Use uniform initialization in main.cpp<commit_after>// This file was developed by Thomas Müller <[email protected]>.
// It is published under the BSD-style license contained in the LICENSE.txt file.
#include "../include/ImageViewer.h"
#include <args.hxx>
#include <ImfThreading.h>
#include <iostream>
#include <thread>
using namespace args;
using namespace std;
TEV_NAMESPACE_BEGIN
int mainFunc(int argc, char* argv[]) {
Imf::setGlobalThreadCount(thread::hardware_concurrency());
ArgumentParser parser{
"Inspection tool for images with a high dynamic range.",
"This goes after the options.",
};
HelpFlag help{
parser,
"help",
"Display this help menu",
{'h', "help"},
};
ValueFlag<float> exposure{
parser,
"exposure",
"Initial exposure setting of the viewer.",
{'e', "exposure"},
};
PositionalList<string> imageFiles{
parser,
"images",
"The image files to be opened by the viewer.",
};
// Parse command line arguments and react to parsing
// errors using exceptions.
try {
parser.ParseCLI(argc, argv);
} catch (args::Help) {
std::cout << parser;
return 0;
} catch (args::ParseError e) {
std::cerr << e.what() << std::endl;
std::cerr << parser;
return -1;
} catch (args::ValidationError e) {
std::cerr << e.what() << std::endl;
std::cerr << parser;
return -2;
}
// Init nanogui application
nanogui::init();
{
auto app = make_unique<ImageViewer>();
app->drawAll();
app->setVisible(true);
// Load all images which were passed in via the command line.
if (imageFiles) {
for (const auto imageFile : get(imageFiles)) {
app->addImage(make_shared<Image>(imageFile));
}
}
// Resize the application window such that the largest image fits into it.
app->fitAllImages();
// Adjust exposure according to potential command line parameters.
if (exposure) {
app->setExposure(get(exposure));
}
nanogui::mainloop();
}
nanogui::shutdown();
return 0;
}
TEV_NAMESPACE_END
int main(int argc, char* argv[]) {
try {
tev::mainFunc(argc, argv);
} catch (const runtime_error& e) {
cerr << "Uncaught exception: "s + e.what() << endl;
return 1;
}
}
<|endoftext|> |
<commit_before>#include "vec2.hpp"
Vec2::Vec2()
{
this->x = 0.0f;
this->y = 0.0f;
}
Vec2::Vec2(float x, float y)
{
this->x = x;
this->y = y;
}
Vec2::Vec2(const Vec2& v)
{
this->x = v.x;
this->y = v.y;
}
Vec2::~Vec2()
{
}
void Vec2::operator=(const Vec2& v)
{
this->x = v.x;
this->y = v.y;
}
bool Vec2::operator==(const Vec2& v) const
{
return (this->x == v.x &&
this->y == v.y);
}
bool Vec2::operator!=(const Vec2& v) const
{
return (this->x != v.x ||
this->y != v.y);
}
float& Vec2::operator[](const int i)
{
if (i == 0) return x;
else return y;
}
const float& Vec2::operator[](const int i) const
{
if (i == 0) return x;
else return y;
}
void Vec2::operator+=(const Vec2& v)
{
x += v.x;
y += v.y;
}
void Vec2::operator-=(const Vec2& v)
{
x -= v.x;
y -= v.y;
}
void Vec2::operator*=(const float f)
{
x *= f;
y *= f;
}
void Vec2::operator/=(const float f)
{
x /= f;
y /= f;
}
Vec2 Vec2::operator-() const
{
return Vec2(-x, -y);
}
Vec2 Vec2::operator+(const Vec2& v) const
{
return Vec2(this->x + v.x, this->y + v.y);
}
Vec2 Vec2::operator-(const Vec2& v) const
{
return Vec2(this->x - v.x, this->y - v.y);
}
Vec2 Vec2::operator*(const float f) const
{
return Vec2(this->x * f, this->y * f);
}
Vec2 Vec2::operator/(const float f) const
{
return Vec2(this->x / f, this->y / f);
}
float Vec2::getMag() const
{
return std::sqrt(x * x + y * y);
}
float Vec2::getSqrMag() const
{
return x * x + y * y;
}
Vec2 Vec2::getNormalized() const
{
const float mag = getMag();
if (mag == 0.0f)
return Vec2();
return (*this) / mag;
}
void Vec2::normalize()
{
const float mag = getMag();
if (mag == 0.0f)
(*this) = Vec2();
(*this) /= mag;
}
<commit_msg>Fix missing cmath include.<commit_after>#include "vec2.hpp"
#include <cmath>
Vec2::Vec2()
{
this->x = 0.0f;
this->y = 0.0f;
}
Vec2::Vec2(float x, float y)
{
this->x = x;
this->y = y;
}
Vec2::Vec2(const Vec2& v)
{
this->x = v.x;
this->y = v.y;
}
Vec2::~Vec2()
{
}
void Vec2::operator=(const Vec2& v)
{
this->x = v.x;
this->y = v.y;
}
bool Vec2::operator==(const Vec2& v) const
{
return (this->x == v.x &&
this->y == v.y);
}
bool Vec2::operator!=(const Vec2& v) const
{
return (this->x != v.x ||
this->y != v.y);
}
float& Vec2::operator[](const int i)
{
if (i == 0) return x;
else return y;
}
const float& Vec2::operator[](const int i) const
{
if (i == 0) return x;
else return y;
}
void Vec2::operator+=(const Vec2& v)
{
x += v.x;
y += v.y;
}
void Vec2::operator-=(const Vec2& v)
{
x -= v.x;
y -= v.y;
}
void Vec2::operator*=(const float f)
{
x *= f;
y *= f;
}
void Vec2::operator/=(const float f)
{
x /= f;
y /= f;
}
Vec2 Vec2::operator-() const
{
return Vec2(-x, -y);
}
Vec2 Vec2::operator+(const Vec2& v) const
{
return Vec2(this->x + v.x, this->y + v.y);
}
Vec2 Vec2::operator-(const Vec2& v) const
{
return Vec2(this->x - v.x, this->y - v.y);
}
Vec2 Vec2::operator*(const float f) const
{
return Vec2(this->x * f, this->y * f);
}
Vec2 Vec2::operator/(const float f) const
{
return Vec2(this->x / f, this->y / f);
}
float Vec2::getMag() const
{
return std::sqrt(x * x + y * y);
}
float Vec2::getSqrMag() const
{
return x * x + y * y;
}
Vec2 Vec2::getNormalized() const
{
const float mag = getMag();
if (mag == 0.0f)
return Vec2();
return (*this) / mag;
}
void Vec2::normalize()
{
const float mag = getMag();
if (mag == 0.0f)
(*this) = Vec2();
(*this) /= mag;
}
<|endoftext|> |
<commit_before>#include <cassert>
#include <iostream>
#include <stdexcept>
#include <fstream>
#include <string>
#include "FileStream.h"
#include "ClassFile.h"
#include "InputStream.h"
#include "OutputStream.h"
#include "JarFile.h"
using namespace std;
ClassFile parseClass(InputStream* fp);
void writeClass(OutputStream* fp, ClassFile const& class_);
void dumpClass(ClassFile const& class_);
map<string, string> classRemap;
void replaceAll(std::string& str, const std::string& from, const std::string& to)
{
if(from.empty())
return;
size_t i = 0;
while((i = str.find(from, i)) != std::string::npos)
{
str.replace(i, from.length(), to);
i += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx'
}
}
void remapDescriptorQuickAndDirty(ConstPoolInfo& desc)
{
assert(desc.tag == CONSTANT::Utf8);
fprintf(stderr, "remapQND '%s'\n", desc.utf8.c_str());
for(auto& remapping : classRemap)
{
auto const from = "L" + remapping.first + ";";
auto const to = "L" + remapping.second + ";";
replaceAll(desc.utf8, from, to);
}
}
void remapFieldDescriptor(ConstPoolInfo& desc)
{
assert(desc.tag == CONSTANT::Utf8);
if(desc.utf8[0] == 'L')
{
assert(desc.utf8.back() == ';');
auto const origClassName = desc.utf8.substr(1, desc.utf8.size() - 2);
auto i_newName = classRemap.find(origClassName);
if(i_newName != classRemap.end())
desc.utf8 = "L" + i_newName->second + ";";
}
}
void remapClassReferences(ClassFile& class_)
{
for(auto& constant : class_.const_pool)
{
if(constant.tag == CONSTANT::Class)
{
auto& classNameEntry = class_.const_pool[constant.name_index];
auto const& origClassName = classNameEntry.utf8;
auto i_newName = classRemap.find(origClassName);
if(i_newName != classRemap.end())
classNameEntry.utf8 = i_newName->second;
}
else if(constant.tag == CONSTANT::NameAndType)
{
auto& typeNameEntry = class_.const_pool[constant.descriptor_index];
remapDescriptorQuickAndDirty(typeNameEntry);
}
}
for(auto& field : class_.fields)
{
auto& desc = class_.const_pool[field.descriptor_index];
remapFieldDescriptor(desc);
}
for(auto& method : class_.methods)
{
auto& desc = class_.const_pool[method.descriptor_index];
remapDescriptorQuickAndDirty(desc);
}
}
void renameFiles(map<string, ClassFile>& files)
{
for(auto& remapping : classRemap)
{
auto const from = remapping.first;
auto const to = remapping.second;
auto i_file = files.find(from);
if(i_file == files.end())
{
cerr << "Available classes: ";
for(auto& file : files)
cerr << file.first << " ";
cerr << endl;
throw runtime_error("Class '" + from + "' doesn't exist");
}
auto file = move(i_file->second);
files.erase(i_file);
files[to] = move(file);
}
}
void loadRemappings(string path)
{
ifstream fp(path);
if(!fp.is_open())
throw runtime_error("can't open '" + path + "' for reading");
string line;
while(!fp.eof())
{
string type, from, to;
fp >> type >> ws >> from >> to;
if(type == "class")
classRemap[from] = to;
}
for(auto& remapping : classRemap)
{
cout << remapping.first << " -> " << remapping.second << endl;
}
}
struct Config
{
string inputPath, outputPath;
string remapPath;
};
Config parseCommandLine(int argc, char** argv)
{
Config config;
int k = 1;
auto moreArgs = [&] () -> bool { return k < argc; };
auto popArg =
[&] () -> string {
if(!moreArgs())
throw runtime_error("unepxected end of command line");
return argv[k++];
};
while(moreArgs())
{
auto word = popArg();
if(word == "-r")
config.remapPath = popArg();
else if(word == "-i")
config.inputPath = popArg();
else if(word == "-o")
config.outputPath = popArg();
else
throw runtime_error("Unknown switch: '" + word + "'");
}
return config;
}
void processOneClass(ClassFile& class_)
{
remapClassReferences(class_);
dumpClass(class_);
}
int main(int argc, char** argv)
{
try
{
auto config = parseCommandLine(argc, argv);
if(config.inputPath.empty())
throw runtime_error("no input path specified");
if(!config.remapPath.empty())
loadRemappings(config.remapPath);
if(endsWith(config.inputPath, ".jar"))
{
JarFile jar(config.inputPath);
if(!config.remapPath.empty())
{
auto& classes = jar.getAllClasses();
for(auto& class_ : classes)
processOneClass(class_.second);
renameFiles(classes);
}
if(!config.outputPath.empty())
jar.save(config.outputPath);
}
else
{
FileStream fp;
fp.open(config.inputPath);
auto class_ = parseClass(&fp);
if(!fp.eof())
throw runtime_error("parse error");
if(!config.remapPath.empty())
processOneClass(class_);
if(!config.outputPath.empty())
{
OutputFileStream out;
out.open(config.outputPath);
writeClass(&out, class_);
}
}
return 0;
}
catch(runtime_error const& e)
{
cerr << "Fatal: " << e.what() << endl;
return 1;
}
}
<commit_msg>Add an optional 'verbose' mode<commit_after>#include <cassert>
#include <iostream>
#include <stdexcept>
#include <fstream>
#include <string>
#include "FileStream.h"
#include "ClassFile.h"
#include "InputStream.h"
#include "OutputStream.h"
#include "JarFile.h"
using namespace std;
ClassFile parseClass(InputStream* fp);
void writeClass(OutputStream* fp, ClassFile const& class_);
void dumpClass(ClassFile const& class_);
map<string, string> classRemap;
void replaceAll(std::string& str, const std::string& from, const std::string& to)
{
if(from.empty())
return;
size_t i = 0;
while((i = str.find(from, i)) != std::string::npos)
{
str.replace(i, from.length(), to);
i += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx'
}
}
void remapDescriptorQuickAndDirty(ConstPoolInfo& desc)
{
assert(desc.tag == CONSTANT::Utf8);
for(auto& remapping : classRemap)
{
auto const from = "L" + remapping.first + ";";
auto const to = "L" + remapping.second + ";";
replaceAll(desc.utf8, from, to);
}
}
void remapFieldDescriptor(ConstPoolInfo& desc)
{
assert(desc.tag == CONSTANT::Utf8);
if(desc.utf8[0] == 'L')
{
assert(desc.utf8.back() == ';');
auto const origClassName = desc.utf8.substr(1, desc.utf8.size() - 2);
auto i_newName = classRemap.find(origClassName);
if(i_newName != classRemap.end())
desc.utf8 = "L" + i_newName->second + ";";
}
}
void remapClassReferences(ClassFile& class_)
{
for(auto& constant : class_.const_pool)
{
if(constant.tag == CONSTANT::Class)
{
auto& classNameEntry = class_.const_pool[constant.name_index];
auto const& origClassName = classNameEntry.utf8;
auto i_newName = classRemap.find(origClassName);
if(i_newName != classRemap.end())
classNameEntry.utf8 = i_newName->second;
}
else if(constant.tag == CONSTANT::NameAndType)
{
auto& typeNameEntry = class_.const_pool[constant.descriptor_index];
remapDescriptorQuickAndDirty(typeNameEntry);
}
}
for(auto& field : class_.fields)
{
auto& desc = class_.const_pool[field.descriptor_index];
remapFieldDescriptor(desc);
}
for(auto& method : class_.methods)
{
auto& desc = class_.const_pool[method.descriptor_index];
remapDescriptorQuickAndDirty(desc);
}
}
void renameFiles(map<string, ClassFile>& files)
{
for(auto& remapping : classRemap)
{
auto const from = remapping.first;
auto const to = remapping.second;
auto i_file = files.find(from);
if(i_file == files.end())
{
cerr << "Available classes: ";
for(auto& file : files)
cerr << file.first << " ";
cerr << endl;
throw runtime_error("Class '" + from + "' doesn't exist");
}
auto file = move(i_file->second);
files.erase(i_file);
files[to] = move(file);
}
}
void loadRemappings(string path)
{
ifstream fp(path);
if(!fp.is_open())
throw runtime_error("can't open '" + path + "' for reading");
string line;
while(!fp.eof())
{
string type, from, to;
fp >> type >> ws >> from >> to;
if(type == "class")
classRemap[from] = to;
}
}
struct Config
{
string inputPath, outputPath;
string remapPath;
bool verbose = false;
};
Config parseCommandLine(int argc, char** argv)
{
Config config;
int k = 1;
auto moreArgs = [&] () -> bool { return k < argc; };
auto popArg =
[&] () -> string {
if(!moreArgs())
throw runtime_error("unepxected end of command line");
return argv[k++];
};
while(moreArgs())
{
auto word = popArg();
if(word == "-r")
config.remapPath = popArg();
else if(word == "-i")
config.inputPath = popArg();
else if(word == "-o")
config.outputPath = popArg();
else if(word == "-v")
config.verbose = true;
else
throw runtime_error("Unknown switch: '" + word + "'");
}
return config;
}
int main(int argc, char** argv)
{
try
{
auto config = parseCommandLine(argc, argv);
if(config.inputPath.empty())
throw runtime_error("no input path specified");
if(!config.remapPath.empty())
{
loadRemappings(config.remapPath);
if(config.verbose)
{
for(auto& remapping : classRemap)
cout << remapping.first << " -> " << remapping.second << endl;
}
}
auto processOneClass =
[&] (ClassFile& class_)
{
remapClassReferences(class_);
if(config.verbose)
dumpClass(class_);
};
if(endsWith(config.inputPath, ".jar"))
{
JarFile jar(config.inputPath);
if(!config.remapPath.empty())
{
auto& classes = jar.getAllClasses();
for(auto& class_ : classes)
processOneClass(class_.second);
renameFiles(classes);
}
if(!config.outputPath.empty())
jar.save(config.outputPath);
}
else
{
FileStream fp;
fp.open(config.inputPath);
auto class_ = parseClass(&fp);
if(!fp.eof())
throw runtime_error("parse error");
if(!config.remapPath.empty())
processOneClass(class_);
if(!config.outputPath.empty())
{
OutputFileStream out;
out.open(config.outputPath);
writeClass(&out, class_);
}
}
return 0;
}
catch(runtime_error const& e)
{
cerr << "Fatal: " << e.what() << endl;
return 1;
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2017 Tmplt <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <cstdint> // explicitly-sized integral types
#include <cstdlib> // EXIT_SUCCESS, EXIT_FAILURE
#include <exception> // std::exception
#include <memory> // std::make_shared
#include "components/command_line.hpp"
#include "components/logger.hpp"
#include "spdlog/spdlog.h"
#include "config.hpp"
int main(int argc, char *argv[])
{
using add_arg = command_line::option;
const command_line::options opts{
add_arg("-h", "--help", "Display this text and exit "),
add_arg("-v", "--version", "Print version information"),
add_arg("-l", "--log", "Set logging level to info"),
/* Exclusive arguments; cannot be combined with any other arguments. */
add_arg("-d", "--ident", "Specify an item identification (such as DOI, URL, etc.)", "IDENT"),
/* Main arguments; at least one of these are required. */
/* auto main = command_line::add_group( */
/* "main", "necessarily inclusive arguments; at least one required" */
/* ); */
add_arg("-a", "--author", "Specify authors", "AUTHOR"),
add_arg("-t", "--title", "Specify title", "TITLE"),
add_arg("-s", "--serie", "Specify serie", "SERIE"),
add_arg("-p", "--publisher", "Specify publisher", "PUBLISHER"),
/* Exact data arguments; all are optional. */
add_arg("-y", "--year", "Specify year of release", "YEAR"),
add_arg("-L", "--language", "Specify text language", "LANG"),
add_arg("-e", "--edition", "Specify item edition", "EDITION"),
add_arg("-E", "--extension", "Specify item extension", "EXT",
{"epub", "pdf", "djvu"}),
add_arg("-i", "--isbn", "Specify item ISBN", "ISBN"),
};
uint8_t exit_code = EXIT_SUCCESS;
auto logger = logger::create("main");
logger->set_pattern("%l: %v");
logger->set_level(spdlog::level::err);
try {
/* Parse command line arguments. */
std::string progname = argv[0];
std::vector<std::string> args(argv + 1, argv + argc);
auto cli = cliparser::make(std::move(progname), std::move(opts));
cli->process_arguments(args);
if (cli->has("log"))
logger->set_level(spdlog::level::info);
logger->info("the mighty eldwyrm has been summoned!");
if (cli->has("help")) {
cli->usage();
return EXIT_SUCCESS;
} else if (cli->has("version")) {
print_build_info();
return EXIT_SUCCESS;
} else if (args.empty()) {
cli->usage();
return EXIT_FAILURE;
}
} catch (const std::exception &err) {
logger->error(err.what());
exit_code = EXIT_FAILURE;
}
logger->info("dropping all loggers and returning exitval = {}", exit_code);
spdlog::drop_all();
return exit_code;
}
<commit_msg>remove unused header<commit_after>/*
* Copyright (C) 2017 Tmplt <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <cstdint> // explicitly-sized integral types
#include <cstdlib> // EXIT_SUCCESS, EXIT_FAILURE
#include <exception> // std::exception
#include "components/command_line.hpp"
#include "components/logger.hpp"
#include "spdlog/spdlog.h"
#include "config.hpp"
int main(int argc, char *argv[])
{
using add_arg = command_line::option;
const command_line::options opts{
add_arg("-h", "--help", "Display this text and exit "),
add_arg("-v", "--version", "Print version information"),
add_arg("-l", "--log", "Set logging level to info"),
/* Exclusive arguments; cannot be combined with any other arguments. */
add_arg("-d", "--ident", "Specify an item identification (such as DOI, URL, etc.)", "IDENT"),
/* Main arguments; at least one of these are required. */
/* auto main = command_line::add_group( */
/* "main", "necessarily inclusive arguments; at least one required" */
/* ); */
add_arg("-a", "--author", "Specify authors", "AUTHOR"),
add_arg("-t", "--title", "Specify title", "TITLE"),
add_arg("-s", "--serie", "Specify serie", "SERIE"),
add_arg("-p", "--publisher", "Specify publisher", "PUBLISHER"),
/* Exact data arguments; all are optional. */
add_arg("-y", "--year", "Specify year of release", "YEAR"),
add_arg("-L", "--language", "Specify text language", "LANG"),
add_arg("-e", "--edition", "Specify item edition", "EDITION"),
add_arg("-E", "--extension", "Specify item extension", "EXT",
{"epub", "pdf", "djvu"}),
add_arg("-i", "--isbn", "Specify item ISBN", "ISBN"),
};
uint8_t exit_code = EXIT_SUCCESS;
auto logger = logger::create("main");
logger->set_pattern("%l: %v");
logger->set_level(spdlog::level::err);
try {
/* Parse command line arguments. */
std::string progname = argv[0];
std::vector<std::string> args(argv + 1, argv + argc);
auto cli = cliparser::make(std::move(progname), std::move(opts));
cli->process_arguments(args);
if (cli->has("log"))
logger->set_level(spdlog::level::info);
logger->info("the mighty eldwyrm has been summoned!");
if (cli->has("help")) {
cli->usage();
return EXIT_SUCCESS;
} else if (cli->has("version")) {
print_build_info();
return EXIT_SUCCESS;
} else if (args.empty()) {
cli->usage();
return EXIT_FAILURE;
}
} catch (const std::exception &err) {
logger->error(err.what());
exit_code = EXIT_FAILURE;
}
logger->info("dropping all loggers and returning exitval = {}", exit_code);
spdlog::drop_all();
return exit_code;
}
<|endoftext|> |
<commit_before>#include <errno.h>
#include <iostream>
#include <string>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <vector>
#include <pwd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <boost/foreach.hpp>
#include <boost/tokenizer.hpp>
#include <boost/algorithm/string.hpp>
using namespace std;
using namespace boost;
string shell_prompt(); //prototype for prompt function
void cmd_interpreter(vector<string>); //prototype for command interpreter
int main (int argc, char** argv)
{
vector<string> inVector;
string input;
while(true)
{
input = shell_prompt();
//while (inVector.back() != "")
if (input == "exit")
{
cout << "Exiting rshell." << endl;
exit(0);
}
else
{
char_separator<char> sep(";|&");
string t;
tokenizer< char_separator<char> > tokens(input, sep);
BOOST_FOREACH(t, tokens);
{
inVector.push_back(t);
// cout << t << endl;
}
}
cmd_interpreter(inVector);
}
return 0;
}
void cmd_interpreter(vector<string> input)
{
// unsigned size = input.size();
string cmd = input.back();
// string file;
// string param;
int len;
// vector<string> strs;
// cout << "last " << input.back() << endl;
// for (unsigned i = 0; i < size ; i++)
// cout << "test " << input.at(i) << endl;
//parse command to seperate command and parameters
// split(strs, cmd, is_any_of(" "));
// file = strs.front();
// for (unsigned i = 1; i < strs.size(); i++)
// {
// param.append(strs.at(i));
// }
// param.append('\0'); //null termination
// const char* filec = file.c_str();
// const char* paramc = param.c_str();
len = cmd.length();
char* const paramc = new char[len + 1];
for (int i = 0; i < len; i++)
{
paramc[i] = cmd[i];
}
paramc[len] = '\0';
char* const argv[] = {paramc};
// char*const param[] = {
//
// char filec[1] = file;
// char paramc[size+1] = param;
// strcpy(filec, file.c_str());
//fork execution to it's own process
int pid = fork();
if(pid == 0)
{
int error = execvp(argv[0], argv);
if (error == -1)
{
perror("execvp"); // throw an error
exit(1);
}
else
{
execvp(argv[0], argv);
}
}
else
{
//parent wait
waitpid(-1, NULL, 0);
}
delete [] paramc;
return;
/*
int pid = fork();
if (pid == 0)
{
int error = execvp(argv[0], argv);
if (error == -1)
{
perror("execvp"); //throw an error
exit(1);
}
else
{
if (argv[0] != "exit")
{
//execute
}
exit(0);
}
}
else
{
wait(NULL);
}
*/
}
string shell_prompt()
{
string in;
//TODO - error checking for getlogin and gethostname
//implement later
/*
char name[256];
int maxlen = 64;
if (!gethostname(name, maxlen))
{
string strname(name);
cout << getlogin() << "@" << name << "$ "; //custom prompt with hostname and login name
cin >> in;
}
else
{
perror("gethostname"); //throw error if not found
}
*/
cout << "rshell$ ";
getline(cin, in);
cin.clear();
return in;
}
<commit_msg>revamped functions<commit_after>#include <errno.h>
#include <iostream>
#include <string>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <vector>
#include <pwd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <boost/foreach.hpp>
#include <boost/tokenizer.hpp>
#include <boost/algorithm/string.hpp>
using namespace std;
using namespace boost;
string shell_prompt(); //prototype for prompt function
char[] cmd_interpreter(vector<string>); //prototype for command interpreter
int main (int argc, char** argv)
{
vector<string> inVector;
string input;
while(true)
{
input = shell_prompt();
//while (inVector.back() != "")
if (input == "exit")
{
cout << "Exiting rshell." << endl;
exit(0);
}
else
{
char_separator<char> sep(";|&", "|&");
string t;
tokenizer< char_separator<char> > tokens(input, sep);
BOOST_FOREACH(t, tokens);
{
//TODO do different things depending on delimiters in vector
inVector.push_back(t);
}
cmd_interpreter(inVector);
}
}
return 0;
}
char[] cmd_interpreter(vector<string> input)
{
// unsigned size = input.size();
string cmd = input.back();
string file;
int len = cmd.length();
// char* param;
vector<string> strs;
// cout << "last " << input.back() << endl;
// for (unsigned i = 0; i < size ; i++)
// cout << "test " << input.at(i) << endl;
//parse command to seperate command and parameters
split(strs, cmd, is_any_of(" "));
// file = strs.front();
// for (unsigned i = 1; i < strs.size(); i++)
// {
// param.append(strs.at(i));
// }
// param.append('\0'); //null termination
// const char* filec = file.c_str();
// const char* paramc = param.c_str();
len = cmd.length();
file = strs.front();
cout << "file:" << file << endl;
char* const paramc = new char[len+1];
// char* const charc = new [file.length()];
for (int i = 0; i != len; i++)
{
if (i == len)
{
paramc[i] = '\0';
}
paramc[i] = strs.at(i).c_str();
}
}
int execute(char* const cmd)
{
//fork execution to it's own process
int pid = fork();
if(pid == 0)
{
int error = execvp(cmd[0], cmd);
if (error == -1)
{
perror("execvp"); // throw an error
exit(1);
return error;
}
else
{
execvp(cmd[0], cmd);
}
}
else
{
//parent wait
waitpid(-1, NULL, 0);
}
return;
}
string shell_prompt()
{
string in;
//TODO - error checking for getlogin and gethostname
//implement later
/*
char name[256];
int maxlen = 64;
if (!gethostname(name, maxlen))
{
string strname(name);
cout << getlogin() << "@" << name << "$ "; //custom prompt with hostname and login name
cin >> in;
}
else
{
perror("gethostname"); //throw error if not found
}
*/
cout << "rshell$ ";
getline(cin, in);
cin.clear();
return in;
}
<|endoftext|> |
<commit_before>#include <limits>
//#include <sys/stat.h>
#include <cerrno>
#include <cstring>
#include <system_error>
#include <iostream>
#include <fstream>
#include <vector>
/*
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <string.h>
*/
#ifdef _WIN32
#ifndef EFU_SIMPLEREADHKLMKEY_H
#include "simple_read_hklm_key.h"
#endif
#ifndef EFU_TARGET_H
#include "target.h"
#endif
#ifndef EFU_WINERRORSTRING_H
#include "win_error_string.h"
#endif
#endif
#ifndef EFU_EFULAUNCHER_H
#include "efulauncher.h"
#endif
#ifndef EFU_CURLEASY_H
#include "curleasy.h"
#endif
bool confirm()
{
char c;
do
{
std::cin >> c;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
c = static_cast<char>(tolower(c));
} while (c != 'y' && c != 'n');
return c == 'y';
}
int main(int argc, char *argv[])
{
CurlGlobalInit curl_global;
#ifdef _WIN32
std::string nwn_bin("nwmain.exe");
std::string nwn_root_dir("./");
std::ifstream nwn(nwn_root_dir + nwn_bin, std::ios::binary);
if (!nwn)
{
std::cout << "Current launcher directory not detected as NWN root"\
" directory.";
nwn_root_dir = "C:/NeverwinterNights/NWN/";
std::cout << "\nTrying " << nwn_root_dir << "... ";
nwn.open(nwn_root_dir + nwn_bin, std::ios::binary);
if (!nwn)
{
std::cout << "not found.\nSearching registry... ";
SimpleReadHKLMKey reg("SOFTWARE\\BioWare\\NWN\\Neverwinter",
"Location");
if (reg.good())
{
nwn_root_dir = reg.str();
std::cout << "key found.";
auto path_sep = nwn_root_dir.at(nwn_root_dir.size() - 1);
if (path_sep != '/' && path_sep != '\\')
{
nwn_root_dir.append("/");
}
std::cout << "\nTrying " << nwn_root_dir << "... ";
nwn.open(nwn_root_dir + nwn_bin, std::ios::binary);
if (!nwn)
{
std::cout << "not found.";
}
}
else
{
std::cout << "no key found.";
}
}
}
if (nwn)
{
std::cout << nwn_bin << " found." << std::endl;
}
else
{
std::cout << "\n\nNWN root directory not found, known"\
" options exhausted."\
"\nThe launcher will not be able to download files to the correct"\
" location or"\
"\nlaunch Neverwinter Nights, however, the launcher"\
" may still download files to"\
"\nthe current directory and you can"\
" move them manually afterwards. To avoid this"\
"\nin the future"\
" either move the launcher to the NWN root directory containing"\
"\nnwmain.exe or pass the -nwn=C:/NeverwinterNights/NWN flag to"\
" the launcher"\
"\nexecutable, substituting the correct path, quoted"\
" if it contains spaces:"\
"\n\t-nwn=\"X:/Games/Neverwinter Nights/NWN\"."\
"\n/ and \\ are interchangeable."\
"\nWould you like to download files anyway (y/n)?" << std::endl;
if (!confirm())
{
std::cout << "Exiting EfU Launcher. Goodbye!" << std::endl;
return 0;
}
nwn_root_dir = "./";
}
#endif
EfuLauncher l(argv[0],
"https://raw.github.com/commonquail/efulauncher/"\
"master/versioncheck");
if (l.has_update())
{
std::cout << "A new version of the launcher is available."\
" Would you like to download it (y/n)?" << std::endl;
bool download(confirm());
if (!download)
{
std::cout << "It is strongly recommended to always use"\
" the latest launcher. Would you like to download it (y/n)?"
<< std::endl;
download = confirm();
}
if (download)
{
// Download.
std::cout << "Downloading new launcher..." << std::endl;
if (l.get_update())
{
std::cout << "Done. Please extract and run the new launcher." << std::endl;
}
return 0;
}
}
try
{
l.stat_targets();
}
catch (std::exception &e)
{
std::cerr << e.what() << std::endl;
}
#ifdef _WIN32
if (nwn)
{
STARTUPINFO si;
PROCESS_INFORMATION pi;
::ZeroMemory(&pi, sizeof(pi));
::ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
auto nwn_path(nwn_root_dir + nwn_bin);
auto cmd_line(nwn_path + " +connect nwn.efupw.com:5121");
const std::vector<const std::string> args(argv + 1, argv + argc);
for (size_t i = 0; i < args.size(); ++i)
{
auto arg(args.at(i));
if (arg.find("-dmpass") == 0)
{
auto cmd(split(arg, '='));
if (cmd.size() == 2)
{
cmd_line.append(" -dmc +password " + cmd.at(1));
}
else
{
std::cout << "-dmpass specified but no value given. Use\n"\
"-dmpass=mypassword" <<std::endl;
}
}
else if (arg.find("-nwn") == 0)
{
auto cmd(split(arg, '='));
if (cmd.size() == 2)
{
// cmd_line.append(" -nwn " + cmd.at(1));
}
else
{
std::cout << "-nwn specified but no value given. Use\n"\
"-nwn=\"path\\to\\NWN\\directory\\" <<std::endl;
}
}
else
{
std::cout << "Ignoring unrecognized argument: " << arg
<< std::endl;
}
}
BOOL success = ::CreateProcess(
const_cast<char *>(nwn_path.c_str()),
const_cast<char *>(cmd_line.c_str()),
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
FALSE, // Set handle inheritance to FALSE
0, // No creation flags
NULL, // Use parent's environment block
const_cast<char *>(nwn_root_dir.c_str()), // Starting directory
&si, &pi);
if (success)
{
::CloseHandle(pi.hProcess);
::CloseHandle(pi.hThread);
}
else
{
WinErrorString we;
std::cout << we.str() << std::endl;
}
}
#endif
return 0;
}
<commit_msg>Notify when done statting.<commit_after>#include <limits>
//#include <sys/stat.h>
#include <cerrno>
#include <cstring>
#include <system_error>
#include <iostream>
#include <fstream>
#include <vector>
/*
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <string.h>
*/
#ifdef _WIN32
#ifndef EFU_SIMPLEREADHKLMKEY_H
#include "simple_read_hklm_key.h"
#endif
#ifndef EFU_TARGET_H
#include "target.h"
#endif
#ifndef EFU_WINERRORSTRING_H
#include "win_error_string.h"
#endif
#endif
#ifndef EFU_EFULAUNCHER_H
#include "efulauncher.h"
#endif
#ifndef EFU_CURLEASY_H
#include "curleasy.h"
#endif
bool confirm()
{
char c;
do
{
std::cin >> c;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
c = static_cast<char>(tolower(c));
} while (c != 'y' && c != 'n');
return c == 'y';
}
int main(int argc, char *argv[])
{
CurlGlobalInit curl_global;
#ifdef _WIN32
std::string nwn_bin("nwmain.exe");
std::string nwn_root_dir("./");
std::ifstream nwn(nwn_root_dir + nwn_bin, std::ios::binary);
if (!nwn)
{
std::cout << "Current launcher directory not detected as NWN root"\
" directory.";
nwn_root_dir = "C:/NeverwinterNights/NWN/";
std::cout << "\nTrying " << nwn_root_dir << "... ";
nwn.open(nwn_root_dir + nwn_bin, std::ios::binary);
if (!nwn)
{
std::cout << "not found.\nSearching registry... ";
SimpleReadHKLMKey reg("SOFTWARE\\BioWare\\NWN\\Neverwinter",
"Location");
if (reg.good())
{
nwn_root_dir = reg.str();
std::cout << "key found.";
auto path_sep = nwn_root_dir.at(nwn_root_dir.size() - 1);
if (path_sep != '/' && path_sep != '\\')
{
nwn_root_dir.append("/");
}
std::cout << "\nTrying " << nwn_root_dir << "... ";
nwn.open(nwn_root_dir + nwn_bin, std::ios::binary);
if (!nwn)
{
std::cout << "not found.";
}
}
else
{
std::cout << "no key found.";
}
}
}
if (nwn)
{
std::cout << nwn_bin << " found." << std::endl;
}
else
{
std::cout << "\n\nNWN root directory not found, known"\
" options exhausted."\
"\nThe launcher will not be able to download files to the correct"\
" location or"\
"\nlaunch Neverwinter Nights, however, the launcher"\
" may still download files to"\
"\nthe current directory and you can"\
" move them manually afterwards. To avoid this"\
"\nin the future"\
" either move the launcher to the NWN root directory containing"\
"\nnwmain.exe or pass the -nwn=C:/NeverwinterNights/NWN flag to"\
" the launcher"\
"\nexecutable, substituting the correct path, quoted"\
" if it contains spaces:"\
"\n\t-nwn=\"X:/Games/Neverwinter Nights/NWN\"."\
"\n/ and \\ are interchangeable."\
"\nWould you like to download files anyway (y/n)?" << std::endl;
if (!confirm())
{
std::cout << "Exiting EfU Launcher. Goodbye!" << std::endl;
return 0;
}
nwn_root_dir = "./";
}
#endif
EfuLauncher l(argv[0],
"https://raw.github.com/commonquail/efulauncher/"\
"master/versioncheck");
if (l.has_update())
{
std::cout << "A new version of the launcher is available."\
" Would you like to download it (y/n)?" << std::endl;
bool download(confirm());
if (!download)
{
std::cout << "It is strongly recommended to always use"\
" the latest launcher. Would you like to download it (y/n)?"
<< std::endl;
download = confirm();
}
if (download)
{
// Download.
std::cout << "Downloading new launcher..." << std::endl;
if (l.get_update())
{
std::cout << "Done. Please extract and run the new launcher." << std::endl;
}
return 0;
}
}
try
{
l.stat_targets();
std::cout << "Done." << std::endl;
}
catch (std::exception &e)
{
std::cerr << e.what() << std::endl;
}
#ifdef _WIN32
if (nwn)
{
STARTUPINFO si;
PROCESS_INFORMATION pi;
::ZeroMemory(&pi, sizeof(pi));
::ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
auto nwn_path(nwn_root_dir + nwn_bin);
auto cmd_line(nwn_path + " +connect nwn.efupw.com:5121");
const std::vector<const std::string> args(argv + 1, argv + argc);
for (size_t i = 0; i < args.size(); ++i)
{
auto arg(args.at(i));
if (arg.find("-dmpass") == 0)
{
auto cmd(split(arg, '='));
if (cmd.size() == 2)
{
cmd_line.append(" -dmc +password " + cmd.at(1));
}
else
{
std::cout << "-dmpass specified but no value given. Use\n"\
"-dmpass=mypassword" <<std::endl;
}
}
else if (arg.find("-nwn") == 0)
{
auto cmd(split(arg, '='));
if (cmd.size() == 2)
{
// cmd_line.append(" -nwn " + cmd.at(1));
}
else
{
std::cout << "-nwn specified but no value given. Use\n"\
"-nwn=\"path\\to\\NWN\\directory\\" <<std::endl;
}
}
else
{
std::cout << "Ignoring unrecognized argument: " << arg
<< std::endl;
}
}
BOOL success = ::CreateProcess(
const_cast<char *>(nwn_path.c_str()),
const_cast<char *>(cmd_line.c_str()),
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
FALSE, // Set handle inheritance to FALSE
0, // No creation flags
NULL, // Use parent's environment block
const_cast<char *>(nwn_root_dir.c_str()), // Starting directory
&si, &pi);
if (success)
{
::CloseHandle(pi.hProcess);
::CloseHandle(pi.hThread);
}
else
{
WinErrorString we;
std::cout << we.str() << std::endl;
}
}
#endif
return 0;
}
<|endoftext|> |
<commit_before>#include "common.hpp"
#include "rand.hpp"
#include <deque>
#include <algorithm>
#include <math.h>
namespace {
const float GRAVITY = 10.f;//1.33f;
const float FLAP_FORCE = 3.666f;
const double TARGET_FPS = 60.0;
const float PI = 3.14159265358979323846f;
const float SCR_W = 135.f;
const float SCR_H = 240.f;
const float GROUND_SPEED = 90.f;
const float HILLS_SPEED = 30.f;
const float CLOUDS_SPEED = 8.f;
const int GAP_HEIGHT = 4;
const float MIN_PIPE_DIST = SCR_W * 0.75f;
const float RND_PIPE_DIST = SCR_W;
sdl::tileset* g_tiles;
double last_pipe_offset = 0;
struct Bird {
Bird() {
x = SCR_W*0.33f;
revive();
}
void init(sdl::screen& screen) {
flight.frames.push_back(0);
flight.frames.push_back(1);
flight.frames.push_back(2);
flight.type = sdl::animation::looping;
flight.speed = 1.f;
flight.start();
}
void tick(double dt) {
velocity -= GRAVITY * dt;
if (velocity < -GRAVITY)
velocity = -GRAVITY;
if (velocity > GRAVITY)
velocity = GRAVITY;
y -= velocity;
if (velocity >= 0.f)
flight.speed = 12.f;
else
flight.speed = 6.f;
flight.update(dt);
if (alive && (y > SCR_H - (float)g_tiles->tilesize))
die();
}
void die() {
velocity = FLAP_FORCE;
alive = false;
}
void render(sdl::screen& screen) {
float w = (float)g_tiles->tilesize;
float h = (float)g_tiles->tilesize;
float x = this->x - w * 0.5f;
float y = this->y - h * 0.5f;
float angle = -velocity * 360.f / (PI * 8.f);
if (angle > 85.f)
angle = 85.f;
else if (angle < -30.f)
angle = -30.f;
sdl::point p(w * 0.33f, h * 0.5f);
int frame = flight.current();
if (!alive)
frame = 3;
g_tiles->draw_angle(screen, frame, sdl::point(x, y), angle, &p);
}
bool flap() {
if (!alive)
return can_revive();
if (y > (float)g_tiles->tilesize * 0.5f)
velocity = FLAP_FORCE;
return false;
}
bool can_revive() {
return y > SCR_H + (float)g_tiles->tilesize * 0.5f;
}
void revive() {
alive = true;
y = SCR_H * 0.5f;
velocity = 0.f;
num_passed = 0;
}
float x;
float y;
float velocity;
int num_passed;
bool alive;
sdl::animation flight;
};
struct Background {
Background() {
}
void init(sdl::screen& screen) {
clouds_pos = 0;
hills_pos = 0;
ground_pos = 0;
}
void tick(double dt) {
ground_pos += GROUND_SPEED * dt;
if (ground_pos > (float)g_tiles->tilesize)
ground_pos -= (float)g_tiles->tilesize;
hills_pos += HILLS_SPEED * dt;
if (hills_pos > (float)g_tiles->tilesize)
hills_pos -= (float)g_tiles->tilesize;
clouds_pos += CLOUDS_SPEED * dt;
if (clouds_pos > (float)g_tiles->tilesize)
clouds_pos -= (float)g_tiles->tilesize;
}
void render(sdl::screen& screen) {
g_tiles->draw(screen, 14, sdl::rect(0, 0, SCR_W, SCR_H));
int ntiles = ((int)SCR_W / g_tiles->tilesize) + 2;
for (int i = 0; i < ntiles; ++i) {
g_tiles->draw(screen, 10, sdl::point((float)(i*g_tiles->tilesize) - clouds_pos, SCR_H - 2*g_tiles->tilesize));
}
for (int i = 0; i < ntiles; ++i) {
g_tiles->draw(screen, 8, sdl::point((float)(i*g_tiles->tilesize) - hills_pos, SCR_H - 2*g_tiles->tilesize));
g_tiles->draw(screen, 9, sdl::point((float)((i + 1)*g_tiles->tilesize) - hills_pos, SCR_H - 2*g_tiles->tilesize));
g_tiles->draw(screen, 13, sdl::point((float)(i*g_tiles->tilesize) - ground_pos, SCR_H - g_tiles->tilesize));
}
}
float clouds_pos;
float hills_pos;
float ground_pos;
};
struct Pipe {
Pipe() {
last_pipe_offset = last_pipe_offset + MIN_PIPE_DIST + util::randint() % (int)RND_PIPE_DIST;
offset = last_pipe_offset;
int total_height = SCR_H / g_tiles->tilesize;
gap = 1 + util::randint() % (total_height - 2 - GAP_HEIGHT);
passed = 0;
outside_screen = false;
}
void tick(double dt) {
offset -= GROUND_SPEED * dt;
outside_screen = offset < -g_tiles->tilesize;
//LOG_TRACE("%f %g", offset, dt);
}
void render(sdl::screen& screen) {
if (offset - (float)g_tiles->tilesize > SCR_W || outside_screen)
return;
int total_height = SCR_H / g_tiles->tilesize + 1;
int top_height = total_height - gap - GAP_HEIGHT - 2;
int bottom_height = gap;
// render below gap
for (int i = 0; i < bottom_height; ++i) {
g_tiles->draw(screen, 4, sdl::point(offset, (top_height + GAP_HEIGHT + i) * g_tiles->tilesize));
}
// render above gap
for (int i = 0; i < top_height; ++i) {
g_tiles->draw(screen, 4, sdl::point(offset, i * g_tiles->tilesize));
}
}
bool collide(const Bird& bird) {
using sdl::rect;
float bx = bird.x - (float)g_tiles->tilesize * 0.5f;
float by = bird.y - (float)g_tiles->tilesize * 0.5f;
if (bx >= offset)
passed++;
int total_height = SCR_H / g_tiles->tilesize + 1;
int top_height = total_height - gap - GAP_HEIGHT - 2;
int bottom_height = gap;
rect top(offset, -SCR_H,
g_tiles->tilesize,
SCR_H + top_height * g_tiles->tilesize);
rect bottom(offset, (top_height + GAP_HEIGHT) * g_tiles->tilesize,
g_tiles->tilesize,
bottom_height * g_tiles->tilesize);
int inset = 4;
rect b(bx + inset/2, by + inset/2, g_tiles->tilesize - inset, g_tiles->tilesize - inset);
return bottom.has_intersection(b) || top.has_intersection(b);
}
double offset;
bool outside_screen;
int passed;
int gap;
};
struct Flappy {
Flappy() {
running = true;
}
void init() {
screen.create("flappy beard", (int)SCR_W, (int)SCR_H, 540, 960);
Mix_OpenAudio(MIX_DEFAULT_FREQUENCY, MIX_DEFAULT_FORMAT, 1, 512);
Mix_AllocateChannels(3);
sfxflap.load("data/flap.wav");
sfxgate.load("data/gate.wav");
sfxfail.load("data/fail.wav");
tiles.load(screen, "data/birds-tiles.png", 16);
g_tiles = &tiles;
npass.load(screen, "data/numbers.png");
bird.init(screen);
bg.init(screen);
reset_game();
}
void play_flap() {
sfxflap.play(0);
}
void play_gate() {
sfxgate.play(1);
}
void play_fail() {
sfxfail.play(2);
}
void handle_event(SDL_Event* e) {
if (e->type == SDL_QUIT) {
running = false;
}
else if (e->type == SDL_KEYDOWN) {
if (e->key.keysym.sym == SDLK_ESCAPE) {
running = false;
}
else if (e->key.keysym.sym == SDLK_SPACE) {
if (bird.flap() && !bird.alive) {
reset_game();
bird.revive();
}
else if (bird.alive) {
play_flap();
}
}
}
}
void reset_game() {
pipes.clear();
last_pipe_offset = SCR_W;
for (int i = 0; i < 2; ++i) {
pipes.push_back(Pipe());
}
}
void tick(double dt) {
bool was_alive = bird.alive;
if (bird.alive) {
bg.tick(dt);
for (auto& pipe : pipes)
pipe.tick(dt);
}
bird.tick(dt);
if (was_alive && !bird.alive)
play_fail();
if (bird.alive) {
for (auto& pipe : pipes) {
if (pipe.collide(bird)) {
bird.die();
play_fail();
break;
}
else if (pipe.passed == 1) {
pipe.passed++;
bird.num_passed++;
play_gate();
}
}
}
if (pipes.front().outside_screen) {
last_pipe_offset = pipes.back().offset;
pipes.pop_front();
pipes.push_back(Pipe());
}
}
void render() {
bg.render(screen);
for (auto& pipe : pipes)
pipe.render(screen);
bird.render(screen);
npass.draw(screen, bird.num_passed, sdl::point(SCR_W/2, 20));
if (!bird.alive) {
tiles.draw(screen, sdl::rect(0, 32, 40, 32),
sdl::rect(SCR_W*0.5f - 20, SCR_H*0.5f - 16, 40, 32));
if (bird.can_revive()) {
int BLINK_FREQ = TARGET_FPS;
ready_blink++;
if (ready_blink < BLINK_FREQ/2) {
tiles.draw(screen, sdl::rect(48, 32, 58, 12),
sdl::rect(SCR_W*0.5f - 29, SCR_H*0.5f + 32, 58, 12));
}
if (ready_blink > BLINK_FREQ) {
ready_blink = 0;
}
}
}
screen.present();
}
sdl::screen screen;
sdl::tileset tiles;
sdl::numbers npass;
sdl::sfx sfxflap;
sdl::sfx sfxgate;
sdl::sfx sfxfail;
Bird bird;
Background bg;
std::deque<Pipe> pipes;
int num_passed;
int ready_blink;
bool running;
};
Flappy game;
void mainloop() {
SDL_Event event;
game.init();
game.render();
Uint32 t = 0.0;
while (game.running) {
t = SDL_GetTicks();
while (SDL_PollEvent(&event)) {
game.handle_event(&event);
}
game.tick(1.0 / TARGET_FPS);
game.render();
t = SDL_GetTicks() - t;
sdl::delay_to_fps(t, (Uint32)(1000.0 / TARGET_FPS));
}
}
}
int main(int argc, char* argv[]) {
try {
util::randseed();
sdl::sdl lib;
mainloop();
}
catch (const std::exception& e) {
LOG_ERROR("%s", e.what());
}
return 0;
}
<commit_msg>Use performance counter and make things harder<commit_after>#include "common.hpp"
#include "rand.hpp"
#include <deque>
#include <algorithm>
#include <math.h>
namespace {
const float GRAVITY = 15.f;//1.33f;
const float FLAP_FORCE = 4.666f;
const double TARGET_FPS = 60.0;
const float PI = 3.14159265358979323846f;
const float SCR_W = 135.f;
const float SCR_H = 240.f;
const float BIRD_POS = SCR_W*0.25f;
const float GROUND_SPEED = 120.f;
const float HILLS_SPEED = 30.f;
const float CLOUDS_SPEED = 8.f;
const int GAP_HEIGHT = 4;
const float MIN_PIPE_DIST = SCR_W * 0.75f;
const float RND_PIPE_DIST = SCR_W;
sdl::tileset* g_tiles;
double last_pipe_offset = 0;
struct Bird {
Bird() {
x = BIRD_POS;
revive();
}
void init(sdl::screen& screen) {
flight.frames.push_back(0);
flight.frames.push_back(1);
flight.frames.push_back(2);
flight.type = sdl::animation::looping;
flight.speed = 1.f;
flight.start();
}
void tick(double dt) {
velocity -= GRAVITY * dt;
if (velocity < -GRAVITY)
velocity = -GRAVITY;
if (velocity > GRAVITY)
velocity = GRAVITY;
y -= velocity;
if (velocity >= 0.f)
flight.speed = 12.f;
else
flight.speed = 6.f;
flight.update(dt);
if (alive && (y > SCR_H - (float)g_tiles->tilesize))
die();
}
void die() {
velocity = FLAP_FORCE;
alive = false;
}
void render(sdl::screen& screen) {
float w = (float)g_tiles->tilesize;
float h = (float)g_tiles->tilesize;
float x = this->x - w * 0.5f;
float y = this->y - h * 0.5f;
float angle = -velocity * 360.f / (PI * 8.f);
if (angle > 85.f)
angle = 85.f;
else if (angle < -30.f)
angle = -30.f;
sdl::point p(w * 0.33f, h * 0.5f);
int frame = flight.current();
if (!alive)
frame = 3;
g_tiles->draw_angle(screen, frame, sdl::point(x, y), angle, &p);
}
bool flap() {
if (!alive)
return can_revive();
if (y > (float)g_tiles->tilesize * 0.5f)
velocity = FLAP_FORCE;
return false;
}
bool can_revive() {
return y > SCR_H + (float)g_tiles->tilesize * 0.5f;
}
void revive() {
alive = true;
y = SCR_H * 0.5f;
velocity = 0.f;
num_passed = 0;
}
float x;
float y;
float velocity;
int num_passed;
bool alive;
sdl::animation flight;
};
struct Background {
Background() {
}
void init(sdl::screen& screen) {
clouds_pos = 0;
hills_pos = 0;
ground_pos = 0;
}
void tick(double dt) {
ground_pos += GROUND_SPEED * dt;
if (ground_pos > (float)g_tiles->tilesize)
ground_pos -= (float)g_tiles->tilesize;
hills_pos += HILLS_SPEED * dt;
if (hills_pos > (float)g_tiles->tilesize)
hills_pos -= (float)g_tiles->tilesize;
clouds_pos += CLOUDS_SPEED * dt;
if (clouds_pos > (float)g_tiles->tilesize)
clouds_pos -= (float)g_tiles->tilesize;
}
void render(sdl::screen& screen) {
g_tiles->draw(screen, 14, sdl::rect(0, 0, SCR_W, SCR_H));
int ntiles = ((int)SCR_W / g_tiles->tilesize) + 2;
for (int i = 0; i < ntiles; ++i) {
g_tiles->draw(screen, 10, sdl::point((float)(i*g_tiles->tilesize) - clouds_pos, SCR_H - 2*g_tiles->tilesize));
}
for (int i = 0; i < ntiles; ++i) {
g_tiles->draw(screen, 8, sdl::point((float)(i*g_tiles->tilesize) - hills_pos, SCR_H - 2*g_tiles->tilesize));
g_tiles->draw(screen, 9, sdl::point((float)((i + 1)*g_tiles->tilesize) - hills_pos, SCR_H - 2*g_tiles->tilesize));
g_tiles->draw(screen, 13, sdl::point((float)(i*g_tiles->tilesize) - ground_pos, SCR_H - g_tiles->tilesize));
}
}
float clouds_pos;
float hills_pos;
float ground_pos;
};
struct Pipe {
Pipe() {
last_pipe_offset = last_pipe_offset + MIN_PIPE_DIST + util::randint() % (int)RND_PIPE_DIST;
offset = last_pipe_offset;
int total_height = SCR_H / g_tiles->tilesize;
gap = 1 + util::randint() % (total_height - 2 - GAP_HEIGHT);
passed = 0;
outside_screen = false;
}
void tick(double dt) {
offset -= GROUND_SPEED * dt;
outside_screen = offset < -g_tiles->tilesize;
//LOG_TRACE("%f %g", offset, dt);
}
void render(sdl::screen& screen) {
if (offset - (float)g_tiles->tilesize > SCR_W || outside_screen)
return;
int total_height = SCR_H / g_tiles->tilesize + 1;
int top_height = total_height - gap - GAP_HEIGHT - 2;
int bottom_height = gap;
// render below gap
for (int i = 0; i < bottom_height; ++i) {
g_tiles->draw(screen, 4, sdl::point(offset, (top_height + GAP_HEIGHT + i) * g_tiles->tilesize));
}
// render above gap
for (int i = 0; i < top_height; ++i) {
g_tiles->draw(screen, 4, sdl::point(offset, i * g_tiles->tilesize));
}
}
bool collide(const Bird& bird) {
using sdl::rect;
float bx = bird.x - (float)g_tiles->tilesize * 0.5f;
float by = bird.y - (float)g_tiles->tilesize * 0.5f;
if (bx >= offset)
passed++;
int total_height = SCR_H / g_tiles->tilesize + 1;
int top_height = total_height - gap - GAP_HEIGHT - 2;
int bottom_height = gap;
rect top(offset, -SCR_H,
g_tiles->tilesize,
SCR_H + top_height * g_tiles->tilesize);
rect bottom(offset, (top_height + GAP_HEIGHT) * g_tiles->tilesize,
g_tiles->tilesize,
bottom_height * g_tiles->tilesize);
int inset = 4;
rect b(bx + inset/2, by + inset/2, g_tiles->tilesize - inset, g_tiles->tilesize - inset);
return bottom.has_intersection(b) || top.has_intersection(b);
}
double offset;
bool outside_screen;
int passed;
int gap;
};
struct Flappy {
Flappy() {
running = true;
}
void init() {
screen.create("flappy beard", (int)SCR_W, (int)SCR_H, 540, 960);
Mix_OpenAudio(MIX_DEFAULT_FREQUENCY, MIX_DEFAULT_FORMAT, 1, 512);
Mix_AllocateChannels(3);
sfxflap.load("data/flap.wav");
sfxgate.load("data/gate.wav");
sfxfail.load("data/fail.wav");
tiles.load(screen, "data/birds-tiles.png", 16);
g_tiles = &tiles;
npass.load(screen, "data/numbers.png");
bird.init(screen);
bg.init(screen);
reset_game();
}
void play_flap() {
sfxflap.play(0);
}
void play_gate() {
sfxgate.play(1);
}
void play_fail() {
sfxfail.play(2);
}
void handle_event(SDL_Event* e) {
if (e->type == SDL_QUIT) {
running = false;
}
else if (e->type == SDL_KEYDOWN) {
if (e->key.keysym.sym == SDLK_ESCAPE) {
running = false;
}
else if (e->key.keysym.sym == SDLK_SPACE) {
if (bird.flap() && !bird.alive) {
reset_game();
bird.revive();
}
else if (bird.alive) {
play_flap();
}
}
}
}
void reset_game() {
pipes.clear();
last_pipe_offset = SCR_W;
for (int i = 0; i < 2; ++i) {
pipes.push_back(Pipe());
}
}
void tick(double dt) {
bool was_alive = bird.alive;
if (bird.alive) {
bg.tick(dt);
for (auto& pipe : pipes)
pipe.tick(dt);
}
bird.tick(dt);
if (was_alive && !bird.alive)
play_fail();
if (bird.alive) {
for (auto& pipe : pipes) {
if (pipe.collide(bird)) {
bird.die();
play_fail();
break;
}
else if (pipe.passed == 1) {
pipe.passed++;
bird.num_passed++;
play_gate();
}
}
}
if (pipes.front().outside_screen) {
last_pipe_offset = pipes.back().offset;
pipes.pop_front();
pipes.push_back(Pipe());
}
}
void render() {
bg.render(screen);
for (auto& pipe : pipes)
pipe.render(screen);
bird.render(screen);
npass.draw(screen, bird.num_passed, sdl::point(SCR_W/2, 20));
if (!bird.alive) {
tiles.draw(screen, sdl::rect(0, 32, 40, 32),
sdl::rect(SCR_W*0.5f - 20, SCR_H*0.5f - 16, 40, 32));
if (bird.can_revive()) {
int BLINK_FREQ = TARGET_FPS;
ready_blink++;
if (ready_blink < BLINK_FREQ/2) {
tiles.draw(screen, sdl::rect(48, 32, 58, 12),
sdl::rect(SCR_W*0.5f - 29, SCR_H*0.5f + 32, 58, 12));
}
if (ready_blink > BLINK_FREQ) {
ready_blink = 0;
}
}
}
screen.present();
}
sdl::screen screen;
sdl::tileset tiles;
sdl::numbers npass;
sdl::sfx sfxflap;
sdl::sfx sfxgate;
sdl::sfx sfxfail;
Bird bird;
Background bg;
std::deque<Pipe> pipes;
int num_passed;
int ready_blink;
bool running;
};
Flappy game;
void mainloop() {
SDL_Event event;
game.init();
game.render();
Uint64 t = 0.0;
Uint64 freq = SDL_GetPerformanceFrequency() / (Uint64)1000;
while (game.running) {
t = SDL_GetPerformanceCounter();
while (SDL_PollEvent(&event)) {
game.handle_event(&event);
}
game.tick(1.0 / TARGET_FPS);
game.render();
t = SDL_GetPerformanceCounter() - t;
Uint64 ms = t / freq;
sdl::delay_to_fps((Uint32)ms, (Uint32)(1000.0 / TARGET_FPS));
}
}
}
int main(int argc, char* argv[]) {
try {
util::randseed();
sdl::sdl lib;
mainloop();
}
catch (const std::exception& e) {
LOG_ERROR("%s", e.what());
}
return 0;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <sys/wait.h>
#include <vector>
#include <boost/tokenizer.hpp>
using namespace std;
using namespace boost;
int main(int argc, char **argv)
{
bool finish = false;
string login = getlogin();
if(getlogin() == NULL)
{
login = "";
perror("get login failed");
}
char hostarray[64];
gethostname(hostarray, 64);
if(gethostname(hostarray, 64) == -1)
perror("get host name failed");
//rshell loop
while(!finish)
{
int semicolon= 0;
int ampersand = 0;
int pipe = 0;
string command = "";
vector <string> commands;
//login name and host info prompt
if(getlogin() != NULL)
cout << login << "@" << hostarray;
//ready prompt
cout << "$ ";
//take in command from user
getline(cin, command);
// cout << command << endl;
//account for #
if(command.find("#") != string::npos)
{
command = command.substr(0, command.find("#"));
cout << command << endl;
}
//tokenizer init
char_separator<char> delim(" ;&|#",";&|#", keep_empty_tokens);
tokenizer< char_separator<char> > mytok(command, delim);
//token check
for(tokenizer<char_separator<char> >::iterator it = mytok.begin(); it != mytok.end(); it++)
{
cout << "(" << *it << ")" << " ";
}
cout << "listed the arguements" << endl;
string temp;
//command list formatting
for(tokenizer<char_separator<char> >::iterator it = mytok.begin(); it != mytok.end(); it++)
{
//cout << "; = " << semicolon << ", & = " << ampersand << ", | =" << pipe << endl;
//cout << *it << endl;
if(*it == ""); //do nothing
else if(*it == ";") //semicolon handling
{
semicolon++;
if(semicolon > 1)
{
perror("Syntax error. Too many ; characters.");
exit(1);
}
else if(semicolon == 1)
{
if(ampersand == 0 && pipe == 0)
{
if(temp == "")
{
perror("No arguments before connector");
exit(1);
}
commands.push_back(temp);
temp = "";
commands.push_back(";");
semicolon = 0;
}
else
{
perror("Syntax error. Improper use of connectors.");
exit(1);
}
}
}
else if(*it == "&") //ampersand handling
{
ampersand++;
if(ampersand > 2)
{
perror("Syntax error. Too many & characters");
exit(1);
}
else if(ampersand == 2)
{
if(semicolon == 0 && pipe == 0)
{
if(temp == "")
{
perror("No arguments before connector");
exit(1);
}
commands.push_back(temp);
temp = "";
commands.push_back("&&");
ampersand = 0;
}
else
{
perror("Syntax error. Improper use of connectors.");
exit(1);
}
}
}
else if(*it == "|") //pipe handling
{
pipe++;
if(pipe > 2)
{
perror("Syntax error. Too many | characters.");
exit(1);
}
else if(pipe == 2)
{
if(semicolon == 0 && ampersand == 0)
{
if(temp == "")
{
perror("No arguments before connector");
exit(1);
}
commands.push_back(temp);
temp = "";
commands.push_back("||");
pipe = 0;
}
else
{
perror("Syntax error. Improper use of connectors.");
exit(1);
}
}
}
else
{
if(semicolon != 0 || ampersand != 0 || pipe != 0)
{
perror("Syntax error. Improper use of connectors.");
//cout << semicolon << " " << ampersand << " " << pipe << endl;
return -1;
}
if(temp != "")
temp += ' ';
temp += *it;
}
}
commands.push_back(temp.c_str());
temp = "";
//check commands
for(int i = 0; i < commands.size(); i++)
{
cout << "(" << commands.at(i) << ") ";
}
cout << "combined arguements into groups" << endl;
char *input[999];
//exec commands
for(int i = 0; i < commands.size(); i++)
{
string current = "";
string word = "";
int k = 0;
for(int j = 0; j < commands.at(i).size(); j++) //itterate through letters
{
current = commands.at(i);
if(current[j] == ' ')
{
input[k] = new char[word.size() + 1];
strcpy(input[k], word.c_str());
k++;
word = "";
}
else
word += current[j]; //add letter
}
input[k] = new char[word.size() + 1];
strcpy(input[k], word.c_str());
k++;
input[k] = new char[1]; //add the NULL char *
input[k] = NULL;
if(commands.at(i) == "exit")
{
finish = true;
cout << "ending session...";
break;
}
//execute command. based off of in-lecture notes
int pid = fork();
if(pid == -1)
{
perror("There was an error with fork(). ");
exit(1);
}
else if(pid == 0) //in child
{
//cout << "CHILD IS RUNNING :D" << endl;
//cout << input << endl;
if(-1 == execvp(input[0], input))
perror("There was an error in execvp.");
exit(1);
}
else if(pid > 0) //in parent
{
if(-1 == wait(0)) //wait for child to finish
perror("There was an error with wait().");
}
}
//shell termination
if(finish)
{
cout << "good-bye!" << endl;
break;
}
}
return 0;
}
<commit_msg>begun work on connector functionality<commit_after>#include <iostream>
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <sys/wait.h>
#include <vector>
#include <boost/tokenizer.hpp>
using namespace std;
using namespace boost;
int main(int argc, char **argv)
{
bool finish = false;
string login = getlogin();
if(getlogin() == NULL)
{
login = "";
perror("get login failed");
}
char hostarray[64];
gethostname(hostarray, 64);
if(gethostname(hostarray, 64) == -1)
perror("get host name failed");
//rshell loop
while(!finish)
{
int semicolon= 0;
int ampersand = 0;
int pipe = 0;
string command = "";
vector <string> commands;
//login name and host info prompt
if(getlogin() != NULL)
cout << login << "@" << hostarray;
//ready prompt
cout << "$ ";
//take in command from user
getline(cin, command);
// cout << command << endl;
//account for #
if(command.find("#") != string::npos)
{
command = command.substr(0, command.find("#"));
cout << command << endl;
}
//tokenizer init
char_separator<char> delim(" ;&|#",";&|#", keep_empty_tokens);
tokenizer< char_separator<char> > mytok(command, delim);
//token check
for(tokenizer<char_separator<char> >::iterator it = mytok.begin(); it != mytok.end(); it++)
{
cout << "(" << *it << ")" << " ";
}
cout << "listed the arguements" << endl;
string temp;
//command list formatting
for(tokenizer<char_separator<char> >::iterator it = mytok.begin(); it != mytok.end(); it++)
{
//cout << "; = " << semicolon << ", & = " << ampersand << ", | =" << pipe << endl;
//cout << *it << endl;
if(*it == ""); //do nothing
else if(*it == ";") //semicolon handling
{
semicolon++;
if(semicolon > 1)
{
perror("Syntax error. Too many ; characters.");
exit(1);
}
else if(semicolon == 1)
{
if(ampersand == 0 && pipe == 0)
{
if(temp == "")
{
perror("No arguments before connector");
exit(1);
}
commands.push_back(temp);
temp = "";
commands.push_back(";");
semicolon = 0;
}
else
{
perror("Syntax error. Improper use of connectors.");
exit(1);
}
}
}
else if(*it == "&") //ampersand handling
{
ampersand++;
if(ampersand > 2)
{
perror("Syntax error. Too many & characters");
exit(1);
}
else if(ampersand == 2)
{
if(semicolon == 0 && pipe == 0)
{
if(temp == "")
{
perror("No arguments before connector");
exit(1);
}
commands.push_back(temp);
temp = "";
commands.push_back("&&");
ampersand = 0;
}
else
{
perror("Syntax error. Improper use of connectors.");
exit(1);
}
}
}
else if(*it == "|") //pipe handling
{
pipe++;
if(pipe > 2)
{
perror("Syntax error. Too many | characters.");
exit(1);
}
else if(pipe == 2)
{
if(semicolon == 0 && ampersand == 0)
{
if(temp == "")
{
perror("No arguments before connector");
exit(1);
}
commands.push_back(temp);
temp = "";
commands.push_back("||");
pipe = 0;
}
else
{
perror("Syntax error. Improper use of connectors.");
exit(1);
}
}
}
else
{
if(semicolon != 0 || ampersand != 0 || pipe != 0)
{
perror("Syntax error. Improper use of connectors.");
//cout << semicolon << " " << ampersand << " " << pipe << endl;
return -1;
}
if(temp != "")
temp += ' ';
temp += *it;
}
}
commands.push_back(temp.c_str());
temp = "";
//check commands
//for(int i = 0; i < commands.size(); i++)
//{
// cout << "(" << commands.at(i) << ") ";
//}
//cout << "combined arguements into groups" << endl;
char *input[999];
//exec commands
for(int i = 0; i < commands.size(); i++)
{
int *status;
int statusvalue = 1;
status = &statusvalue;
string current = "";
string word = "";
int k = 0;
for(int j = 0; j < commands.at(i).size(); j++) //itterate through letters
{
current = commands.at(i);
if(current[j] == ' ')
{
input[k] = new char[word.size() + 1];
strcpy(input[k], word.c_str());
k++;
word = "";
}
else
word += current[j]; //add letter
}
input[k] = new char[word.size() + 1];
strcpy(input[k], word.c_str());
k++;
input[k] = new char[1]; //add the NULL char *
input[k] = NULL;
if(commands.at(i) == "exit") //exit command
{
finish = true;
cout << "ending session...";
break;
}
else if(commands.at(i) == ";") //semicolon case
{
continue;
}
else if(commands.at(i) == "&&") //ampersand case
{
if(*status)
continue;
else
{
i++;
continue;
}
}
else if(commands.at(i) == "||") //pipe case
{
if(*status == 0)
continue;
else
{
i++;
continue;
}
}
//execute command. based off of in-lecture notes
int pid = fork();
if(pid == -1)
{
perror("There was an error with fork(). ");
exit(1);
}
else if(pid == 0) //in child
{
//cout << "CHILD IS RUNNING :D" << endl;
//cout << input << endl;
statusvalue = 1;
cout << "statusvalue = " << statusvalue << endl;
cout << "status = " << *status << endl;
cout << "status address = " << status << endl;
if(-1 == execvp(input[0], input))
{
statusvalue = 0;
cout << "statusvalue = " << statusvalue << endl;
cout << "status = " << *status << endl;
cout << "status address = " << status << endl;
perror("There was an error in execvp.");
}
exit(1);
}
else if(pid > 0) //in parent
{
if(-1 == wait(0)) //wait for child to finish
perror("There was an error with wait().");
cout << *status << endl;
cout << "status address = " << status << endl;
}
}
//shell termination
if(finish)
{
cout << "good-bye!" << endl;
break;
}
}
return 0;
}
<|endoftext|> |
<commit_before>/*****************************************************************************
* x266.cpp: WC Encoder Functions
*****************************************************************************
* Copyright (C) 2015-2020 x266 project
*
* Authors: Min Chen <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111, USA.
*
* This program is also available under a commercial proprietary license.
* For more information, contact us at [email protected].
*****************************************************************************/
int main(int argc, char *argv[])
{
return 0;
}
<commit_msg>[x266] command line parser<commit_after>/*****************************************************************************
* x266.cpp: WC Encoder Functions
*****************************************************************************
* Copyright (C) 2015-2020 x266 project
*
* Authors: Min Chen <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111, USA.
*
* This program is also available under a commercial proprietary license.
* For more information, contact us at [email protected].
*****************************************************************************/
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
if(argc < 5)
{
fprintf(stderr, "Usage: %s -i in_file -o out_file -w width -h height -f frames\n", argv[0]);
return 0;
}
// Encoder parameters
FILE *fpi = NULL;
FILE *fpo = NULL;
int nWidth = 0;
int nHeight = 0;
int nFrames = 0;
int i;
for(i = 1; i < argc; i++)
{
if(!_stricmp(argv[i], "-i"))
{
fpi = fopen(argv[++i], "rb");
}
else if(!_stricmp(argv[i], "-o"))
{
fpo = fopen(argv[++i], "wb");
}
else if(!_stricmp(argv[i], "-w"))
{
nWidth = atoi(argv[++i]);
}
else if(!_stricmp(argv[i], "-h"))
{
nHeight = atoi(argv[++i]);
}
else if(!_stricmp(argv[i], "-f"))
{
nFrames = atoi(argv[++i]);
}
}
// Validate parameters
if(nWidth == 0 ||
nHeight == 0 ||
fpi == NULL ||
fpo == NULL)
{
fprintf(stderr, "Parameters check failed\n");
if(fpi)
fclose(fpi);
if(fpo)
fclose(fpo);
return -1;
}
// Encode
// Cleanup
fclose(fpi);
fclose(fpo);
return 0;
}
<|endoftext|> |
<commit_before>// main.cpp
// Efficient Compression Tool
// Created by Felix Hanau on 19.12.14.
// Copyright (c) 2014-2015 Felix Hanau.
#include "main.h"
#include "support.h"
#include <thread>
#ifdef MP3_SUPPORTED
#include <id3/tag.h>
#endif
static unsigned long processedfiles;
static long long bytes;
static long long savings;
static void Usage() {
printf (
"Efficient Compression Tool\n"
"(C) 2014-2015 Felix Hanau.\n"
"Version 0.1"
#ifdef __DATE__
" compiled on %s\n"
#endif
"Folder support "
#ifdef BOOST_SUPPORTED
"enabled\n"
#else
"disabled\n"
#endif
"Losslessly optimizes JPEG and PNG images\n"
"Usage: ECT [Options] File"
#ifdef BOOST_SUPPORTED
"/Folder"
#endif
"\n"
"Options:\n"
" -M1 to -M5 Set compression level (Default: 1)\n"
" -strip Strip metadata\n"
" -progressive Use progressive encoding for JPEGs\n"
#ifdef BOOST_SUPPORTED
" -recurse Recursively search directories\n"
#endif
" -gzip Compress file with GZIP algorithm\n"
" -quiet Print only error messages\n"
" -help Print this help\n"
"Advanced Options:\n"
#ifdef BOOST_SUPPORTED
" --disable-png Disable PNG optimization\n"
" --disable-jpg Disable JPEG optimization\n"
#endif
" --strict Enable strict losslessness\n"
" --mt-deflate Use per block multithreading in Deflate\n"
" --mt-deflate=i Use per block multithreading in Deflate, use i threads\n"
//" --arithmetic Use arithmetic encoding for JPEGs, incompatible with most software\n"
#ifdef __DATE__
,__DATE__
#endif
);
}
static void ECT_ReportSavings(){
if (processedfiles){
int bk = 0;
int k = 0;
double smul = savings;
double bmul = bytes;
while (smul > 1024) {smul /= 1024; k++;}
while (bmul > 1024) {bmul /= 1024; bk++;}
char *counter;
if (k == 1) {counter = (char *)"K";}
else if (k == 2) {counter = (char *)"M";}
else if (k == 3) {counter = (char *)"G";}
else {counter = (char *)"";}
char *counter2;
if (bk == 1){counter2 = (char *)"K";}
else if (bk == 2){counter2 = (char *)"M";}
else if (bk == 3){counter2 = (char *)"G";}
else {counter2 = (char *)"";}
printf("Processed %lu file%s\n"
"Saved ", processedfiles, processedfiles > 1 ? "s":"");
if (k == 0){printf("%0.0f", smul);}
else{printf("%0.2f", smul);}
printf("%sB out of ", counter);
if (bk == 0){printf("%0.0f", bmul);}
else{printf("%0.2f", bmul);}
printf("%sB (%0.3f%%)\n", counter2, (100.0 * savings)/bytes);}
else {printf("No compatible files found\n");}
}
static int ECTGzip(const char * Infile, const int Mode, unsigned char multithreading){
if (!IsGzip(Infile)){
if (exists(((std::string)Infile).append(".gz").c_str())){
return 2;
}
ZopfliGzip(Infile, NULL, Mode, multithreading);
return 1;
}
else {
if (exists(((std::string)Infile).append(".ungz").c_str())){
return 2;
}
if (exists(((std::string)Infile).append(".ungz.gz").c_str())){
return 2;
}
ungz(Infile, ((std::string)Infile).append(".ungz").c_str());
ZopfliGzip(((std::string)Infile).append(".ungz").c_str(), NULL, Mode, multithreading);
if (filesize(((std::string)Infile).append(".ungz.gz").c_str()) < filesize(Infile)){
unlink(Infile);
rename(((std::string)Infile).append(".ungz.gz").c_str(), Infile);
}
else {
unlink(((std::string)Infile).append(".ungz.gz").c_str());
}
unlink(((std::string)Infile).append(".ungz").c_str());
return 0;
}
}
static void OptimizePNG(const char * Infile, const ECTOptions& Options){
int x = 1;
long long size = filesize(Infile);
if(Options.Mode == 5){
x = Zopflipng(Options.strip, Infile, Options.Strict, 2, 0, Options.DeflateMultithreading);
}
//Disabled as using this causes libpng warnings
//int filter = Optipng(Options.Mode, Infile, true);
int filter = Optipng(Options.Mode, Infile, false);
if (filter == -1){
return;
}
if (Options.Mode != 1){
if (Options.Mode == 5){
Zopflipng(Options.strip, Infile, Options.Strict, 5, filter, Options.DeflateMultithreading);}
else {
x = Zopflipng(Options.strip, Infile, Options.Strict, Options.Mode, filter, Options.DeflateMultithreading);}
}
else {
if (filesize(Infile) <= size){
unlink(((std::string)Infile).append(".bak").c_str());
}
else {
unlink(Infile);
rename(((std::string)Infile).append(".bak").c_str(), Infile);
}
}
if(Options.strip && x){
Optipng(0, Infile, false);
}
}
static void OptimizeJPEG(const char * Infile, const ECTOptions& Options){
mozjpegtran(Options.Arithmetic, Options.Progressive, Options.strip, Infile, Infile);
if (Options.Progressive){
long long fs = filesize(Infile);
if((Options.Mode == 1 && fs < 6142) || (Options.Mode == 2 && fs < 8192) || (Options.Mode == 3 && fs < 15360) || (Options.Mode == 4 && fs < 30720) || (Options.Mode == 5 && fs < 51200)){
mozjpegtran(Options.Arithmetic, false, Options.strip, Infile, Infile);
}
}
}
#ifdef MP3_SUPPORTED
static void OptimizeMP3(const char * Infile, const ECTOptions& Options){
ID3_Tag orig (Infile);
unsigned start = orig.Size();
ID3_Frame* picFrame = orig.Find(ID3FID_PICTURE);
if (picFrame)
{
ID3_Field* mime = picFrame->GetField(ID3FN_MIMETYPE);
if (mime){
char mimetxt[20];
mime->Get(mimetxt, 19);
printf("%s", mimetxt);
ID3_Field* pic = picFrame->GetField(ID3FN_DATA);
bool ispng = memcmp(mimetxt, "image/png", 9) == 0 || memcmp(mimetxt, "PNG", 3) == 0;
if (pic && (memcmp(mimetxt, "image/jpeg", 10) == 0 || ispng)){
pic->ToFile("out.jpg");
if (ispng){
OptimizePNG("out.jpg", Options);
}
else{
OptimizeJPEG("out.jpg", Options);
}
pic->FromFile("out.jpg");
unlink("out.jpg");
orig.SetPadding(false);
//orig.SetCompression(true);
if (orig.Size() < start){
orig.Update();
}
}
}
}
}
#endif
static void PerFileWrapper(const char * Infile, const ECTOptions& Options){
std::string Ext = Infile;
std::string x = Ext.substr(Ext.find_last_of(".") + 1);
if ((Options.PNG_ACTIVE && (x == "PNG" || x == "png")) || (Options.JPEG_ACTIVE && (x == "jpg" || x == "JPG" || x == "JPEG" || x == "jpeg")) || Options.Gzip){
long long size = filesize(Infile);
int statcompressedfile = 0;
if (size<100000000) {
if (x == "PNG" || x == "png"){
OptimizePNG(Infile, Options);
}
else if (x == "jpg" || x == "JPG" || x == "JPEG" || x == "jpeg"){
OptimizeJPEG(Infile, Options);
}
else if (Options.Gzip){
statcompressedfile = ECTGzip(Infile, Options.Mode, Options.DeflateMultithreading);
}
if(Options.SavingsCounter){
processedfiles++;
bytes += size;
if (!statcompressedfile){
savings = savings + size - filesize(Infile);
}
else if (statcompressedfile == 1){
savings = savings + size - filesize(((std::string)Infile).append(".gz").c_str());
}
}
}
else{printf("File too big\n");}
}
#ifdef MP3_SUPPORTED
else if(x == "mp3"){
OptimizeMP3(Infile, Options);
}
#endif
}
int main(int argc, const char * argv[]) {
ECTOptions Options;
Options.strip = false;
Options.Progressive = false;
Options.Mode = 1;
#ifdef BOOST_SUPPORTED
Options.Recurse = false;
#endif
Options.PNG_ACTIVE = true;
Options.JPEG_ACTIVE = true;
Options.Arithmetic = false;
Options.Gzip = false;
Options.SavingsCounter = true;
Options.Strict = false;
Options.DeflateMultithreading = 0;
if (argc >= 2){
for (int i = 1; i < argc-1; i++) {
if (strncmp(argv[i], "-strip", 2) == 0){Options.strip = true;}
else if (strncmp(argv[i], "-progressive", 2) == 0) {Options.Progressive = true;}
else if (strcmp(argv[i], "-M1") == 0) {Options.Mode = 1;}
else if (strcmp(argv[i], "-M2") == 0) {Options.Mode = 2;}
else if (strcmp(argv[i], "-M3") == 0) {Options.Mode = 3;}
else if (strcmp(argv[i], "-M4") == 0) {Options.Mode = 4;}
else if (strcmp(argv[i], "-M5") == 0) {Options.Mode = 5;}
else if (strncmp(argv[i], "-gzip", 2) == 0) {Options.Gzip = true;}
else if (strncmp(argv[i], "-help", 2) == 0) {Usage(); return 0;}
else if (strncmp(argv[i], "-quiet", 2) == 0) {Options.SavingsCounter = false;}
#ifdef BOOST_SUPPORTED
else if (strcmp(argv[i], "--disable-jpeg") == 0 || strcmp(argv[i], "--disable-jpg") == 0 ){Options.JPEG_ACTIVE = false;}
else if (strcmp(argv[i], "--disable-png") == 0){Options.PNG_ACTIVE = false;}
else if (strncmp(argv[i], "-recurse", 2) == 0) {Options.Recurse = 1;}
#endif
else if (strcmp(argv[i], "--strict") == 0) {Options.Strict = true;}
else if (strncmp(argv[i], "--mt-deflate", 12) == 0) {
if (strncmp(argv[i], "--mt-deflate=", 13) == 0){
Options.DeflateMultithreading = atoi(argv[i] + 13);
}
else{
Options.DeflateMultithreading = std::thread::hardware_concurrency();
}
}
//else if (strcmp(argv[i], "--arithmetic") == 0) {Options.Arithmetic = true;}
else {printf("Unknown flag: %s\n", argv[i]); return 0;}
}
#ifdef BOOST_SUPPORTED
if (boost::filesystem::is_regular_file(argv[argc-1])){
PerFileWrapper(argv[argc-1], Options);
}
else if (boost::filesystem::is_directory(argv[argc-1])){
if(Options.Recurse){boost::filesystem::recursive_directory_iterator a(argv[argc-1]), b;
std::vector<boost::filesystem::path> paths(a, b);
for(unsigned i = 0; i < paths.size(); i++){PerFileWrapper(paths[i].c_str(), Options);}
}
else{
boost::filesystem::directory_iterator a(argv[argc-1]), b;
std::vector<boost::filesystem::path> paths(a, b);
for(unsigned i = 0; i < paths.size(); i++){
PerFileWrapper(paths[i].c_str(), Options);}
}
}
#else
PerFileWrapper(argv[argc-1], Options);
#endif
if(Options.SavingsCounter){ECT_ReportSavings();}
}
else {Usage();}
}
<commit_msg>Set default Mode to 2<commit_after>// main.cpp
// Efficient Compression Tool
// Created by Felix Hanau on 19.12.14.
// Copyright (c) 2014-2015 Felix Hanau.
#include "main.h"
#include "support.h"
#include <thread>
#ifdef MP3_SUPPORTED
#include <id3/tag.h>
#endif
static unsigned long processedfiles;
static long long bytes;
static long long savings;
static void Usage() {
printf (
"Efficient Compression Tool\n"
"(C) 2014-2015 Felix Hanau.\n"
"Version 0.1"
#ifdef __DATE__
" compiled on %s\n"
#endif
"Folder support "
#ifdef BOOST_SUPPORTED
"enabled\n"
#else
"disabled\n"
#endif
"Losslessly optimizes JPEG and PNG images\n"
"Usage: ECT [Options] File"
#ifdef BOOST_SUPPORTED
"/Folder"
#endif
"\n"
"Options:\n"
" -M1 to -M5 Set compression level (Default: 1)\n"
" -strip Strip metadata\n"
" -progressive Use progressive encoding for JPEGs\n"
#ifdef BOOST_SUPPORTED
" -recurse Recursively search directories\n"
#endif
" -gzip Compress file with GZIP algorithm\n"
" -quiet Print only error messages\n"
" -help Print this help\n"
"Advanced Options:\n"
#ifdef BOOST_SUPPORTED
" --disable-png Disable PNG optimization\n"
" --disable-jpg Disable JPEG optimization\n"
#endif
" --strict Enable strict losslessness\n"
" --mt-deflate Use per block multithreading in Deflate\n"
" --mt-deflate=i Use per block multithreading in Deflate, use i threads\n"
//" --arithmetic Use arithmetic encoding for JPEGs, incompatible with most software\n"
#ifdef __DATE__
,__DATE__
#endif
);
}
static void ECT_ReportSavings(){
if (processedfiles){
int bk = 0;
int k = 0;
double smul = savings;
double bmul = bytes;
while (smul > 1024) {smul /= 1024; k++;}
while (bmul > 1024) {bmul /= 1024; bk++;}
char *counter;
if (k == 1) {counter = (char *)"K";}
else if (k == 2) {counter = (char *)"M";}
else if (k == 3) {counter = (char *)"G";}
else {counter = (char *)"";}
char *counter2;
if (bk == 1){counter2 = (char *)"K";}
else if (bk == 2){counter2 = (char *)"M";}
else if (bk == 3){counter2 = (char *)"G";}
else {counter2 = (char *)"";}
printf("Processed %lu file%s\n"
"Saved ", processedfiles, processedfiles > 1 ? "s":"");
if (k == 0){printf("%0.0f", smul);}
else{printf("%0.2f", smul);}
printf("%sB out of ", counter);
if (bk == 0){printf("%0.0f", bmul);}
else{printf("%0.2f", bmul);}
printf("%sB (%0.3f%%)\n", counter2, (100.0 * savings)/bytes);}
else {printf("No compatible files found\n");}
}
static int ECTGzip(const char * Infile, const int Mode, unsigned char multithreading){
if (!IsGzip(Infile)){
if (exists(((std::string)Infile).append(".gz").c_str())){
return 2;
}
ZopfliGzip(Infile, NULL, Mode, multithreading);
return 1;
}
else {
if (exists(((std::string)Infile).append(".ungz").c_str())){
return 2;
}
if (exists(((std::string)Infile).append(".ungz.gz").c_str())){
return 2;
}
ungz(Infile, ((std::string)Infile).append(".ungz").c_str());
ZopfliGzip(((std::string)Infile).append(".ungz").c_str(), NULL, Mode, multithreading);
if (filesize(((std::string)Infile).append(".ungz.gz").c_str()) < filesize(Infile)){
unlink(Infile);
rename(((std::string)Infile).append(".ungz.gz").c_str(), Infile);
}
else {
unlink(((std::string)Infile).append(".ungz.gz").c_str());
}
unlink(((std::string)Infile).append(".ungz").c_str());
return 0;
}
}
static void OptimizePNG(const char * Infile, const ECTOptions& Options){
int x = 1;
long long size = filesize(Infile);
if(Options.Mode == 5){
x = Zopflipng(Options.strip, Infile, Options.Strict, 2, 0, Options.DeflateMultithreading);
}
//Disabled as using this causes libpng warnings
//int filter = Optipng(Options.Mode, Infile, true);
int filter = Optipng(Options.Mode, Infile, false);
if (filter == -1){
return;
}
if (Options.Mode != 1){
if (Options.Mode == 5){
Zopflipng(Options.strip, Infile, Options.Strict, 5, filter, Options.DeflateMultithreading);}
else {
x = Zopflipng(Options.strip, Infile, Options.Strict, Options.Mode, filter, Options.DeflateMultithreading);}
}
else {
if (filesize(Infile) <= size){
unlink(((std::string)Infile).append(".bak").c_str());
}
else {
unlink(Infile);
rename(((std::string)Infile).append(".bak").c_str(), Infile);
}
}
if(Options.strip && x){
Optipng(0, Infile, false);
}
}
static void OptimizeJPEG(const char * Infile, const ECTOptions& Options){
mozjpegtran(Options.Arithmetic, Options.Progressive, Options.strip, Infile, Infile);
if (Options.Progressive){
long long fs = filesize(Infile);
if((Options.Mode == 1 && fs < 6142) || (Options.Mode == 2 && fs < 8192) || (Options.Mode == 3 && fs < 15360) || (Options.Mode == 4 && fs < 30720) || (Options.Mode == 5 && fs < 51200)){
mozjpegtran(Options.Arithmetic, false, Options.strip, Infile, Infile);
}
}
}
#ifdef MP3_SUPPORTED
static void OptimizeMP3(const char * Infile, const ECTOptions& Options){
ID3_Tag orig (Infile);
unsigned start = orig.Size();
ID3_Frame* picFrame = orig.Find(ID3FID_PICTURE);
if (picFrame)
{
ID3_Field* mime = picFrame->GetField(ID3FN_MIMETYPE);
if (mime){
char mimetxt[20];
mime->Get(mimetxt, 19);
printf("%s", mimetxt);
ID3_Field* pic = picFrame->GetField(ID3FN_DATA);
bool ispng = memcmp(mimetxt, "image/png", 9) == 0 || memcmp(mimetxt, "PNG", 3) == 0;
if (pic && (memcmp(mimetxt, "image/jpeg", 10) == 0 || ispng)){
pic->ToFile("out.jpg");
if (ispng){
OptimizePNG("out.jpg", Options);
}
else{
OptimizeJPEG("out.jpg", Options);
}
pic->FromFile("out.jpg");
unlink("out.jpg");
orig.SetPadding(false);
//orig.SetCompression(true);
if (orig.Size() < start){
orig.Update();
}
}
}
}
}
#endif
static void PerFileWrapper(const char * Infile, const ECTOptions& Options){
std::string Ext = Infile;
std::string x = Ext.substr(Ext.find_last_of(".") + 1);
if ((Options.PNG_ACTIVE && (x == "PNG" || x == "png")) || (Options.JPEG_ACTIVE && (x == "jpg" || x == "JPG" || x == "JPEG" || x == "jpeg")) || Options.Gzip){
long long size = filesize(Infile);
int statcompressedfile = 0;
if (size<100000000) {
if (x == "PNG" || x == "png"){
OptimizePNG(Infile, Options);
}
else if (x == "jpg" || x == "JPG" || x == "JPEG" || x == "jpeg"){
OptimizeJPEG(Infile, Options);
}
else if (Options.Gzip){
statcompressedfile = ECTGzip(Infile, Options.Mode, Options.DeflateMultithreading);
}
if(Options.SavingsCounter){
processedfiles++;
bytes += size;
if (!statcompressedfile){
savings = savings + size - filesize(Infile);
}
else if (statcompressedfile == 1){
savings = savings + size - filesize(((std::string)Infile).append(".gz").c_str());
}
}
}
else{printf("File too big\n");}
}
#ifdef MP3_SUPPORTED
else if(x == "mp3"){
OptimizeMP3(Infile, Options);
}
#endif
}
int main(int argc, const char * argv[]) {
ECTOptions Options;
Options.strip = false;
Options.Progressive = false;
Options.Mode = 2;
#ifdef BOOST_SUPPORTED
Options.Recurse = false;
#endif
Options.PNG_ACTIVE = true;
Options.JPEG_ACTIVE = true;
Options.Arithmetic = false;
Options.Gzip = false;
Options.SavingsCounter = true;
Options.Strict = false;
Options.DeflateMultithreading = 0;
if (argc >= 2){
for (int i = 1; i < argc-1; i++) {
if (strncmp(argv[i], "-strip", 2) == 0){Options.strip = true;}
else if (strncmp(argv[i], "-progressive", 2) == 0) {Options.Progressive = true;}
else if (strcmp(argv[i], "-M1") == 0) {Options.Mode = 1;}
else if (strcmp(argv[i], "-M2") == 0) {Options.Mode = 2;}
else if (strcmp(argv[i], "-M3") == 0) {Options.Mode = 3;}
else if (strcmp(argv[i], "-M4") == 0) {Options.Mode = 4;}
else if (strcmp(argv[i], "-M5") == 0) {Options.Mode = 5;}
else if (strncmp(argv[i], "-gzip", 2) == 0) {Options.Gzip = true;}
else if (strncmp(argv[i], "-help", 2) == 0) {Usage(); return 0;}
else if (strncmp(argv[i], "-quiet", 2) == 0) {Options.SavingsCounter = false;}
#ifdef BOOST_SUPPORTED
else if (strcmp(argv[i], "--disable-jpeg") == 0 || strcmp(argv[i], "--disable-jpg") == 0 ){Options.JPEG_ACTIVE = false;}
else if (strcmp(argv[i], "--disable-png") == 0){Options.PNG_ACTIVE = false;}
else if (strncmp(argv[i], "-recurse", 2) == 0) {Options.Recurse = 1;}
#endif
else if (strcmp(argv[i], "--strict") == 0) {Options.Strict = true;}
else if (strncmp(argv[i], "--mt-deflate", 12) == 0) {
if (strncmp(argv[i], "--mt-deflate=", 13) == 0){
Options.DeflateMultithreading = atoi(argv[i] + 13);
}
else{
Options.DeflateMultithreading = std::thread::hardware_concurrency();
}
}
//else if (strcmp(argv[i], "--arithmetic") == 0) {Options.Arithmetic = true;}
else {printf("Unknown flag: %s\n", argv[i]); return 0;}
}
#ifdef BOOST_SUPPORTED
if (boost::filesystem::is_regular_file(argv[argc-1])){
PerFileWrapper(argv[argc-1], Options);
}
else if (boost::filesystem::is_directory(argv[argc-1])){
if(Options.Recurse){boost::filesystem::recursive_directory_iterator a(argv[argc-1]), b;
std::vector<boost::filesystem::path> paths(a, b);
for(unsigned i = 0; i < paths.size(); i++){PerFileWrapper(paths[i].c_str(), Options);}
}
else{
boost::filesystem::directory_iterator a(argv[argc-1]), b;
std::vector<boost::filesystem::path> paths(a, b);
for(unsigned i = 0; i < paths.size(); i++){
PerFileWrapper(paths[i].c_str(), Options);}
}
}
#else
PerFileWrapper(argv[argc-1], Options);
#endif
if(Options.SavingsCounter){ECT_ReportSavings();}
}
else {Usage();}
}
<|endoftext|> |
Subsets and Splits