hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
96dbaa699af4505593828a33675e95e9fd705c74 | 12,955 | cpp | C++ | src/cli/test/test_CLI.cpp | pozsa/sarus | 5117a0da8d2171c4bf9ebc6835e0dd6b73812930 | [
"BSD-3-Clause"
] | null | null | null | src/cli/test/test_CLI.cpp | pozsa/sarus | 5117a0da8d2171c4bf9ebc6835e0dd6b73812930 | [
"BSD-3-Clause"
] | null | null | null | src/cli/test/test_CLI.cpp | pozsa/sarus | 5117a0da8d2171c4bf9ebc6835e0dd6b73812930 | [
"BSD-3-Clause"
] | null | null | null | /*
* Sarus
*
* Copyright (c) 2018-2020, ETH Zurich. All rights reserved.
*
* Please, refer to the LICENSE file in the root directory.
* SPDX-License-Identifier: BSD-3-Clause
*
*/
#include <memory>
#include <boost/filesystem.hpp>
#include "common/Utility.hpp"
#include "common/Config.hpp"
#include "common/CLIArguments.hpp"
#include "cli/CommandObjectsFactory.hpp"
#include "cli/CLI.hpp"
#include "cli/CommandHelp.hpp"
#include "cli/CommandHelpOfCommand.hpp"
#include "cli/CommandImages.hpp"
#include "cli/CommandLoad.hpp"
#include "cli/CommandPull.hpp"
#include "cli/CommandRmi.hpp"
#include "cli/CommandRun.hpp"
#include "cli/CommandSshKeygen.hpp"
#include "cli/CommandVersion.hpp"
#include "runtime/Mount.hpp"
#include "test_utility/config.hpp"
#include "test_utility/unittest_main_function.hpp"
using namespace sarus;
TEST_GROUP(CLITestGroup) {
};
std::unique_ptr<cli::Command> generateCommandFromCLIArguments(const common::CLIArguments& args) {
auto cli = cli::CLI{};
auto configRAII = test_utility::config::makeConfig();
return cli.parseCommandLine(args, configRAII.config);
}
template<class ExpectedDynamicType>
void checkCommandDynamicType(const cli::Command& command) {
CHECK(dynamic_cast<const ExpectedDynamicType*>(&command) != nullptr);
}
TEST(CLITestGroup, LogLevel) {
auto& logger = common::Logger::getInstance();
generateCommandFromCLIArguments({"sarus"});
CHECK(logger.getLevel() == common::LogLevel::WARN);
generateCommandFromCLIArguments({"sarus", "--verbose"});
CHECK(logger.getLevel() == common::LogLevel::INFO);
generateCommandFromCLIArguments({"sarus", "--debug"});
CHECK(logger.getLevel() == common::LogLevel::DEBUG);
}
TEST(CLITestGroup, CommandTypes) {
auto command = generateCommandFromCLIArguments({"sarus"});
checkCommandDynamicType<cli::CommandHelp>(*command);
command = generateCommandFromCLIArguments({"sarus", "help"});
checkCommandDynamicType<cli::CommandHelp>(*command);
command = generateCommandFromCLIArguments({"sarus", "--help"});
checkCommandDynamicType<cli::CommandHelp>(*command);
command = generateCommandFromCLIArguments({"sarus", "help", "pull"});
checkCommandDynamicType<cli::CommandHelpOfCommand>(*command);
command = generateCommandFromCLIArguments({"sarus", "images"});
checkCommandDynamicType<cli::CommandImages>(*command);
command = generateCommandFromCLIArguments({"sarus", "load", "archive.tar", "image"});
checkCommandDynamicType<cli::CommandLoad>(*command);
command = generateCommandFromCLIArguments({"sarus", "pull", "image"});
checkCommandDynamicType<cli::CommandPull>(*command);
command = generateCommandFromCLIArguments({"sarus", "rmi", "image"});
checkCommandDynamicType<cli::CommandRmi>(*command);
command = generateCommandFromCLIArguments({"sarus", "run", "image"});
checkCommandDynamicType<cli::CommandRun>(*command);
command = generateCommandFromCLIArguments({"sarus", "ssh-keygen"});
checkCommandDynamicType<cli::CommandSshKeygen>(*command);
command = generateCommandFromCLIArguments({"sarus", "version"});
checkCommandDynamicType<cli::CommandVersion>(*command);
command = generateCommandFromCLIArguments({"sarus", "--version"});
checkCommandDynamicType<cli::CommandVersion>(*command);
}
TEST(CLITestGroup, UnrecognizedGlobalOptions) {
CHECK_THROWS(common::Error, generateCommandFromCLIArguments({"sarus", "--mpi", "run"}));
CHECK_THROWS(common::Error, generateCommandFromCLIArguments({"sarus", "---run"}));
}
std::shared_ptr<common::Config> generateConfig(const common::CLIArguments& args) {
auto commandName = args.argv()[0];
auto configRAII = test_utility::config::makeConfig();
auto factory = cli::CommandObjectsFactory{};
auto command = factory.makeCommandObject(commandName, args, configRAII.config);
return configRAII.config;
}
TEST(CLITestGroup, generated_config_for_CommandLoad) {
// centralized repo
{
auto conf = generateConfig(
{"load", "--centralized-repository", "archive.tar", "library/image:tag"});
auto expectedArchivePath = boost::filesystem::absolute("archive.tar");
CHECK_EQUAL(conf->directories.tempFromCLI.empty(), true);
CHECK_EQUAL(conf->useCentralizedRepository, true);
CHECK_EQUAL(conf->archivePath.string(), expectedArchivePath.string());
CHECK_EQUAL(conf->imageID.server, std::string{"load"});
CHECK_EQUAL(conf->imageID.repositoryNamespace, std::string{"library"});
CHECK_EQUAL(conf->imageID.image, std::string{"image"});
CHECK_EQUAL(conf->imageID.tag, std::string{"tag"});
}
// temp dir
{
auto conf = generateConfig(
{"load", "--temp-dir=/custom-temp-dir", "archive.tar", "library/image:tag"});
auto expectedArchivePath = boost::filesystem::absolute("archive.tar");
CHECK_EQUAL(conf->directories.temp.string(), std::string{"/custom-temp-dir"});
CHECK_EQUAL(conf->useCentralizedRepository, false);
CHECK_EQUAL(conf->archivePath.string(), expectedArchivePath.string());
CHECK_EQUAL(conf->imageID.server, std::string{"load"});
CHECK_EQUAL(conf->imageID.repositoryNamespace, std::string{"library"});
CHECK_EQUAL(conf->imageID.image, std::string{"image"});
CHECK_EQUAL(conf->imageID.tag, std::string{"tag"});
}
}
TEST(CLITestGroup, generated_config_for_CommandPull) {
// defaults
{
auto conf = generateConfig({"pull", "ubuntu"});
CHECK(conf->directories.tempFromCLI.empty() == true);
CHECK(conf->useCentralizedRepository == false);
CHECK(conf->imageID.server == "index.docker.io");
CHECK(conf->imageID.repositoryNamespace == "library");
CHECK(conf->imageID.image == "ubuntu");
CHECK(conf->imageID.tag == "latest");
}
// centralized repo
{
auto conf = generateConfig({"pull", "--centralized-repository", "ubuntu"});
CHECK(conf->directories.tempFromCLI.empty() == true);
CHECK(conf->useCentralizedRepository == true);
CHECK(conf->imageID.server == "index.docker.io");
CHECK(conf->imageID.repositoryNamespace == "library");
CHECK(conf->imageID.image == "ubuntu");
CHECK(conf->imageID.tag == "latest");
}
// temp-dir option and custom server
{
auto conf = generateConfig(
{"pull",
"--temp-dir=/custom-temp-dir",
"my.own.server:5000/user/image:tag"});
CHECK(conf->directories.temp.string() == "/custom-temp-dir");
CHECK(conf->imageID.server == "my.own.server:5000");
CHECK(conf->imageID.repositoryNamespace == "user");
CHECK(conf->imageID.image == "image");
CHECK(conf->imageID.tag == "tag");
}
}
TEST(CLITestGroup, generated_config_for_CommandRmi) {
// defaults
{
auto conf = generateConfig({"rmi", "ubuntu"});
CHECK_EQUAL(conf->useCentralizedRepository, false);
CHECK_EQUAL(conf->imageID.server, std::string{"index.docker.io"});
CHECK_EQUAL(conf->imageID.repositoryNamespace, std::string{"library"});
CHECK_EQUAL(conf->imageID.image, std::string{"ubuntu"});
CHECK_EQUAL(conf->imageID.tag, std::string{"latest"});
}
// centralized repo
{
auto conf = generateConfig({"rmi", "--centralized-repository", "ubuntu"});
CHECK_EQUAL(conf->useCentralizedRepository, true);
CHECK_EQUAL(conf->imageID.server, std::string{"index.docker.io"});
CHECK_EQUAL(conf->imageID.repositoryNamespace, std::string{"library"});
CHECK_EQUAL(conf->imageID.image, std::string{"ubuntu"});
CHECK_EQUAL(conf->imageID.tag, std::string{"latest"});
}
}
TEST(CLITestGroup, generated_config_for_CommandRun) {
// empty values
{
auto conf = generateConfig({"run", "image"});
CHECK_EQUAL(conf->imageID.server, std::string{"index.docker.io"});
CHECK_EQUAL(conf->imageID.repositoryNamespace, std::string{"library"});
CHECK_EQUAL(conf->imageID.image, std::string{"image"});
CHECK_EQUAL(conf->imageID.tag, std::string{"latest"});
CHECK_EQUAL(conf->useCentralizedRepository, false);
CHECK_EQUAL(conf->commandRun.addInitProcess, false);
CHECK_EQUAL(conf->commandRun.mounts.size(), 1); // 1 site mount + 0 user mount
CHECK_EQUAL(conf->commandRun.useMPI, false);
CHECK_EQUAL(conf->commandRun.enableGlibcReplacement, 0);
CHECK_EQUAL(conf->commandRun.enableSSH, false);
CHECK_EQUAL(conf->commandRun.allocatePseudoTTY, false);
CHECK(conf->commandRun.execArgs.argc() == 0);
}
// centralized repository
{
auto conf = generateConfig({"run", "--centralized-repository", "image"});
CHECK_EQUAL(conf->useCentralizedRepository, true);
}
// entrypoint
{
auto conf = generateConfig({"run", "--entrypoint", "myprogram", "image"});
CHECK_EQUAL(conf->commandRun.entrypoint->argc(), 1);
CHECK_EQUAL(conf->commandRun.entrypoint->argv()[0], std::string{"myprogram"});
conf = generateConfig({"run", "--entrypoint", "myprogram --option", "image"});
CHECK_EQUAL(conf->commandRun.entrypoint->argc(), 2);
CHECK_EQUAL(conf->commandRun.entrypoint->argv()[0], std::string{"myprogram"});
CHECK_EQUAL(conf->commandRun.entrypoint->argv()[1], std::string{"--option"});
}
// init
{
auto conf = generateConfig({"run", "--init", "image"});
CHECK_EQUAL(conf->commandRun.addInitProcess, true);
}
// mount
{
auto conf = generateConfig({"run", "--mount",
"type=bind,source=/source,destination=/destination",
"image"});
CHECK_EQUAL(conf->commandRun.mounts.size(), 2); // 1 site mount + 1 user mount
}
// mpi
{
auto conf = generateConfig({"run", "--mpi", "image"});
CHECK_EQUAL(conf->commandRun.useMPI, true);
conf = generateConfig({"run", "-m", "image"});
CHECK_EQUAL(conf->commandRun.useMPI, true);
}
// ssh
{
auto conf = generateConfig({"run", "--ssh", "image"});
CHECK_EQUAL(conf->commandRun.enableSSH, true);
}
// tty
{
auto conf = generateConfig({"run", "--tty", "image"});
CHECK_EQUAL(conf->commandRun.allocatePseudoTTY, true);
conf = generateConfig({"run", "-t", "image"});
CHECK_EQUAL(conf->commandRun.allocatePseudoTTY, true);
}
// workdir
{
// long option with whitespace
auto conf = generateConfig({"run", "--workdir", "/workdir", "image"});
CHECK_EQUAL(conf->commandRun.workdir->string(), std::string{"/workdir"});
// short option with whitespace
conf = generateConfig({"run", "-w", "/workdir", "image"});
CHECK_EQUAL(conf->commandRun.workdir->string(), std::string{"/workdir"});
}
// sticky short options
{
auto conf = generateConfig({"run", "-mt", "image"});
CHECK_EQUAL(conf->commandRun.useMPI, true);
CHECK_EQUAL(conf->commandRun.allocatePseudoTTY, true);
}
// options as application arguments (for images with an entrypoint)
{
auto conf = generateConfig({"run", "image", "--option0", "--option1", "-q"});
CHECK(conf->commandRun.execArgs.argc() == 3);
CHECK_EQUAL(conf->commandRun.execArgs.argv()[0], std::string{"--option0"});
CHECK_EQUAL(conf->commandRun.execArgs.argv()[1], std::string{"--option1"});
CHECK_EQUAL(conf->commandRun.execArgs.argv()[2], std::string{"-q"});
}
// combined test
{
auto conf = generateConfig({"run",
"--workdir=/workdir",
"--mpi",
"--glibc",
"--mount=type=bind,source=/source,destination=/destination",
"ubuntu", "bash", "-c", "ls /dev |grep nvidia"});
CHECK_EQUAL(conf->commandRun.workdir->string(), std::string{"/workdir"});
CHECK_EQUAL(conf->commandRun.useMPI, true);
CHECK_EQUAL(conf->commandRun.enableGlibcReplacement, true);
CHECK_EQUAL(conf->commandRun.mounts.size(), 2); // 1 site mount + 1 user mount
CHECK_EQUAL(conf->imageID.server, std::string{"index.docker.io"});
CHECK_EQUAL(conf->imageID.repositoryNamespace, std::string{"library"});
CHECK_EQUAL(conf->imageID.image, std::string{"ubuntu"});
CHECK_EQUAL(conf->imageID.tag, std::string{"latest"});
CHECK(conf->commandRun.execArgs.argc() == 3);
CHECK_EQUAL(conf->commandRun.execArgs.argv()[0], std::string{"bash"});
CHECK_EQUAL(conf->commandRun.execArgs.argv()[1], std::string{"-c"});
CHECK_EQUAL(conf->commandRun.execArgs.argv()[2], std::string{"ls /dev |grep nvidia"});
}
}
SARUS_UNITTEST_MAIN_FUNCTION();
| 41.790323 | 97 | 0.647009 | pozsa |
96dde259489171ceacdd6bd8abccc719b69def10 | 11,428 | cpp | C++ | src/test/syscoin_snapshot_tests.cpp | vpubchain/syscoin | 72af49f24d2f4dd3628fd3ca8f7e3415534f55c8 | [
"MIT"
] | 1 | 2020-02-09T21:15:36.000Z | 2020-02-09T21:15:36.000Z | src/test/syscoin_snapshot_tests.cpp | vpubchain/syscoin | 72af49f24d2f4dd3628fd3ca8f7e3415534f55c8 | [
"MIT"
] | null | null | null | src/test/syscoin_snapshot_tests.cpp | vpubchain/syscoin | 72af49f24d2f4dd3628fd3ca8f7e3415534f55c8 | [
"MIT"
] | 1 | 2021-12-01T07:18:04.000Z | 2021-12-01T07:18:04.000Z | // Copyright (c) 2016 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 <test/test_syscoin_services.h>
#include <test/data/utxo.json.h>
#include <test/data/assetbalances.json.h>
#include <util/time.h>
#include <rpc/server.h>
#include <boost/test/unit_test.hpp>
#include <univalue.h>
#include <util/strencodings.h>
#include <core_io.h>
#include <rpc/util.h>
#include <services/rpc/assetrpc.h>
using namespace std;
int currentTx = 0;
extern UniValue read_json(const std::string& jsondata);
BOOST_FIXTURE_TEST_SUITE(syscoin_snapshot_tests, SyscoinMainNetSetup)
struct PaymentAmount
{
std::string address;
std::string amount;
};
struct AssetAllocationKey
{
std::string guid;
std::string sender;
};
void SendSnapShotPayment(const std::string &strSend)
{
currentTx++;
std::string strSendMany = "sendmany \"\" \"{" + strSend + "}\"";
CallExtRPC("mainnet1", strSendMany, false, false);
}
void GenerateSnapShot(const std::vector<PaymentAmount> &paymentAmounts)
{
// generate snapshot payments and let it mature
tfm::format(std::cout,"Generating 101 blocks to start the mainnet\n");
GenerateMainNetBlocks(101, "mainnet1");
int numberOfTxPerBlock = 250;
int totalTx = 0;
double nTotal =0;
std::string sendManyString = "";
for(unsigned int i =0;i<paymentAmounts.size();i++)
{
if(sendManyString != "")
sendManyString += ",";
sendManyString += "\\\"" + paymentAmounts[i].address + "\\\":" + paymentAmounts[i].amount;
double total;
BOOST_CHECK(ParseDouble(paymentAmounts[i].amount, &total));
nTotal += total;
totalTx++;
if(i != 0 && (i%numberOfTxPerBlock) == 0)
{
tfm::format(std::cout,"strSendMany #%d, total %f, num txs %d\n", currentTx, nTotal, totalTx);
SendSnapShotPayment(sendManyString);
GenerateMainNetBlocks(1, "mainnet1");
sendManyString = "";
nTotal = 0;
}
}
if(sendManyString != "")
{
tfm::format(std::cout,"FINAL strSendMany #%d, total %f, num txs %d\n", currentTx, nTotal, totalTx);
SendSnapShotPayment(sendManyString);
GenerateMainNetBlocks(1, "mainnet1");
}
GenerateMainNetBlocks(1, "mainnet1");
tfm::format(std::cout,"done!\n");
}
void GetUTXOs(std::vector<PaymentAmount> &paymentAmounts)
{
int countTx = 0;
int rejectTx = 0;
UniValue tests = read_json(std::string(json_tests::utxo, json_tests::utxo + sizeof(json_tests::utxo)));
for (unsigned int idx = 0; idx < tests.size(); idx++) {
UniValue test = tests[idx];
std::string strTest = test.write();
if (test.size() < 2) // Allow for extra stuff (useful for comments)
{
BOOST_ERROR("Bad test: " << strTest);
continue;
}
PaymentAmount payment;
payment.address = test[0].get_str();
CAmount amountInSys1 = test[1].get_int64();
// don't transfer less than 1 coin utxo's
if(amountInSys1 <= 0.1*COIN)
{
rejectTx++;
continue;
}
countTx++;
payment.amount = ValueFromAmount(amountInSys1).write();
paymentAmounts.push_back(payment);
}
tfm::format(std::cout,"Read %d total utxo sets, rejected %d, valid %d\n", rejectTx+countTx, rejectTx, countTx);
}
void SendSnapShotAssetAllocation(const std::string &guid, const std::string &strSend)
{
currentTx++;
// string AssetSend(const string& node, const string& name, const string& inputs, const string& witness = "''", bool completetx=true, bool bRegtest = true);
AssetSend("mainnet1", guid, "[" + strSend + "]", "''", true, false);
}
void GenerateAssetAllocationSnapshots(const std::string &guid, const UniValue &assetAllocations, int precision)
{
UniValue r;
int numberOfTxPerBlock = 249;
int totalTx = 0;
CAmount nTotal =0;
currentTx = 0;
std::string sendManyString = "";
tfm::format(std::cout,"Sending allocations for asset %s\n", guid.c_str());
for(unsigned int i =0;i<assetAllocations.size();i++)
{
const UniValue& assetAllocationObj = assetAllocations[i].get_obj();
const std::string &address = find_value(assetAllocationObj, "address").get_str();
UniValue amountValue = find_value(assetAllocationObj, "balance");
const CAmount &nBalance = AssetAmountFromValue(amountValue, precision);
const std::string &balance = ValueFromAssetAmount(nBalance, precision).write();
BOOST_CHECK_NO_THROW(r = CallExtRPC("mainnet1", "convertaddress " + address, false));
const std::string &witnessaddress = find_value(r.get_obj(), "v4address").get_str();
if(sendManyString != "")
sendManyString += ",";
sendManyString += "{\\\"address\\\":\\\"" + witnessaddress + "\\\",\\\"amount\\\":" + balance + "}";
nTotal += nBalance;
totalTx++;
if(i != 0 && (i%numberOfTxPerBlock) == 0)
{
tfm::format(std::cout,"strSendMany #%d, total %s, num txs %d\n", currentTx, ValueFromAssetAmount(nTotal, precision).write().c_str(), totalTx);
SendSnapShotAssetAllocation(guid, sendManyString);
sendManyString = "";
nTotal = 0;
}
}
if(sendManyString != "")
{
tfm::format(std::cout,"FINAL strSendMany #%d, total %s, num txs %d\n", currentTx, ValueFromAssetAmount(nTotal, precision).write().c_str(), totalTx);
SendSnapShotAssetAllocation(guid, sendManyString);
}
GenerateMainNetBlocks(1, "mainnet1");
tfm::format(std::cout,"done!\n");
}
void GetAssetBalancesAndPrepareAsset()
{
UniValue assetBalanceArray = read_json(std::string(json_tests::assetbalances, json_tests::assetbalances + sizeof(json_tests::assetbalances)));
tfm::format(std::cout,"Creating and distributing %d assets\n", assetBalanceArray.size());
for (unsigned int idx = 0; idx < assetBalanceArray.size(); idx++) {
UniValue r;
const std::string &newaddress = GetNewFundedAddress("mainnet1",false);
tfm::format(std::cout,"Got funded address %s\n", newaddress.c_str());
const UniValue &assetBalances = assetBalanceArray[idx].get_obj();
const std::string &address = find_value(assetBalances, "address").get_str();
const std::string &symbol = find_value(assetBalances, "symbol").get_str();
std::string publicvalue = find_value(assetBalances, "publicvalue").get_str();
if(publicvalue.empty())
publicvalue = "''";
const std::string &balance = find_value(assetBalances, "balance").get_str();
const std::string &total_supply = find_value(assetBalances, "total_supply").get_str();
const std::string &max_supply = find_value(assetBalances, "max_supply").get_str();
const int &nPrecision = find_value(assetBalances, "precision").get_int();
const UniValue& paymentAmounts = find_value(assetBalances, "allocations").get_array();
// string AssetNew(const string& node, const string& address, const string& pubdata = "''", const string& contract="''", const string& precision="8", const string& supply = "1", const string& maxsupply = "10", const string& updateflags = "31", const string& witness = "''", const string& symbol = "SYM", bool bRegtest = true);
std::string guid = AssetNew("mainnet1", newaddress, publicvalue, "''", itostr(nPrecision), total_supply, max_supply, "31", "''", symbol, false);
tfm::format(std::cout,"Created asset %s - %s with %d allocations\n", guid.c_str(), symbol.c_str(), paymentAmounts.size());
if(paymentAmounts.size() > 0){
GenerateAssetAllocationSnapshots(guid, paymentAmounts, nPrecision);
tfm::format(std::cout,"Created %d allocations\n", paymentAmounts.size());
}
BOOST_CHECK_NO_THROW(r = CallExtRPC("mainnet1", "convertaddress " + address, false));
const std::string &witnessaddress = find_value(r.get_obj(), "v4address").get_str();
// void AssetTransfer(const string& node, const string &tonode, const string& guid, const string& toaddress, const string& witness = "''", bool bRegtest = true);
AssetTransfer("mainnet1", "mainnet2", guid, witnessaddress, "''", false);
}
}
bool IsMainNetAlreadyCreated()
{
int height;
UniValue r;
BOOST_CHECK_NO_THROW(r = CallExtRPC("mainnet1", "getblockchaininfo", false));
height = find_value(r.get_obj(), "blocks").get_int();
return height > 1;
}
void generate_snapshot_asset_consistency_check()
{
UniValue assetInvalidatedResults, assetNowResults, assetValidatedResults;
UniValue assetAllocationsInvalidatedResults, assetAllocationsNowResults, assetAllocationsValidatedResults;
UniValue r;
tfm::format(std::cout,"Running generate_snapshot_asset_consistency_check...\n");
GenerateBlocks(5);
BOOST_CHECK_NO_THROW(r = CallExtRPC("mainnet1", "getblockcount", false, false));
string strBeforeBlockCount = r.write();
// first check around disconnect/connect by invalidating and revalidating an early block
BOOST_CHECK_NO_THROW(assetNowResults = CallExtRPC("mainnet1", "listassets " + itostr(INT_MAX) + " 0"));
BOOST_CHECK_NO_THROW(assetAllocationsNowResults = CallExtRPC("mainnet1", "listassetallocations" , itostr(INT_MAX) + ",0"));
// disconnect back to block 10 where no assets would have existed
BOOST_CHECK_NO_THROW(r = CallExtRPC("mainnet1", "getblockhash 10", false, false));
string blockHashInvalidated = r.get_str();
BOOST_CHECK_NO_THROW(CallExtRPC("mainnet1", "invalidateblock " + blockHashInvalidated, false, false));
BOOST_CHECK_NO_THROW(r = CallExtRPC("mainnet1", "getblockcount", false, false));
string strAfterBlockCount = r.write();
BOOST_CHECK_EQUAL(strAfterBlockCount, "9");
UniValue emptyResult(UniValue::VARR);
BOOST_CHECK_NO_THROW(assetInvalidatedResults = CallExtRPC("mainnet1", "listassets " + itostr(INT_MAX) + " 0", false));
BOOST_CHECK_EQUAL(assetInvalidatedResults.write(), emptyResult.write());
BOOST_CHECK_NO_THROW(assetAllocationsInvalidatedResults = CallExtRPC("mainnet1", "listassetallocations " + itostr(INT_MAX) + " 0", false));
BOOST_CHECK_EQUAL(assetAllocationsInvalidatedResults.write(), emptyResult.write());
// reconnect to tip and ensure block count matches
BOOST_CHECK_NO_THROW(CallExtRPC("mainnet1", "reconsiderblock " + blockHashInvalidated, false, false));
BOOST_CHECK_NO_THROW(r = CallExtRPC("mainnet1", "getblockcount", false, false));
string strRevalidatedBlockCount = r.write();
BOOST_CHECK_EQUAL(strRevalidatedBlockCount, strBeforeBlockCount);
BOOST_CHECK_NO_THROW(assetValidatedResults = CallExtRPC("mainnet1", "listassets " + itostr(INT_MAX) + " 0", false));
BOOST_CHECK_EQUAL(assetValidatedResults.write(), assetNowResults.write());
BOOST_CHECK_NO_THROW(assetAllocationsValidatedResults = CallExtRPC("mainnet1", "listassetallocations " + itostr(INT_MAX) + " 0", false));
BOOST_CHECK_EQUAL(assetAllocationsValidatedResults.write(), assetAllocationsNowResults.write());
// try to check after reindex
StopNode("mainnet1", false);
StartNode("mainnet1", false, "", true);
BOOST_CHECK_NO_THROW(assetValidatedResults = CallExtRPC("mainnet1", "listassets " + itostr(INT_MAX) + " 0", false));
BOOST_CHECK_EQUAL(assetValidatedResults.write(), assetNowResults.write());
BOOST_CHECK_NO_THROW(assetAllocationsValidatedResults = CallExtRPC("mainnet1", "listassetallocations " + itostr(INT_MAX) + " 0", false));
BOOST_CHECK_EQUAL(assetAllocationsValidatedResults.write(), assetAllocationsNowResults.write());
}
BOOST_AUTO_TEST_CASE (generate_and_verify_snapshot)
{
tfm::format(std::cout,"Running generate_and_verify_snapshot...\n");
std::vector<PaymentAmount> paymentAmounts;
if(!IsMainNetAlreadyCreated())
{
GetUTXOs(paymentAmounts);
GenerateSnapShot(paymentAmounts);
GetAssetBalancesAndPrepareAsset();
generate_snapshot_asset_consistency_check();
}
}
BOOST_AUTO_TEST_SUITE_END ()
| 45.16996 | 329 | 0.727511 | vpubchain |
96de8eca2039cd70a4ff2f12d9244983c282be9a | 13,550 | cpp | C++ | moveit_visual_tools/src/imarker_robot_state.cpp | errrr0501/wrs2020 | 8695eca402081d3d02dc12bb50b3ebd78464e96f | [
"MIT"
] | null | null | null | moveit_visual_tools/src/imarker_robot_state.cpp | errrr0501/wrs2020 | 8695eca402081d3d02dc12bb50b3ebd78464e96f | [
"MIT"
] | null | null | null | moveit_visual_tools/src/imarker_robot_state.cpp | errrr0501/wrs2020 | 8695eca402081d3d02dc12bb50b3ebd78464e96f | [
"MIT"
] | 2 | 2020-10-12T07:48:51.000Z | 2020-10-19T15:28:28.000Z | /*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2016, University of Colorado, Boulder
* 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 PickNik LLC 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.
*********************************************************************/
/* Author: Dave Coleman
Desc: Class to encapsule a visualized robot state that can be controlled using an interactive marker
*/
// MoveIt
#include <moveit/robot_state/conversions.h>
#include <moveit/transforms/transforms.h>
// this package
#include <moveit_visual_tools/imarker_robot_state.h>
#include <moveit_visual_tools/imarker_end_effector.h>
// C++
#include <string>
#include <utility>
#include <vector>
namespace moveit_visual_tools
{
IMarkerRobotState::IMarkerRobotState(planning_scene_monitor::PlanningSceneMonitorPtr psm,
const std::string& imarker_name, std::vector<ArmData> arm_datas,
rviz_visual_tools::colors color, const std::string& package_path)
: name_(imarker_name)
, nh_("~")
, arm_datas_(std::move(arm_datas))
, psm_(std::move(psm))
, color_(color)
, package_path_(package_path)
{
// Load Visual tools with respect to Eigen memory alignment
visual_tools_ = std::allocate_shared<moveit_visual_tools::MoveItVisualTools>(
Eigen::aligned_allocator<moveit_visual_tools::MoveItVisualTools>(), psm_->getRobotModel()->getModelFrame(),
nh_.getNamespace() + "/" + imarker_name, psm_);
// visual_tools_->setPlanningSceneMonitor(psm_);
visual_tools_->loadRobotStatePub(nh_.getNamespace() + "/imarker_" + imarker_name + "_state");
// Load robot state
imarker_state_ = std::make_shared<moveit::core::RobotState>(psm_->getRobotModel());
imarker_state_->setToDefaultValues();
// Create Marker Server
const std::string imarker_topic = nh_.getNamespace() + "/" + imarker_name + "_imarker";
imarker_server_ = std::make_shared<interactive_markers::InteractiveMarkerServer>(imarker_topic, "", false);
// Get file name
if (!getFilePath(file_path_, "imarker_" + name_ + ".csv", "config/imarkers"))
exit(-1);
// Load previous pose from file
if (!loadFromFile(file_path_))
ROS_INFO_STREAM_NAMED(name_, "Unable to find state from file, setting to default");
// Show initial robot state loaded from file
publishRobotState();
// Create each end effector
end_effectors_.resize(arm_datas_.size());
for (std::size_t i = 0; i < arm_datas_.size(); ++i)
{
std::string eef_name;
if (i == 0)
eef_name = imarker_name + "_right";
else
eef_name = imarker_name + "_left";
// respect Eigen alignment
end_effectors_[i] = std::allocate_shared<IMarkerEndEffector>(Eigen::aligned_allocator<IMarkerEndEffector>(), this,
eef_name, arm_datas_[i], color);
// Create map from eef name to object
name_to_eef_[eef_name] = end_effectors_[i];
}
// After both end effectors have been added, apply on server
imarker_server_->applyChanges();
ROS_DEBUG_STREAM_NAMED(name_, "IMarkerRobotState '" << name_ << "' Ready.");
}
bool IMarkerRobotState::loadFromFile(const std::string& file_name)
{
if (!boost::filesystem::exists(file_name))
{
ROS_WARN_STREAM_NAMED(name_, "File not found: " << file_name);
return false;
}
std::ifstream input_file(file_name);
std::string line;
if (!std::getline(input_file, line))
{
ROS_ERROR_STREAM_NAMED(name_, "Unable to read line");
return false;
}
// Get robot state from file
moveit::core::streamToRobotState(*imarker_state_, line);
return true;
}
bool IMarkerRobotState::saveToFile()
{
output_file_.open(file_path_);
moveit::core::robotStateToStream(*imarker_state_, output_file_, false);
output_file_.close();
return true;
}
void IMarkerRobotState::setIMarkerCallback(const IMarkerCallback& callback)
{
for (const IMarkerEndEffectorPtr& ee : end_effectors_)
ee->setIMarkerCallback(callback);
}
void IMarkerRobotState::setRobotState(const moveit::core::RobotStatePtr& state)
{
// Do a copy
*imarker_state_ = *state;
// Update the imarkers
for (const IMarkerEndEffectorPtr& ee : end_effectors_)
ee->setPoseFromRobotState();
}
void IMarkerRobotState::setToCurrentState()
{
// Get the real current state
planning_scene_monitor::LockedPlanningSceneRO scene(psm_); // Lock planning scene
(*imarker_state_) = scene->getCurrentState();
// Set updated pose from robot state
for (std::size_t i = 0; i < arm_datas_.size(); ++i)
end_effectors_[i]->setPoseFromRobotState();
// Show new state
visual_tools_->publishRobotState(imarker_state_, color_);
}
bool IMarkerRobotState::setToRandomState(double clearance)
{
static const std::size_t MAX_ATTEMPTS = 1000;
for (std::size_t attempt = 0; attempt < MAX_ATTEMPTS; ++attempt)
{
// Set each planning group to random
for (std::size_t i = 0; i < arm_datas_.size(); ++i)
{
imarker_state_->setToRandomPositions(arm_datas_[i].jmg_);
}
// Update transforms
imarker_state_->update();
planning_scene_monitor::LockedPlanningSceneRO planning_scene(psm_); // Read only lock
// Collision check
// which planning group to collision check, "" is everything
static const bool verbose = false;
if (planning_scene->isStateValid(*imarker_state_, "", verbose))
{
// Check clearance
if (clearance > 0)
{
// which planning group to collision check, "" is everything
if (planning_scene->distanceToCollision(*imarker_state_) < clearance)
{
continue; // clearance is not enough
}
}
ROS_INFO_STREAM_NAMED(name_, "Found valid random robot state after " << attempt << " attempts");
// Set updated pose from robot state
for (std::size_t i = 0; i < arm_datas_.size(); ++i)
end_effectors_[i]->setPoseFromRobotState();
// Send to imarker
for (std::size_t i = 0; i < arm_datas_.size(); ++i)
end_effectors_[i]->sendUpdatedIMarkerPose();
return true;
}
if (attempt == 100)
ROS_WARN_STREAM_NAMED(name_, "Taking long time to find valid random state");
}
ROS_ERROR_STREAM_NAMED(name_, "Unable to find valid random robot state for imarker after " << MAX_ATTEMPTS << " attem"
"pts");
return false;
}
bool IMarkerRobotState::isStateValid(bool verbose)
{
// Update transforms
imarker_state_->update();
planning_scene_monitor::LockedPlanningSceneRO planning_scene(psm_); // Read only lock
// which planning group to collision check, "" is everything
return planning_scene->isStateValid(*imarker_state_, "", verbose);
}
void IMarkerRobotState::publishRobotState()
{
visual_tools_->publishRobotState(imarker_state_, color_);
}
moveit_visual_tools::MoveItVisualToolsPtr IMarkerRobotState::getVisualTools()
{
return visual_tools_;
}
bool IMarkerRobotState::getFilePath(std::string& file_path, const std::string& file_name,
const std::string& subdirectory) const
{
namespace fs = boost::filesystem;
// Check that the directory exists, if not, create it
fs::path rootPath = fs::path(package_path_);
rootPath = rootPath / fs::path(subdirectory);
boost::system::error_code returnedError;
fs::create_directories(rootPath, returnedError);
if (returnedError)
{
// did not successfully create directories
ROS_ERROR("Unable to create directory %s", subdirectory.c_str());
return false;
}
// directories successfully created, append the group name as the file name
rootPath = rootPath / fs::path(file_name);
file_path = rootPath.string();
// ROS_DEBUG_STREAM_NAMED(name_, "Config file: " << file_path);
return true;
}
bool IMarkerRobotState::setFromPoses(const EigenSTL::vector_Isometry3d& poses,
const moveit::core::JointModelGroup* group)
{
std::vector<std::string> tips;
for (std::size_t i = 0; i < arm_datas_.size(); ++i)
tips.push_back(arm_datas_[i].ee_link_->getName());
// ROS_DEBUG_STREAM_NAMED(name_, "First pose should be for joint model group: " << arm_datas_[0].ee_link_->getName());
const double timeout = 1.0 / 30.0; // 30 fps
// Optionally collision check
moveit::core::GroupStateValidityCallbackFn constraint_fn;
#if 1
bool collision_checking_verbose_ = false;
bool only_check_self_collision_ = false;
// TODO(davetcoleman): this is currently not working, the locking seems to cause segfaults
// TODO(davetcoleman): change to std shared_ptr
boost::scoped_ptr<planning_scene_monitor::LockedPlanningSceneRO> ls;
ls.reset(new planning_scene_monitor::LockedPlanningSceneRO(psm_));
constraint_fn = boost::bind(&isIKStateValid, static_cast<const planning_scene::PlanningSceneConstPtr&>(*ls).get(),
collision_checking_verbose_, only_check_self_collision_, visual_tools_, _1, _2, _3);
#endif
// Solve
std::size_t outer_attempts = 20;
for (std::size_t i = 0; i < outer_attempts; ++i)
{
if (!imarker_state_->setFromIK(group, poses, tips, timeout, constraint_fn))
{
ROS_DEBUG_STREAM_NAMED(name_, "Failed to find dual arm pose, trying again");
// Re-seed
imarker_state_->setToRandomPositions(group);
}
else
{
ROS_DEBUG_STREAM_NAMED(name_, "Found IK solution");
// Visualize robot
publishRobotState();
// Update the imarkers
for (const IMarkerEndEffectorPtr& ee : end_effectors_)
ee->setPoseFromRobotState();
return true;
}
}
ROS_ERROR_STREAM_NAMED(name_, "Failed to find dual arm pose");
return false;
}
} // namespace moveit_visual_tools
namespace
{
bool isIKStateValid(const planning_scene::PlanningScene* planning_scene, bool verbose, bool only_check_self_collision,
const moveit_visual_tools::MoveItVisualToolsPtr& visual_tools,
moveit::core::RobotState* robot_state, const moveit::core::JointModelGroup* group,
const double* ik_solution)
{
// Apply IK solution to robot state
robot_state->setJointGroupPositions(group, ik_solution);
robot_state->update();
#if 0 // Ensure there are objects in the planning scene
const std::size_t num_collision_objects = planning_scene->getCollisionEnv()->getWorld()->size();
if (num_collision_objects == 0)
{
ROS_ERROR_STREAM_NAMED("imarker_robot_state", "No collision objects exist in world, you need at least a table "
"modeled for the controller to work");
ROS_ERROR_STREAM_NAMED("imarker_robot_state", "To fix this, relaunch the teleop/head tracking/whatever MoveIt "
"node to publish the collision objects");
return false;
}
#endif
if (!planning_scene)
{
ROS_ERROR_STREAM_NAMED("imarker_robot_state", "No planning scene provided");
return false;
}
if (only_check_self_collision)
{
// No easy API exists for only checking self-collision, so we do it here.
// TODO(davetcoleman): move this into planning_scene.cpp
collision_detection::CollisionRequest req;
req.verbose = verbose;
req.group_name = group->getName();
collision_detection::CollisionResult res;
planning_scene->checkSelfCollision(req, res, *robot_state);
if (!res.collision)
return true; // not in collision
}
else if (!planning_scene->isStateColliding(*robot_state, group->getName()))
return true; // not in collision
// Display more info about the collision
if (verbose)
{
visual_tools->publishRobotState(*robot_state, rviz_visual_tools::RED);
planning_scene->isStateColliding(*robot_state, group->getName(), true);
visual_tools->publishContactPoints(*robot_state, planning_scene);
ROS_WARN_STREAM_THROTTLE_NAMED(2.0, "imarker_robot_state", "Collision in IK CC callback");
}
return false;
}
} // namespace
| 34.566327 | 120 | 0.691661 | errrr0501 |
96e0cf58acfe50d0693960d3dfd0ad346cd27ee5 | 3,599 | cpp | C++ | Base/PLCore/src/File/FileSearchAndroid.cpp | ktotheoz/pixellight | 43a661e762034054b47766d7e38d94baf22d2038 | [
"MIT"
] | 83 | 2015-01-08T15:06:14.000Z | 2021-07-20T17:07:00.000Z | Base/PLCore/src/File/FileSearchAndroid.cpp | PixelLightFoundation/pixellight | 43a661e762034054b47766d7e38d94baf22d2038 | [
"MIT"
] | 27 | 2019-06-18T06:46:07.000Z | 2020-02-02T11:11:28.000Z | Base/PLCore/src/File/FileSearchAndroid.cpp | naetherm/PixelLight | d7666f5b49020334cbb5debbee11030f34cced56 | [
"MIT"
] | 40 | 2015-02-25T18:24:34.000Z | 2021-03-06T09:01:48.000Z | /*********************************************************\
* File: FileSearchAndroid.cpp *
*
* Copyright (C) 2002-2013 The PixelLight Team (http://www.pixellight.org/)
*
* This file is part of PixelLight.
*
* 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.
\*********************************************************/
//[-------------------------------------------------------]
//[ Includes ]
//[-------------------------------------------------------]
#include <stdio.h> // For e.g. "off_t"
#include <stdint.h> // For e.g. "size_t"
#include <android/asset_manager.h>
#include "PLCore/System/SystemAndroid.h"
#include "PLCore/File/FileSearchAndroid.h"
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
namespace PLCore {
//[-------------------------------------------------------]
//[ Private functions ]
//[-------------------------------------------------------]
/**
* @brief
* Constructor
*/
FileSearchAndroid::FileSearchAndroid(const String &sPath, const FileAccess *pAccess) : FileSearchImpl(pAccess),
m_pAAssetDir(nullptr),
m_sPath(sPath),
m_pszNextFilename(nullptr)
{
// Get the Android asset manager instance
AAssetManager *pAAssetManager = SystemAndroid::GetAssetManager();
if (pAAssetManager) {
// Start search
m_pAAssetDir = AAssetManager_openDir(pAAssetManager, (m_sPath.GetFormat() == String::ASCII) ? m_sPath.GetASCII() : m_sPath.GetUTF8());
if (m_pAAssetDir) {
// Something has been found
m_pszNextFilename = AAssetDir_getNextFileName(m_pAAssetDir);
}
}
}
/**
* @brief
* Destructor
*/
FileSearchAndroid::~FileSearchAndroid()
{
// Close the search
if (m_pAAssetDir)
AAssetDir_close(m_pAAssetDir);
}
//[-------------------------------------------------------]
//[ Private virtual FileSearchImpl functions ]
//[-------------------------------------------------------]
bool FileSearchAndroid::HasNextFile()
{
return (m_pszNextFilename != nullptr);
}
String FileSearchAndroid::GetNextFile()
{
if (m_pszNextFilename) {
m_sFilename = m_pszNextFilename;
m_pszNextFilename = AAssetDir_getNextFileName(m_pAAssetDir);
return m_sFilename;
} else {
return "";
}
}
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
} // PLCore
| 35.633663 | 136 | 0.548486 | ktotheoz |
96e4f68f9e2d37940d54a68cce1ac7d4c0426ac7 | 3,844 | cpp | C++ | Model/ModelGrid.cpp | robbor78/OpenGLTetris3D | b388cbdc2eda9fcc9a073f8aa857b0912819e695 | [
"Apache-2.0"
] | null | null | null | Model/ModelGrid.cpp | robbor78/OpenGLTetris3D | b388cbdc2eda9fcc9a073f8aa857b0912819e695 | [
"Apache-2.0"
] | null | null | null | Model/ModelGrid.cpp | robbor78/OpenGLTetris3D | b388cbdc2eda9fcc9a073f8aa857b0912819e695 | [
"Apache-2.0"
] | null | null | null | /*
* ModelGrid.cpp
*
* Created on: 22 Dec 2013
* Author: bert
*/
#include "ModelGrid.h"
namespace Tetris3D {
ModelGrid::ModelGrid(OpenGLProgram* program) :
AbstractModelPiece(program) {
well = 0;
vbo = -1;
}
ModelGrid::~ModelGrid() {
program = 0;
well = 0;
glBindBuffer(GL_ARRAY_BUFFER, 0);
glDeleteBuffers(1, &vbo);
}
void ModelGrid::GenerateBuffers() {
std::vector<float> grid;
MakeGrid(grid);
GenerateArrayBuffer(vbo, grid);
}
void ModelGrid::InitBuffers() {
glBindBuffer(GL_ARRAY_BUFFER, vbo);
AbstractModelPiece::InitBuffers();
}
void ModelGrid::DrawBuffers() {
int size = 0;
glGetBufferParameteriv(GL_ARRAY_BUFFER, GL_BUFFER_SIZE, &size);
glDrawArrays(GL_LINES, 0, size / sizeof(VertexStructure));
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
void ModelGrid::MakeGrid(std::vector<float> &cs) {
cs.clear();
unsigned int maxCol = well->GetCol();
unsigned int maxRow = well->GetRow();
unsigned int maxDep = well->GetDep();
for (unsigned int row = 0; row <= maxRow; row++) {
float xStart = xOffset;
float y = -(float) (row * sideLength) + yOffset;
float xEnd = (float) (maxCol * sideLength) + xOffset;
float zStart = 0.0; //sideLength * maxDep;
PushIntoVector(cs, new float[3] { xStart, y, zStart }, new float[3] { 0.0, 0.0, -1.0 }, new float[4] { 1.0, 1.0,
0.0, 1.0 });
PushIntoVector(cs, new float[3] { xEnd, y, zStart }, new float[3] { 0.0, 0.0, -1.0 }, new float[4] { 1.0, 1.0, 0.0,
1.0 });
float zEnd = sideLength * maxDep;
PushIntoVector(cs, new float[3] { xStart, y, zStart }, new float[3] { 0.0, 0.0, -1.0 }, new float[4] { 1.0, 1.0,
0.0, 1.0 });
PushIntoVector(cs, new float[3] { xStart, y, zEnd }, new float[3] { 0.0, 0.0, -1.0 }, new float[4] { 1.0, 1.0, 0.0,
1.0 });
PushIntoVector(cs, new float[3] { xEnd, y, zStart }, new float[3] { 0.0, 0.0, -1.0 }, new float[4] { 1.0, 1.0, 0.0,
1.0 });
PushIntoVector(cs, new float[3] { xEnd, y, zEnd }, new float[3] { 0.0, 0.0, -1.0 }, new float[4] { 1.0, 1.0, 0.0,
1.0 });
}
for (unsigned int col = 0; col <= maxCol; col++) {
float yStart = yOffset;
float yEnd = -(float) (maxRow * sideLength) + yOffset;
float x = (float) (col * sideLength) + xOffset;
float zStart = 0.0;
float zEnd = sideLength * maxDep;
PushIntoVector(cs, new float[3] { x, yStart, zStart }, new float[3] { 0.0, 0.0, -1.0 }, new float[4] { 1.0, 0.0, 1.0, 1.0 });
PushIntoVector(cs, new float[3] { x, yEnd, zStart }, new float[3] { 0.0, 0.0, -1.0 }, new float[4] { 1.0, 0.0, 1.0, 1.0 });
PushIntoVector(cs, new float[3] { x, yEnd, zStart }, new float[3] { 0.0, 0.0, -1.0 }, new float[4] { 1.0, 1.0, 0.0,
1.0 });
PushIntoVector(cs, new float[3] { x, yEnd, zEnd }, new float[3] { 0.0, 0.0, -1.0 }, new float[4] { 1.0, 1.0, 0.0,
1.0 });
}
for (unsigned int dep = 1; dep <= maxDep; dep++) {
float z = dep * sideLength;
float xStart = xOffset;
float xEnd = (float) (maxCol * sideLength) + xOffset;
float yStart = 14.0;
float yEnd = -(float) (maxRow * sideLength) + yOffset;
PushIntoVector(cs, new float[3] { xStart, yStart, z }, new float[3] { 0.0, 0.0, -1.0 }, new float[4] { 1.0, 1.0,
0.0, 1.0 });
PushIntoVector(cs, new float[3] { xStart, yEnd, z }, new float[3] { 0.0, 0.0, -1.0 }, new float[4] { 1.0, 1.0, 0.0,
1.0 });
PushIntoVector(cs, new float[3] { xEnd, yStart, z }, new float[3] { 0.0, 0.0, -1.0 }, new float[4] { 1.0, 1.0, 0.0,
1.0 });
PushIntoVector(cs, new float[3] { xEnd, yEnd, z }, new float[3] { 0.0, 0.0, -1.0 }, new float[4] { 1.0, 1.0, 0.0,
1.0 });
PushIntoVector(cs, new float[3] { xStart, yEnd, z }, new float[3] { 0.0, 0.0, -1.0 }, new float[4] { 1.0, 1.0, 0.0,
1.0 });
PushIntoVector(cs, new float[3] { xEnd, yEnd, z }, new float[3] { 0.0, 0.0, -1.0 }, new float[4] { 1.0, 1.0, 0.0,
1.0 });
}
}
} /* namespace Tetris3D */
| 30.752 | 127 | 0.588189 | robbor78 |
96e7bbcce9ad7f8b0208c8cd243525d9f87d612d | 404 | hpp | C++ | src/arithmetic.hpp | UtopiaLang/src | be8904f978f3ea0d92afb72895cc2bb052cf4107 | [
"Unlicense"
] | 7 | 2021-03-01T17:24:45.000Z | 2021-10-01T02:28:25.000Z | src/arithmetic.hpp | UtopiaLang/Utopia | be8904f978f3ea0d92afb72895cc2bb052cf4107 | [
"Unlicense"
] | 6 | 2021-02-27T18:25:45.000Z | 2021-09-10T21:27:39.000Z | src/arithmetic.hpp | UtopiaLang/src | be8904f978f3ea0d92afb72895cc2bb052cf4107 | [
"Unlicense"
] | null | null | null | #pragma once
namespace Utopia
{
using arithmetic_func_t = long long(*)(const long long, const long long);
long long arithmetic_plus(const long long left, const long long right);
long long arithmetic_minus(const long long left, const long long right);
long long arithmetic_multiply(const long long left, const long long right);
long long arithmetic_divide(const long long left, long long right);
}
| 33.666667 | 76 | 0.779703 | UtopiaLang |
96e8e95e2fad0184250fd1bdeebe56d670ac8932 | 6,795 | cc | C++ | selfdrive/can/dbc_out/cadillac_ct6_chassis.cc | ziggysnorkel/openpilot | 695859fb49976c2ef0a6a4a73d30d5cef2ad1945 | [
"MIT"
] | 1 | 2021-03-05T18:09:52.000Z | 2021-03-05T18:09:52.000Z | selfdrive/can/dbc_out/cadillac_ct6_chassis.cc | ziggysnorkel/openpilot | 695859fb49976c2ef0a6a4a73d30d5cef2ad1945 | [
"MIT"
] | null | null | null | selfdrive/can/dbc_out/cadillac_ct6_chassis.cc | ziggysnorkel/openpilot | 695859fb49976c2ef0a6a4a73d30d5cef2ad1945 | [
"MIT"
] | null | null | null | #include <cstdint>
#include "common.h"
namespace {
const Signal sigs_338[] = {
{
.name = "LKASteeringCmd",
.b1 = 2,
.b2 = 14,
.bo = 48,
.is_signed = true,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LKASteeringCmdActive",
.b1 = 0,
.b2 = 1,
.bo = 63,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LKASVehicleSpeed",
.b1 = 19,
.b2 = 13,
.bo = 32,
.is_signed = false,
.factor = 0.22,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "SetMe1",
.b1 = 18,
.b2 = 1,
.bo = 45,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "RollingCounter",
.b1 = 16,
.b2 = 2,
.bo = 46,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LKASteeringCmdChecksum",
.b1 = 38,
.b2 = 10,
.bo = 16,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LKASMode",
.b1 = 35,
.b2 = 2,
.bo = 27,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_340[] = {
{
.name = "LKASteeringCmd",
.b1 = 2,
.b2 = 14,
.bo = 48,
.is_signed = true,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LKASteeringCmdActive",
.b1 = 0,
.b2 = 1,
.bo = 63,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LKASVehicleSpeed",
.b1 = 19,
.b2 = 13,
.bo = 32,
.is_signed = false,
.factor = 0.22,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "SetMe1",
.b1 = 18,
.b2 = 1,
.bo = 45,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "RollingCounter",
.b1 = 16,
.b2 = 2,
.bo = 46,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LKASteeringCmdChecksum",
.b1 = 38,
.b2 = 10,
.bo = 16,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LKASteeringCmdActive2",
.b1 = 36,
.b2 = 1,
.bo = 27,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_368[] = {
{
.name = "FrictionBrakePressure",
.b1 = 16,
.b2 = 16,
.bo = 32,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_560[] = {
{
.name = "Regen",
.b1 = 6,
.b2 = 10,
.bo = 48,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_789[] = {
{
.name = "FrictionBrakeCmd",
.b1 = 4,
.b2 = 12,
.bo = 48,
.is_signed = true,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FrictionBrakeMode",
.b1 = 0,
.b2 = 4,
.bo = 60,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FrictionBrakeChecksum",
.b1 = 16,
.b2 = 16,
.bo = 32,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "RollingCounter",
.b1 = 34,
.b2 = 6,
.bo = 24,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_823[] = {
{
.name = "SteeringWheelCmd",
.b1 = 16,
.b2 = 16,
.bo = 32,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "RollingCounter",
.b1 = 36,
.b2 = 2,
.bo = 26,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "SteeringWheelChecksum",
.b1 = 40,
.b2 = 16,
.bo = 8,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Msg msgs[] = {
{
.name = "ASCMLKASteeringCmd",
.address = 0x152,
.size = 6,
.num_sigs = ARRAYSIZE(sigs_338),
.sigs = sigs_338,
},
{
.name = "ASCMBLKASteeringCmd",
.address = 0x154,
.size = 6,
.num_sigs = ARRAYSIZE(sigs_340),
.sigs = sigs_340,
},
{
.name = "EBCMFrictionBrakeStatus",
.address = 0x170,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_368),
.sigs = sigs_368,
},
{
.name = "EBCMRegen",
.address = 0x230,
.size = 6,
.num_sigs = ARRAYSIZE(sigs_560),
.sigs = sigs_560,
},
{
.name = "EBCMFrictionBrakeCmd",
.address = 0x315,
.size = 5,
.num_sigs = ARRAYSIZE(sigs_789),
.sigs = sigs_789,
},
{
.name = "PACMParkAssitCmd",
.address = 0x337,
.size = 7,
.num_sigs = ARRAYSIZE(sigs_823),
.sigs = sigs_823,
},
};
const Val vals[] = {
{
.name = "LKASteeringCmdActive",
.address = 0x152,
.def_val = "1 ACTIVE 0 INACTIVE",
.sigs = sigs_338,
},
{
.name = "LKASMode",
.address = 0x152,
.def_val = "2 SUPERCRUISE 1 LKAS 0 INACTIVE",
.sigs = sigs_338,
},
};
}
const DBC cadillac_ct6_chassis = {
.name = "cadillac_ct6_chassis",
.num_msgs = ARRAYSIZE(msgs),
.msgs = msgs,
.vals = vals,
.num_vals = ARRAYSIZE(vals),
};
dbc_init(cadillac_ct6_chassis) | 19.810496 | 51 | 0.474467 | ziggysnorkel |
96e94bd855b46b2d3194b61dbab8765d6454b0ea | 1,668 | cpp | C++ | Bootstrap/Patcher/Tests/Suite.spec.cpp | XionsProphecy-Software/MelonLoader | 7af96f573242bbbbc707b385b4c9c07e5ff51c25 | [
"Apache-2.0"
] | 6 | 2021-04-30T02:40:23.000Z | 2022-03-16T16:54:32.000Z | Bootstrap/Patcher/Tests/Suite.spec.cpp | XionsProphecy-Software/MelonLoader | 7af96f573242bbbbc707b385b4c9c07e5ff51c25 | [
"Apache-2.0"
] | null | null | null | Bootstrap/Patcher/Tests/Suite.spec.cpp | XionsProphecy-Software/MelonLoader | 7af96f573242bbbbc707b385b4c9c07e5ff51c25 | [
"Apache-2.0"
] | 8 | 2021-04-13T18:32:57.000Z | 2022-03-12T18:42:07.000Z | #include "./Suite.spec.h"
#include <string>
#include <android/log.h>
#include "../../Utils/UnitTesting/TestHelper.h"
#include "../../Utils/UnitTesting/TestHelper.h"
#include "../../Base/funchook/include/funchook.h"
#include "../../Managers/Hook.h"
namespace Patcher
{
class TestV
{
public:
typedef bool (*OriginalMethod_A_t) ();
static OriginalMethod_A_t OriginalMethod_A;
static bool OriginalMethod()
{
UnitTesting::InternalLog(Console::Red, "Unpatched method");
return false;
}
};
TestV::OriginalMethod_A_t TestV::OriginalMethod_A = NULL;
bool PatchWorks()
{
UnitTesting::InternalLog(Console::Red, "Intercepted");
bool res = TestV::OriginalMethod_A();
return !res;
}
bool TestAll()
{
UnitTesting::Test TestSequence[] = {
// {
// "Patcher",
// []()
// {
// void* trampoline = NULL;
// A64HookFunction((void*)OriginalMethod, (void*)PatchWorks, &trampoline);
// UnitTesting::InternalLog(Console::Cyan, "Patch Created");
// return (trampoline != NULL) && OriginalMethod();
// }
// }
{
"funchook",
[]()
{
TestV::OriginalMethod_A = TestV::OriginalMethod;
//
// funchook* funchook = funchook_create();
// funchook_prepare(funchook, (void**)&TestV::OriginalMethod_A, (void*)PatchWorks);
// funchook_install(funchook, 0);
//
Hook::Attach((void**)&TestV::OriginalMethod_A, (void*)PatchWorks);
return TestV::OriginalMethod();
}
},
// {
// "auto fail",
// []()
// {
// return false;
// }
// }
};
return UnitTesting::RunTests(TestSequence, sizeof(TestSequence) / sizeof(TestSequence[0]));
}
}
| 21.947368 | 93 | 0.616906 | XionsProphecy-Software |
96eb5448be918c54a3a35b49c7a9d9632a0e59d7 | 26,330 | cpp | C++ | test/test_manifest_tsv.cpp | rkimballn1/aeon-merged | 062136993c0f326c95caaddf6118a84789e206b1 | [
"MIT",
"BSL-1.0",
"Apache-2.0",
"BSD-3-Clause"
] | 63 | 2016-08-14T07:19:45.000Z | 2021-09-21T15:57:08.000Z | test/test_manifest_tsv.cpp | NervanaSystems/aeon | a63b9f8d75311b8d9e9b0be58a066e749aeb81d4 | [
"MIT",
"BSL-1.0",
"Apache-2.0",
"BSD-3-Clause"
] | 64 | 2016-08-08T18:35:19.000Z | 2022-03-11T23:43:51.000Z | test/test_manifest_tsv.cpp | rkimballn1/aeon-merged | 062136993c0f326c95caaddf6118a84789e206b1 | [
"MIT",
"BSL-1.0",
"Apache-2.0",
"BSD-3-Clause"
] | 44 | 2016-08-10T01:20:52.000Z | 2020-07-01T19:47:48.000Z | /*******************************************************************************
* Copyright 2016-2018 Intel Corporation
*
* 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 <fcntl.h>
#include <unistd.h>
#include <sys/time.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <stdexcept>
#include <memory>
#include <chrono>
#include "gtest/gtest.h"
#include "manifest_file.hpp"
#include "manifest_builder.hpp"
#include "util.hpp"
#include "file_util.hpp"
#include "manifest_file.hpp"
#include "crc.hpp"
#include "file_util.hpp"
#include "block_loader_file.hpp"
#include "base64.hpp"
#include "gen_image.hpp"
#include "loader.hpp"
using namespace std;
using namespace nervana;
static string test_data_directory = file_util::path_join(string(CURDIR), "test_data");
TEST(manifest, constructor)
{
manifest_builder mm;
auto& ms = mm.sizes({0, 0}).record_count(0).create();
nervana::manifest_file manifest0(ms, false);
}
TEST(manifest, no_file)
{
ASSERT_THROW(nervana::manifest_file manifest0("/tmp/jsdkfjsjkfdjaskdfj_doesnt_exist", false),
std::runtime_error);
}
TEST(manifest, version_eq)
{
manifest_builder mm;
auto& ms = mm.sizes({0, 0}).record_count(0).create();
nervana::manifest_file manifest1(ms, false);
nervana::manifest_file manifest2(ms, false);
ASSERT_EQ(manifest1.version(), manifest2.version());
}
TEST(manifest, parse_file_doesnt_exist)
{
manifest_builder mm;
auto& ms = mm.sizes({0, 0}).record_count(0).create();
nervana::manifest_file manifest0(ms, false);
ASSERT_EQ(manifest0.record_count(), 0);
}
TEST(manifest, parse_file)
{
manifest_builder mm;
auto& ms = mm.sizes({0, 0}).record_count(2).create();
nervana::manifest_file manifest0(ms, false);
ASSERT_EQ(manifest0.record_count(), 2);
}
TEST(manifest, no_shuffle)
{
manifest_builder mm1;
auto& ms1 = mm1.sizes({4, 4}).record_count(20).create();
nervana::manifest_file manifest1(ms1, false);
manifest_builder mm2;
auto& ms2 = mm2.sizes({4, 4}).record_count(20).create();
nervana::manifest_file manifest2(ms2, false);
ASSERT_EQ(1, manifest1.block_count());
ASSERT_EQ(1, manifest2.block_count());
auto& m1_block = *manifest1.next();
auto& m2_block = *manifest2.next();
ASSERT_EQ(manifest1.record_count(), manifest2.record_count());
ASSERT_EQ(2, manifest1.elements_per_record());
for (int i = 0; i < manifest1.record_count(); i++)
{
ASSERT_EQ(m1_block[i][0], m2_block[i][0]);
ASSERT_EQ(m1_block[i][1], m2_block[i][1]);
}
}
namespace {
void test_multinode_manifest(bool shuffle)
{
const uint32_t record_count = 17;
const uint32_t batch_size = 3;
const uint32_t node_count = 2;
manifest_builder mm1;
auto& ms1 = mm1.sizes({4, 4}).record_count(record_count).create();
nervana::manifest_file manifest(ms1, shuffle, "", 1.0f, 5000, 1234, 0, 0, batch_size);
manifest_builder mmn1;
auto& msn1 = mmn1.sizes({4, 4}).record_count(record_count).create();
nervana::manifest_file manifest_node1(msn1, shuffle, "", 1.0f, 5000, 1234, 0, 2, batch_size);
manifest_builder mmn2;
auto& msn2 = mmn2.sizes({4, 4}).record_count(record_count).create();
nervana::manifest_file manifest_node2(msn2, shuffle, "", 1.0f, 5000, 1234, 1, 2, batch_size);
ASSERT_EQ(1, manifest_node1.block_count());
ASSERT_EQ(1, manifest_node2.block_count());
ASSERT_EQ(8, manifest_node1.record_count());
ASSERT_EQ(8, manifest_node2.record_count());
ASSERT_EQ(2, manifest_node1.elements_per_record());
ASSERT_EQ(2, manifest_node2.elements_per_record());
auto record_count_node = (manifest.record_count() / node_count) * node_count;
uint32_t batches = ((record_count_node / node_count) / batch_size) * node_count;
for (int i = 0; i < batches; i++)
{
for (int j = 0; j < batch_size; j++)
{
uint32_t src_index = i * batch_size + j;
uint32_t dst_index = ( i / node_count ) * batch_size + j;
if ( i % node_count == 0)
{
ASSERT_EQ(manifest[src_index][0], manifest_node1[dst_index][0]);
ASSERT_EQ(manifest[src_index][1], manifest_node1[dst_index][1]);
}
else
{
ASSERT_EQ(manifest[src_index][0], manifest_node2[dst_index][0]);
ASSERT_EQ(manifest[src_index][1], manifest_node2[dst_index][1]);
}
}
}
auto remain = record_count_node - batches * batch_size;
for (int i = 0; i < remain; i++)
{
uint32_t src_index = batches * batch_size + i;
uint32_t dst_index = batches * batch_size / node_count + i % node_count;
if ( i / node_count == 0)
{
ASSERT_EQ(manifest[src_index][0], manifest_node1[dst_index][0]);
ASSERT_EQ(manifest[src_index][1], manifest_node1[dst_index][1]);
}
else
{
ASSERT_EQ(manifest[src_index][0], manifest_node2[dst_index][0]);
ASSERT_EQ(manifest[src_index][1], manifest_node2[dst_index][1]);
}
}
auto block = manifest.next();
auto block_node1 = manifest_node1.next();
auto block_node2 = manifest_node2.next();
manifest.reset();
manifest_node1.reset();
manifest_node2.reset();
block = manifest.next();
block_node1 = manifest_node1.next();
block_node2 = manifest_node2.next();
}
}
TEST(manifest, no_shuffle_multinode)
{
test_multinode_manifest(false);
}
TEST(manifest, shuffle_multinode)
{
test_multinode_manifest(true);
}
TEST(manifest, shuffle)
{
manifest_builder mm1;
auto& ms1 = mm1.sizes({4, 4}).record_count(20).create();
nervana::manifest_file manifest1(ms1, false);
manifest_builder mm2;
auto& ms2 = mm2.sizes({4, 4}).record_count(20).create();
nervana::manifest_file manifest2(ms2, true);
bool different = false;
ASSERT_EQ(1, manifest1.block_count());
ASSERT_EQ(1, manifest2.block_count());
auto& m1_block = *manifest1.next();
auto& m2_block = *manifest2.next();
ASSERT_EQ(manifest1.record_count(), manifest2.record_count());
for (int i = 0; i < manifest1.record_count(); i++)
{
if (m1_block[i][0] != m2_block[i][0])
{
different = true;
}
}
ASSERT_EQ(different, true);
}
TEST(manifest, non_paired_manifests)
{
{
manifest_builder mm;
auto& ms = mm.sizes({4, 4, 4}).record_count(20).create();
nervana::manifest_file manifest1(ms, false);
ASSERT_EQ(manifest1.record_count(), 20);
}
{
manifest_builder mm;
auto& ms = mm.sizes({4}).record_count(20).create();
nervana::manifest_file manifest1(ms, false);
ASSERT_EQ(manifest1.record_count(), 20);
}
}
TEST(manifest, root_path)
{
string manifest_file = "tmp_manifest.tsv";
{
ofstream f(manifest_file);
f << "@FILE\tFILE\n";
for (int i = 0; i < 10; i++)
{
f << "/t1/image" << i << ".png" << manifest_file::get_delimiter();
f << "/t1/target" << i << ".txt\n";
}
f.close();
nervana::manifest_file manifest(manifest_file, false);
ASSERT_EQ(1, manifest.block_count());
auto& block = *manifest.next();
for (int i = 0; i < manifest.record_count(); i++)
{
const vector<string>& x = block[i];
ASSERT_EQ(2, x.size());
stringstream ss;
ss << "/t1/image" << i << ".png";
EXPECT_STREQ(x[0].c_str(), ss.str().c_str());
ss.str("");
ss << "/t1/target" << i << ".txt";
EXPECT_STREQ(x[1].c_str(), ss.str().c_str());
}
}
{
ofstream f(manifest_file);
f << "@FILE\tFILE\n";
for (int i = 0; i < 10; i++)
{
f << "/t1/image" << i << ".png" << manifest_file::get_delimiter();
f << "/t1/target" << i << ".txt\n";
}
f.close();
nervana::manifest_file manifest(manifest_file, false, "/x1");
ASSERT_EQ(1, manifest.block_count());
auto& block = *manifest.next();
for (int i = 0; i < manifest.record_count(); i++)
{
const vector<string>& x = block[i];
ASSERT_EQ(2, x.size());
stringstream ss;
ss << "/t1/image" << i << ".png";
EXPECT_STREQ(x[0].c_str(), ss.str().c_str());
ss.str("");
ss << "/t1/target" << i << ".txt";
EXPECT_STREQ(x[1].c_str(), ss.str().c_str());
}
}
{
ofstream f(manifest_file);
f << "@FILE\tFILE\n";
for (int i = 0; i < 10; i++)
{
f << "t1/image" << i << ".png" << manifest_file::get_delimiter();
f << "t1/target" << i << ".txt\n";
}
f.close();
nervana::manifest_file manifest(manifest_file, false, "/x1");
ASSERT_EQ(1, manifest.block_count());
auto& block = *manifest.next();
for (int i = 0; i < manifest.record_count(); i++)
{
const vector<string>& x = block[i];
ASSERT_EQ(2, x.size());
stringstream ss;
ss << "/x1/t1/image" << i << ".png";
EXPECT_STREQ(x[0].c_str(), ss.str().c_str());
ss.str("");
ss << "/x1/t1/target" << i << ".txt";
EXPECT_STREQ(x[1].c_str(), ss.str().c_str());
}
}
remove(manifest_file.c_str());
}
TEST(manifest, crc)
{
const string input = "123456789";
uint32_t expected = 0xe3069283;
uint32_t actual = 0;
CryptoPP::CRC32C crc;
crc.Update((const uint8_t*)input.data(), input.size());
crc.TruncatedFinal((uint8_t*)&actual, sizeof(actual));
EXPECT_EQ(expected, actual);
}
TEST(manifest, file_implicit)
{
vector<string> image_files = {"flowers.jpg", "img_2112_70.jpg"};
vector<string> target_files = {"1.txt", "2.txt"};
stringstream ss;
for (int count = 0; count < 32; count++)
{
for (int i = 0; i < image_files.size(); i++)
{
ss << image_files[i] << "\t" << target_files[i] << "\n";
}
}
size_t block_size = 16;
EXPECT_THROW(manifest_file(ss, false, test_data_directory, 1.0, block_size),
std::invalid_argument);
}
TEST(manifest, wrong_elements_number)
{
string image_file = "flowers.jpg";
stringstream ss;
ss << "@FILE"
<< "\t"
<< "FILE"
<< "\n";
ss << image_file << "\n";
size_t block_size = 1;
EXPECT_THROW(manifest_file manifest(ss, false, test_data_directory, 1.0, block_size),
std::runtime_error);
}
TEST(manifest, changing_elements_number)
{
string image_file = "flowers.jpg";
string target_file = "1.txt";
stringstream ss;
ss << "@FILE"
<< "\t"
<< "FILE"
<< "\n";
ss << image_file << "\t" << target_file << "\n";
ss << image_file << "\n";
size_t block_size = 2;
EXPECT_THROW(manifest_file manifest(ss, false, test_data_directory, 1.0, block_size),
std::runtime_error);
}
TEST(manifest, file_explicit)
{
vector<string> image_files = {"flowers.jpg", "img_2112_70.jpg"};
vector<string> target_files = {"1.txt", "2.txt"};
stringstream ss;
ss << "@FILE"
<< "\t"
<< "FILE"
<< "\n";
for (int count = 0; count < 32; count++)
{
for (int i = 0; i < image_files.size(); i++)
{
ss << image_files[i] << "\t" << target_files[i] << "\n";
}
}
size_t block_size = 16;
auto manifest = make_shared<manifest_file>(ss, false, test_data_directory, 1.0, block_size);
auto types = manifest->get_element_types();
ASSERT_EQ(2, types.size());
EXPECT_EQ(manifest::element_t::FILE, types[0]);
EXPECT_EQ(manifest::element_t::FILE, types[1]);
block_loader_file bload{manifest, block_size};
for (int i = 0; i < 2; i++)
{
encoded_record_list* buffer = bload.filler();
ASSERT_NE(nullptr, buffer);
ASSERT_EQ(block_size, buffer->size());
for (int j = 0; j < buffer->size(); j++)
{
encoded_record record = buffer->record(j);
auto idata = record.element(0);
auto tdata = record.element(1);
string target{tdata.data(), tdata.size()};
int value = stod(target);
EXPECT_EQ(j % 2 + 1, value);
}
}
}
string make_target_data(size_t index)
{
stringstream tmp;
tmp << "target_number" << index++;
return tmp.str();
}
TEST(manifest, binary)
{
vector<string> image_files = {"flowers.jpg", "img_2112_70.jpg"};
stringstream ss;
size_t index = 0;
ss << "@FILE"
<< "\t"
<< "BINARY"
<< "\n";
for (int count = 0; count < 32; count++)
{
for (int i = 0; i < image_files.size(); i++)
{
vector<char> str = string2vector(make_target_data(index++));
auto data_string = base64::encode(str);
ss << image_files[i] << "\t" << vector2string(data_string) << "\n";
}
}
size_t block_size = 16;
auto manifest = make_shared<manifest_file>(ss, false, test_data_directory, 1.0, block_size);
auto types = manifest->get_element_types();
ASSERT_EQ(2, types.size());
EXPECT_EQ(manifest::element_t::FILE, types[0]);
EXPECT_EQ(manifest::element_t::BINARY, types[1]);
block_loader_file block_loader{manifest, block_size};
index = 0;
for (int i = 0; i < 2; i++)
{
encoded_record_list* buffer = block_loader.filler();
ASSERT_NE(nullptr, buffer);
ASSERT_EQ(block_size, buffer->size());
for (int j = 0; j < buffer->size(); j++)
{
encoded_record record = buffer->record(j);
auto idata = record.element(0);
auto tdata = record.element(1);
string str = vector2string(tdata);
string expected = make_target_data(index);
index = (index + 1) % manifest->record_count();
EXPECT_STREQ(expected.c_str(), str.c_str());
}
}
}
TEST(manifest, string)
{
vector<string> image_files = {"flowers.jpg", "img_2112_70.jpg"};
stringstream ss;
size_t index = 0;
ss << "@FILE"
<< "\t"
<< "STRING"
<< "\n";
for (int count = 0; count < 32; count++)
{
for (int i = 0; i < image_files.size(); i++)
{
string str = make_target_data(index++);
ss << image_files[i] << "\t" << str << "\n";
}
}
size_t block_size = 16;
auto manifest = make_shared<manifest_file>(ss, false, test_data_directory, 1.0, block_size);
// for (auto data : manifest)
// {
// INFO << data[0] << ", " << data[1];
// }
auto types = manifest->get_element_types();
ASSERT_EQ(2, types.size());
EXPECT_EQ(manifest::element_t::FILE, types[0]);
EXPECT_EQ(manifest::element_t::STRING, types[1]);
block_loader_file block_loader{manifest, block_size};
index = 0;
for (int i = 0; i < 2; i++)
{
encoded_record_list* buffer = block_loader.filler();
ASSERT_NE(nullptr, buffer);
ASSERT_EQ(block_size, buffer->size());
for (int j = 0; j < buffer->size(); j++)
{
encoded_record record = buffer->record(j);
auto idata = record.element(0);
auto tdata = record.element(1);
string str = vector2string(tdata);
string expected = make_target_data(index);
index = (index + 1) % manifest->record_count();
EXPECT_STREQ(expected.c_str(), str.c_str());
}
}
}
TEST(manifest, ascii_int)
{
vector<string> image_files = {"flowers.jpg", "img_2112_70.jpg"};
stringstream ss;
size_t index = 0;
ss << "@FILE"
<< "\t"
<< "ASCII_INT"
<< "\n";
for (int count = 0; count < 32; count++)
{
for (int i = 0; i < image_files.size(); i++)
{
ss << image_files[i] << "\t" << count * 2 + i << "\n";
}
}
size_t block_size = 16;
auto manifest = make_shared<manifest_file>(ss, false, test_data_directory, 1.0, block_size);
auto types = manifest->get_element_types();
ASSERT_EQ(2, types.size());
EXPECT_EQ(manifest::element_t::FILE, types[0]);
EXPECT_EQ(manifest::element_t::ASCII_INT, types[1]);
block_loader_file block_loader{manifest, block_size};
index = 0;
for (int i = 0; i < 2; i++)
{
encoded_record_list* buffer = block_loader.filler();
ASSERT_NE(nullptr, buffer);
ASSERT_EQ(block_size, buffer->size());
for (int j = 0; j < buffer->size(); j++)
{
encoded_record record = buffer->record(j);
auto idata = record.element(0);
int32_t tdata = unpack<int32_t>(record.element(1).data());
EXPECT_EQ(tdata, index);
index++;
}
}
}
TEST(manifest, ascii_float)
{
vector<string> image_files = {"flowers.jpg", "img_2112_70.jpg"};
stringstream ss;
size_t index = 0;
ss << "@FILE"
<< "\t"
<< "ASCII_FLOAT"
<< "\n";
for (int count = 0; count < 32; count++)
{
for (int i = 0; i < image_files.size(); i++)
{
ss << image_files[i] << "\t" << (float)(count * 2 + i) / 10. << "\n";
}
}
size_t block_size = 16;
auto manifest = make_shared<manifest_file>(ss, false, test_data_directory, 1.0, block_size);
auto types = manifest->get_element_types();
ASSERT_EQ(2, types.size());
EXPECT_EQ(manifest::element_t::FILE, types[0]);
EXPECT_EQ(manifest::element_t::ASCII_FLOAT, types[1]);
block_loader_file block_loader{manifest, block_size};
index = 0;
for (int i = 0; i < 2; i++)
{
encoded_record_list* buffer = block_loader.filler();
ASSERT_NE(nullptr, buffer);
ASSERT_EQ(block_size, buffer->size());
for (int j = 0; j < buffer->size(); j++)
{
encoded_record record = buffer->record(j);
auto idata = record.element(0);
float tdata = unpack<float>(record.element(1).data());
float expected = (float)index / 10.;
EXPECT_EQ(tdata, expected);
index++;
}
}
}
extern string test_cache_directory;
class manifest_manager
{
public:
manifest_manager(const string& source_dir, size_t count, int rows, int cols)
{
test_root = source_dir;
source_directory = file_util::make_temp_directory(source_dir);
manifest_filename = file_util::path_join(source_directory, "manifest.tsv");
file_list.push_back(manifest_filename);
ofstream mfile(manifest_filename);
mfile << "@FILE\tFILE\n";
for (size_t i = 0; i < count; i++)
{
cv::Mat image = embedded_id_image::generate_image(rows, cols, i);
string number = to_string(i);
string image_filename =
file_util::path_join(source_directory, "image" + number + ".png");
string target_filename =
file_util::path_join(source_directory, "target" + number + ".txt");
// cout << image_filename << ", " << target_filename << endl;
file_list.push_back(image_filename);
file_list.push_back(target_filename);
cv::imwrite(image_filename, image);
ofstream tfile(target_filename);
tfile << i;
mfile << image_filename << manifest_file::get_delimiter();
mfile << target_filename << "\n";
}
}
const string& manifest_file() const { return manifest_filename; }
~manifest_manager() { file_util::remove_directory(test_root); }
private:
string test_root;
string manifest_filename;
string source_directory;
vector<string> file_list;
};
TEST(manifest, manifest_shuffle)
{
const uint32_t seed = 1234;
const size_t block_size = 4;
const float subset_fraction = 1.0;
string source_dir = file_util::make_temp_directory(test_cache_directory);
manifest_manager manifest_builder{source_dir, 10, 25, 25};
string manifest_root;
nervana::manifest_file manifest1{
manifest_builder.manifest_file(), true, manifest_root, subset_fraction, block_size, seed};
nervana::manifest_file manifest2{
manifest_builder.manifest_file(), false, manifest_root, subset_fraction, block_size, seed};
EXPECT_EQ(manifest1.get_crc(), manifest2.get_crc());
}
TEST(manifest, manifest_shuffle_repeatable)
{
const uint32_t seed = 1234;
const size_t block_size = 4;
const float subset_fraction = 1.0;
string source_dir = file_util::make_temp_directory(test_cache_directory);
manifest_manager manifest_builder{source_dir, 10, 25, 25};
string manifest_root;
nervana::manifest_file manifest1{
manifest_builder.manifest_file(), true, manifest_root, subset_fraction, block_size, seed};
nervana::manifest_file manifest2{
manifest_builder.manifest_file(), true, manifest_root, subset_fraction, block_size, seed};
EXPECT_EQ(manifest1.get_crc(), manifest2.get_crc());
}
TEST(manifest, subset_fraction)
{
string source_dir = file_util::make_temp_directory(test_cache_directory);
manifest_manager manifest_builder{source_dir, 1000, 25, 25};
uint32_t manifest1_crc;
uint32_t manifest2_crc;
const uint32_t seed = 1234;
float subset_fraction = 0.01;
int block_size = 4;
bool shuffle_manifest = true;
string manifest_root;
{
auto manifest = make_shared<nervana::manifest_file>(manifest_builder.manifest_file(),
shuffle_manifest,
manifest_root,
subset_fraction,
block_size,
seed);
ASSERT_NE(nullptr, manifest);
manifest1_crc = manifest->get_crc();
}
{
auto manifest = make_shared<nervana::manifest_file>(manifest_builder.manifest_file(),
shuffle_manifest,
manifest_root,
subset_fraction,
block_size,
seed);
ASSERT_NE(nullptr, manifest);
manifest2_crc = manifest->get_crc();
}
EXPECT_EQ(manifest1_crc, manifest2_crc);
}
TEST(manifest, crc_root_dir)
{
stringstream ss;
ss << manifest_file::get_metadata_char();
ss << manifest_file::get_file_type_id() << manifest_file::get_delimiter()
<< manifest_file::get_string_type_id() << "\n";
for (size_t i = 0; i < 100; i++)
{
ss << "relative/path/image" << i << ".jpg" << manifest_file::get_delimiter() << i << "\n";
}
uint32_t manifest1_crc;
uint32_t manifest2_crc;
float subset_fraction = 1.0;
int block_size = 4;
bool shuffle_manifest = false;
{
stringstream tmp{ss.str()};
string manifest_root = "/root1/";
auto manifest = make_shared<nervana::manifest_file>(
tmp, shuffle_manifest, manifest_root, subset_fraction, block_size);
ASSERT_NE(nullptr, manifest);
manifest1_crc = manifest->get_crc();
}
{
stringstream tmp{ss.str()};
string manifest_root = "/root2/";
auto manifest = make_shared<nervana::manifest_file>(
tmp, shuffle_manifest, manifest_root, subset_fraction, block_size);
ASSERT_NE(nullptr, manifest);
manifest2_crc = manifest->get_crc();
}
EXPECT_EQ(manifest1_crc, manifest2_crc);
}
TEST(manifest, comma)
{
string manifest_file = "tmp_manifest.tsv";
{
int height = 224;
int width = 224;
size_t batch_size = 128;
nlohmann::json image_config = {
{"type", "image"}, {"height", height}, {"width", width}, {"channel_major", false}};
nlohmann::json label_config = {{"type", "label"}, {"binary", false}};
nlohmann::json config = {{"manifest_filename", manifest_file},
{"batch_size", batch_size},
{"iteration_mode", "INFINITE"},
{"etl", {image_config, label_config}}};
loader_factory factory;
EXPECT_THROW(factory.get_loader(config), std::runtime_error);
}
}
| 32.070646 | 100 | 0.558033 | rkimballn1 |
96ed42bf3424581e9f4cf97c9a782dff03f56971 | 42,285 | cpp | C++ | code_reading/oceanbase-master/src/storage/blocksstable/ob_macro_block.cpp | wangcy6/weekly_read | 3a8837ee9cd957787ee1785e4066dd623e02e13a | [
"Apache-2.0"
] | null | null | null | code_reading/oceanbase-master/src/storage/blocksstable/ob_macro_block.cpp | wangcy6/weekly_read | 3a8837ee9cd957787ee1785e4066dd623e02e13a | [
"Apache-2.0"
] | null | null | null | code_reading/oceanbase-master/src/storage/blocksstable/ob_macro_block.cpp | wangcy6/weekly_read | 3a8837ee9cd957787ee1785e4066dd623e02e13a | [
"Apache-2.0"
] | 1 | 2020-10-18T12:59:31.000Z | 2020-10-18T12:59:31.000Z | /**
* Copyright (c) 2021 OceanBase
* OceanBase CE is licensed under Mulan PubL v2.
* You can use this software according to the terms and conditions of the Mulan PubL v2.
* You may obtain a copy of Mulan PubL v2 at:
* http://license.coscl.org.cn/MulanPubL-2.0
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PubL v2 for more details.
*/
#include "ob_macro_block.h"
#include "ob_store_file.h"
#include "lib/utility/ob_tracepoint.h"
#include "share/ob_task_define.h"
#include "storage/ob_multi_version_col_desc_generate.h"
#include "storage/ob_sstable.h"
#include "common/sql_mode/ob_sql_mode_utils.h"
#include "common/ob_store_format.h"
#include "observer/ob_server_struct.h"
#include "storage/ob_partition_meta_redo_module.h"
#include "storage/ob_file_system_util.h"
using namespace oceanbase::common;
using namespace oceanbase::share;
using namespace oceanbase::share::schema;
using namespace oceanbase::storage;
namespace oceanbase {
namespace blocksstable {
/**
* -------------------------------------------------------------------ObDataStoreDesc-------------------------------------------------------------------
*/
const char* ObDataStoreDesc::DEFAULT_MINOR_COMPRESS_NAME = "lz4_1.0";
int ObDataStoreDesc::cal_row_store_type(const share::schema::ObTableSchema& table_schema, const ObMergeType merge_type)
{
int ret = OB_SUCCESS;
if (!is_major_merge(merge_type)) { // not major
if (GCONF._enable_sparse_row) { // enable use sparse row
// buf minor merge and trans table write flat row
if (is_trans_table_id(table_schema.get_table_id())) {
row_store_type_ = FLAT_ROW_STORE;
} else {
row_store_type_ = SPARSE_ROW_STORE;
}
} else {
row_store_type_ = FLAT_ROW_STORE;
}
} else {
// major merge support flat only
row_store_type_ = FLAT_ROW_STORE;
}
STORAGE_LOG(DEBUG, "row store type", K(row_store_type_), K(merge_type));
return ret;
}
int ObDataStoreDesc::get_major_working_cluster_version()
{
int ret = OB_SUCCESS;
if (OB_UNLIKELY(!is_major_ || data_version_ <= 0)) {
ret = OB_ERR_UNEXPECTED;
STORAGE_LOG(
WARN, "Unexpected data store to get major working cluster version", K(ret), K_(is_major), K_(data_version));
} else {
ObFreezeInfoSnapshotMgr::FreezeInfoLite freeze_info;
if (OB_FAIL(ObFreezeInfoMgrWrapper::get_instance().get_freeze_info_by_major_version(data_version_, freeze_info))) {
STORAGE_LOG(WARN, "Failed to get freeze info", K(ret), K_(data_version));
} else if (freeze_info.cluster_version < 0) {
STORAGE_LOG(ERROR, "Unexpected cluster version of freeze info", K(ret), K(freeze_info));
major_working_cluster_version_ = 0;
} else {
major_working_cluster_version_ = freeze_info.cluster_version;
}
if (OB_SUCC(ret)) {
ObTaskController::get().allow_next_syslog();
STORAGE_LOG(INFO,
"Succ to get major working cluster version",
K_(major_working_cluster_version),
K(freeze_info),
K_(data_version));
}
}
return ret;
}
int ObDataStoreDesc::init(const ObTableSchema& table_schema, const int64_t data_version,
const ObMultiVersionRowInfo* multi_version_row_info, const int64_t partition_id, const ObMergeType merge_type,
const bool need_calc_column_checksum, const bool store_micro_block_column_checksum, const common::ObPGKey& pg_key,
const ObStorageFileHandle& file_handle, const int64_t snapshot_version, const bool need_check_order,
const bool need_index_tree)
{
int ret = OB_SUCCESS;
if (!table_schema.is_valid() || data_version < 0 || !pg_key.is_valid() || snapshot_version <= 0) {
ret = OB_INVALID_ARGUMENT;
STORAGE_LOG(WARN, "arguments is invalid", K(ret), K(table_schema), K(data_version), K(pg_key), K(snapshot_version));
} else {
reset();
is_major_ = storage::is_major_merge(merge_type);
table_id_ = table_schema.get_table_id();
partition_id_ = partition_id;
data_version_ = data_version;
pg_key_ = pg_key;
schema_rowkey_col_cnt_ = table_schema.get_rowkey_column_num();
column_index_scale_ = 1;
schema_version_ = table_schema.get_schema_version();
pct_free_ = table_schema.get_pctfree();
micro_block_size_ = table_schema.get_block_size();
macro_block_size_ = OB_FILE_SYSTEM.get_macro_block_size();
need_calc_column_checksum_ = need_calc_column_checksum && is_major_;
need_index_tree_ = need_index_tree;
store_micro_block_column_checksum_ = store_micro_block_column_checksum;
snapshot_version_ = snapshot_version;
need_calc_physical_checksum_ = true;
rowkey_helper_ = nullptr;
need_check_order_ = need_check_order;
// need_calc_physical_checksum_ = table_schema.get_storage_format_version() >=
// ObIPartitionStorage::STORAGE_FORMAT_VERSION_V3;
if (pct_free_ >= 0 && pct_free_ <= 50) {
macro_store_size_ = macro_block_size_ * (100 - pct_free_) / 100;
} else {
macro_store_size_ = macro_block_size_ * DEFAULT_RESERVE_PERCENT / 100;
}
if (OB_SUCC(ret)) {
if (OB_FAIL(file_handle_.assign(file_handle))) {
STORAGE_LOG(WARN, "failed to assign file handle", K(ret), K(file_handle));
}
}
if (OB_SUCC(ret)) {
if (OB_NOT_NULL(multi_version_row_info) && multi_version_row_info->is_valid()) {
row_column_count_ = multi_version_row_info->column_cnt_;
rowkey_column_count_ = multi_version_row_info->multi_version_rowkey_column_cnt_;
} else if (OB_FAIL(table_schema.get_store_column_count(row_column_count_))) {
STORAGE_LOG(WARN, "failed to get store column count", K(ret), K_(table_id), K_(partition_id));
} else {
rowkey_column_count_ = table_schema.get_rowkey_column_num();
}
}
if (OB_SUCC(ret)) {
const char* compress_func = nullptr;
if (OB_ISNULL(compress_func = table_schema.get_compress_func_name())) {
ret = OB_ERR_UNEXPECTED;
STORAGE_LOG(WARN, "Unexpected null compress func name", K(ret), K(table_schema));
} else if (strlen(compress_func) < static_cast<uint64_t>(OB_MAX_HEADER_COMPRESSOR_NAME_LENGTH)) {
if (!is_major_ && 0 != strcmp(compress_func, "none")) {
compress_func = DEFAULT_MINOR_COMPRESS_NAME;
}
strncpy(compressor_name_, compress_func, OB_MAX_HEADER_COMPRESSOR_NAME_LENGTH);
} else {
ret = OB_SIZE_OVERFLOW;
STORAGE_LOG(WARN, "The name of compressor is too long", K(ret), K(table_schema));
}
}
if (OB_SUCC(ret)) {
const int64_t header_version =
store_micro_block_column_checksum ? RECORD_HEADER_VERSION_V3 : RECORD_HEADER_VERSION_V2;
const int64_t entry_size = ObMicroBlockIndexWriter::get_entry_size(NULL != multi_version_row_info);
const int64_t record_header_size = ObRecordHeaderV3::get_serialize_size(header_version, row_column_count_);
const ObMacroBlockCommonHeader common_header;
micro_block_size_limit_ = macro_block_size_ - common_header.get_serialize_size() -
sizeof(ObSSTableMacroBlockHeader) - entry_size - record_header_size -
ObMicroBlockIndexWriter::INDEX_ENTRY_SIZE // last entry
- MIN_RESERVED_SIZE;
progressive_merge_round_ = table_schema.get_progressive_merge_round();
need_prebuild_bloomfilter_ = table_schema.is_use_bloomfilter();
bloomfilter_size_ = 0;
bloomfilter_rowkey_prefix_ = 0;
}
if (OB_FAIL(ret)) {
} else if (OB_FAIL(cal_row_store_type(table_schema, merge_type))) {
STORAGE_LOG(WARN, "Failed to make the row store type", K(ret));
} else if (OB_FAIL(table_schema.has_lob_column(has_lob_column_, true))) {
STORAGE_LOG(WARN, "Failed to check lob column in table schema", K(ret));
} else if (is_major_ && OB_FAIL(get_major_working_cluster_version())) {
STORAGE_LOG(WARN, "Failed to get major working cluster version", K(ret));
} else {
ObSEArray<ObColDesc, OB_DEFAULT_SE_ARRAY_COUNT> column_list;
if (OB_NOT_NULL(multi_version_row_info) && multi_version_row_info->is_valid()) {
ObMultiVersionColDescGenerate multi_version_col_desc_gen;
if (OB_FAIL(multi_version_col_desc_gen.init(&table_schema))) {
STORAGE_LOG(WARN, "fail to init multi version col desc generate", K(ret));
} else if (OB_FAIL(multi_version_col_desc_gen.generate_column_ids(column_list))) {
STORAGE_LOG(WARN, "fail to get multi version col desc column list", K(ret));
}
} else {
if (OB_FAIL(table_schema.get_store_column_ids(column_list))) {
STORAGE_LOG(WARN, "Fail to get column ids, ", K(ret));
}
}
if (OB_SUCC(ret) && 0 == column_list.count()) {
ret = OB_ERR_UNEXPECTED;
STORAGE_LOG(WARN, "column ids should not be empty", K(ret), K(column_list.count()));
}
if (OB_SUCC(ret)) {
for (int64_t i = 0; OB_SUCC(ret) && i < column_list.count(); ++i) {
if (i >= common::OB_MAX_COLUMN_NUMBER) {
ret = OB_SIZE_OVERFLOW;
STORAGE_LOG(WARN, "column type&id list overflow.", K(ret));
} else {
column_ids_[i] = column_list.at(i).col_id_;
column_types_[i] = column_list.at(i).col_type_;
column_orders_[i] = column_list.at(i).col_order_;
}
}
}
}
}
return ret;
}
bool ObDataStoreDesc::is_valid() const
{
return table_id_ > 0 && data_version_ >= 0 && micro_block_size_ > 0 && micro_block_size_limit_ > 0 &&
row_column_count_ > 0 && rowkey_column_count_ > 0 && row_column_count_ >= rowkey_column_count_ &&
column_index_scale_ > 0 && schema_version_ >= 0 && schema_rowkey_col_cnt_ >= 0 && partition_id_ >= -1 &&
pct_free_ >= 0 && snapshot_version_ > 0 && pg_key_.is_valid() && file_handle_.is_valid();
// TODO:compresor_name_
// row_store_type_
}
void ObDataStoreDesc::reset()
{
table_id_ = 0;
partition_id_ = -1;
data_version_ = 0;
macro_block_size_ = 0;
macro_store_size_ = 0;
micro_block_size_ = 0;
micro_block_size_limit_ = 0;
row_column_count_ = 0;
rowkey_column_count_ = 0;
column_index_scale_ = 0;
schema_rowkey_col_cnt_ = 0;
row_store_type_ = FLAT_ROW_STORE;
schema_version_ = 0;
pct_free_ = 0;
mark_deletion_maker_ = NULL;
merge_info_ = NULL;
has_lob_column_ = false;
is_major_ = false;
MEMSET(compressor_name_, 0, OB_MAX_HEADER_COMPRESSOR_NAME_LENGTH);
MEMSET(column_ids_, 0, sizeof(column_ids_));
MEMSET(column_types_, 0, sizeof(column_types_));
MEMSET(column_orders_, 0, sizeof(column_orders_));
need_calc_column_checksum_ = false;
need_index_tree_ = false;
store_micro_block_column_checksum_ = false;
snapshot_version_ = 0;
need_calc_physical_checksum_ = false;
need_prebuild_bloomfilter_ = false;
bloomfilter_size_ = 0;
bloomfilter_rowkey_prefix_ = 0;
rowkey_helper_ = nullptr;
pg_key_.reset();
file_handle_.reset();
need_check_order_ = true;
progressive_merge_round_ = 0;
major_working_cluster_version_ = 0;
}
int ObDataStoreDesc::assign(const ObDataStoreDesc& desc)
{
int ret = OB_SUCCESS;
table_id_ = desc.table_id_;
partition_id_ = desc.partition_id_;
data_version_ = desc.data_version_;
macro_block_size_ = desc.macro_block_size_;
macro_store_size_ = desc.macro_store_size_;
micro_block_size_ = desc.micro_block_size_;
micro_block_size_limit_ = desc.micro_block_size_limit_;
row_column_count_ = desc.row_column_count_;
rowkey_column_count_ = desc.rowkey_column_count_;
column_index_scale_ = desc.column_index_scale_;
row_store_type_ = desc.row_store_type_;
schema_version_ = desc.schema_version_;
schema_rowkey_col_cnt_ = desc.schema_rowkey_col_cnt_;
pct_free_ = desc.pct_free_;
mark_deletion_maker_ = desc.mark_deletion_maker_;
merge_info_ = desc.merge_info_;
has_lob_column_ = desc.has_lob_column_;
is_major_ = desc.is_major_;
MEMCPY(compressor_name_, desc.compressor_name_, OB_MAX_HEADER_COMPRESSOR_NAME_LENGTH);
MEMCPY(column_ids_, desc.column_ids_, sizeof(column_ids_));
MEMCPY(column_types_, desc.column_types_, sizeof(column_types_));
MEMCPY(column_orders_, desc.column_orders_, sizeof(column_orders_));
need_calc_column_checksum_ = desc.need_calc_column_checksum_;
store_micro_block_column_checksum_ = desc.store_micro_block_column_checksum_;
snapshot_version_ = desc.snapshot_version_;
need_calc_physical_checksum_ = desc.need_calc_physical_checksum_;
need_index_tree_ = desc.need_index_tree_;
need_prebuild_bloomfilter_ = desc.need_prebuild_bloomfilter_;
bloomfilter_size_ = desc.need_prebuild_bloomfilter_;
bloomfilter_rowkey_prefix_ = desc.bloomfilter_rowkey_prefix_;
rowkey_helper_ = desc.rowkey_helper_;
pg_key_ = desc.pg_key_;
need_check_order_ = desc.need_check_order_;
major_working_cluster_version_ = desc.major_working_cluster_version_;
if (OB_FAIL(file_handle_.assign(desc.file_handle_))) {
STORAGE_LOG(WARN, "failed to assign file handle", K(ret), K(desc.file_handle_));
}
return ret;
}
/**
* -------------------------------------------------------------------ObMicroBlockCompressor-------------------------------------------------------------------
*/
ObMicroBlockCompressor::ObMicroBlockCompressor()
: is_none_(false),
micro_block_size_(0),
compressor_(NULL),
comp_buf_(0, "MicrBlocComp"),
decomp_buf_(0, "MicrBlocDecomp")
{}
ObMicroBlockCompressor::~ObMicroBlockCompressor()
{}
void ObMicroBlockCompressor::reset()
{
is_none_ = false;
micro_block_size_ = 0;
compressor_ = NULL;
comp_buf_.reuse();
decomp_buf_.reuse();
}
int ObMicroBlockCompressor::init(const int64_t micro_block_size, const char* compname)
{
int ret = OB_SUCCESS;
reset();
if (OB_UNLIKELY(micro_block_size <= 0)) {
ret = OB_INVALID_ARGUMENT;
STORAGE_LOG(WARN, "Invalid argument, ", K(ret), K(micro_block_size), KP(compname));
} else if (NULL == compname || compname[0] == '\0' || 0 == strcmp(compname, "none")) {
is_none_ = true;
} else if (OB_FAIL(ObCompressorPool::get_instance().get_compressor(compname, compressor_))) {
STORAGE_LOG(WARN, "Fail to get compressor, ", K(ret), "compressor_name", compname);
} else {
is_none_ = false;
micro_block_size_ = micro_block_size;
}
return ret;
}
int ObMicroBlockCompressor::compress(const char* in, const int64_t in_size, const char*& out, int64_t& out_size)
{
int ret = OB_SUCCESS;
int64_t max_overflow_size = 0;
if (is_none_) {
out = in;
out_size = in_size;
} else if (OB_FAIL(compressor_->get_max_overflow_size(in_size, max_overflow_size))) {
STORAGE_LOG(WARN, "fail to get max_overflow_size, ", K(ret), K(in_size));
} else {
int64_t comp_size = 0;
int64_t max_comp_size = max_overflow_size + in_size;
int64_t need_size = std::max(max_comp_size, micro_block_size_ * 2);
if (OB_SUCCESS != (ret = comp_buf_.ensure_space(need_size))) {
STORAGE_LOG(WARN, "macro block writer fail to allocate memory for comp_buf_.", K(ret), K(need_size));
} else if (OB_SUCCESS != (ret = compressor_->compress(in, in_size, comp_buf_.data(), max_comp_size, comp_size))) {
STORAGE_LOG(WARN,
"compressor fail to compress.",
K(in),
K(in_size),
"comp_ptr",
comp_buf_.data(),
K(max_comp_size),
K(comp_size));
} else if (comp_size >= in_size) {
STORAGE_LOG(INFO, "compressed_size is larger than origin_size", K(comp_size), K(in_size));
out = in;
out_size = in_size;
} else {
out = comp_buf_.data();
out_size = comp_size;
comp_buf_.reuse();
}
}
return ret;
}
int ObMicroBlockCompressor::decompress(
const char* in, const int64_t in_size, const int64_t uncomp_size, const char*& out, int64_t& out_size)
{
int ret = OB_SUCCESS;
int64_t decomp_size = 0;
decomp_buf_.reuse();
if (is_none_ || in_size == uncomp_size) {
out = in;
out_size = in_size;
} else if (OB_FAIL(decomp_buf_.ensure_space(uncomp_size))) {
STORAGE_LOG(WARN, "failed to ensure decomp space", K(ret), K(uncomp_size));
} else if (OB_FAIL(compressor_->decompress(in, in_size, decomp_buf_.data(), uncomp_size, decomp_size))) {
STORAGE_LOG(WARN, "failed to decompress data", K(ret), K(in_size), K(uncomp_size));
} else {
out = decomp_buf_.data();
out_size = decomp_size;
}
return ret;
}
/**
* -------------------------------------------------------------------ObMicroBlockDesc-------------------------------------------------------------------
*/
bool ObMicroBlockDesc::is_valid() const
{
return !last_rowkey_.empty() && NULL != buf_ && buf_size_ > 0 && data_size_ > 0 && row_count_ > 0 &&
column_count_ > 0 && max_merged_trans_version_ >= 0;
}
void ObMicroBlockDesc::reset()
{
last_rowkey_.reset();
buf_ = NULL;
buf_size_ = 0;
data_size_ = 0;
row_count_ = 0;
column_count_ = 0;
row_count_delta_ = 0;
can_mark_deletion_ = false;
column_checksums_ = NULL;
max_merged_trans_version_ = 0;
contain_uncommitted_row_ = false;
}
/**
* -------------------------------------------------------------------ObMacroBlock-------------------------------------------------------------------
*/
ObMacroBlock::ObMacroBlock()
: spec_(NULL),
row_reader_(NULL),
data_(0, "MacrBlocData"),
index_(),
header_(NULL),
column_ids_(NULL),
column_types_(NULL),
column_orders_(NULL),
column_checksum_(NULL),
data_base_offset_(0),
row_(),
is_dirty_(false),
is_multi_version_(false),
macro_block_deletion_flag_(true),
delta_(0),
need_calc_column_checksum_(false),
common_header_(),
max_merged_trans_version_(0),
contain_uncommitted_row_(false),
pg_guard_(),
pg_file_(NULL)
{
row_.cells_ = rowkey_objs_;
row_.count_ = 0;
}
ObMacroBlock::~ObMacroBlock()
{}
int ObMacroBlock::init_row_reader(const ObRowStoreType row_store_type)
{
int ret = OB_SUCCESS;
if (FLAT_ROW_STORE == row_store_type) {
row_reader_ = &flat_row_reader_;
} else if (SPARSE_ROW_STORE == row_store_type) {
row_reader_ = &sparse_row_reader_;
} else {
ret = OB_INVALID_ARGUMENT;
STORAGE_LOG(WARN, "invalid argument", K(ret), K(row_store_type));
}
return ret;
}
int ObMacroBlock::init(ObDataStoreDesc& spec)
{
int ret = OB_SUCCESS;
reset();
if (OB_FAIL(data_.ensure_space(spec.macro_block_size_))) {
STORAGE_LOG(WARN, "macro block fail to ensure space for data.", K(ret), "macro_block_size", spec.macro_block_size_);
} else if (OB_FAIL(index_.init(spec.macro_block_size_, spec.is_multi_version_minor_sstable()))) {
STORAGE_LOG(
WARN, "macro block fail to ensure space for index.", K(ret), "macro_block_size", spec.macro_block_size_);
} else if (OB_FAIL(reserve_header(spec))) {
STORAGE_LOG(WARN, "macro block fail to reserve header.", K(ret));
} else if (OB_ISNULL(pg_file_ = spec.file_handle_.get_storage_file())) {
ret = OB_ERR_UNEXPECTED;
STORAGE_LOG(WARN, "fail to get pg file", K(ret), K(spec.file_handle_));
} else if (OB_FAIL(init_row_reader(spec.row_store_type_))) {
STORAGE_LOG(WARN, "macro block fail to init row reader.", K(ret));
} else {
is_multi_version_ = spec.is_multi_version_minor_sstable();
need_calc_column_checksum_ = spec.need_calc_column_checksum_;
spec_ = &spec;
}
return ret;
}
int ObMacroBlock::write_micro_record_header(const ObMicroBlockDesc& micro_block_desc)
{
int ret = OB_SUCCESS;
if (OB_UNLIKELY(!micro_block_desc.is_valid())) {
ret = OB_INVALID_ARGUMENT;
STORAGE_LOG(WARN, "invalid arguments", K(ret), K(micro_block_desc));
} else {
const char* buf = micro_block_desc.buf_;
const int64_t size = micro_block_desc.buf_size_;
const int64_t data_size = micro_block_desc.data_size_;
const int64_t header_version =
spec_->store_micro_block_column_checksum_ ? RECORD_HEADER_VERSION_V3 : RECORD_HEADER_VERSION_V2;
ObRecordHeaderV3 record_header;
int64_t pos = 0;
record_header.magic_ = MICRO_BLOCK_HEADER_MAGIC;
record_header.header_length_ =
RECORD_HEADER_VERSION_V2 == header_version
? static_cast<int8_t>(ObRecordHeaderV3::get_serialize_size(header_version, 0 /*column cnt*/))
: static_cast<int8_t>(sizeof(ObRecordHeaderV3));
record_header.version_ = static_cast<int8_t>(header_version);
record_header.header_checksum_ = 0;
record_header.reserved16_ = 0;
record_header.data_length_ = data_size;
record_header.data_zlength_ = size;
record_header.data_checksum_ = ob_crc64_sse42(0, buf, size);
record_header.data_encoding_length_ = 0;
record_header.row_count_ = static_cast<int32_t>(micro_block_desc.row_count_);
record_header.column_cnt_ = static_cast<uint16_t>(micro_block_desc.column_count_);
record_header.column_checksums_ = micro_block_desc.column_checksums_;
record_header.set_header_checksum();
header_->data_checksum_ =
ob_crc64_sse42(header_->data_checksum_, &record_header.data_checksum_, sizeof(record_header.data_checksum_));
if (OB_FAIL(record_header.serialize(data_.current(), get_remain_size(), pos))) {
STORAGE_LOG(WARN, "fail to serialize record header", K(ret));
}
if (OB_SUCC(ret)) {
const int64_t header_size = ObRecordHeaderV3::get_serialize_size(header_version, micro_block_desc.column_count_);
if (OB_FAIL(data_.advance(header_size))) {
STORAGE_LOG(WARN, "fail to advance record header", K(ret));
}
}
}
return ret;
}
int ObMacroBlock::write_micro_block(const ObMicroBlockDesc& micro_block_desc, int64_t& data_offset)
{
int ret = OB_SUCCESS;
data_offset = data_.length() - data_base_offset_;
if (!micro_block_desc.is_valid()) {
ret = OB_INVALID_ARGUMENT;
STORAGE_LOG(WARN, "invalid arguments", K(micro_block_desc), K(ret));
} else {
const int64_t entry_size = ObMicroBlockIndexWriter::get_entry_size(is_multi_version_);
const int64_t header_version =
spec_->store_micro_block_column_checksum_ ? RECORD_HEADER_VERSION_V3 : RECORD_HEADER_VERSION_V2;
const int64_t record_header_size =
ObRecordHeaderV3::get_serialize_size(header_version, micro_block_desc.column_count_);
if (micro_block_desc.buf_size_ + entry_size + record_header_size + micro_block_desc.last_rowkey_.length() >
get_remain_size()) {
ret = OB_BUF_NOT_ENOUGH;
}
}
if (OB_SUCC(ret)) {
const char* buf = micro_block_desc.buf_;
const int64_t size = micro_block_desc.buf_size_;
if (OB_FAIL(index_.add_entry(micro_block_desc.last_rowkey_,
data_offset,
micro_block_desc.can_mark_deletion_,
micro_block_desc.row_count_delta_))) {
STORAGE_LOG(WARN,
"index add entry failed",
K(ret),
"last_rowkey",
micro_block_desc.last_rowkey_,
K(data_offset),
K(micro_block_desc.can_mark_deletion_),
K(micro_block_desc.row_count_delta_));
} else if (OB_FAIL(write_micro_record_header(micro_block_desc))) {
STORAGE_LOG(WARN, "fail to write micro record header", K(ret), K(micro_block_desc));
} else {
is_dirty_ = true;
MEMCPY(data_.current(), buf, static_cast<size_t>(size));
if (OB_FAIL(data_.advance(size))) {
STORAGE_LOG(WARN, "data advance failed", K(ret), K(size));
}
}
if (OB_SUCC(ret)) {
delta_ += micro_block_desc.row_count_delta_;
++header_->micro_block_count_;
header_->row_count_ += static_cast<int32_t>(micro_block_desc.row_count_);
header_->occupy_size_ = static_cast<int32_t>(get_data_size());
// update info from micro_block
update_max_merged_trans_version(micro_block_desc.max_merged_trans_version_);
if (micro_block_desc.contain_uncommitted_row_) {
set_contain_uncommitted_row();
}
if (macro_block_deletion_flag_) {
macro_block_deletion_flag_ = micro_block_desc.can_mark_deletion_;
}
if (need_calc_column_checksum_) {
if (OB_FAIL(add_column_checksum(
micro_block_desc.column_checksums_, micro_block_desc.column_count_, column_checksum_))) {
STORAGE_LOG(WARN, "fail to add column checksum", K(ret));
}
}
}
}
return ret;
}
int ObMacroBlock::flush(
const int64_t cur_macro_seq, ObMacroBlockHandle& macro_handle, ObMacroBlocksWriteCtx& block_write_ctx)
{
int ret = OB_SUCCESS;
ObFullMacroBlockMeta full_meta;
ObMacroBlockMetaV2 macro_block_meta;
ObMacroBlockSchemaInfo macro_schema;
full_meta.meta_ = ¯o_block_meta;
full_meta.schema_ = ¯o_schema;
#ifdef ERRSIM
ret = E(EventTable::EN_BAD_BLOCK_ERROR) OB_SUCCESS;
if (OB_CHECKSUM_ERROR == ret) { // obtest will set this code
STORAGE_LOG(INFO, "ERRSIM bad block: Insert a bad block.");
header_->magic_ = 0;
header_->data_checksum_ = 0;
}
#endif
if (OB_FAIL(build_header(cur_macro_seq))) {
STORAGE_LOG(WARN, "Fail to build header, ", K(ret), K(cur_macro_seq));
} else if (OB_FAIL(build_macro_meta(full_meta))) {
STORAGE_LOG(WARN, "Fail to build macro block meta, ", K(ret));
} else if (OB_FAIL(build_index())) {
STORAGE_LOG(WARN, "Fail to build index, ", K(ret));
} else if (spec_->need_calc_physical_checksum_) {
const int64_t common_header_size = common_header_.get_serialize_size();
const char* payload_buf = data_.data() + common_header_size;
const int64_t payload_size = data_.length() - common_header_size;
common_header_.set_payload_size(static_cast<int32_t>(payload_size));
common_header_.set_payload_checksum(static_cast<int32_t>(ob_crc64(payload_buf, payload_size)));
}
if (OB_FAIL(ret)) {
// do nothing
} else if (OB_FAIL(common_header_.build_serialized_header(data_.data(), data_.capacity()))) {
STORAGE_LOG(WARN, "Fail to build common header, ", K(ret), K_(common_header));
} else {
ObMacroBlockWriteInfo write_info;
write_info.buffer_ = data_.data();
write_info.size_ = data_.capacity();
write_info.meta_ = full_meta;
write_info.io_desc_.category_ = SYS_IO;
write_info.io_desc_.wait_event_no_ = ObWaitEventIds::DB_FILE_COMPACT_WRITE;
write_info.block_write_ctx_ = &block_write_ctx;
macro_handle.set_file(pg_file_);
if (OB_ISNULL(pg_file_)) {
ret = OB_ERR_SYS;
STORAGE_LOG(WARN, "pg_file is null", K(ret), K(pg_file_));
} else if (OB_FAIL(pg_file_->async_write_block(write_info, macro_handle))) {
STORAGE_LOG(WARN, "Fail to async write block, ", K(ret));
} else {
if (NULL != spec_ && NULL != spec_->merge_info_) {
spec_->merge_info_->macro_block_count_++;
spec_->merge_info_->occupy_size_ += macro_block_meta.occupy_size_;
if (macro_block_meta.is_sstable_data_block()) {
spec_->merge_info_->total_row_count_ += macro_block_meta.row_count_;
}
}
ObTaskController::get().allow_next_syslog();
STORAGE_LOG(INFO,
"macro block writer succeed to flush macro block.",
"block_id",
macro_handle.get_macro_id(),
K(*header_),
K(full_meta),
KP(¯o_handle));
}
}
return ret;
}
int ObMacroBlock::merge(const ObMacroBlock& macro_block)
{
int ret = OB_SUCCESS;
const uint64_t cluster_observer_version = GET_MIN_CLUSTER_VERSION();
int64_t prev_data_offset = data_.length() - data_base_offset_;
if (get_remain_size() < macro_block.get_raw_data_size()) {
STORAGE_LOG(WARN,
"current macro block raw size out of remain buffer.",
"remain_size",
get_remain_size(),
"raw_data_size",
macro_block.get_raw_data_size());
ret = OB_BUF_NOT_ENOUGH;
} else if (OB_FAIL(index_.merge(prev_data_offset, macro_block.index_))) {
STORAGE_LOG(WARN, "current macro block index data out of index buffer.", K(ret));
} else if (OB_FAIL(data_.write(macro_block.get_micro_block_data_ptr(), macro_block.get_micro_block_data_size()))) {
STORAGE_LOG(WARN,
"macro block fail to writer micro block data.",
K(ret),
"buf",
OB_P(macro_block.get_micro_block_data_ptr()),
"size",
macro_block.get_micro_block_data_size());
} else {
header_->row_count_ += macro_block.header_->row_count_;
header_->occupy_size_ = static_cast<int32_t>(get_data_size());
header_->micro_block_count_ += macro_block.header_->micro_block_count_;
delta_ = is_multi_version_ ? (macro_block.delta_ + delta_) : 0;
macro_block_deletion_flag_ =
is_multi_version_ && macro_block_deletion_flag_ && macro_block.macro_block_deletion_flag_;
max_merged_trans_version_ = std::max(max_merged_trans_version_, macro_block.max_merged_trans_version_);
contain_uncommitted_row_ = contain_uncommitted_row_ || macro_block.contain_uncommitted_row_;
if (cluster_observer_version < CLUSTER_VERSION_140) {
header_->data_checksum_ = ob_crc64_sse42(
header_->data_checksum_, ¯o_block.header_->data_checksum_, sizeof(header_->data_checksum_));
} else {
if (OB_FAIL(merge_data_checksum(macro_block))) {
STORAGE_LOG(WARN, "failed to merge data checksum", K(ret), K(cluster_observer_version));
}
if (OB_SUCC(ret) && need_calc_column_checksum_) {
if (OB_FAIL(add_column_checksum(macro_block.column_checksum_, header_->column_count_, column_checksum_))) {
STORAGE_LOG(WARN, "fail to add column checksum", K(ret));
}
}
}
}
return ret;
}
bool ObMacroBlock::can_merge(const ObMacroBlock& macro_block)
{
return is_dirty_ && macro_block.is_dirty_ && get_remain_size() > macro_block.get_raw_data_size();
}
void ObMacroBlock::reset()
{
data_.reuse();
index_.reset();
header_ = NULL;
column_ids_ = NULL;
column_types_ = NULL;
column_orders_ = NULL;
column_checksum_ = NULL;
data_base_offset_ = 0;
is_dirty_ = false;
delta_ = 0;
row_reader_ = NULL;
macro_block_deletion_flag_ = true;
need_calc_column_checksum_ = false;
max_merged_trans_version_ = 0;
contain_uncommitted_row_ = false;
pg_guard_.reset();
pg_file_ = NULL;
}
int ObMacroBlock::reserve_header(const ObDataStoreDesc& spec)
{
int ret = OB_SUCCESS;
common_header_.reset();
common_header_.set_attr(ObMacroBlockCommonHeader::SSTableData);
common_header_.set_data_version(spec.data_version_);
common_header_.set_reserved(0);
const int64_t common_header_size = common_header_.get_serialize_size();
MEMSET(data_.data(), 0, data_.capacity());
if (OB_FAIL(data_.advance(common_header_size))) {
STORAGE_LOG(WARN, "data buffer is not enough for common header.", K(ret), K(common_header_size));
}
if (OB_SUCC(ret)) {
int64_t column_count = spec.row_column_count_;
int64_t rowkey_column_count = spec.rowkey_column_count_;
int64_t column_checksum_size = sizeof(int64_t) * column_count;
int64_t column_id_size = sizeof(uint16_t) * column_count;
int64_t column_type_size = sizeof(ObObjMeta) * column_count;
int64_t column_order_size = sizeof(ObOrderType) * column_count;
int64_t macro_block_header_size = sizeof(ObSSTableMacroBlockHeader);
header_ = reinterpret_cast<ObSSTableMacroBlockHeader*>(data_.current());
column_ids_ = reinterpret_cast<uint16_t*>(data_.current() + macro_block_header_size);
column_types_ = reinterpret_cast<ObObjMeta*>(data_.current() + macro_block_header_size + column_id_size);
column_orders_ =
reinterpret_cast<ObOrderType*>(data_.current() + macro_block_header_size + column_id_size + column_type_size);
column_checksum_ = reinterpret_cast<int64_t*>(
data_.current() + macro_block_header_size + column_id_size + column_type_size + column_order_size);
macro_block_header_size += column_checksum_size + column_id_size + column_type_size + column_order_size;
// for compatibility, fill 0 to checksum and this will be serialized to disk
for (int i = 0; i < column_count; i++) {
column_checksum_[i] = 0;
}
if (OB_FAIL(data_.advance(macro_block_header_size))) {
STORAGE_LOG(WARN, "macro_block_header_size out of data buffer.", K(ret));
} else {
memset(header_, 0, macro_block_header_size);
header_->header_size_ = static_cast<int32_t>(macro_block_header_size);
header_->version_ = SSTABLE_MACRO_BLOCK_HEADER_VERSION_v3;
header_->magic_ = SSTABLE_DATA_HEADER_MAGIC;
header_->attr_ = 0;
header_->table_id_ = spec.table_id_;
header_->data_version_ = spec.data_version_;
header_->column_count_ = static_cast<int32_t>(column_count);
header_->rowkey_column_count_ = static_cast<int32_t>(rowkey_column_count);
header_->column_index_scale_ = static_cast<int32_t>(spec.column_index_scale_);
header_->row_store_type_ = static_cast<int32_t>(spec.row_store_type_);
header_->micro_block_size_ = static_cast<int32_t>(spec.micro_block_size_);
header_->micro_block_data_offset_ = header_->header_size_ + static_cast<int32_t>(common_header_size);
memset(header_->compressor_name_, 0, OB_MAX_HEADER_COMPRESSOR_NAME_LENGTH);
MEMCPY(header_->compressor_name_, spec.compressor_name_, strlen(spec.compressor_name_));
header_->data_seq_ = 0;
header_->partition_id_ = spec.partition_id_;
// copy column id & type array;
for (int64_t i = 0; i < header_->column_count_; ++i) {
column_ids_[i] = static_cast<int16_t>(spec.column_ids_[i]);
column_types_[i] = spec.column_types_[i];
column_orders_[i] = spec.column_orders_[i];
}
}
}
if (OB_SUCC(ret)) {
data_base_offset_ = header_->header_size_ + common_header_size;
}
return ret;
}
int ObMacroBlock::build_header(const int64_t cur_macro_seq)
{
int ret = OB_SUCCESS;
if (OB_ISNULL(header_)) {
ret = OB_ERR_UNEXPECTED;
STORAGE_LOG(WARN, "The header is NULL, ", K(ret), KP_(header));
} else {
int64_t data_length = data_.length();
int64_t index_length = index_.get_index().length();
int64_t endkey_length = index_.get_data().length();
header_->micro_block_data_size_ = static_cast<int32_t>(data_length - data_base_offset_);
header_->micro_block_index_offset_ = static_cast<int32_t>(data_length);
header_->micro_block_index_size_ = static_cast<int32_t>(index_length + ObMicroBlockIndexWriter::INDEX_ENTRY_SIZE);
header_->micro_block_endkey_offset_ = static_cast<int32_t>(data_length + header_->micro_block_index_size_);
header_->micro_block_endkey_size_ = static_cast<int32_t>(endkey_length);
header_->data_seq_ = cur_macro_seq;
}
return ret;
}
int ObMacroBlock::build_index()
{
int ret = OB_SUCCESS;
if (index_.get_block_size() > data_.remain()) {
STORAGE_LOG(WARN,
"micro block index size is larger than macro data remain size.",
"index_size",
index_.get_block_size(),
"data_remain_size",
data_.remain());
ret = OB_BUF_NOT_ENOUGH;
} else if (OB_FAIL(index_.add_last_entry(header_->micro_block_data_size_))) {
STORAGE_LOG(WARN,
"micro block index fail to add last entry",
K(ret),
"micro_block_data_size",
header_->micro_block_data_size_);
} else if (OB_FAIL(data_.write(index_.get_index().data(), index_.get_index().length()))) {
STORAGE_LOG(WARN,
"macro block fail to copy index.",
K(ret),
"index_ptr",
OB_P(index_.get_index().data()),
"index_length",
index_.get_index().length());
} else if (OB_FAIL(data_.write(index_.get_data().data(), index_.get_data().length()))) {
STORAGE_LOG(WARN,
"macro block fail to copy endkey.",
K(ret),
"endkey_ptr",
OB_P(index_.get_data().data()),
"endkey_length",
index_.get_data().length());
} else if (is_multi_version_) {
if (OB_FAIL(data_.write(index_.get_mark_deletion().data(), index_.get_mark_deletion().length()))) {
STORAGE_LOG(WARN,
"macro block fail to copy mark deletion.",
K(ret),
"mark_deletion_ptr",
OB_P(index_.get_mark_deletion().data()),
"mark_deletion_length",
index_.get_mark_deletion().length());
} else if (OB_FAIL(data_.write(index_.get_delta().data(), index_.get_delta().length()))) {
STORAGE_LOG(WARN,
"macro block fail to copy delta",
K(ret),
"delta ptr",
OB_P(index_.get_delta().data()),
"delta size",
index_.get_delta().length());
}
}
return ret;
}
int ObMacroBlock::build_macro_meta(ObFullMacroBlockMeta& full_meta)
{
int ret = OB_SUCCESS;
ObString s_rowkey;
int64_t pos = 0;
if (OB_ISNULL(row_reader_)) {
ret = OB_ERR_UNEXPECTED;
STORAGE_LOG(WARN, "row reader is null", K(ret));
} else if (OB_UNLIKELY(nullptr == full_meta.meta_ || nullptr == full_meta.schema_)) {
ret = OB_INVALID_ARGUMENT;
STORAGE_LOG(WARN, "invalid arguments", K(ret), K(full_meta));
} else if (OB_FAIL(index_.get_last_rowkey(s_rowkey))) {
STORAGE_LOG(WARN, "micro block index writer fail to get last rowkey", K(ret));
} else if (OB_FAIL(row_reader_->read_compact_rowkey(
spec_->column_types_, spec_->rowkey_column_count_, s_rowkey.ptr(), s_rowkey.length(), pos, row_))) {
STORAGE_LOG(WARN, "row reader fail to read row.", K(ret));
} else {
ObMacroBlockMetaV2& mbi = const_cast<ObMacroBlockMetaV2&>(*full_meta.meta_);
ObMacroBlockSchemaInfo& schema = const_cast<ObMacroBlockSchemaInfo&>(*full_meta.schema_);
mbi.endkey_ = row_.cells_;
mbi.snapshot_version_ = spec_->snapshot_version_;
mbi.attr_ = ObMacroBlockCommonHeader::SSTableData;
mbi.create_timestamp_ = 0;
mbi.data_version_ = header_->data_version_;
mbi.column_number_ = static_cast<int16_t>(header_->column_count_);
mbi.rowkey_column_number_ = static_cast<int16_t>(header_->rowkey_column_count_);
mbi.column_index_scale_ = static_cast<int16_t>(header_->column_index_scale_);
mbi.row_store_type_ = static_cast<int16_t>(header_->row_store_type_);
mbi.row_count_ = header_->row_count_;
mbi.occupy_size_ = header_->occupy_size_;
mbi.column_checksum_ = column_checksum_;
mbi.data_checksum_ = header_->data_checksum_;
mbi.micro_block_count_ = header_->micro_block_count_;
mbi.micro_block_data_offset_ = header_->micro_block_data_offset_;
mbi.micro_block_index_offset_ = header_->micro_block_index_offset_;
mbi.micro_block_endkey_offset_ = header_->micro_block_endkey_offset_;
mbi.table_id_ = header_->table_id_;
mbi.data_seq_ = header_->data_seq_;
mbi.schema_version_ = spec_->schema_version_;
mbi.schema_rowkey_col_cnt_ = static_cast<int16_t>(spec_->schema_rowkey_col_cnt_);
mbi.row_count_delta_ = is_multi_version_ ? delta_ : 0;
mbi.micro_block_mark_deletion_offset_ =
is_multi_version_ ? header_->micro_block_endkey_offset_ + header_->micro_block_endkey_size_ : 0;
mbi.macro_block_deletion_flag_ = is_multi_version_ && macro_block_deletion_flag_;
mbi.micro_block_delta_offset_ = is_multi_version_ ? mbi.micro_block_mark_deletion_offset_ +
static_cast<int32_t>(index_.get_mark_deletion().length())
: 0;
mbi.partition_id_ = header_->partition_id_;
mbi.column_checksum_method_ = spec_->need_calc_column_checksum_ ? CCM_VALUE_ONLY : CCM_UNKOWN;
mbi.progressive_merge_round_ = spec_->progressive_merge_round_;
mbi.max_merged_trans_version_ = max_merged_trans_version_;
mbi.contain_uncommitted_row_ = contain_uncommitted_row_;
schema.column_number_ = static_cast<int16_t>(header_->column_count_);
schema.rowkey_column_number_ = static_cast<int16_t>(header_->rowkey_column_count_);
schema.schema_rowkey_col_cnt_ = static_cast<int16_t>(spec_->schema_rowkey_col_cnt_);
schema.schema_version_ = spec_->schema_version_;
schema.compressor_ = header_->compressor_name_;
schema.column_id_array_ = column_ids_;
schema.column_type_array_ = column_types_;
schema.column_order_array_ = column_orders_;
if (!mbi.is_valid() || !schema.is_valid()) {
ret = OB_INVALID_ARGUMENT;
STORAGE_LOG(WARN, "build incorrect meta", K(full_meta), K(*header_), K(mbi.is_valid()), K(schema.is_valid()));
}
}
return ret;
}
int ObMacroBlock::merge_data_checksum(const ObMacroBlock& macro_block)
{
int ret = OB_SUCCESS;
int64_t micro_block_count = 0;
const char* buf_ptr = macro_block.get_micro_block_data_ptr();
const int64_t buf_size = macro_block.get_micro_block_data_size();
int64_t offset = 0;
if (NULL == macro_block.header_) {
ret = OB_ERR_SYS;
STORAGE_LOG(ERROR, "macro block header must not null", K(ret));
} else {
micro_block_count = macro_block.header_->micro_block_count_;
}
for (int64_t i = 0; OB_SUCC(ret) && i < micro_block_count; ++i) {
ObRecordHeaderV3 header;
int64_t pos = 0;
if (OB_FAIL(header.deserialize(buf_ptr + offset, buf_size, pos))) {
STORAGE_LOG(WARN, "fail to deserialize record header", K(ret));
} else {
offset += header.get_serialize_size() + header.data_zlength_;
header_->data_checksum_ =
ob_crc64_sse42(header_->data_checksum_, &header.data_checksum_, sizeof(header.data_checksum_));
if (OB_FAIL(header.check_header_checksum())) {
STORAGE_LOG(WARN, "failed to check header checksum", K(ret), K(i), K(i), KP(buf_ptr), K(offset), K(buf_size));
}
}
}
return ret;
}
int ObMacroBlock::add_column_checksum(
const int64_t* to_add_checksum, const int64_t column_cnt, int64_t* column_checksum)
{
int ret = OB_SUCCESS;
if (OB_UNLIKELY(NULL == to_add_checksum || column_cnt <= 0 || NULL == column_checksum)) {
ret = OB_INVALID_ARGUMENT;
STORAGE_LOG(WARN, "invalid arguments", K(ret), KP(to_add_checksum), K(column_cnt), KP(column_checksum));
} else {
for (int64_t i = 0; i < column_cnt; ++i) {
column_checksum[i] += to_add_checksum[i];
}
}
return ret;
}
} // namespace blocksstable
} // namespace oceanbase
| 40.934172 | 159 | 0.700721 | wangcy6 |
96ee220be8cb51800b6a6f633795ec66351b59e7 | 701 | cpp | C++ | C++/638.cpp | TianChenjiang/LeetCode | a680c90bc968eba5aa76c3674af1f2d927986ec7 | [
"MIT"
] | 1 | 2021-08-31T08:53:47.000Z | 2021-08-31T08:53:47.000Z | C++/638.cpp | TianChenjiang/LeetCode | a680c90bc968eba5aa76c3674af1f2d927986ec7 | [
"MIT"
] | null | null | null | C++/638.cpp | TianChenjiang/LeetCode | a680c90bc968eba5aa76c3674af1f2d927986ec7 | [
"MIT"
] | null | null | null | class Solution {
public:
int shoppingOffers(vector<int>& price, vector<vector<int>>& special, vector<int>& needs) {
int res = 0, n = price.size();
for (int i = 0; i < n; i++) {
res += price[i] * needs[i];
}
for (auto coupon : special) {
bool isVaild = true;
for (int i = 0; i < n; i++) {
if (needs[i] < coupon[i]) isVaild = false;
needs[i] -= coupon[i];
}
if (isVaild) res = min(res, shoppingOffers(price, special, needs) + coupon.back());
for (int i = 0; i < n; i++) {
needs[i] += coupon[i];
}
}
return res;
}
}; | 33.380952 | 95 | 0.437946 | TianChenjiang |
96f6c44ea96b4a9d526f8476396dfd1d359e8e9d | 3,758 | hpp | C++ | gtfo/algorithm/search_n.hpp | TMorozovsky/Generic_Tools_for_Frequent_Operations | bbc6804e1259f53a84375316cddeb9b648359c28 | [
"MIT"
] | 1 | 2016-01-09T09:57:55.000Z | 2016-01-09T09:57:55.000Z | gtfo/algorithm/search_n.hpp | TMorozovsky/Generic_Tools_for_Frequent_Operations | bbc6804e1259f53a84375316cddeb9b648359c28 | [
"MIT"
] | null | null | null | gtfo/algorithm/search_n.hpp | TMorozovsky/Generic_Tools_for_Frequent_Operations | bbc6804e1259f53a84375316cddeb9b648359c28 | [
"MIT"
] | null | null | null | #ifndef GTFO_FILE_INCLUDED_ALGORITHM_SEARCH_N_HPP
#define GTFO_FILE_INCLUDED_ALGORITHM_SEARCH_N_HPP
/*
* Defines the following overloads:
* search_n(ForwardIterator, ForwardIterator, Size, const Value &);
* search_n(ForwardIterator, ForwardIterator, Size, const Value &, BinaryPredicate);
* search_n(Range, Size, const Value &);
* search_n(Range, Size, const Value &, BinaryPredicate);
*/
#include <algorithm>
#include "gtfo/_impl/utility.hpp"
#include "gtfo/_impl/type_traits/are_comparable_op_eq.hpp"
#include "gtfo/_impl/type_traits/are_comparable_pred.hpp"
#include "gtfo/_impl/type_traits/result_of_dereferencing.hpp"
#include "gtfo/_impl/type_traits/iterator_of_range.hpp"
namespace gtfo
{
#define GTFO_RESULT_OF_SEARCH_N(ForwardIterator, Value) \
typename _tt::enable_if \
< \
_tt::are_comparable_op_eq \
< \
typename _tt::result_of_dereferencing< ForwardIterator >::type, \
Value \
>::value, \
ForwardIterator \
>::type
#define GTFO_RESULT_OF_SEARCH_N_PRED(ForwardIterator, Value, BinaryPredicate) \
typename _tt::enable_if \
< \
_tt::are_comparable_pred \
< \
BinaryPredicate, \
typename _tt::result_of_dereferencing< ForwardIterator >::type, \
Value \
>::value, \
ForwardIterator \
>::type
template<typename ForwardIterator, typename Size, typename Value>
inline
GTFO_RESULT_OF_SEARCH_N(ForwardIterator,
Value)
search_n(ForwardIterator _it_begin,
ForwardIterator _it_end,
Size _count,
const Value & _value)
{
return ::std::search_n(::gtfo::move(_it_begin),
::gtfo::move(_it_end),
::gtfo::move(_count),
_value);
}
template<typename ForwardIterator, typename Size, typename Value, typename BinaryPredicate>
inline
ForwardIterator
search_n(ForwardIterator _it_begin,
ForwardIterator _it_end,
Size _count,
const Value & _value,
BinaryPredicate _pred)
{
return ::std::search_n(::gtfo::move(_it_begin),
::gtfo::move(_it_end),
::gtfo::move(_count),
_value,
::gtfo::move(_pred));
}
template<typename Range, typename Size, typename Value>
inline
typename _tt::iterator_of_range< Range >::type
search_n(Range && _range,
Size _count,
const Value & _value)
{
return ::std::search_n(begin(_range),
end(_range),
::gtfo::move(_count),
_value);
}
template<typename Range, typename Size, typename Value, typename BinaryPredicate>
inline
GTFO_RESULT_OF_SEARCH_N_PRED(typename _tt::iterator_of_range< Range >::type,
Value,
BinaryPredicate)
search_n(Range && _range,
Size _count,
const Value & _value,
BinaryPredicate _pred)
{
return ::std::search_n(begin(_range),
end(_range),
::gtfo::move(_count),
_value,
::gtfo::move(_pred));
}
#undef GTFO_RESULT_OF_SEARCH_N_PRED
#undef GTFO_RESULT_OF_SEARCH_N
}
#endif // GTFO_FILE_INCLUDED_ALGORITHM_SEARCH_N_HPP
| 33.553571 | 97 | 0.552155 | TMorozovsky |
96fab864cfa6183c048e07f09223ff4be016dfb0 | 3,191 | cpp | C++ | src/mfx/ControlledParam.cpp | mikelange49/pedalevite | a81bd8a6119c5920995ec91b9f70e11e9379580e | [
"WTFPL"
] | 69 | 2017-01-17T13:17:31.000Z | 2022-03-01T14:56:32.000Z | src/mfx/ControlledParam.cpp | mikelange49/pedalevite | a81bd8a6119c5920995ec91b9f70e11e9379580e | [
"WTFPL"
] | 1 | 2020-11-03T14:52:45.000Z | 2020-12-01T20:31:15.000Z | src/mfx/ControlledParam.cpp | mikelange49/pedalevite | a81bd8a6119c5920995ec91b9f70e11e9379580e | [
"WTFPL"
] | 8 | 2017-02-08T13:30:42.000Z | 2021-12-09T08:43:09.000Z | /*****************************************************************************
ControlledParam.cpp
Author: Laurent de Soras, 2016
--- Legal stuff ---
This program is free software. It comes without any warranty, to
the extent permitted by applicable law. You can redistribute it
and/or modify it under the terms of the Do What The Fuck You Want
To Public License, Version 2, as published by Sam Hocevar. See
http://sam.zoy.org/wtfpl/COPYING for more details.
*Tab=3***********************************************************************/
#if defined (_MSC_VER)
#pragma warning (1 : 4130 4223 4705 4706)
#pragma warning (4 : 4355 4786 4800)
#endif
/*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
#include "fstb/fnc.h"
#include "mfx/ControlledParam.h"
#include "mfx/CtrlUnit.h"
#include "mfx/PluginPool.h"
#include "mfx/ProcessingContext.h"
#include <cassert>
namespace mfx
{
/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
ControlledParam::ControlledParam (const ParamCoord ¶m)
: _param (param)
, _ctrl_list ()
{
// Nothing
}
const ParamCoord & ControlledParam::use_coord () const
{
return _param;
}
ControlledParam::CtrlUnitList & ControlledParam::use_unit_list ()
{
return _ctrl_list;
}
const ControlledParam::CtrlUnitList & ControlledParam::use_unit_list () const
{
return _ctrl_list;
}
// For parameters with relative sources
void ControlledParam::update_internal_val(float val_nrm)
{
assert (! _ctrl_list.empty () && _ctrl_list [0]->_abs_flag);
CtrlUnit & unit = *_ctrl_list [0];
unit.update_internal_val (val_nrm);
}
// Controller absolute values should have been updated beforehand
// Parameter value in the plug-in pool is updated if there is an absolute controler.
float ControlledParam::compute_final_val (PluginPool &pi_pool) const
{
PluginPool::PluginDetails & details =
pi_pool.use_plugin (_param._plugin_id);
float val = 0;
int beg = 0;
const int index = _param._param_index;
if ( ! _ctrl_list.empty ()
&& _ctrl_list [0]->_abs_flag)
{
CtrlUnit & unit = *_ctrl_list [0];
// If the modification comes from the audio thread (controller),
// we calculate the new value and update the reference.
if (details._param_update_from_audio [index])
{
val = unit.evaluate (0);
details._param_arr [index] = fstb::limit (val, 0.f, 1.f);
}
// Otherwise, we get the value from the reference.
else
{
val = details._param_arr [index];
if (unit._source.is_relative ())
{
// Forces internal value for relative sources
unit.update_internal_val (val);
}
}
beg = 1;
}
else
{
val = details._param_arr [index];
}
for (int m = beg; m < int (_ctrl_list.size ()); ++m)
{
const CtrlUnit & unit = *_ctrl_list [m];
val = unit.evaluate (val);
}
val = fstb::limit (val, 0.f, 1.f);
return val;
}
/*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
/*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
} // namespace mfx
/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
| 20.856209 | 84 | 0.579442 | mikelange49 |
96fcd45b14a5c76cdefc0fec95107889abdad464 | 429 | cpp | C++ | Pbinfo/Prime.cpp | Al3x76/cpp | 08a0977d777e63e0d36d87fcdea777de154697b7 | [
"MIT"
] | 7 | 2019-01-06T19:10:14.000Z | 2021-10-16T06:41:23.000Z | Pbinfo/Prime.cpp | Al3x76/cpp | 08a0977d777e63e0d36d87fcdea777de154697b7 | [
"MIT"
] | null | null | null | Pbinfo/Prime.cpp | Al3x76/cpp | 08a0977d777e63e0d36d87fcdea777de154697b7 | [
"MIT"
] | 6 | 2019-01-06T19:17:30.000Z | 2020-02-12T22:29:17.000Z | #include <fstream>
using namespace std;
ifstream cin("prime.in");
ofstream cout("prime.out");
bool prim(int n){
if(n==0 || n==1) return 0;
if(n==2) return 1;
if(n%2==0) return 0;
for(int d=3; d*d<=n; d=d+2)
if(n%d==0) return 0;
return 1;
}
int main()
{
int n, a[1000];
cin>>n;
for(int i=1; i<=n; i++){
cin>>a[i];
if(prim(a[i])) cout<<a[i]<<" ";
}
return 0;
} | 14.793103 | 39 | 0.482517 | Al3x76 |
8c09474b8e7a2f675356d4a8ad0217eb803a6de9 | 2,788 | hh | C++ | recorder/src/main/cpp/profiler.hh | Flipkart/fk-prof | ed801c32a8c3704204be670e16c6465297431e1a | [
"Apache-2.0",
"MIT"
] | 7 | 2017-01-17T11:29:08.000Z | 2021-06-07T10:36:59.000Z | recorder/src/main/cpp/profiler.hh | Flipkart/fk-prof | ed801c32a8c3704204be670e16c6465297431e1a | [
"Apache-2.0",
"MIT"
] | 106 | 2017-01-12T04:38:40.000Z | 2017-10-04T11:12:54.000Z | recorder/src/main/cpp/profiler.hh | Flipkart/fk-prof | ed801c32a8c3704204be670e16c6465297431e1a | [
"Apache-2.0",
"MIT"
] | 4 | 2016-12-22T08:56:27.000Z | 2018-07-26T17:13:42.000Z | #ifndef PROFILER_H
#define PROFILER_H
#include <signal.h>
#include <unistd.h>
#include <chrono>
#include <sstream>
#include <string>
#include "globals.hh"
#include "profile_writer.hh"
#include "thread_map.hh"
#include "signal_handler.hh"
#include "stacktraces.hh"
#include "processor.hh"
#include "perf_ctx.hh"
using namespace std::chrono;
using std::ofstream;
using std::ostringstream;
using std::string;
template <bool blocking = true>
class SimpleSpinLockGuard {
private:
std::atomic_bool& f;
bool rel;
public:
SimpleSpinLockGuard(std::atomic_bool& field, bool relaxed = false) : f(field), rel(relaxed) {
bool expectedState = false;
while (!f.compare_exchange_weak(expectedState, true, std::memory_order_acquire)) {
expectedState = false;
sched_yield();
}
}
~SimpleSpinLockGuard() {
f.store(false, rel ? std::memory_order_relaxed : std::memory_order_release);
}
};
template <>
class SimpleSpinLockGuard<false> {
public:
SimpleSpinLockGuard(std::atomic_bool& field) {
field.load(std::memory_order_acquire);
}
~SimpleSpinLockGuard() {}
};
class Profiler : public Process {
public:
static std::uint32_t calculate_max_stack_depth(std::uint32_t hinted_max_stack_depth);
explicit Profiler(JavaVM *_jvm, jvmtiEnv *_jvmti, ThreadMap &_thread_map, ProfileSerializingWriter& _serializer, std::uint32_t _max_stack_depth, std::uint32_t _sampling_freq, ProbPct& _prob_pct, std::uint8_t _noctx_cov_pct, bool _capture_native_bt, bool _capture_unknown_thd_bt);
bool start(JNIEnv *jniEnv);
void stop();
void run();
void handle(int signum, siginfo_t *info, void *context);
~Profiler();
private:
JavaVM *jvm;
jvmtiEnv *jvmti;
ThreadMap &thread_map;
std::uint32_t max_stack_depth;
std::uint32_t itvl_min, itvl_max;
std::shared_ptr<ProfileWriter> writer;
CircularQueue *buffer;
SignalHandler* handler;
ProfileSerializingWriter& serializer;
ProbPct& prob_pct;
std::atomic<std::uint32_t> sampling_attempts;
const std::uint8_t noctx_cov_pct;
const bool capture_native_bt;
const bool capture_unknown_thd_bt;
bool running;
std::uint32_t samples_handled;
metrics::Ctr& s_c_cpu_samp_total;
metrics::Ctr& s_c_cpu_samp_err_no_jni;
metrics::Ctr& s_c_cpu_samp_err_unexpected;
metrics::Hist& s_h_pop_spree_len;
metrics::Timer& s_t_pop_spree_tm;
SiteResolver::SymInfo si;
void set_sampling_freq(std::uint32_t sampling_freq);
void set_max_stack_depth(std::uint32_t max_stack_depth);
void configure();
inline std::uint32_t capture_stack_depth() {
return max_stack_depth + 1;
}
DISALLOW_COPY_AND_ASSIGN(Profiler);
};
#endif // PROFILER_H
| 23.041322 | 283 | 0.713415 | Flipkart |
8c102b026fa270923c5e1b5b590a34376b49cedd | 8,748 | cc | C++ | src/s3_cmds/zgw_s3_completemultiupload.cc | baotiao/zeppelin-gateway | bff8d8e160422322e306dfc1dc1768b29001a8c0 | [
"Apache-2.0"
] | 20 | 2017-05-04T00:49:55.000Z | 2022-03-27T10:06:02.000Z | src/s3_cmds/zgw_s3_completemultiupload.cc | baotiao/zeppelin-gateway | bff8d8e160422322e306dfc1dc1768b29001a8c0 | [
"Apache-2.0"
] | null | null | null | src/s3_cmds/zgw_s3_completemultiupload.cc | baotiao/zeppelin-gateway | bff8d8e160422322e306dfc1dc1768b29001a8c0 | [
"Apache-2.0"
] | 16 | 2017-04-11T08:10:04.000Z | 2020-06-16T02:49:48.000Z | #include "src/s3_cmds/zgw_s3_object.h"
#include <algorithm>
#include "slash/include/env.h"
#include "src/s3_cmds/zgw_s3_xml.h"
#include "src/zgw_utils.h"
bool CompleteMultiUploadCmd::DoInitial() {
http_request_xml_.clear();
http_response_xml_.clear();
received_parts_info_.clear();
upload_id_ = query_params_.at("uploadId");
md5_ctx_.Init();
request_id_ = md5(bucket_name_ +
object_name_ +
upload_id_ +
std::to_string(slash::NowMicros()));
if (!TryAuth()) {
DLOG(INFO) << request_id_ << " " <<
"CompleteMultiUpload(DoInitial) - Auth failed: " << client_ip_port_;
g_zgw_monitor->AddAuthFailed();
return false;
}
DLOG(INFO) << request_id_ << " " <<
"CompleteMultiUpload(DoInitial) - " << bucket_name_ << "/" << object_name_ <<
", uploadId: " << upload_id_;
return true;
}
void CompleteMultiUploadCmd::DoReceiveBody(const char* data, size_t data_size) {
http_request_xml_.append(data, data_size);
}
bool CompleteMultiUploadCmd::ParseReqXml() {
S3XmlDoc doc;
if (!doc.ParseFromString(http_request_xml_)) {
return false;
}
S3XmlNode root;
if (!doc.FindFirstNode("CompleteMultipartUpload", &root)) {
return false;
}
S3XmlNode node;
if (!root.FindFirstNode("Part", &node)) {
return false;
}
do {
S3XmlNode part_num, etag;
if (!node.FindFirstNode("PartNumber", &part_num) ||
!node.FindFirstNode("ETag", &etag)) {
return false;
}
// Trim quote of etag
std::string etag_s = etag.value();
if (!etag_s.empty() && etag_s.at(0) == '"') {
etag_s.assign(etag_s.substr(1, 32));
}
received_parts_info_.push_back(std::make_pair(part_num.value(), etag_s));
} while (node.NextSibling());
return true;
}
void CompleteMultiUploadCmd::DoAndResponse(pink::HTTPResponse* resp) {
if (http_ret_code_ == 200) {
if (!ParseReqXml()) {
http_ret_code_ = 400;
GenerateErrorXml(kMalformedXML);
}
std::string virtual_bucket = "__TMPB" + upload_id_ +
bucket_name_ + "|" + object_name_;
std::string new_data_blocks;
uint64_t data_size = 0;
std::vector<zgwstore::Object> stored_parts;
DLOG(INFO) << request_id_ << " " <<
"CompleteMultiUpload(DoAndResponse) - virtual_bucket: " << virtual_bucket;
Status s = store_->Lock();
if (s.ok()) {
DLOG(INFO) << request_id_ << " " <<
"CompleteMultiUpload(DoAndResponse) - Lock success";
if (http_ret_code_ == 200) {
s = store_->ListObjects(user_name_, virtual_bucket, &stored_parts);
if (!s.ok()) {
if (s.ToString().find("Bucket Doesn't Belong To This User") !=
std::string::npos) {
http_ret_code_ = 404;
GenerateErrorXml(kNoSuchUpload, upload_id_);
} else {
http_ret_code_ = 500;
LOG(ERROR) << request_id_ << " " <<
"CompleteMultiUpload(DoAndResponse) - ListVirtObjects " <<
virtual_bucket << "error: " << s.ToString();
}
} else {
// Complete multiupload
if (received_parts_info_.size() != stored_parts.size()) {
http_ret_code_ = 400;
GenerateErrorXml(kInvalidPart);
} else {
// sort stored parts
std::sort(stored_parts.begin(), stored_parts.end(),
[](const zgwstore::Object& a, const zgwstore::Object& b) {
return std::atoi(a.object_name.c_str()) <
std::atoi(b.object_name.c_str());
});
for (size_t i = 0 ; i < received_parts_info_.size(); i++) {
bool found_part = false;
for (auto& stored_part : stored_parts) {
if (received_parts_info_[i].first == stored_part.object_name) {
found_part = true;
break;
}
}
if (!found_part) {
http_ret_code_ = 400;
GenerateErrorXml(kInvalidPart);
break;
}
if (received_parts_info_[i].first != stored_parts[i].object_name) {
http_ret_code_ = 400;
GenerateErrorXml(kInvalidPartOrder);
break;
}
if (received_parts_info_[i].second != stored_parts[i].etag) {
http_ret_code_ = 400;
GenerateErrorXml(kInvalidPart);
break;
}
md5_ctx_.Update(stored_parts[i].etag);
data_size += stored_parts[i].size;
// AddMultiBlockSet
// Add sort sign
char buf[100];
sprintf(buf, "%05d", std::atoi(stored_parts[i].object_name.c_str()));
s = store_->AddMultiBlockSet(bucket_name_, object_name_, upload_id_,
std::string(buf) + stored_parts[i].data_block);
if (!s.ok()) {
http_ret_code_ = 500;
LOG(ERROR) << request_id_ << " " <<
"CompleteMultiUpload(DoAndResponse) - AddMultiBlockSet" <<
virtual_bucket << "/" << stored_parts[i].object_name << " " <<
upload_id_ << " error: " << s.ToString();
}
}
}
}
}
if (http_ret_code_ == 200) {
// Initial new_object_
new_object_.bucket_name = bucket_name_;
new_object_.object_name = object_name_;
new_object_.etag = md5_ctx_.ToString() + "-" +
std::to_string(stored_parts.size());
new_object_.size = data_size;
new_object_.owner = user_name_;
new_object_.last_modified = slash::NowMicros();
new_object_.storage_class = 0; // Unused
new_object_.acl = "FULL_CONTROL";
new_object_.upload_id = upload_id_;
new_object_.data_block = upload_id_ + bucket_name_ + "|" + object_name_;
// Write meta
Status s = store_->AddObject(new_object_, false);
if (!s.ok()) {
http_ret_code_ = 500;
LOG(ERROR) << request_id_ << " " <<
"CompleteMultiUpload(DoAndResponse) - AddObject " << bucket_name_ <<
"/" << object_name_ << "error: " << s.ToString();
} else {
DLOG(INFO) << request_id_ << " " <<
"CompleteMultiUpload(DoAndResponse) - AddObject " << bucket_name_ <<
"/" << object_name_ << "success, cleaning...";
for (auto& p : stored_parts) {
s = store_->DeleteObject(user_name_, virtual_bucket, p.object_name, false, false);
if (s.IsIOError()) {
http_ret_code_ = 500;
LOG(ERROR) << request_id_ << " " <<
"CompleteMultiUpload(DoAndResponse) - DeleteVirtObject " <<
virtual_bucket << "/" << p.object_name << " error: " << s.ToString();
}
}
if (http_ret_code_ == 200) {
s = store_->DeleteBucket(user_name_, virtual_bucket, false);
if (s.IsIOError()) {
http_ret_code_ = 500;
LOG(ERROR) << request_id_ << " " <<
"CompleteMultiUpload(DoAndResponse) - DeleteVirtBucket " <<
virtual_bucket << " error: " << s.ToString();
}
}
}
}
s = store_->UnLock();
}
if (!s.ok()) {
http_ret_code_ = 500;
LOG(ERROR) << request_id_ << " " <<
"CompleteMultiUpload(DoAndResponse) - Lock or Unlock error:" <<
s.ToString();
}
DLOG(INFO) << request_id_ << " " <<
"CompleteMultiUpload(DoAndResponse) - UnLock success";
if (http_ret_code_ == 200) {
DLOG(INFO) << "CompleteMultiUpload(DoAndResponse) - Clean OK";
// Build response XML
GenerateRespXml();
}
}
g_zgw_monitor->AddApiRequest(kCompleteMultiUpload, http_ret_code_);
resp->SetStatusCode(http_ret_code_);
resp->SetContentLength(http_response_xml_.size());
}
void CompleteMultiUploadCmd::GenerateRespXml() {
S3XmlDoc doc("CompleteMultipartUploadResult");
doc.AppendToRoot(doc.AllocateNode("Bucket", bucket_name_));
doc.AppendToRoot(doc.AllocateNode("Key", object_name_));
doc.AppendToRoot(doc.AllocateNode("ETag", "\"" + new_object_.etag + "\""));
doc.ToString(&http_response_xml_);
}
int CompleteMultiUploadCmd::DoResponseBody(char* buf, size_t max_size) {
if (max_size < http_response_xml_.size()) {
memcpy(buf, http_response_xml_.data(), max_size);
http_response_xml_.assign(http_response_xml_.substr(max_size));
} else {
memcpy(buf, http_response_xml_.data(), http_response_xml_.size());
}
return std::min(max_size, http_response_xml_.size());
}
| 36 | 94 | 0.569845 | baotiao |
8c11d122e12a48ff10ca8c38233a976fff4b0436 | 399 | cpp | C++ | Trab2/livro.cpp | danielfavoreto/Fourth-semester-programacao-3- | 27c36958abdb78ab88b862b5371c573a324dcd0b | [
"MIT"
] | null | null | null | Trab2/livro.cpp | danielfavoreto/Fourth-semester-programacao-3- | 27c36958abdb78ab88b862b5371c573a324dcd0b | [
"MIT"
] | null | null | null | Trab2/livro.cpp | danielfavoreto/Fourth-semester-programacao-3- | 27c36958abdb78ab88b862b5371c573a324dcd0b | [
"MIT"
] | null | null | null | /* livro.cpp
*
* Created on: 24 de nov de 2015
* Author: 2013101847
*/
#include "livro.h"
// construtor de livro
livro::livro(int codigo, string nome, string tipo, list<pessoa*> atores, int tamanho, genero* midiaGenero, bool possui, bool consumiu, bool deseja, double preco):midia(codigo, nome, tipo, atores, tamanho, midiaGenero, possui, consumiu, deseja, preco)
{
}
livro::~livro()
{
}
| 26.6 | 250 | 0.699248 | danielfavoreto |
8c133eae91343f1c73fc113ec3000ca89419bf20 | 4,151 | cpp | C++ | cplusplus/contrib/AI_painting/src/data_receiver.cpp | Dedederek/samples | 31d99de20af2f7046556e0f48c4b789b99e422f8 | [
"Apache-2.0"
] | 5 | 2021-02-26T17:58:12.000Z | 2022-03-15T06:21:28.000Z | cplusplus/contrib/AI_painting/src/data_receiver.cpp | Dedederek/samples | 31d99de20af2f7046556e0f48c4b789b99e422f8 | [
"Apache-2.0"
] | null | null | null | cplusplus/contrib/AI_painting/src/data_receiver.cpp | Dedederek/samples | 31d99de20af2f7046556e0f48c4b789b99e422f8 | [
"Apache-2.0"
] | 5 | 2021-03-22T21:13:11.000Z | 2021-09-24T06:52:33.000Z | /**
* Copyright 2020 Huawei Technologies Co., Ltd
*
* 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.
* File data_receiver.cpp
* Description: receive data
*/
#include <memory>
#include <fstream>
#include <sstream>
#include <stdio.h>
#include <string.h>
#include <cmath>
#include <regex>
#include "data_receiver.h"
#include "utils.h"
using namespace std;
Result DataReceiver::Init() {
string input_file = "./param.conf";
string presenter_server_ip = "";
int presenter_server_port = 0;
// get presenter server ip and port
Utils::GetPresenterServerParam(input_file, presenter_server_ip, presenter_server_port);
if (presenter_server_ip == "" || presenter_server_port == 0){
ERROR_LOG("Get presenter_server ip or port failed, please check param.conf.");
return FAILED;
}
PresenterServerParams register_param;
register_param.app_id = "AIPainting";
register_param.app_type = "display";
register_param.host_ip = presenter_server_ip;
register_param.port = presenter_server_port;
PresenterChannels::GetInstance().Init(register_param);
// create agent channel and register app
ascend::presenter::Channel *agent_channel = PresenterChannels::GetInstance().GetChannel();
if (agent_channel == nullptr) {
ERROR_LOG("Register app failed.");
return FAILED;
}
INFO_LOG("register app success.");
return SUCCESS;
}
Result DataReceiver::DoReceiverProcess(void* objectData, void* layoutData) {
// get agent channel
ascend::presenter::Channel *agent_channel = PresenterChannels::GetInstance().GetChannel();
if (agent_channel == nullptr) {
ERROR_LOG("get agent channel to send failed.");
return FAILED;
}
// construct registered request Message and read message
unique_ptr<google::protobuf::Message> data_rec;
ascend::presenter::PresenterErrorCode agent_ret = agent_channel->ReceiveMessage(data_rec);
if (agent_ret == ascend::presenter::PresenterErrorCode::kNone) {
PaintingMessage::DataPackage *model_input_data_package = (PaintingMessage::DataPackage * )(data_rec.get());
if(model_input_data_package == nullptr){
INFO_LOG("Receive data is null");
return FAILED;
}
PaintingMessage::ModelInputData object_input = model_input_data_package->objectdata();
std::string object_input_name = object_input.name();
std::string object_input_data = object_input.data();
INFO_LOG("object_input_name: %s", object_input_name.c_str());
INFO_LOG("object_input_data size: %ld", object_input_data.size());
PaintingMessage::ModelInputData layout_input = model_input_data_package->layoutdata();
std::string layout_input_name = layout_input.name();
std::string layout_input_data = layout_input.data();
INFO_LOG("layout_input_name: %s", layout_input_name.c_str());
INFO_LOG("layout_input_data size: %ld", layout_input_data.size());
aclrtRunMode runMode;
aclrtGetRunMode (& runMode);
aclrtMemcpyKind policy = (runMode == ACL_HOST) ?
ACL_MEMCPY_HOST_TO_DEVICE : ACL_MEMCPY_DEVICE_TO_DEVICE;
aclError ret = aclrtMemcpy(objectData, object_input_data.size(),
object_input_data.c_str(), object_input_data.size(), policy);
ret = aclrtMemcpy(layoutData, layout_input_data.size(),
layout_input_data.c_str(), layout_input_data.size(), policy);
if (ret != ACL_ERROR_NONE) {
ERROR_LOG("Copy resized image data to device failed.");
return FAILED;
}
return SUCCESS;
} else {
return FAILED;
}
} | 36.412281 | 115 | 0.70224 | Dedederek |
8c147229939933595fc2b15fa4eadcc02734e81b | 5,164 | cpp | C++ | engine/samples/ModelLoading/src/MainState.cpp | Arthapz/StormKit | 7c8dead874734d04b97776287b25bf2ebe9be617 | [
"MIT"
] | 17 | 2019-02-12T14:40:06.000Z | 2021-12-21T12:54:17.000Z | engine/samples/ModelLoading/src/MainState.cpp | Arthapz/StormKit | 7c8dead874734d04b97776287b25bf2ebe9be617 | [
"MIT"
] | null | null | null | engine/samples/ModelLoading/src/MainState.cpp | Arthapz/StormKit | 7c8dead874734d04b97776287b25bf2ebe9be617 | [
"MIT"
] | 2 | 2019-02-21T10:07:42.000Z | 2020-05-08T19:49:10.000Z | #include "MainState.hpp"
#include "Log.hpp"
/////////// - StormKit::entities - ///////////
#include <storm/entities/MessageBus.hpp>
/////////// - StormKit::render - ///////////
#include <storm/render/core/Device.hpp>
#include <storm/render/core/PhysicalDevice.hpp>
#include <storm/render/core/Surface.hpp>
/////////// - StormKit::window - ///////////
#include <storm/window/Keyboard.hpp>
#include <storm/window/Mouse.hpp>
#include <storm/window/Window.hpp>
/////////// - StormKit::engine - ///////////
#include <storm/engine/Engine.hpp>
#include <storm/engine/NameComponent.hpp>
#include <storm/engine/render/DrawableComponent.hpp>
#include <storm/engine/render/MaterialComponent.hpp>
#include <storm/engine/render/TransformComponent.hpp>
#include <storm/engine/render/3D/FPSCamera.hpp>
#include <storm/engine/render/3D/Model.hpp>
#include <storm/engine/render/3D/PbrMesh.hpp>
#include <storm/engine/render/3D/PbrRenderSystem.hpp>
using namespace storm;
static constexpr auto ROTATE_ANGLE = 5.f;
class RotationSystem: public entities::System {
public:
explicit RotationSystem(entities::EntityManager &manager)
: System { manager, 1, { engine::TransformComponent::TYPE } } {}
~RotationSystem() override = default;
RotationSystem(RotationSystem &&) noexcept = default;
RotationSystem &operator=(RotationSystem &&) noexcept = default;
void update(core::Secondf delta) override {
for (auto e : m_entities) {
auto &transform_component = m_manager->getComponent<engine::TransformComponent>(e);
transform_component.transform.rotateRoll(ROTATE_ANGLE * delta.count());
}
}
protected:
void onMessageReceived(const entities::Message &message) override {}
};
////////////////////////////////////////
////////////////////////////////////////
MainState::MainState(core::StateManager &owner, engine::Engine &engine, window::Window &window)
: State { owner, engine }, m_window { window },
m_keyboard { window.createKeyboardPtr() }, m_mouse { window.createMousePtr() } {
m_mouse->setPositionOnWindow(
core::Position2i { window.size().width / 2, window.size().height / 2 });
const auto extent = State::engine().surface().extent();
m_render_system = &m_world.addSystem<engine::PbrRenderSystem>(State::engine());
m_world.addSystem<RotationSystem>();
m_camera = engine::FPSCamera::allocateOwned(extent);
m_camera->setPosition({ 0.f, 0.f, -3.f });
m_render_system->setCamera(*m_camera);
m_model = engine::Model::allocateOwned(engine, EXAMPLES_DATA_DIR "models/Sword.glb");
auto mesh = m_model->createMesh();
auto e = m_world.makeEntity();
auto &name_component = m_world.addComponent<engine::NameComponent>(e);
name_component.name = "MyMesh";
auto &drawable_component = m_world.addComponent<engine::DrawableComponent>(e);
drawable_component.drawable = std::move(mesh);
m_world.addComponent<engine::TransformComponent>(e);
enableCamera();
}
////////////////////////////////////////
////////////////////////////////////////
MainState::~MainState() = default;
////////////////////////////////////////
////////////////////////////////////////
MainState::MainState(MainState &&) noexcept = default;
////////////////////////////////////////
////////////////////////////////////////
MainState &MainState::operator=(MainState &&) noexcept = default;
////////////////////////////////////////
////////////////////////////////////////
void MainState::update(core::Secondf delta) {
if (m_camera_enabled) {
auto inputs = engine::FPSCamera::Inputs {
.up = m_keyboard->isKeyPressed(window::Key::Z),
.down = m_keyboard->isKeyPressed(window::Key::S),
.right = m_keyboard->isKeyPressed(window::Key::D),
.left = m_keyboard->isKeyPressed(window::Key::Q),
};
const auto extent = core::Extenti { State::engine().surface().extent() };
const auto position = [&inputs, &extent, this]() {
auto position = m_mouse->getPositionOnWindow();
if (position->x <= 5 || position->x > (extent.width - 5)) {
position->x = extent.width / 2;
inputs.mouse_ignore = true;
}
if (position->y <= 5 || position->y > (extent.height - 5)) {
position->y = extent.height / 2;
inputs.mouse_ignore = true;
}
m_mouse->setPositionOnWindow(position);
return position;
}();
inputs.mouse_updated = true;
inputs.x_mouse = static_cast<float>(position->x);
inputs.y_mouse = static_cast<float>(position->y);
m_camera->feedInputs(inputs);
m_camera->update(delta);
}
auto &frame = engine().beginFrame();
m_world.step(delta);
m_render_system->render(frame);
engine().endFrame();
}
void MainState::enableCamera() noexcept {
m_window.get().lockMouse();
m_camera_enabled = true;
}
void MainState::disableCamera() noexcept {
m_window.get().unlockMouse();
m_camera_enabled = false;
}
| 33.532468 | 95 | 0.595275 | Arthapz |
8c160271accfd70ae96f7927cded666e7b29cca6 | 15,061 | cpp | C++ | graphics/cgal/Polyhedron/demo/Polyhedron/Plugins/Point_set/Point_set_selection_plugin.cpp | hlzz/dotfiles | 0591f71230c919c827ba569099eb3b75897e163e | [
"BSD-3-Clause"
] | 4 | 2016-03-30T14:31:52.000Z | 2019-02-02T05:01:32.000Z | graphics/cgal/Polyhedron/demo/Polyhedron/Plugins/Point_set/Point_set_selection_plugin.cpp | hlzz/dotfiles | 0591f71230c919c827ba569099eb3b75897e163e | [
"BSD-3-Clause"
] | null | null | null | graphics/cgal/Polyhedron/demo/Polyhedron/Plugins/Point_set/Point_set_selection_plugin.cpp | hlzz/dotfiles | 0591f71230c919c827ba569099eb3b75897e163e | [
"BSD-3-Clause"
] | null | null | null | #include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/Bbox_2.h>
#include <CGAL/Polygon_2.h>
#include <QtCore/qglobal.h>
#include <QGLViewer/manipulatedCameraFrame.h>
#include "opengl_tools.h"
#include "Messages_interface.h"
#include "Scene_points_with_normal_item.h"
#include "Scene_polylines_item.h"
#include <CGAL/Three/Scene_interface.h>
#include <CGAL/Three/Polyhedron_demo_plugin_helper.h>
#include "ui_Point_set_selection_widget.h"
#include "Point_set_3.h"
#include <QAction>
#include <QMainWindow>
#include <QApplication>
#include <QEvent>
#include <QKeyEvent>
#include <QMouseEvent>
#include <map>
#include <fstream>
// Class for visualizing selection
// provides mouse selection functionality
class Q_DECL_EXPORT Scene_point_set_selection_visualizer : public CGAL::Three::Scene_item
{
Q_OBJECT
private:
typedef CGAL::Exact_predicates_inexact_constructions_kernel K;
typedef K::Point_2 Point_2;
typedef K::Point_3 Point_3;
typedef CGAL::Polygon_2<K> Polygon_2;
bool rectangle;
std::vector<Point_2> contour_2d;
Scene_polylines_item* polyline;
Bbox point_set_bbox;
CGAL::Bbox_2 domain_rectangle;
Polygon_2 domain_freeform;
public:
Scene_point_set_selection_visualizer(bool rectangle, const Bbox& point_set_bbox)
: rectangle (rectangle), point_set_bbox (point_set_bbox)
{
polyline = new Scene_polylines_item();
polyline->setRenderingMode (Wireframe);
polyline->setVisible (true);
polyline->polylines.push_back (Scene_polylines_item::Polyline());
}
~Scene_point_set_selection_visualizer() {
}
bool isFinite() const { return true; }
bool isEmpty() const { return poly().empty(); }
void compute_bbox() const {
_bbox = point_set_bbox;
}
Scene_point_set_selection_visualizer* clone() const {
return 0;
}
QString toolTip() const {
return tr("%1").arg(name());
}
bool supportsRenderingMode(RenderingMode m) const {
return (m == Wireframe);
}
void draw_edges(CGAL::Three::Viewer_interface* viewer) const {
viewer->glLineWidth(3.f);
polyline->setRbgColor(0, 255, 0);
polyline->draw_edges(viewer);
}
Scene_polylines_item::Polyline& poly() const
{ return polyline->polylines.front(); }
bool update_polyline () const
{
if (contour_2d.size() < 2 ||
(!(poly().empty()) && scene_point (contour_2d.back ()) == poly().back()))
return false;
if (rectangle)
{
poly().clear();
poly().push_back (scene_point (Point_2 (domain_rectangle.xmin(),
domain_rectangle.ymin())));
poly().push_back (scene_point (Point_2 (domain_rectangle.xmax(),
domain_rectangle.ymin())));
poly().push_back (scene_point (Point_2 (domain_rectangle.xmax(),
domain_rectangle.ymax())));
poly().push_back (scene_point (Point_2 (domain_rectangle.xmin(),
domain_rectangle.ymax())));
poly().push_back (scene_point (Point_2 (domain_rectangle.xmin(),
domain_rectangle.ymin())));
}
else
{
if (!(poly().empty()) && scene_point (contour_2d.back ()) == poly().back())
return false;
poly().clear();
for (unsigned int i = 0; i < contour_2d.size (); ++ i)
poly().push_back (scene_point (contour_2d[i]));
}
return true;
}
Point_3 scene_point (const Point_2& p) const
{
QGLViewer* viewer = *QGLViewer::QGLViewerPool().begin();
qglviewer::Camera* camera = viewer->camera();
qglviewer::Vec vp (p.x(), p.y(), 0.1);
qglviewer::Vec vsp = camera->unprojectedCoordinatesOf (vp);
return Point_3 (vsp.x, vsp.y, vsp.z);
}
void sample_mouse_path()
{
QGLViewer* viewer = *QGLViewer::QGLViewerPool().begin();
const QPoint& p = viewer->mapFromGlobal(QCursor::pos());
if (rectangle && contour_2d.size () == 2)
{
contour_2d[1] = Point_2 (p.x (), p.y ());
domain_rectangle = CGAL::bbox_2 (contour_2d.begin (), contour_2d.end ());
}
else
contour_2d.push_back (Point_2 (p.x (), p.y ()));
if (update_polyline ())
{
Q_EMIT itemChanged();
}
}
void apply_path()
{
update_polyline ();
domain_rectangle = CGAL::bbox_2 (contour_2d.begin (), contour_2d.end ());
if (!rectangle)
domain_freeform = Polygon_2 (contour_2d.begin (), contour_2d.end ());
}
bool is_selected (qglviewer::Vec& p)
{
if (domain_rectangle.xmin () < p.x &&
p.x < domain_rectangle.xmax () &&
domain_rectangle.ymin () < p.y &&
p.y < domain_rectangle.ymax ())
{
if (rectangle)
return true;
if (domain_freeform.has_on_bounded_side (Point_2 (p.x, p.y)))
return true;
}
return false;
}
}; // end class Scene_point_set_selection_visualizer
///////////////////////////////////////////////////////////////////////////////////////////////////
using namespace CGAL::Three;
class Polyhedron_demo_point_set_selection_plugin :
public QObject,
public Polyhedron_demo_plugin_helper
{
Q_OBJECT
Q_INTERFACES(CGAL::Three::Polyhedron_demo_plugin_interface)
Q_PLUGIN_METADATA(IID "com.geometryfactory.PolyhedronDemo.PluginInterface/1.0")
public:
bool applicable(QAction*) const {
return qobject_cast<Scene_points_with_normal_item*>(scene->item(scene->mainSelectionIndex()));
}
void print_message(QString message) { messages->information(message); }
QList<QAction*> actions() const { return QList<QAction*>() << actionPointSetSelection; }
using Polyhedron_demo_plugin_helper::init;
void init(QMainWindow* mainWindow, CGAL::Three::Scene_interface* scene_interface, Messages_interface* m) {
mw = mainWindow;
scene = scene_interface;
messages = m;
actionPointSetSelection = new QAction(tr("Selection"), mw);
connect(actionPointSetSelection, SIGNAL(triggered()), this, SLOT(selection_action()));
dock_widget = new QDockWidget("Point Set Selection", mw);
dock_widget->setVisible(false);
ui_widget.setupUi(dock_widget);
add_dock_widget(dock_widget);
connect(ui_widget.Selection_tool_combo_box, SIGNAL(currentIndexChanged(int)),
this, SLOT(on_Selection_tool_combo_box_changed(int)));
connect(ui_widget.Selection_mode_combo_box, SIGNAL(currentIndexChanged(int)),
this, SLOT(on_Selection_mode_combo_box_changed(int)));
connect(ui_widget.Select_all_button, SIGNAL(clicked()), this, SLOT(on_Select_all_button_clicked()));
connect(ui_widget.Clear_button, SIGNAL(clicked()), this, SLOT(on_Clear_button_clicked()));
connect(ui_widget.Invert_selection_button, SIGNAL(clicked()), this, SLOT(on_Invert_selection_button_clicked()));
connect(ui_widget.Erase_selected_points_button, SIGNAL(clicked()), this, SLOT(on_Erase_selected_points_button_clicked()));
connect(ui_widget.Create_point_set_item_button, SIGNAL(clicked()), this, SLOT(on_Create_point_set_item_button_clicked()));
rectangle = true;
selection_mode = 0;
visualizer = NULL;
shift_pressing = false;
QGLViewer* viewer = *QGLViewer::QGLViewerPool().begin();
viewer->installEventFilter(this);
mainWindow->installEventFilter(this);
}
virtual void closure()
{
dock_widget->hide();
}
protected:
bool eventFilter(QObject *, QEvent *event) {
if (dock_widget->isHidden() || !(dock_widget->isActiveWindow()))
return false;
Scene_points_with_normal_item* point_set_item
= qobject_cast<Scene_points_with_normal_item*>(scene->item(scene->mainSelectionIndex()));
if(!point_set_item) {
return false;
}
int item_id = scene->item_id (point_set_item);
if(event->type() == QEvent::KeyPress || event->type() == QEvent::KeyRelease) {
QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
Qt::KeyboardModifiers modifiers = keyEvent->modifiers();
shift_pressing = modifiers.testFlag(Qt::ShiftModifier);
}
// mouse events
if(shift_pressing && event->type() == QEvent::MouseButtonPress)
{
QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
// Start selection
if (mouseEvent->button() == Qt::LeftButton && !visualizer)
{
QApplication::setOverrideCursor(Qt::CrossCursor);
QGLViewer* viewer = *QGLViewer::QGLViewerPool().begin();
if (viewer->camera()->frame()->isSpinning())
viewer->camera()->frame()->stopSpinning();
visualizer = new Scene_point_set_selection_visualizer(rectangle,
point_set_item->bbox());
visualizer->setName(tr("Point set selection visualizer"));
visualizer->setRenderingMode (Wireframe);
visualizer->setVisible (true);
// Hack to prevent camera for "jumping" when creating new item
scene->addItem(visualizer);
scene->setSelectedItem(item_id);
visualizer->sample_mouse_path();
return true;
}
// Cancel selection
else if (mouseEvent->button() == Qt::RightButton && visualizer)
{
scene->erase( scene->item_id(visualizer) );
scene->setSelectedItem(item_id);
visualizer = NULL;
QApplication::restoreOverrideCursor();
return true;
}
}
// End selection
else if (event->type() == QEvent::MouseButtonRelease && visualizer)
{
visualizer->apply_path();
select_points();
scene->erase( scene->item_id(visualizer) );
scene->setSelectedItem(item_id);
visualizer = NULL;
QApplication::restoreOverrideCursor();
return true;
}
// Update selection
else if (event->type() == QEvent::MouseMove && visualizer)
{
visualizer->sample_mouse_path();
return true;
}
return false;
}
void select_points()
{
Scene_points_with_normal_item* point_set_item = get_selected_item<Scene_points_with_normal_item>();
if(!point_set_item)
{
print_message("Error: no point set selected!");
return;
}
if (selection_mode == 0) // New selection
point_set_item->point_set()->unselect_all();
QGLViewer* viewer = *QGLViewer::QGLViewerPool().begin();
qglviewer::Camera* camera = viewer->camera();
std::vector<UI_point_3<Kernel> > unselected, selected;
for(Point_set::iterator it = point_set_item->point_set()->begin ();
it != point_set_item->point_set()->end(); ++ it)
{
bool already_selected = point_set_item->point_set()->is_selected (it);
qglviewer::Vec vp (it->x (), it->y (), it->z ());
qglviewer::Vec vsp = camera->projectedCoordinatesOf (vp);
bool now_selected = visualizer->is_selected (vsp);
// NEW INTERSECTION
if (selection_mode == 0)
{
if (now_selected)
selected.push_back (*it);
else
unselected.push_back (*it);
}
// UNION
else if (selection_mode == 1)
{
if (already_selected || now_selected)
selected.push_back (*it);
else
unselected.push_back (*it);
}
// INTERSECTION
// * Unselect point if it was selected and is not anymore
else if (selection_mode == 2)
{
if (already_selected && now_selected)
selected.push_back (*it);
else
unselected.push_back (*it);
}
// DIFFERENCE
// * Unselect point if it was selected and is now selected
else if (selection_mode == 3)
{
if (already_selected && !now_selected)
selected.push_back (*it);
else
unselected.push_back (*it);
}
}
point_set_item->point_set()->clear();
std::copy (unselected.begin (), unselected.end (),
std::back_inserter (*(point_set_item->point_set())));
std::size_t size = unselected.size();
if (selected.empty ())
{
point_set_item->point_set()->unselect_all();
}
else
{
std::copy (selected.begin (), selected.end (),
std::back_inserter (*(point_set_item->point_set())));
point_set_item->point_set()->set_first_selected
(point_set_item->point_set()->begin() + size);
}
point_set_item->invalidateOpenGLBuffers();
}
public Q_SLOTS:
void selection_action() {
dock_widget->show();
dock_widget->raise();
}
// Select all
void on_Select_all_button_clicked() {
Scene_points_with_normal_item* point_set_item = get_selected_item<Scene_points_with_normal_item>();
if(!point_set_item)
{
print_message("Error: no point set selected!");
return;
}
point_set_item->selectAll();
}
// Clear selection
void on_Clear_button_clicked() {
Scene_points_with_normal_item* point_set_item
= qobject_cast<Scene_points_with_normal_item*>(scene->item(scene->mainSelectionIndex()));
if(!point_set_item) {
print_message("Error: no point set selected!");
return;
}
point_set_item->resetSelection();
}
void on_Erase_selected_points_button_clicked() {
Scene_points_with_normal_item* point_set_item
= qobject_cast<Scene_points_with_normal_item*>(scene->item(scene->mainSelectionIndex()));
if(!point_set_item) {
print_message("Error: no point set selected!");
return;
}
point_set_item->deleteSelection();
}
void on_Invert_selection_button_clicked() {
Scene_points_with_normal_item* point_set_item
= qobject_cast<Scene_points_with_normal_item*>(scene->item(scene->mainSelectionIndex()));
if(!point_set_item) {
print_message("Error: no point set selected!");
return;
}
point_set_item->invertSelection();
}
void on_Create_point_set_item_button_clicked() {
Scene_points_with_normal_item* point_set_item
= qobject_cast<Scene_points_with_normal_item*>(scene->item(scene->mainSelectionIndex()));
if(!point_set_item) {
print_message("Error: no point set selected!");
return;
}
if(point_set_item->isSelectionEmpty ()) {
print_message("Error: there is no selected point in point set item!");
return;
}
Scene_points_with_normal_item* new_item = new Scene_points_with_normal_item();
new_item->setName(QString("%1 (selected points)").arg(point_set_item->name()));
new_item->set_has_normals (point_set_item->has_normals());
new_item->setColor(point_set_item->color());
new_item->setRenderingMode(point_set_item->renderingMode());
new_item->setVisible(point_set_item->visible());
typedef Point_set_3<Kernel> Point_set;
for(Point_set::iterator it = point_set_item->point_set()->begin ();
it != point_set_item->point_set()->end(); ++ it) {
if (point_set_item->point_set()->is_selected (it))
new_item->point_set()->push_back(*it);
}
new_item->resetSelection();
new_item->invalidateOpenGLBuffers();
scene->addItem(new_item);
}
void on_Selection_tool_combo_box_changed (int index)
{
rectangle = (index == 0);
}
void on_Selection_mode_combo_box_changed (int index)
{
selection_mode = index;
}
private:
Messages_interface* messages;
QAction* actionPointSetSelection;
QDockWidget* dock_widget;
Ui::PointSetSelection ui_widget;
bool rectangle;
int selection_mode;
Scene_point_set_selection_visualizer* visualizer;
bool shift_pressing;
}; // end Polyhedron_demo_point_set_selection_plugin
//Q_EXPORT_PLUGIN2(Polyhedron_demo_point_set_selection_plugin, Polyhedron_demo_point_set_selection_plugin)
#include "Point_set_selection_plugin.moc"
| 29.531373 | 127 | 0.685081 | hlzz |
22c49f58b40dfb1128231c78099a753b486200b9 | 1,143 | cpp | C++ | atreyu/main.cpp | AiRT-Software/ocs | 2d6056a1260ac9ac75cfd507fb1a77db3b26298a | [
"BSD-4-Clause"
] | 1 | 2019-02-07T12:24:51.000Z | 2019-02-07T12:24:51.000Z | atreyu/main.cpp | AiRT-Software/ocs | 2d6056a1260ac9ac75cfd507fb1a77db3b26298a | [
"BSD-4-Clause"
] | null | null | null | atreyu/main.cpp | AiRT-Software/ocs | 2d6056a1260ac9ac75cfd507fb1a77db3b26298a | [
"BSD-4-Clause"
] | 1 | 2020-07-06T10:33:10.000Z | 2020-07-06T10:33:10.000Z |
/*
AiRT Software
http://www.airt.eu
This project has received funding from the European Union's Horizon 2020 research
and innovation programme under grant agreement No 732433.
Copyright Universitat Politecnica de Valencia 2017-2018.
All rights reserved.
Instituto de Automática e Informática Industrial (ai2)
http://www.ai2.upv.es
Contact: Paco Abad (fjabad@dsic.upv.es)
*/
#include <log.h>
#include "server.h"
#include "globalSettings.h"
using namespace airt;
int main(int argc, char **argv)
{
Log::setFile("atreyu.log");
// Remove for final release
Log::setOutputToConsole(true);
//
for (int i = 1; i < argc; i++)
{
std::string opt(argv[i]);
if (opt == "-l" && (i + 1 < argc))
{
Log::setFile(argv[++i]);
}
else if (opt == "-i" && (i + 1 < argc))
{
GlobalSettings::setIniFile(argv[++i]);
}
else if (opt == "-h" || opt == "--help")
{
std::cerr << argv[0] << " [-l logfile] [-i initfile] [-h]\n";
return -2;
}
}
Server server;
server.run();
return 0;
}
| 19.372881 | 81 | 0.55818 | AiRT-Software |
22c557929df89e8dc17f778d87fdd7bcc1010935 | 289 | cpp | C++ | tsc/src/SkyObject/Earth.cpp | jbangelo/tsc | 3251f81a27c7dbee043736e0f579f5d2a9e991a1 | [
"MIT"
] | 1 | 2016-11-29T01:31:26.000Z | 2016-11-29T01:31:26.000Z | tsc/src/SkyObject/Earth.cpp | jbangelo/tsc | 3251f81a27c7dbee043736e0f579f5d2a9e991a1 | [
"MIT"
] | null | null | null | tsc/src/SkyObject/Earth.cpp | jbangelo/tsc | 3251f81a27c7dbee043736e0f579f5d2a9e991a1 | [
"MIT"
] | null | null | null | /*
* Earth.cpp
*
* Created on: Nov 21, 2015
* Author: ben
*/
#include "SkyObject/Earth.h"
using tsc::SkyObject::Earth;
using tsc::Utils::IDataStorage;
Earth::Earth(IDataStorage& dataStorage) :
Planet(EARTH, dataStorage, *this)
{
_isEarth = true;
}
Earth::~Earth()
{
}
| 11.56 | 41 | 0.640138 | jbangelo |
22c5d248230d936ccfccf7d90f14524cf2dd5bcd | 221 | hpp | C++ | Includes/pyTheGame/Game/GameState.hpp | JYPark09/TheGame | 2af0bbe1199df794bd1688837c0f814479deded8 | [
"MIT"
] | null | null | null | Includes/pyTheGame/Game/GameState.hpp | JYPark09/TheGame | 2af0bbe1199df794bd1688837c0f814479deded8 | [
"MIT"
] | null | null | null | Includes/pyTheGame/Game/GameState.hpp | JYPark09/TheGame | 2af0bbe1199df794bd1688837c0f814479deded8 | [
"MIT"
] | null | null | null | #ifndef PYTHEGAME_GAME_STATE_HPP
#define PYTHEGAME_GAME_STATE_HPP
#include <pybind11/pybind11.h>
void buildGameResult(pybind11::module& m);
void buildGameState(pybind11::module& m);
#endif // PYTHEGAME_GAME_STATE_HPP
| 22.1 | 42 | 0.81448 | JYPark09 |
22c60e356e68db2412b1696f5d97877bcf0148df | 9,831 | cpp | C++ | trace_server/3rd/qwt/qwt_spline_cardinal.cpp | mojmir-svoboda/DbgToolkit | 590887987d0856032be906068a3103b6ce31d21c | [
"MIT"
] | null | null | null | trace_server/3rd/qwt/qwt_spline_cardinal.cpp | mojmir-svoboda/DbgToolkit | 590887987d0856032be906068a3103b6ce31d21c | [
"MIT"
] | null | null | null | trace_server/3rd/qwt/qwt_spline_cardinal.cpp | mojmir-svoboda/DbgToolkit | 590887987d0856032be906068a3103b6ce31d21c | [
"MIT"
] | null | null | null | /* -*- mode: C++ ; c-file-style: "stroustrup" -*- *****************************
* Qwt Widget Library
* Copyright (C) 1997 Josef Wilgen
* Copyright (C) 2002 Uwe Rathmann
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the Qwt License, Version 1.0
*****************************************************************************/
#include "qwt_spline_cardinal.h"
namespace QwtSplineCardinalG1P
{
class PathStore
{
public:
inline void init( int )
{
}
inline void start( const QPointF &p0 )
{
path.moveTo( p0 );
}
inline void addCubic( const QPointF &cp1,
const QPointF &cp2, const QPointF &p2 )
{
path.cubicTo( cp1, cp2, p2 );
}
QPainterPath path;
};
class ControlPointsStore
{
public:
inline ControlPointsStore():
d_cp( NULL )
{
}
inline void init( int size )
{
controlPoints.resize( size );
d_cp = controlPoints.data();
}
inline void start( const QPointF & )
{
}
inline void addCubic( const QPointF &cp1,
const QPointF &cp2, const QPointF & )
{
QLineF &l = *d_cp++;
l.setPoints( cp1, cp2 );
}
QVector<QLineF> controlPoints;
private:
QLineF* d_cp;
};
}
static inline QwtSplineCardinalG1::Tension qwtTension(
double d13, double d23, double d24,
const QPointF &p1, const QPointF &p2,
const QPointF &p3, const QPointF &p4 )
{
const bool b1 = ( d13 / 3.0 ) < d23;
const bool b2 = ( d24 / 3.0 ) < d23;
QwtSplineCardinalG1::Tension tension;
if ( b1 & b2 )
{
tension.t1 = ( p1 != p2 ) ? ( 1.0 / 3.0 ) : ( 2.0 / 3.0 );
tension.t2 = ( p3 != p4 ) ? ( 1.0 / 3.0 ) : ( 2.0 / 3.0 );
}
else
{
tension.t1 = d23 / ( b1 ? d24 : d13 );
tension.t2 = d23 / ( b2 ? d13 : d24 );
}
return tension;
}
template< class Param >
static inline QVector<QwtSplineCardinalG1::Tension> qwtTensions(
const QPolygonF &points, bool isClosed, Param param )
{
const int size = points.size();
QVector<QwtSplineCardinalG1::Tension> tensions2( isClosed ? size : size - 1 );
const QPointF *p = points.constData();
QwtSplineCardinalG1::Tension *t = tensions2.data();
const QPointF &p0 = isClosed ? p[size-1] : p[0];
double d13 = param(p[0], p[2]);
t[0] = qwtTension( param(p0, p[1]), param(p[0], p[1]),
d13, p0, p[0], p[1], p[2] );
for ( int i = 1; i < size - 2; i++ )
{
const double d23 = param( p[i], p[i+1] );
const double d24 = param( p[i], p[i+2] );
t[i] = qwtTension( d13, d23, d24, p[i-1], p[i], p[i+1], p[i+2] );
d13 = d24;
}
const QPointF &pn = isClosed ? p[0] : p[size-1];
const double d24 = param( p[size-2], pn );
t[size-2] = qwtTension( d13, param( p[size-2], p[size-1] ), d24,
p[size - 3], p[size - 2], p[size - 1], pn );
if ( isClosed )
{
const double d34 = param( p[size-1], p[0] );
const double d35 = param( p[size-1], p[1] );
t[size-1] = qwtTension( d24, d34, d35, p[size-2], p[size-1], p[0], p[1] );
}
return tensions2;
}
template< class SplineStore >
static SplineStore qwtSplinePathG1(
const QwtSplineCardinalG1 *spline, const QPolygonF &points )
{
const int size = points.size();
const int numTensions = spline->isClosing() ? size : size - 1;
const QVector<QwtSplineCardinalG1::Tension> tensions2 = spline->tensions( points );
if ( tensions2.size() != numTensions )
return SplineStore();
const QPointF *p = points.constData();
const QwtSplineCardinalG1::Tension *t = tensions2.constData();
SplineStore store;
store.init( numTensions );
store.start( p[0] );
const QPointF &p0 = spline->isClosing() ? p[size-1] : p[0];
QPointF vec1 = ( p[1] - p0 ) * 0.5;
for ( int i = 0; i < size - 2; i++ )
{
const QPointF vec2 = ( p[i+2] - p[i] ) * 0.5;
store.addCubic( p[i] + vec1 * t[i].t1,
p[i+1] - vec2 * t[i].t2, p[i+1] );
vec1 = vec2;
}
const QPointF &pn = spline->isClosing() ? p[0] : p[size-1];
const QPointF vec2 = 0.5 * ( pn - p[size - 2] );
store.addCubic( p[size - 2] + vec1 * t[size-2].t1,
p[size - 1] - vec2 * t[size-2].t2, p[size - 1] );
if ( spline->isClosing() )
{
const QPointF vec3 = 0.5 * ( p[1] - p[size-1] );
store.addCubic( p[size-1] + vec2 * t[size-1].t1,
p[0] - vec3 * t[size-1].t2, p[0] );
}
return store;
}
template< class SplineStore, class Param >
static SplineStore qwtSplinePathPleasing( const QPolygonF &points,
bool isClosed, Param param )
{
const int size = points.size();
const QPointF *p = points.constData();
SplineStore store;
store.init( isClosed ? size : size - 1 );
store.start( p[0] );
const QPointF &p0 = isClosed ? p[size-1] : p[0];
double d13 = param(p[0], p[2]);
const QwtSplineCardinalG1::Tension t0 = qwtTension(
param(p0, p[1]), param(p[0], p[1]), d13, p0, p[0], p[1], p[2] );
const QPointF vec0 = ( p[1] - p0 ) * 0.5;
QPointF vec1 = ( p[2] - p[0] ) * 0.5;
store.addCubic( p[0] + vec0 * t0.t1, p[1] - vec1 * t0.t2, p[1] );
for ( int i = 1; i < size - 2; i++ )
{
const double d23 = param(p[i], p[i+1]);
const double d24 = param(p[i], p[i+2]);
const QPointF vec2 = ( p[i+2] - p[i] ) * 0.5;
const QwtSplineCardinalG1::Tension t =
qwtTension( d13, d23, d24, p[i-1], p[i], p[i+1], p[i+2] );
store.addCubic( p[i] + vec1 * t.t1, p[i+1] - vec2 * t.t2, p[i+1] );
d13 = d24;
vec1 = vec2;
}
const QPointF &pn = isClosed ? p[0] : p[size-1];
const double d24 = param( p[size-2], pn );
const QwtSplineCardinalG1::Tension tn = qwtTension(
d13, param( p[size-2], p[size-1] ), d24, p[size-3], p[size-2], p[size-1], pn );
const QPointF vec2 = 0.5 * ( pn - p[size-2] );
store.addCubic( p[size-2] + vec1 * tn.t1, p[size-1] - vec2 * tn.t2, p[size-1] );
if ( isClosed )
{
const double d34 = param( p[size-1], p[0] );
const double d35 = param( p[size-1], p[1] );
const QPointF vec3 = 0.5 * ( p[1] - p[size-1] );
const QwtSplineCardinalG1::Tension tn =
qwtTension( d24, d34, d35, p[size-2], p[size-1], p[0], p[1] );
store.addCubic( p[size-1] + vec2 * tn.t1, p[0] - vec3 * tn.t2, p[0] );
}
return store;
}
QwtSplineCardinalG1::QwtSplineCardinalG1()
{
}
QwtSplineCardinalG1::~QwtSplineCardinalG1()
{
}
QVector<QLineF> QwtSplineCardinalG1::bezierControlPointsP(
const QPolygonF &points ) const
{
using namespace QwtSplineCardinalG1P;
const ControlPointsStore store =
qwtSplinePathG1<ControlPointsStore>( this, points );
return store.controlPoints;
}
QPainterPath QwtSplineCardinalG1::pathP( const QPolygonF &points ) const
{
using namespace QwtSplineCardinalG1P;
PathStore store = qwtSplinePathG1<PathStore>( this, points );
if ( isClosing() )
store.path.closeSubpath();
return store.path;
}
QwtSplinePleasing::QwtSplinePleasing()
{
}
QwtSplinePleasing::~QwtSplinePleasing()
{
}
QPainterPath QwtSplinePleasing::pathP( const QPolygonF &points ) const
{
const int size = points.size();
if ( size <= 2 )
return QwtSplineCardinalG1::pathP( points );
using namespace QwtSplineCardinalG1P;
PathStore store;
switch( parametrization()->type() )
{
case QwtSplineParameter::ParameterX:
{
store = qwtSplinePathPleasing<PathStore>( points,
isClosing(), QwtSplineParameter::paramX() );
break;
}
case QwtSplineParameter::ParameterUniform:
{
store = qwtSplinePathPleasing<PathStore>( points,
isClosing(), QwtSplineParameter::paramUniform() );
break;
}
case QwtSplineParameter::ParameterChordal:
{
store = qwtSplinePathPleasing<PathStore>( points,
isClosing(), QwtSplineParameter::paramChordal() );
break;
}
default:
{
store = qwtSplinePathPleasing<PathStore>( points,
isClosing(), QwtSplineParameter::param( parametrization() ) );
}
}
if ( isClosing() )
store.path.closeSubpath();
return store.path;
}
QVector<QLineF> QwtSplinePleasing::bezierControlPointsP(
const QPolygonF &points ) const
{
return QwtSplineCardinalG1::bezierControlPointsP( points );
}
QVector<QwtSplineCardinalG1::Tension>
QwtSplinePleasing::tensions( const QPolygonF &points ) const
{
QVector<Tension> tensions2;
if ( points.size() <= 2 )
return tensions2;
switch( parametrization()->type() )
{
case QwtSplineParameter::ParameterX:
{
tensions2 = qwtTensions( points,
isClosing(), QwtSplineParameter::paramX() );
break;
}
case QwtSplineParameter::ParameterUniform:
{
tensions2 = qwtTensions( points,
isClosing(), QwtSplineParameter::paramUniform() );
break;
}
case QwtSplineParameter::ParameterChordal:
{
tensions2 = qwtTensions( points,
isClosing(), QwtSplineParameter::paramChordal() );
break;
}
default:
{
tensions2 = qwtTensions( points,
isClosing(), QwtSplineParameter::param( parametrization() ) );
}
}
return tensions2;
}
| 27.157459 | 87 | 0.551521 | mojmir-svoboda |
22c62abcae296cc143d5e364ae8c021641d9991e | 982 | cpp | C++ | Shared/Src/Shin/Vertex/TextureVertex.cpp | sindharta/vulkan-sandbox | 45ef4be936273723b0d8f84a7396293016e4254b | [
"Apache-2.0"
] | null | null | null | Shared/Src/Shin/Vertex/TextureVertex.cpp | sindharta/vulkan-sandbox | 45ef4be936273723b0d8f84a7396293016e4254b | [
"Apache-2.0"
] | null | null | null | Shared/Src/Shin/Vertex/TextureVertex.cpp | sindharta/vulkan-sandbox | 45ef4be936273723b0d8f84a7396293016e4254b | [
"Apache-2.0"
] | 1 | 2021-06-15T06:15:24.000Z | 2021-06-15T06:15:24.000Z | #include "TextureVertex.h"
//---------------------------------------------------------------------------------------------------------------------
const VkVertexInputBindingDescription* TextureVertex::GetBindingDescription() {
static VkVertexInputBindingDescription bindingDescription = {
0, sizeof(TextureVertex), VK_VERTEX_INPUT_RATE_VERTEX
};
return &bindingDescription;
}
//---------------------------------------------------------------------------------------------------------------------
const std::vector<VkVertexInputAttributeDescription>* TextureVertex::GetAttributeDescriptions() {
static std::vector<VkVertexInputAttributeDescription> attributeDescriptions{
{ 0, 0, VK_FORMAT_R32G32_SFLOAT, offsetof(TextureVertex, Pos) },
{ 1, 0, VK_FORMAT_R32G32B32_SFLOAT, offsetof(TextureVertex, Color) },
{ 2, 0, VK_FORMAT_R32G32_SFLOAT, offsetof(TextureVertex, TexCoord) },
};
return &attributeDescriptions;
}
| 39.28 | 119 | 0.564155 | sindharta |
22c7cbbf15e6ff0d998153c996df2a85b8060ed5 | 2,202 | cpp | C++ | source/parser/interp.cpp | zhiayang/peirce-alpha | 49931a234ba173ed7ea4bdcca9949f28d64d7b4f | [
"Apache-2.0"
] | 1 | 2021-05-03T22:51:13.000Z | 2021-05-03T22:51:13.000Z | source/parser/interp.cpp | zhiayang/peirce-alpha | 49931a234ba173ed7ea4bdcca9949f28d64d7b4f | [
"Apache-2.0"
] | 1 | 2021-05-03T22:52:59.000Z | 2021-05-10T15:31:26.000Z | source/parser/interp.cpp | zhiayang/peirce-alpha | 49931a234ba173ed7ea4bdcca9949f28d64d7b4f | [
"Apache-2.0"
] | null | null | null | // interp.cpp
// Copyright (c) 2021, zhiayang
// Licensed under the Apache License Version 2.0.
#include "ast.h"
namespace ast
{
Expr* Var::evaluate(const std::unordered_map<std::string, bool>& syms) const
{
if(auto it = syms.find(this->name); it != syms.end())
return new Lit(it->second);
return new Var(this->name);
}
Expr* Lit::evaluate(const std::unordered_map<std::string, bool>& syms) const
{
return new Lit(this->value);
}
Expr* Not::evaluate(const std::unordered_map<std::string, bool>& syms) const
{
auto ee = this->e->evaluate(syms);
if(auto elit = dynamic_cast<Lit*>(ee); elit != nullptr)
{
auto v = elit->value;
delete ee;
return new Lit(!v);
}
// check if the inside is a not -- eliminate the double negation
if(auto enot = dynamic_cast<Not*>(ee); enot)
return enot->e;
return new Not(ee);
}
Expr* And::evaluate(const std::unordered_map<std::string, bool>& syms) const
{
auto ll = this->left->evaluate(syms);
if(auto llit = dynamic_cast<Lit*>(ll); llit != nullptr)
{
if(llit->value)
{
delete ll;
return this->right->evaluate(syms);
}
else
{
return new Lit(false);
}
}
auto rr = this->right->evaluate(syms);
if(auto rlit = dynamic_cast<Lit*>(rr); rlit != nullptr)
{
if(rlit->value)
{
delete rr;
return ll;
}
else
{
delete ll;
return new Lit(false);
}
}
return new And(ll, rr);
}
// these 3 don't need to be evaluated, since we'll use transform()
// to reduce everything to ands and nots.
Expr* Or::evaluate(const std::unordered_map<std::string, bool>& syms) const
{
return nullptr;
}
Expr* Implies::evaluate(const std::unordered_map<std::string, bool>& syms) const
{
return nullptr;
}
Expr* BidirImplies::evaluate(const std::unordered_map<std::string, bool>& syms) const
{
return nullptr;
}
Expr::~Expr() { }
Var::~Var() { }
Lit::~Lit() { }
And::~And() { delete this->left; delete this->right; }
Not::~Not() { delete this->e; }
Or::~Or() { delete this->left; delete this->right; }
Implies::~Implies() { delete this->left; delete this->right; }
BidirImplies::~BidirImplies() { delete this->left; delete this->right; }
}
| 22.02 | 86 | 0.631698 | zhiayang |
22c857a309705824486a47aba5a2571c3bc1f99d | 748 | cpp | C++ | Algorithms/LC/cpp/0520 Detect Capital/LC0520.cpp | tjzhym/LeetCode-solution | 06bd35bae619caaf8153b81849dae9dcc7bc9491 | [
"MIT"
] | null | null | null | Algorithms/LC/cpp/0520 Detect Capital/LC0520.cpp | tjzhym/LeetCode-solution | 06bd35bae619caaf8153b81849dae9dcc7bc9491 | [
"MIT"
] | null | null | null | Algorithms/LC/cpp/0520 Detect Capital/LC0520.cpp | tjzhym/LeetCode-solution | 06bd35bae619caaf8153b81849dae9dcc7bc9491 | [
"MIT"
] | null | null | null | // Problem : https://leetcode.com/problems/detect-capital/
// Solution: https://github.com/tjzhym/LeetCode-solution
// Author : zhym (tjzhym)
// Date : 2021-11-13
#include <string>
using namespace std;
class Solution {
public:
bool detectCapitalUse(string word) {
if (islower(word[0]) && word.size() > 1 && isupper(word[1])) {
return false;
}
int isCapital = 0; // isupper function return int
if (word.size() > 2) {
isCapital = isupper(word[1]);
}
for (int index = 2; index < word.size(); ++index) {
if (isupper(word[index]) != isCapital) {
return false;
}
}
return true;
}
};
// Traverse | 22.666667 | 70 | 0.529412 | tjzhym |
22cb7c1f8e26893ec4d1132e8a428de01983c32a | 10,849 | cxx | C++ | Applications/OverView/Core/ToolbarActions.cxx | utkarshayachit/ParaView | 7bbb2aa16fdef9cfbcf4a3786cad905d6770771b | [
"BSD-3-Clause"
] | null | null | null | Applications/OverView/Core/ToolbarActions.cxx | utkarshayachit/ParaView | 7bbb2aa16fdef9cfbcf4a3786cad905d6770771b | [
"BSD-3-Clause"
] | null | null | null | Applications/OverView/Core/ToolbarActions.cxx | utkarshayachit/ParaView | 7bbb2aa16fdef9cfbcf4a3786cad905d6770771b | [
"BSD-3-Clause"
] | null | null | null | /*=========================================================================
Program: ParaView
Module: ToolbarActions.cxx
Copyright (c) 2005-2008 Sandia Corporation, Kitware Inc.
All rights reserved.
ParaView is a free software; you can redistribute it and/or modify it
under the terms of the ParaView license version 1.2.
See License_v1.2.txt for the full ParaView license.
A copy of this license can be obtained by contacting
Kitware Inc.
28 Corporate Drive
Clifton Park, NY 12065
USA
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 AUTHORS 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 "ToolbarActions.h"
#include <pqActiveView.h>
#include <pqApplicationCore.h>
#include <pqDataRepresentation.h>
#include <pqDisplayPolicy.h>
#include <pqObjectBuilder.h>
#include <pqOutputPort.h>
#include <pqPendingDisplayManager.h>
#include <pqPluginManager.h>
#include <pqPipelineSource.h>
#include <pqRepresentation.h>
#include <pqServer.h>
#include <pqServerManagerModel.h>
#include <pqServerManagerModelItem.h>
#include <pqServerManagerSelectionModel.h>
#include <pqServerResource.h>
#include <pqServerResources.h>
#include <pqView.h>
#include <vtkPVDataInformation.h>
#include <vtkPVXMLParser.h>
#include <vtkSmartPointer.h>
#include <vtkSMInputProperty.h>
#include <vtkSMProperty.h>
#include <vtkSMProxyManager.h>
#include <vtkSMSourceProxy.h>
#include <QAction>
#include <QFile>
#include <QIcon>
#include <QtDebug>
ToolbarActions::ToolbarActions(QObject* p)
: QActionGroup(p)
{
}
ToolbarActions::~ToolbarActions()
{
}
//-----------------------------------------------------------------------------
pqPipelineSource *ToolbarActions::getActiveSource() const
{
pqServerManagerModelItem *item = 0;
pqServerManagerSelectionModel *selection =
pqApplicationCore::instance()->getSelectionModel();
const pqServerManagerSelection *selected = selection->selectedItems();
if(selected->size() == 1)
{
item = selected->first();
}
else if(selected->size() > 1)
{
item = selection->currentItem();
if(item && !selection->isSelected(item))
{
item = 0;
}
}
if (item && qobject_cast<pqPipelineSource*>(item))
{
return static_cast<pqPipelineSource*>(item);
}
else if (item && qobject_cast<pqOutputPort*>(item))
{
pqOutputPort* port = static_cast<pqOutputPort*>(item);
return port->getSource();
}
return 0;
}
//-----------------------------------------------------------------------------
void ToolbarActions::createSource()
{
QAction* action = qobject_cast<QAction*>(this->sender());
if (!action)
{
return;
}
QString type = action->data().toString();
this->createSource(type);
}
//-----------------------------------------------------------------------------
void ToolbarActions::createSource(const QString &type)
{
pqServer* server= pqApplicationCore::instance()->
getServerManagerModel()->getItemAtIndex<pqServer*>(0);
if (!server)
{
qDebug() << "No server present cannot convert source.";
return;
}
pqObjectBuilder* builder = pqApplicationCore::instance()->getObjectBuilder();
// Create source of the given type
builder->createSource("sources", type, server);
}
//-----------------------------------------------------------------------------
void ToolbarActions::createFilter()
{
QAction* action = qobject_cast<QAction*>(this->sender());
if (!action)
{
return;
}
QString type = action->data().toString();
this->createFilter(type);
}
//-----------------------------------------------------------------------------
void ToolbarActions::createFilter(const QString &type)
{
pqServer* server= pqApplicationCore::instance()->
getServerManagerModel()->getItemAtIndex<pqServer*>(0);
if (!server)
{
qDebug() << "No server present cannot convert source.";
return;
}
// Get the currently selected source
pqPipelineSource *src = this->getActiveSource();
if(!src)
{
return;
}
pqObjectBuilder* builder = pqApplicationCore::instance()->getObjectBuilder();
builder->createFilter("filters", type, src);
}
//-----------------------------------------------------------------------------
void ToolbarActions::createAndExecuteFilter()
{
QAction* action = qobject_cast<QAction*>(this->sender());
if (!action)
{
return;
}
QString type = action->data().toString();
this->createAndExecuteFilter(type);
}
//-----------------------------------------------------------------------------
void ToolbarActions::createAndExecuteFilter(const QString &type)
{
pqServer* server= pqApplicationCore::instance()->
getServerManagerModel()->getItemAtIndex<pqServer*>(0);
if (!server)
{
qDebug() << "No server present cannot convert source.";
return;
}
// Get the currently selected source
pqPipelineSource *src = this->getActiveSource();
if(!src)
{
return;
}
pqObjectBuilder* builder = pqApplicationCore::instance()->getObjectBuilder();
// Create filter of the given type
pqPendingDisplayManager *pdm = qobject_cast<pqPendingDisplayManager*>(pqApplicationCore::instance()->manager("PENDING_DISPLAY_MANAGER"));
pdm->setAddSourceIgnored(true);
pqPipelineSource *filter = builder->createFilter("filters", type, src);
filter->getProxy()->UpdateVTKObjects();
filter->setModifiedState(pqProxy::UNMODIFIED);
pqOutputPort* opPort = filter->getOutputPort(0);
QString preferredViewType = pqApplicationCore::instance()->getDisplayPolicy()->getPreferredViewType(opPort,0);
if(preferredViewType.isNull())
{
return;
}
// Add it to the view
pqView *view = builder->createView(preferredViewType, server);
builder->createDataRepresentation(filter->getOutputPort(0),view);
pdm->setAddSourceIgnored(false);
}
//-----------------------------------------------------------------------------
void ToolbarActions::createView()
{
QAction* action = qobject_cast<QAction*>(this->sender());
if(!action)
{
return;
}
QString type = action->data().toString();
this->createView(type);
}
//-----------------------------------------------------------------------------
void ToolbarActions::createView(const QString &type)
{
pqServer* server= pqApplicationCore::instance()->
getServerManagerModel()->getItemAtIndex<pqServer*>(0);
if (!server)
{
qDebug() << "No server present cannot convert view.";
return;
}
pqObjectBuilder* builder =
pqApplicationCore::instance()-> getObjectBuilder();
// Try to create a view of the given type
pqView *view = builder->createView(type, server);
if(!view)
{
return;
}
// Get the currently selected source
pqPipelineSource *src = this->getActiveSource();
if(!src)
{
return;
}
pqOutputPort* opPort = src->getOutputPort(0);
// Add a representation of the source to the view
builder->createDataRepresentation(opPort,view);
view->render();
}
//-----------------------------------------------------------------------------
void ToolbarActions::createSelectionFilter()
{
QAction* action = qobject_cast<QAction*>(this->sender());
if (!action)
{
return;
}
QString type = action->data().toString();
this->createSelectionFilter(type);
}
//-----------------------------------------------------------------------------
void ToolbarActions::createSelectionFilter(const QString &type)
{
pqServer* server= pqApplicationCore::instance()->
getServerManagerModel()->getItemAtIndex<pqServer*>(0);
if (!server)
{
qDebug() << "No server present cannot convert source.";
return;
}
pqView *view = pqActiveView::instance().current();
if(!view)
{
return;
}
// Find the view's first visible representation
QList<pqRepresentation*> reps = view->getRepresentations();
pqDataRepresentation* pqRepr = NULL;
for(int i=0; i<reps.size(); ++i)
{
if(reps[i]->isVisible())
{
pqRepr = qobject_cast<pqDataRepresentation*>(reps[i]);
break;
}
}
// No visible rep
if(!pqRepr)
return;
pqOutputPort* opPort = pqRepr->getOutputPortFromInput();
vtkSMSourceProxy* srcProxy = vtkSMSourceProxy::SafeDownCast(
opPort->getSource()->getProxy());
vtkSMSourceProxy *selProxy = vtkSMSourceProxy::SafeDownCast(srcProxy->GetSelectionInput(0));
vtkSMSourceProxy* filterProxy = vtkSMSourceProxy::SafeDownCast(
vtkSMProxyManager::GetProxyManager()->NewProxy("filters", type.toAscii().data()));
filterProxy->SetConnectionID(server->GetConnectionID());
vtkSMInputProperty *selInput = vtkSMInputProperty::SafeDownCast(filterProxy->GetProperty("Input"));
selInput->AddProxy(selProxy);
vtkSMInputProperty *graphInput = vtkSMInputProperty::SafeDownCast(filterProxy->GetProperty("Graph"));
graphInput->AddProxy(srcProxy);
filterProxy->UpdatePipeline();
srcProxy->SetSelectionInput(opPort->getPortNumber(), filterProxy, 0);
selInput->RemoveAllProxies();
graphInput->RemoveAllProxies();
filterProxy->Delete();
}
//-----------------------------------------------------------------------------
void ToolbarActions::loadState()
{
QAction* action = qobject_cast<QAction*>(this->sender());
if(!action)
{
return;
}
QString xmlfilename = action->data().toString();
pqServer* server= pqApplicationCore::instance()->
getServerManagerModel()->getItemAtIndex<pqServer*>(0);
if (!server)
{
qDebug() << "No server present, cannot load state.";
return;
}
QFile xml(xmlfilename);
if (!xml.open(QIODevice::ReadOnly))
{
qDebug() << "Failed to load " << xmlfilename;
return;
}
QByteArray dat = xml.readAll();
// Read in the xml file to restore.
vtkSmartPointer<vtkPVXMLParser> xmlParser =
vtkSmartPointer<vtkPVXMLParser>::New();
if(!xmlParser->Parse(dat.data()))
{
qDebug() << "Failed to parse " << xmlfilename;
xml.close();
return;
}
// Get the root element from the parser.
vtkPVXMLElement *root = xmlParser->GetRootElement();
pqApplicationCore::instance()->loadState(root, server);
}
| 27.605598 | 139 | 0.630289 | utkarshayachit |
22d1eb53c0a65998647ccedf5f8eed35fadb14c4 | 10,789 | hpp | C++ | src/Evolution/Systems/Cce/OptionTags.hpp | desperadoshi/spectre | b61c12dce108a98a875a1e9476e5630bea634119 | [
"MIT"
] | null | null | null | src/Evolution/Systems/Cce/OptionTags.hpp | desperadoshi/spectre | b61c12dce108a98a875a1e9476e5630bea634119 | [
"MIT"
] | null | null | null | src/Evolution/Systems/Cce/OptionTags.hpp | desperadoshi/spectre | b61c12dce108a98a875a1e9476e5630bea634119 | [
"MIT"
] | null | null | null | // Distributed under the MIT License.
// See LICENSE.txt for details.
#pragma once
#include <cstddef>
#include <limits>
#include "DataStructures/DataBox/Tag.hpp"
#include "Evolution/Systems/Cce/Initialize/InitializeJ.hpp"
#include "Evolution/Systems/Cce/InterfaceManagers/GhInterfaceManager.hpp"
#include "Evolution/Systems/Cce/InterfaceManagers/GhLockstep.hpp"
#include "Evolution/Systems/Cce/ReadBoundaryDataH5.hpp"
#include "NumericalAlgorithms/Interpolation/SpanInterpolator.hpp"
#include "Options/Options.hpp"
namespace Cce {
namespace OptionTags {
/// %Option group
struct Cce {
static constexpr OptionString help = {"Options for the Cce evolution system"};
};
/// %Option group
struct Filtering {
static constexpr OptionString help = {"Options for the filtering in Cce"};
using group = Cce;
};
struct LMax {
using type = size_t;
static constexpr OptionString help{
"Maximum l value for spin-weighted spherical harmonics"};
using group = Cce;
};
struct FilterLMax {
using type = size_t;
static constexpr OptionString help{"l mode cutoff for angular filtering"};
using group = Filtering;
};
struct RadialFilterAlpha {
using type = double;
static constexpr OptionString help{
"alpha parameter in exponential radial filter"};
using group = Filtering;
};
struct RadialFilterHalfPower {
using type = size_t;
static constexpr OptionString help{
"Half-power of the exponential radial filter argument"};
using group = Filtering;
};
struct ObservationLMax {
using type = size_t;
static constexpr OptionString help{"Maximum l value for swsh output"};
using group = Cce;
};
struct NumberOfRadialPoints {
using type = size_t;
static constexpr OptionString help{
"Number of radial grid points in the spherical domain"};
using group = Cce;
};
struct ExtractionRadius {
using type = double;
static constexpr OptionString help{"Extraction radius from the GH system."};
using group = Cce;
};
struct EndTime {
using type = double;
static constexpr OptionString help{"End time for the Cce Evolution."};
static double default_value() noexcept {
return std::numeric_limits<double>::infinity();
}
using group = Cce;
};
struct StartTime {
using type = double;
static constexpr OptionString help{
"Cce Start time (default to earliest possible time)."};
static double default_value() noexcept {
return -std::numeric_limits<double>::infinity();
}
using group = Cce;
};
struct TargetStepSize {
using type = double;
static constexpr OptionString help{"Target time step size for Cce Evolution"};
using group = Cce;
};
struct BoundaryDataFilename {
using type = std::string;
static constexpr OptionString help{
"H5 file to read the wordltube data from."};
using group = Cce;
};
struct H5LookaheadTimes {
using type = size_t;
static constexpr OptionString help{
"Number of times steps from the h5 to cache each read."};
static size_t default_value() noexcept { return 200; }
using group = Cce;
};
struct H5Interpolator {
using type = std::unique_ptr<intrp::SpanInterpolator>;
static constexpr OptionString help{
"The interpolator for imported h5 worldtube data."};
using group = Cce;
};
struct GhInterfaceManager {
using type = std::unique_ptr<InterfaceManagers::GhInterfaceManager>;
static constexpr OptionString help{
"Class to manage worldtube data from a GH system."};
using group = Cce;
};
struct ScriInterpolationOrder {
static std::string name() noexcept { return "ScriInterpOrder"; }
using type = size_t;
static constexpr OptionString help{"Order of time interpolation at scri+."};
static size_t default_value() noexcept { return 5; }
using group = Cce;
};
struct ScriOutputDensity {
using type = size_t;
static constexpr OptionString help{
"Number of scri output points per timestep."};
static size_t default_value() noexcept { return 1; }
using group = Cce;
};
struct InitializeJ {
using type = std::unique_ptr<::Cce::InitializeJ::InitializeJ>;
static constexpr OptionString help{
"The initialization for the first hypersurface for J"};
using group = Cce;
};
} // namespace OptionTags
namespace InitializationTags {
/// An initialization tag that constructs a `WorldtubeDataManager` from options
struct H5WorldtubeBoundaryDataManager : db::SimpleTag {
using type = WorldtubeDataManager;
using option_tags =
tmpl::list<OptionTags::LMax, OptionTags::BoundaryDataFilename,
OptionTags::H5LookaheadTimes, OptionTags::H5Interpolator>;
static constexpr bool pass_metavariables = false;
static WorldtubeDataManager create_from_options(
const size_t l_max, const std::string& filename,
const size_t number_of_lookahead_times,
const std::unique_ptr<intrp::SpanInterpolator>& interpolator) noexcept {
return WorldtubeDataManager{
std::make_unique<SpecWorldtubeH5BufferUpdater>(filename), l_max,
number_of_lookahead_times, interpolator->get_clone()};
}
};
struct ScriInterpolationOrder : db::SimpleTag {
using type = size_t;
using option_tags = tmpl::list<OptionTags::ScriInterpolationOrder>;
static constexpr bool pass_metavariables = false;
static size_t create_from_options(
const size_t scri_plus_interpolation_order) noexcept {
return scri_plus_interpolation_order;
}
};
struct TargetStepSize : db::SimpleTag {
using type = double;
using option_tags = tmpl::list<OptionTags::TargetStepSize>;
static constexpr bool pass_metavariables = false;
static double create_from_options(const double target_step_size) noexcept {
return target_step_size;
}
};
struct ExtractionRadius : db::SimpleTag {
using type = double;
using option_tags = tmpl::list<OptionTags::ExtractionRadius>;
template <typename Metavariables>
static double create_from_options(const double extraction_radius) noexcept {
return extraction_radius;
}
};
struct ScriOutputDensity : db::SimpleTag {
using type = size_t;
using option_tags = tmpl::list<OptionTags::ScriOutputDensity>;
static constexpr bool pass_metavariables = false;
static size_t create_from_options(const size_t scri_output_density) noexcept {
return scri_output_density;
}
};
} // namespace InitializationTags
namespace Tags {
struct LMax : db::SimpleTag, Spectral::Swsh::Tags::LMaxBase {
using type = size_t;
using option_tags = tmpl::list<OptionTags::LMax>;
static constexpr bool pass_metavariables = false;
static size_t create_from_options(const size_t l_max) noexcept {
return l_max;
}
};
struct NumberOfRadialPoints : db::SimpleTag,
Spectral::Swsh::Tags::NumberOfRadialPointsBase {
using type = size_t;
using option_tags = tmpl::list<OptionTags::NumberOfRadialPoints>;
static constexpr bool pass_metavariables = false;
static size_t create_from_options(
const size_t number_of_radial_points) noexcept {
return number_of_radial_points;
}
};
struct ObservationLMax : db::SimpleTag {
using type = size_t;
using option_tags = tmpl::list<OptionTags::ObservationLMax>;
static constexpr bool pass_metavariables = false;
static size_t create_from_options(const size_t observation_l_max) noexcept {
return observation_l_max;
}
};
struct FilterLMax : db::SimpleTag {
using type = size_t;
using option_tags = tmpl::list<OptionTags::FilterLMax>;
static constexpr bool pass_metavariables = false;
static size_t create_from_options(const size_t filter_l_max) noexcept {
return filter_l_max;
}
};
struct RadialFilterAlpha : db::SimpleTag {
using type = double;
using option_tags = tmpl::list<OptionTags::RadialFilterAlpha>;
static constexpr bool pass_metavariables = false;
static double create_from_options(const double radial_filter_alpha) noexcept {
return radial_filter_alpha;
}
};
struct RadialFilterHalfPower : db::SimpleTag {
using type = size_t;
using option_tags = tmpl::list<OptionTags::RadialFilterHalfPower>;
static constexpr bool pass_metavariables = false;
static size_t create_from_options(
const size_t radial_filter_half_power) noexcept {
return radial_filter_half_power;
}
};
struct StartTime : db::SimpleTag {
using type = double;
using option_tags =
tmpl::list<OptionTags::StartTime, OptionTags::BoundaryDataFilename>;
static constexpr bool pass_metavariables = false;
static double create_from_options(double start_time,
const std::string& filename) noexcept {
if (start_time == -std::numeric_limits<double>::infinity()) {
SpecWorldtubeH5BufferUpdater h5_boundary_updater{filename};
const auto& time_buffer = h5_boundary_updater.get_time_buffer();
start_time = time_buffer[0];
}
return start_time;
}
};
/// \brief Represents the final time of a bounded CCE evolution, determined
/// either from option specification or from the file
///
/// \details If the option `OptionTags::EndTime` is set to
/// `std::numeric_limits<double>::%infinity()`, this will find the end time from
/// the provided H5 file. If `OptionTags::EndTime` takes any other value, it
/// will be used directly as the end time for the CCE evolution instead.
struct EndTime : db::SimpleTag {
using type = double;
using option_tags =
tmpl::list<OptionTags::EndTime, OptionTags::BoundaryDataFilename>;
static constexpr bool pass_metavariables = false;
static double create_from_options(double end_time,
const std::string& filename) {
if (end_time == std::numeric_limits<double>::infinity()) {
SpecWorldtubeH5BufferUpdater h5_boundary_updater{filename};
const auto& time_buffer = h5_boundary_updater.get_time_buffer();
end_time = time_buffer[time_buffer.size() - 1];
}
return end_time;
}
};
struct GhInterfaceManager : db::SimpleTag {
using type = std::unique_ptr<InterfaceManagers::GhInterfaceManager>;
using option_tags = tmpl::list<OptionTags::GhInterfaceManager>;
template <typename Metavariables>
static std::unique_ptr<InterfaceManagers::GhInterfaceManager>
create_from_options(
const std::unique_ptr<InterfaceManagers::GhInterfaceManager>&
interface_manager) noexcept {
return interface_manager->get_clone();
}
};
struct InitializeJ : db::SimpleTag {
using type = std::unique_ptr<::Cce::InitializeJ::InitializeJ>;
using option_tags = tmpl::list<OptionTags::InitializeJ>;
static constexpr bool pass_metavariables = false;
static std::unique_ptr<::Cce::InitializeJ::InitializeJ> create_from_options(
const std::unique_ptr<::Cce::InitializeJ::InitializeJ>&
initialize_j) noexcept {
return initialize_j->get_clone();
}
};
} // namespace Tags
} // namespace Cce
| 30.91404 | 80 | 0.736769 | desperadoshi |
22d2f10d921c9f1cd7ca1c6742ea221a46a9fb3d | 2,809 | cc | C++ | graph-tool-2.27/src/graph/topology/graph_similarity.cc | Znigneering/CSCI-3154 | bc318efc73d2a80025b98f5b3e4f7e4819e952e4 | [
"MIT"
] | null | null | null | graph-tool-2.27/src/graph/topology/graph_similarity.cc | Znigneering/CSCI-3154 | bc318efc73d2a80025b98f5b3e4f7e4819e952e4 | [
"MIT"
] | null | null | null | graph-tool-2.27/src/graph/topology/graph_similarity.cc | Znigneering/CSCI-3154 | bc318efc73d2a80025b98f5b3e4f7e4819e952e4 | [
"MIT"
] | null | null | null | // graph-tool -- a general graph modification and manipulation thingy
//
// Copyright (C) 2006-2018 Tiago de Paula Peixoto <tiago@skewed.de>
//
// 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 "graph_python_interface.hh"
#include "graph.hh"
#include "graph_filtering.hh"
#include "graph_properties.hh"
#include "graph_selectors.hh"
#include "graph_similarity.hh"
using namespace std;
using namespace boost;
using namespace graph_tool;
template <class Type, class Index>
auto uncheck(boost::unchecked_vector_property_map<Type,Index>, boost::any p)
{
return boost::any_cast<boost::checked_vector_property_map<Type,Index>>(p).get_unchecked();
}
template <class T>
auto&& uncheck(T&&, boost::any p)
{
return boost::any_cast<T>(p);
}
typedef UnityPropertyMap<size_t,GraphInterface::edge_t> ecmap_t;
typedef boost::mpl::push_back<edge_scalar_properties, ecmap_t>::type
weight_props_t;
python::object similarity(GraphInterface& gi1, GraphInterface& gi2,
boost::any weight1, boost::any weight2,
boost::any label1, boost::any label2, double norm,
bool asym)
{
if (weight1.empty())
weight1 = ecmap_t();
if (weight2.empty())
weight2 = ecmap_t();
python::object s;
gt_dispatch<>()
([&](const auto& g1, const auto& g2, auto ew1, auto l1)
{
auto l2 = uncheck(l1, label2);
auto ew2 = uncheck(ew1, weight2);
auto ret = get_similarity(g1, g2, ew1, ew2, l1, l2, asym, norm);
s = python::object(ret);
},
all_graph_views(),
all_graph_views(),
weight_props_t(),
vertex_scalar_properties())
(gi1.get_graph_view(), gi2.get_graph_view(), weight1, label1);
return s;
}
python::object similarity_fast(GraphInterface& gi1, GraphInterface& gi2,
boost::any weight1, boost::any weight2,
boost::any label1, boost::any label2,
double norm, bool asym);
void export_similarity()
{
python::def("similarity", &similarity);
python::def("similarity_fast", &similarity_fast);
};
| 33.440476 | 94 | 0.655037 | Znigneering |
22d39c9953c594931b7016a1f9ca7edcfb004c79 | 717 | cpp | C++ | cc150/2.1.cpp | WIZARD-CXY/pl | 22b7f5d81804f4e333d3cff6433364ba1a0ac7ef | [
"Apache-2.0"
] | 1 | 2016-01-20T08:26:34.000Z | 2016-01-20T08:26:34.000Z | cc150/2.1.cpp | WIZARD-CXY/pl | 22b7f5d81804f4e333d3cff6433364ba1a0ac7ef | [
"Apache-2.0"
] | 1 | 2015-10-21T05:38:17.000Z | 2015-11-02T07:42:55.000Z | cc150/2.1.cpp | WIZARD-CXY/pl | 22b7f5d81804f4e333d3cff6433364ba1a0ac7ef | [
"Apache-2.0"
] | null | null | null | #include <iostream>
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode(int v):val(v),next(NULL){}
};
void deleteDup(ListNode *head){
if(head==NULL){
return;
}
ListNode *cur=head;
while(cur){
ListNode *run=cur;
while(run->next){
if(run->next->val==cur->val){
//delete run->next;
ListNode *temp=run->next;
run->next=run->next->next;
delete temp;
}else{
run=run->next;
}
}
cur=cur->next;
}
}
int main(){
ListNode *a= new ListNode(1);
a->next= new ListNode(2);
a->next->next= new ListNode(1);
a->next->next->next= new ListNode(2);
a->next->next->next->next= new ListNode(1);
deleteDup(a);
while(a){
cout<<a->val<<endl;
a=a->next;
}
} | 15.586957 | 44 | 0.6053 | WIZARD-CXY |
22d70eeca2ffd57dcd8d43633cb8f6a6d6b810d7 | 1,604 | cpp | C++ | Applied/CCore/src/AbstFileToMem.cpp | SergeyStrukov/CCore-4-xx | 5faeadd50a24a7dbe18ffff8efe5f49212588637 | [
"BSL-1.0"
] | null | null | null | Applied/CCore/src/AbstFileToMem.cpp | SergeyStrukov/CCore-4-xx | 5faeadd50a24a7dbe18ffff8efe5f49212588637 | [
"BSL-1.0"
] | null | null | null | Applied/CCore/src/AbstFileToMem.cpp | SergeyStrukov/CCore-4-xx | 5faeadd50a24a7dbe18ffff8efe5f49212588637 | [
"BSL-1.0"
] | null | null | null | /* AbstFileToMem.cpp */
//----------------------------------------------------------------------------------------
//
// Project: CCore 4.01
//
// Tag: Applied
//
// License: Boost Software License - Version 1.0 - August 17th, 2003
//
// see http://www.boost.org/LICENSE_1_0.txt or the local copy
//
// Copyright (c) 2020 Sergey Strukov. All rights reserved.
//
//----------------------------------------------------------------------------------------
#include <CCore/inc/AbstFileToMem.h>
#include <CCore/inc/Exception.h>
namespace CCore {
/* class AbstFileToMem */
AbstFileToMem::AbstFileToMem(AbstFileToRead file,StrLen file_name,ulen max_len)
{
file->open(file_name);
ScopeGuard guard( [&] () { file->close(); } );
auto file_len=file->getLen();
if( file_len>max_len )
{
Printf(Exception,"CCore::AbstFileToMem::AbstFileToMem(...,#.q;,max_len=#;) : file is too long #;",file_name,max_len,file_len);
}
ulen len=(ulen)file_len;
file->read_all(0,alloc(len),len);
}
/* class PartAbstFileToMem */
PartAbstFileToMem::PartAbstFileToMem(AbstFileToRead file_,StrLen file_name,ulen buf_len)
: file(file_),
buf(buf_len),
off(0)
{
file->open(file_name);
file_len=file->getLen();
}
PartAbstFileToMem::~PartAbstFileToMem()
{
file->close();
}
PtrLen<const uint8> PartAbstFileToMem::pump()
{
uint8 *ptr=buf.getPtr();
ulen len=buf.getLen();
FilePosType delta=file_len-off;
if( !delta ) return Empty;
if( delta<len ) len=(ulen)delta;
file->read_all(off,ptr,len);
off+=len;
return Range(ptr,len);
}
} // namespace CCore
| 20.303797 | 131 | 0.591022 | SergeyStrukov |
22d9b729ef4dbfb5a190fb699a03d6e75c3bf331 | 131 | hxx | C++ | src/Providers/UNIXProviders/RangeOfIPAddresses/UNIX_RangeOfIPAddresses_STUB.hxx | brunolauze/openpegasus-providers-old | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | [
"MIT"
] | 1 | 2020-10-12T09:00:09.000Z | 2020-10-12T09:00:09.000Z | src/Providers/UNIXProviders/RangeOfIPAddresses/UNIX_RangeOfIPAddresses_STUB.hxx | brunolauze/openpegasus-providers-old | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | [
"MIT"
] | null | null | null | src/Providers/UNIXProviders/RangeOfIPAddresses/UNIX_RangeOfIPAddresses_STUB.hxx | brunolauze/openpegasus-providers-old | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | [
"MIT"
] | null | null | null | #ifdef PEGASUS_OS_STUB
#ifndef __UNIX_RANGEOFIPADDRESSES_PRIVATE_H
#define __UNIX_RANGEOFIPADDRESSES_PRIVATE_H
#endif
#endif
| 10.916667 | 43 | 0.854962 | brunolauze |
22dd38870431ad1cab052d3fa095b8f60f7aaf24 | 480 | cpp | C++ | URI/2143-the-return-of-radar.cpp | SusmoySenGupta/online-judge-solutions | 8735a1bc71a05dc46255664c3ec6f47f042bfa6c | [
"MIT"
] | null | null | null | URI/2143-the-return-of-radar.cpp | SusmoySenGupta/online-judge-solutions | 8735a1bc71a05dc46255664c3ec6f47f042bfa6c | [
"MIT"
] | null | null | null | URI/2143-the-return-of-radar.cpp | SusmoySenGupta/online-judge-solutions | 8735a1bc71a05dc46255664c3ec6f47f042bfa6c | [
"MIT"
] | null | null | null | /*
problem no: 2143
problem name: The Return of Radar
problem link: https://www.urionlinejudge.com.br/judge/en/problems/view/2143
author: Susmoy Sen Gupta
Status: __Solved__
Solved at: 6/24/21, 12:35:28 AM
*/
#include <iostream>
using namespace std;
int main()
{
int t, x;
while(1)
{
cin >> t;
if(t == 0) break;
while(t--)
{
cin >> x;
x % 2 == 0 ? cout << (x * 2) - 2 : cout << (x*2) - 1;
cout << endl;
}
}
return 0;
}
| 12.631579 | 76 | 0.547917 | SusmoySenGupta |
22e212002a88c7e751084384cc1acc28ec76208a | 315 | hpp | C++ | Main course/Homework3/Problem1/Header files/Counter.hpp | nia-flo/FMI-OOP | 9d6ab384b5b7a48e76965ca5bff1e6a995b1bcba | [
"MIT"
] | null | null | null | Main course/Homework3/Problem1/Header files/Counter.hpp | nia-flo/FMI-OOP | 9d6ab384b5b7a48e76965ca5bff1e6a995b1bcba | [
"MIT"
] | null | null | null | Main course/Homework3/Problem1/Header files/Counter.hpp | nia-flo/FMI-OOP | 9d6ab384b5b7a48e76965ca5bff1e6a995b1bcba | [
"MIT"
] | null | null | null | #pragma once
class Counter
{
public:
Counter();
Counter(int initial);
Counter(int initial, unsigned step);
virtual void increment();
virtual int getTotal() const;
virtual unsigned getStep() const;
protected:
const int DEFAULT_INITIAL_VALUE = 0;
const int DEFAULT_STEP = 1;
int value;
unsigned step;
}; | 15.75 | 37 | 0.733333 | nia-flo |
22e7f33c27d1943350d329689f94b85b9a189098 | 6,486 | hpp | C++ | src/core/lib/core_data_model/i_model_extension.hpp | wgsyd/wgtf | d8cacb43e2c5d40080d33c18a8c2f5bd27d21bed | [
"BSD-3-Clause"
] | 28 | 2016-06-03T05:28:25.000Z | 2019-02-14T12:04:31.000Z | src/core/lib/core_data_model/i_model_extension.hpp | karajensen/wgtf | 740397bcfdbc02bc574231579d57d7c9cd5cc26d | [
"BSD-3-Clause"
] | null | null | null | src/core/lib/core_data_model/i_model_extension.hpp | karajensen/wgtf | 740397bcfdbc02bc574231579d57d7c9cd5cc26d | [
"BSD-3-Clause"
] | 14 | 2016-06-03T05:52:27.000Z | 2019-03-21T09:56:03.000Z | #ifndef I_MODEL_EXTENSION_HPP
#define I_MODEL_EXTENSION_HPP
#include "core_variant/variant.hpp"
#include "core_data_model/i_item_role.hpp"
#include "core_data_model/abstract_item_model.hpp"
#include "core_common/signal.hpp"
#include <cassert>
#include <vector>
#include <string>
#include <functional>
namespace wgt
{
/** A user extension to a view.
An extension provides additional functionality to a model, by adding additional roles.
Any roles defined in this extension are exposed as additional properties in QML.*/
class IModelExtension
{
public:
enum class Orientation
{
HORIZONTAL,
VERTICAL
};
enum class LayoutHint
{
NO_SORT,
VERTICAL_SORT,
HORIZONTAL_SORT
};
struct IModelIndexData
{
virtual int row() const = 0;
virtual int column() const = 0;
virtual void* pointer() const = 0;
virtual const void* model() const = 0;
};
struct ModelIndex
{
ModelIndex(const std::shared_ptr<IModelIndexData>& data = nullptr)
{
data_ = data;
}
bool isValid() const
{
return row() >= 0 && column() >= 0 && model() != nullptr;
}
bool operator==(const ModelIndex& other) const
{
return (!isValid() && !other.isValid()) || (row() == other.row() && column() == other.column() &&
pointer() == other.pointer() && model() == other.model());
}
bool operator!=(const ModelIndex& other) const
{
return !this->operator==(other);
}
int row() const
{
if (!data_)
{
return -1;
}
return data_->row();
}
int column() const
{
if (!data_)
{
return -1;
}
return data_->column();
}
void* pointer() const
{
if (!data_)
{
return nullptr;
}
return data_->pointer();
}
const void* model() const
{
if (!data_)
{
return nullptr;
}
return data_->model();
}
std::shared_ptr<IModelIndexData> data() const
{
return data_;
}
protected:
std::shared_ptr<IModelIndexData> data_;
};
struct IExtensionData
{
virtual Variant data(const ModelIndex& index, ItemRole::Id roleId) const = 0;
virtual bool setData(const ModelIndex& index, const Variant& value, ItemRole::Id roleId) = 0;
virtual void dataChanged(const ModelIndex& from, const ModelIndex& to,
std::vector<ItemRole::Id> roleIds) const = 0;
virtual Variant headerData(int section, Orientation orientation, ItemRole::Id roleId) const = 0;
virtual bool setHeaderData(int section, Orientation orientation, const Variant& value, ItemRole::Id roleId) = 0;
virtual void headerDataChanged(Orientation orientation, int from, int to) const = 0;
};
IModelExtension();
virtual ~IModelExtension();
void setExtensionData(IExtensionData* extensionData);
/** Returns all roles used by the extension.
@return A vector of role names.*/
const std::vector<std::string>& roles() const;
/** Get role data at an index position.
@param index The position the data applies to.
@param role The decoded role identifier.
@return The role data.*/
virtual Variant data(const ModelIndex& index, ItemRole::Id roleId) const;
/** Set role data at an index position.
@param index The position the data applies to.
@param value The role data.
@param role The decoded role identifier.
@return True if successful.*/
virtual bool setData(const ModelIndex& index, const Variant& value, ItemRole::Id roleId);
/** Get role data for a header row or column.
@param section The row or column number.
@param orientation Specifies whether section refers to a row or column.
@param role The decoded role identifier.
@return The role data.*/
virtual Variant headerData(int section, Orientation orientation, ItemRole::Id roleId) const;
/** Set role data for a header row or column.
@param section The row or column number.
@param orientation Specifies whether section refers to a row or column.
@param value The role data.
@param role The decoded role identifier.
@return True if successful.*/
virtual bool setHeaderData(int section, Orientation orientation, const Variant& value, ItemRole::Id roleId);
virtual void onDataChanged(const ModelIndex& topLeft, const ModelIndex& bottomRight,
const std::vector<ItemRole::Id>& roles);
virtual void onHeaderDataChanged(Orientation orientation, int first, int last);
virtual void onLayoutAboutToBeChanged(const std::vector<ModelIndex>& parents, LayoutHint hint);
virtual void onLayoutChanged(const std::vector<ModelIndex>& parents, LayoutHint hint);
virtual void onRowsAboutToBeInserted(const ModelIndex& parent, int first, int last);
virtual void onRowsInserted(const ModelIndex& parent, int first, int last);
virtual void onRowsAboutToBeRemoved(const ModelIndex& parent, int first, int last);
virtual void onRowsRemoved(const ModelIndex& parent, int first, int last);
virtual void onRowsAboutToBeMoved(const ModelIndex& sourceParent, int sourceFirst, int sourceLast,
const ModelIndex& destinationParent, int destinationRow);
virtual void onRowsMoved(const ModelIndex& sourceParent, int sourceFirst, int sourceLast,
const ModelIndex& destinationParent, int destinationRow);
virtual void onColumnsAboutToBeInserted(const ModelIndex& parent, int first, int last);
virtual void onColumnsInserted(const ModelIndex& parent, int first, int last);
virtual void onColumnsAboutToBeRemoved(const ModelIndex& parent, int first, int last);
virtual void onColumnsRemoved(const ModelIndex& parent, int first, int last);
virtual void onColumnsAboutToBeMoved(const ModelIndex& sourceParent, int sourceFirst, int sourceLast,
const ModelIndex& destinationParent, int destinationRow);
virtual void onColumnsMoved(const ModelIndex& sourceParent, int sourceFirst, int sourceLast,
const ModelIndex& destinationParent, int destinationColumn);
protected:
std::vector<std::string> roles_;
IExtensionData* extensionData_;
};
} // end namespace wgt
namespace std
{
template <>
struct hash<wgt::IModelExtension::ModelIndex>
{
typedef wgt::IModelExtension::ModelIndex argument_type;
typedef size_t result_type;
result_type operator()(argument_type const& i) const
{
result_type temp =
result_type(i.model()) + result_type(i.pointer()) + result_type(i.row()) + result_type(i.column());
return static_cast<size_t>(wgt::HashUtilities::compute(static_cast<uint64_t>(temp)));
}
};
}
#endif // I_MODEL_EXTENSION_HPP
| 31.182692 | 114 | 0.71292 | wgsyd |
22f11ea3e8f409014978db4f07563439b38c7790 | 418 | cpp | C++ | code/client/src/core/hooks/application.cpp | mufty/MafiaMP | 2dc0e3362c505079e26e598bd4a7f4b5de7400bc | [
"OpenSSL"
] | 16 | 2021-10-08T17:47:04.000Z | 2022-03-28T13:26:37.000Z | code/client/src/core/hooks/application.cpp | mufty/MafiaMP | 2dc0e3362c505079e26e598bd4a7f4b5de7400bc | [
"OpenSSL"
] | 4 | 2022-01-19T08:11:57.000Z | 2022-01-29T19:02:24.000Z | code/client/src/core/hooks/application.cpp | mufty/MafiaMP | 2dc0e3362c505079e26e598bd4a7f4b5de7400bc | [
"OpenSSL"
] | 4 | 2021-10-09T11:15:08.000Z | 2022-01-27T22:42:26.000Z | #include <MinHook.h>
#include <utils/hooking/hook_function.h>
#include <utils/hooking/hooking.h>
#include "../../sdk/patterns.h"
bool __fastcall C_GameFramework__IsSuspended(void *_this) {
return false;
}
static InitFunction init([]() {
// Don't pause the game when out of window
MH_CreateHook((LPVOID)SDK::gPatterns.C_GameFramework__IsSuspendedAddr, (PBYTE)&C_GameFramework__IsSuspended, nullptr);
});
| 27.866667 | 122 | 0.746411 | mufty |
22fb5c516feb119498f1af063d0adf8783349e05 | 1,542 | cpp | C++ | src/problem_14.cpp | MihailsKuzmins/daily-coding-problem | ca8b7589b6ce2eb6dec846829c82a12c1272a5ec | [
"Apache-2.0"
] | null | null | null | src/problem_14.cpp | MihailsKuzmins/daily-coding-problem | ca8b7589b6ce2eb6dec846829c82a12c1272a5ec | [
"Apache-2.0"
] | null | null | null | src/problem_14.cpp | MihailsKuzmins/daily-coding-problem | ca8b7589b6ce2eb6dec846829c82a12c1272a5ec | [
"Apache-2.0"
] | null | null | null | // The area of a circle is defined as πr^2. Estimate π to 3 decimal places using a Monte Carlo method.
// Hint: The basic equation of a circle is x^2 + y^2 = r^2.
// Example:
// auto result = problem_fourteen(1'000'000);
#include <random>
#include <math.h>
using namespace std;
double problem_fourteen(const unsigned int n) noexcept
{
const double radius_square = 0.25; // r = 0.5, a and b = 1
double pi_estimated = 0;
int circle_count = 0;
const uniform_real_distribution<double> distr(-0.5, 0.5);
default_random_engine random_enginde;
for (unsigned int i = 0; i < n; i++)
{
const auto x = distr(random_enginde);
const auto y = distr(random_enginde);
if (x * x + y * y <= radius_square)
circle_count++;
}
// see below for explanation
const auto pi = 4 * static_cast<double>(circle_count) / n;
return round(pi * 1000) / 1000;
}
// Explanation:
// Area (circle) / Area (square) = Points (circle) / Points (square)
// We imagined a square with a length of 1, i.e. d = 1, and r = 0.5 (1 / 2)
// Area (circle) = PI * r^2; Area (square) = l^2, therefore, the left-hand side is as follows:
// (PI * (0.5)^2) / 1^2 => PI * 0.25 / 1 => PI / 4
// Now let us express PI:
// PI = 4 * Points (circe) / Points (square)
// Implementation
// All random numbers we generate are within [-0.5; 0.5], which guarantees that 100% of (x;y) Points
// will be withing the quare. So we need to get a probaility that a Point is within the circle
// Points (circle) / Points (square).
// This probability is compared to the area equations.
| 32.808511 | 102 | 0.667315 | MihailsKuzmins |
22fbc3f626eadc7344182e303f29a4c011894e5e | 74,086 | cpp | C++ | waspmoteapi-master/waspmote-api/WaspSD.cpp | MahendraSondagar/Libelium-Waspmote | ba14e04ca10e6d147d73da447a5aa9c5f5325a99 | [
"MIT"
] | null | null | null | waspmoteapi-master/waspmote-api/WaspSD.cpp | MahendraSondagar/Libelium-Waspmote | ba14e04ca10e6d147d73da447a5aa9c5f5325a99 | [
"MIT"
] | null | null | null | waspmoteapi-master/waspmote-api/WaspSD.cpp | MahendraSondagar/Libelium-Waspmote | ba14e04ca10e6d147d73da447a5aa9c5f5325a99 | [
"MIT"
] | null | null | null | /*
* Copyright (C) 2018 Libelium Comunicaciones Distribuidas S.L.
* http://www.libelium.com
*
* 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, see <http://www.gnu.org/licenses/>.
*
* Version: 3.2
* Design: David Gascón
* Implementation: David Cuartielles, Alberto Bielsa, Yuri Carmona
*/
#ifndef __WPROGRAM_H__
#include "WaspClasses.h"
#endif
/// table_SD ///////////////////////////////////////////////////////////////////
const char sd_string_00[] PROGMEM = "\nmanuf: 0x%x\noem: %c%c\nprod: %x\nrev: %x.%x\nserial: 0x%lx\ndate: %u/%u\n";
const char sd_string_01[] PROGMEM = "no SD";
const char* const table_SD[] PROGMEM =
{
sd_string_00, // 0
sd_string_01, // 1
};
/*******************************************************************************
* Functions
*******************************************************************************/
/*
* User provided date time callback function.
* See SdFile::dateTimeCallback() for usage.
*/
void dateTime(uint16_t* date, uint16_t* time)
{
// User gets date and time from GPS or real-time
// clock in real callback function
// return date using FAT_DATE macro to format fields
*date = FAT_DATE(RTC.year+2000, RTC.month, RTC.date);
// return time using FAT_TIME macro to format fields
*time = FAT_TIME(RTC.hour, RTC.minute, RTC.second);
}
/* getNextPathComponent ( path, *p_offset, *buffer) - Parse individual
* path components from a path.
*
* e.g. after repeated calls '/foo/bar/baz' will be split
* into 'foo', 'bar', 'baz'.
* This is similar to `strtok()` but copies the component into the
* supplied buffer rather than modifying the original string.
*
*
* `buffer` needs to be PATH_COMPONENT_BUFFER_LEN in size.
*
* `p_offset` needs to point to an integer of the offset at
* which the previous path component finished.
*
* Returns `true` if more components remain.
*
* Returns `false` if this is the last component.
* (This means path ended with 'foo' or 'foo/'.)
*/
bool getNextPathComponent( char *path,
unsigned int *p_offset,
char *buffer)
{
// TODO: Have buffer local to this function, so we know it's the
// correct length?
int bufferOffset = 0;
int offset = *p_offset;
// Skip root or other separator
if (path[offset] == '/') {
offset++;
}
// Copy the next next path segment
while (bufferOffset < MAX_COMPONENT_LEN
&& (path[offset] != '/')
&& (path[offset] != '\0')) {
buffer[bufferOffset++] = path[offset++];
}
buffer[bufferOffset] = '\0';
// Skip trailing separator so we can determine if this
// is the last component in the path or not.
if (path[offset] == '/') {
offset++;
}
*p_offset = offset;
return (path[offset] != '\0');
}
/*
* When given a file path (and parent directory--normally root),
* this function traverses the directories in the path and at each
* level calls the supplied callback function while also providing
* the supplied object for context if required.
*
* e.g. given the path '/foo/bar/baz'
* the callback would be called at the equivalent of
* '/foo', '/foo/bar' and '/foo/bar/baz'.
*
* The implementation swaps between two different directory/file
* handles as it traverses the directories and does not use recursion
* in an attempt to use memory efficiently.
*
* If a callback wishes to stop the directory traversal it should
* return false--in this case the function will stop the traversal,
* tidy up and return false.
*
* If a directory path doesn't exist at some point this function will
* also return false and not subsequently call the callback.
* If a directory path specified is complete, valid and the callback
* did not indicate the traversal should be interrupted then this
* function will return true.
*/
boolean walkPath( char *filepath,
SdFile& parentDir,
boolean (*callback)( SdFile& parentDir,
char *filePathComponent,
boolean isLastComponent,
void *object),
void *object=NULL)
{
SdFile subfile1;
SdFile subfile2;
char buffer[PATH_COMPONENT_BUFFER_LEN];
unsigned int offset = 0;
SdFile *p_parent;
SdFile *p_child;
SdFile *p_tmp_sdfile;
p_child = &subfile1;
p_parent = &parentDir;
while (true)
{
boolean moreComponents = getNextPathComponent(filepath, &offset, buffer);
boolean shouldContinue = callback((*p_parent), buffer, !moreComponents, object);
if (!shouldContinue)
{
// TODO: Don't repeat this code?
// If it's one we've created then we
// don't need the parent handle anymore.
if (p_parent != &parentDir)
{
(*p_parent).close();
}
return false;
}
if (!moreComponents)
{
break;
}
boolean exists = (*p_child).open(p_parent, buffer, O_RDONLY);
// If it's one we've created then we
// don't need the parent handle anymore.
if (p_parent != &parentDir)
{
(*p_parent).close();
}
// Handle case when it doesn't exist and we can't continue...
if (exists)
{
// We alternate between two file handles as we go down
// the path.
if (p_parent == &parentDir)
{
p_parent = &subfile2;
}
p_tmp_sdfile = p_parent;
p_parent = p_child;
p_child = p_tmp_sdfile;
}
else
{
return false;
}
}
if (p_parent != &parentDir)
{
(*p_parent).close(); // TODO: Return/ handle different?
}
return true;
}
/*******************************************************************************
The callbacks used to implement various functionality follow.
Each callback is supplied with a parent directory handle,
character string with the name of the current file path component,
a flag indicating if this component is the last in the path and
a pointer to an arbitrary object used for context.
*******************************************************************************/
/*
* Callback used to determine if a file/directory exists in parent
* directory.
*
* Returns true if file path exists
*/
boolean callback_pathExists( SdFile& parentDir,
char *filePathComponent,
boolean isLastComponent,
void *object)
{
SdFile child;
boolean exists = child.open(&parentDir, filePathComponent, O_RDONLY);
if (exists) {
child.close();
}
return exists;
}
/*
* Callback used to create a directory in the parent directory if
* it does not already exist.
*
* Returns true if a directory was created or it already existed.
*/
boolean callback_makeDirPath( SdFile& parentDir,
char *filePathComponent,
boolean isLastComponent,
void *object)
{
boolean result = false;
SdFile child;
result = callback_pathExists(parentDir, filePathComponent, isLastComponent, object);
if (!result) {
result = child.makeDir(&parentDir, filePathComponent);
}
return result;
}
/*
* Callback used to delete a file specified by a path that may
* specify one or more directories above it.
*/
boolean callback_remove( SdFile& parentDir,
char *filePathComponent,
boolean isLastComponent,
void *object)
{
if (isLastComponent) {
return SdFile::remove(&parentDir, filePathComponent);
}
return true;
}
/*
* Callback used to delete a directory specified by a path that may
* specify one or more directories above it.
*/
boolean callback_rmdir( SdFile& parentDir,
char *filePathComponent,
boolean isLastComponent,
void *object)
{
if (isLastComponent) {
SdFile f;
if (!f.open(&parentDir, filePathComponent, O_READ)) return false;
return f.rmDir();
}
return true;
}
/*
* Callback used to delete a directory specified by a path and all
* contained files.
*/
boolean callback_rmRfdir( SdFile& parentDir,
char *filePathComponent,
boolean isLastComponent,
void *object)
{
if (isLastComponent)
{
SdFile f;
if (!f.open(&parentDir, filePathComponent, O_READ))
{
// delete possible "damaged" file
SdFile::remove(&parentDir, filePathComponent);
return false;
}
// remove all contents and directory
if(!f.rmRfStar())
{
// in the case it fails
// delete possible "damaged" file
if(!f.remove())
{
return false;
}
}
}
return true;
}
/*******************************************************************************
* Class methods
*******************************************************************************/
/// Constructors ///////////////////////////////////////////////////////
WaspSD::WaspSD()
{
// init SD flag
flag = 0;
}
/// Public Methods /////////////////////////////////////////////////////
/*
* ON (void) - It powers the SD card, initialize it and prepare it to
* work with
*
* It powers the SD card, initialize it and prepare it to work with
*/
uint8_t WaspSD::ON(void)
{
// enable Chip select
pinMode(SD_SS, OUTPUT);
digitalWrite(SD_SS, LOW);
// update Waspmote Control Register
WaspRegister |= REG_SD;
// mandatory delay
delay(100);
// configure pins as input/output
pinMode(MEM_PW, OUTPUT);
pinMode(SD_PRESENT, INPUT);
// enable SD SPI flag
SPI.isSD = true;
// set power supply to the SD card
setMode(SD_ON);
// initialize FAT volume
return init();
}
/*
* OFF (void) - It powers off the SD card and closes the pointers
*
* It powers off the SD card and closes the pointers
*/
void WaspSD::OFF(void)
{
// delay for waiting pending operations
delay(100);
// disable SD SPI flag
SPI.isSD = false;
// close current working directory if it is not the root directory
if(!currentDir.isRoot())
{
currentDir.close();
}
// close root directory
root.close();
// SD_SS (SD chip select) is disabled
pinMode(SD_SS, OUTPUT);
digitalWrite(SD_SS, HIGH);
// close SPI bus if it is posible
SPI.close();
// switch SD off
setMode(SD_OFF);
delay(100);
// update Waspmote Control Register
WaspRegister &= ~(REG_SD);
}
/* setMode() - sets energy mode
*
* It sets SD ON/OFF, switching On or Off the corresponding pin
* 'mode': Selects between SD_ON/SD_OFF
*/
void WaspSD::setMode(uint8_t mode)
{
switch(mode)
{
case SD_ON: digitalWrite(MEM_PW, HIGH);
delay(10);
break;
case SD_OFF:digitalWrite(MEM_PW,LOW);
break;
}
}
/* init ( void ) - initializes the use of SD cards, looks into the
* root partition, opens the file system and initializes the
* public pointer that can be used to access the filesystem
*
* Returns 1 when ok;
* Returns 0 when error.
* Also, there is a flag with the corresponding value of error:
*
* - NOTHING_FAILED = 0
* - CARD_NOT_PRESENT = 1
* - INIT_FAILED = 2
* - VOLUME_FAILED = 3
* - ROOT_FAILED = 4
*
*/
uint8_t WaspSD::init()
{
// check if the card is there or not
if (!isSD())
{
flag = CARD_NOT_PRESENT;
return 0;
}
// init SPI bus
if(!card.init(SPI_FULL_SPEED))
{
flag = INIT_FAILED;
return 0;
}
// initialize a FAT volume
if(!volume.init(&card))
{
flag = INIT_FAILED;
return 0;
}
// open the root directory
if(!root.openRoot(&volume))
{
flag = ROOT_FAILED;
return 0;
}
// Update current working directory to 'root' directory
memcpy(¤tDir, &root, sizeof(SdFile));
// update flag with no error
flag = NOTHING_FAILED;
return 1;
}
/*
* isSD (void) - Is the SD inside the slot?
*
* This function checks if there is a SD card in the slot
*
* Here we make a call to close(), to avoid errors if users
* tried to call any functions making use of the card
*
* Returns 1 if SD card is present, 0 otherwise
*/
uint8_t WaspSD::isSD()
{
if(digitalRead(SD_PRESENT)) return 1;
return 0;
}
/*
* getDiskSize (void) - disk total size
*
* Returns the total size for the disk, but also updates the
* SD.diskSize variable.
* Returns 0 when error
*/
uint32_t WaspSD::getDiskSize()
{
// check if the card is there or not
if (!isSD())
{
flag = CARD_NOT_PRESENT;
return 0;
}
// update the attribute 'diskSize' in bytes
diskSize = 512*card.cardSize();
return diskSize;
}
/*
* print_disk_info (void) - disk information
*
* packs all the data about the disk into the buffer and returns it back.
* The SD.buffer will then be available and offer the data to the
* developers as a human-readable encoded string.
*
* An example of the output by this system would be:
*
* manuf: 0x2
* oem: TM
* prod: SD01G
* rev: 32
* serial: 0x9f70db88
* date: 2/8
*
* Not all the information is relevant for further use. It is possible
* to access different parts via the fat-implemented variables as you
* will see in this function
*
*/
char* WaspSD::print_disk_info()
{
char aux[100];
// Local variable
cid_t cid;
// check if the card is there or not
if (!isSD())
{
flag = CARD_NOT_PRESENT;
// aux <-- "no SD"
strcpy_P(aux, (char*)pgm_read_word(&(table_SD[1])));
sprintf(buffer, aux);
return buffer;
}
// Read CID register
card.readCID(&cid);
// aux <--
strcpy_P(aux, (char*)pgm_read_word(&(table_SD[0])));
//Compose buffer to return
snprintf(buffer
, sizeof(buffer)
, aux
, cid.mid
, cid.oid[0]
, cid.oid[1]
, cid.pnm
, cid.prv_n
, cid.prv_m
, cid.psn
, (int)cid.mdt_month
, (int)cid.mdt_year_low);
USB.println(buffer);
return buffer;
}
/*
* mkdir ( filepath ) - create directory/ies indicated by filepath
*
* Returns 1 on directory creation, 0 if error, will mark the flag with
* DIR_CREATION_ERROR
*
* Be careful when calling this function to create a directory for the
* first time. If it is interrupted, the directory results damaged and
* it is necessary to delete it as a regular file using SD.del
*
* Remarks only short 8.3 names are valid!
*/
boolean WaspSD::mkdir(char *filepath)
{
// set date for directory creation
setFileDate();
// check if the card is there or not
if (!isSD())
{
flag = CARD_NOT_PRESENT;
flag |= DIR_CREATION_ERROR;
snprintf(buffer, sizeof(buffer), "%s", CARD_NOT_PRESENT_em);
return false;
}
// check if directory already exists
if(walkPath(filepath, currentDir, callback_pathExists, NULL))
{
flag |= DIR_CREATION_ERROR;
return false;
}
// Makes a single directory or a hierarchy of directories.
// A rough equivalent to `mkdir -p`. */
return walkPath(filepath, currentDir, callback_makeDirPath, NULL);
}
/*
* ls ( void ) - directory listing
*
* Lists the directory contents
*
* The information is printed through the serial port (UART0). This way,
* the info can be seen in Waspmote IDE's serial port.
* A possible example is:
*
* empty.txt 2945
* secret/
* hello.txt 1149
*
* Files are shown with their extention. The file size is shown in bytes.
* Folders have a slash as the last character.
*
*/
void WaspSD::ls(void)
{
return currentDir.ls(LS_SIZE, 0);
}
/*
* ls (flags) - directory listing
*
* Lists the directory contents
*
* The information is printed through the serial port (UART0). This way,
* the info can be seen in Waspmote IDE's serial port.
* A possible example is:
*
* FILE8 1980-01-01 00:00:00 204
* FILE2 1980-01-01 00:00:00 2754
* FOLDER/ 2000-01-01 01:00:00
* SUBFOLD/ 2000-01-01 01:00:00
* FILE.TXT 2012-06-11 11:58:10 811
*
* parameter 'flags' is the inclusive OR of
*
* LS_DATE - Print file modification date
* LS_SIZE - Print file size.
* LS_R - Recursive list of subdirectories.
*
* Files are shown with their extention. The file size is shown in bytes.
* Folders have a slash as the last character.
*
*/
void WaspSD::ls(uint8_t flags)
{
return currentDir.ls(flags, 0);
}
/*
* find_file_in_dir (filepath) - tests existence of a specific
* file in the current working directory
*
* Returns If the file is available in the folder, it will answer 1
* (TRUE), if not available it will answer 0 (FALSE)
*
*/
uint8_t WaspSD::find_file_in_dir(const char* filepath)
{
// Check if path exists
if(walkPath((char*)filepath, currentDir, callback_pathExists, NULL)) return 1;
else return 0;
}
/*
* isFile (filepath) - checks if 'filepath' is a file or not
*
* Answers whether the file "filepath" is available in the current
* working directory or not.
*
* If the file is available in the folder, it will answer 1 (TRUE),
* if it is not a file it will answer 0 (FALSE), and if it is not
* available it will answer -1 (ERROR)
*
*/
int8_t WaspSD::isFile(const char* filepath)
{
// Local variable
SdFile file;
// try to open the file
if(!openFile( (char*)filepath, &file, O_RDONLY)) return -1;
else
{
// File opened. Check if it is a valid file
if (!file.isFile())
{
file.close();
return 0;
}
else file.close();
}
return 1;
}
/*
* getParentDir(filepath, index) - gets parent directory of a filepath
*
* This function is a little helper used to traverse paths.
* Answers the object SdFile which is related to the parent directory
* of a path specified in 'filepath'
*
* If the file is available in the folder, it will answer 1 (TRUE),
* if it is not a file it will answer 0 (FALSE), and if it is not
* available it will answer -1 (ERROR)
*
*/
SdFile WaspSD::getParentDir(const char *filepath, int *index)
{
// get parent directory
SdFile d1 = currentDir; // start with the current working directory
SdFile d2;
// we'll use the pointers to swap between the two objects
SdFile *parent = &d1;
SdFile *subdir = &d2;
// copy original path
const char *origpath = filepath;
// loop while we find character: '/'
while (strchr(filepath, '/'))
{
// get rid of leading /'s
if (filepath[0] == '/')
{
filepath++;
continue;
}
if (! strchr(filepath, '/'))
{
// it was in the root directory, so leave now
break;
}
// extract just the name of the next subdirectory
uint8_t idx = strchr(filepath, '/') - filepath;
if (idx > 12)
{
// dont let them specify long names
idx = 12;
}
char subdirname[13];
strncpy(subdirname, filepath, idx);
subdirname[idx] = 0;
// close the subdir (we reuse them) if open
subdir->close();
if (! subdir->open(parent, subdirname, O_READ))
{
// failed to open one of the subdirectories
return SdFile();
}
// move forward to the next subdirectory
filepath += idx;
// we reuse the objects, close it.
parent->close();
// swap the pointers
SdFile *t = parent;
parent = subdir;
subdir = t;
}
// set index from the beginning of the path to the parent directory
*index = (int)(filepath - origpath);
// parent is now the parent diretory of the file!
return *parent;
}
/*
* getDir(filepath, index) - gets directory of a filepath
*
* This function is a little helper used to traverse paths.
* Answers the object SdFile which is related to the directory
* of a path specified in 'filepath'
*
* If the directory is available in the parent folder, it will answer 1
* (TRUE), if it is not a directory it will answer 0 (FALSE), and if it
* is not available it will answer -1 (ERROR)
*
*/
SdFile WaspSD::getDir(const char *filepath, int *index)
{
// get parent directory
SdFile d1 = currentDir; // start with the current working directory
SdFile d2;
// we'll use the pointers to swap between the two objects
SdFile *parent = &d1;
SdFile *subdir = &d2;
// copy original path
const char *origpath = filepath;
// loop while we find character: '/'
while (strchr(filepath, '/'))
{
// get rid of leading /'s
if (filepath[0] == '/')
{
filepath++;
continue;
}
if (! strchr(filepath, '/'))
{
// it was in the root directory, so leave now
break;
}
// extract just the name of the next subdirectory
uint8_t idx = strchr(filepath, '/') - filepath;
if (idx > 12)
{
// dont let them specify long names
idx = 12;
}
char subdirname[13];
strncpy(subdirname, filepath, idx);
subdirname[idx] = 0;
// close the subdir (we reuse them) if open
subdir->close();
if (! subdir->open(parent, subdirname, O_READ))
{
// failed to open one of the subdirectories
return SdFile();
}
// move forward to the next subdirectory
filepath += idx;
// we reuse the objects, close it.
parent->close();
// swap the pointers
SdFile *t = parent;
parent = subdir;
subdir = t;
}
// there isn't any '/' character left
// copy directory name in order to open it
char * pch;
char str[strlen(filepath)+1];
strncpy(str,filepath, strlen(filepath));
str[strlen(filepath)]='\0';
pch = strtok (str,"/");
if( pch == NULL )
{
// Any name found
return SdFile();
}
// close the subdir (we reuse them) if open
subdir->close();
if (! subdir->open(parent, pch, O_READ))
{
// failed to open one of the subdirectories
return SdFile();
}
// check if it is the root directory
if( subdir->firstCluster() == 0 )
{
// Update current working directory to 'root' directory
subdir=(SdFile*)&root;
}
// close parent
parent->close();
// swap the pointers
parent = subdir;
*index = (int)(filepath - origpath);
// parent is now the parent directory of the file!
return *parent;
}
/*
* openFile (filepath, file, mode) - opens a file
*
* opens the file "filepath" if available.
* 'filepath' is the string with the file name
* 'file' is the return pointer to a opened SdFile object
* 'mode' selects the mode. This flag is constructed by a
* bitwise-inclusive OR of flags from the following list:
*
* O_READ - Open for reading.
*
* O_RDONLY - Same as O_READ.
*
* O_WRITE - Open for writing.
*
* O_WRONLY - Same as O_WRITE.
*
* O_RDWR - Open for reading and writing.
*
* O_APPEND - If set, the file offset shall be set to the end of the
* file prior to each write.
*
* O_CREAT - If the file exists, this flag has no effect except as
* noted under O_EXCL below. Otherwise, the file shall be created
*
* O_EXCL - If O_CREAT and O_EXCL are set, open() shall fail if the
* file exists.
*
* O_SYNC - Call sync() after each write. This flag should not be
* used with write(uint8_t), write_P(PGM_P), writeln_P(PGM_P), or the
* Arduino Print class. These functions do character at a time writes
* so sync() will be called after each byte.
*
* O_TRUNC - If the file exists and is a regular file, and the file is
* successfully opened and is not read only, its length shall be
* truncated to 0.
*
* Returns '1' on success, '0' otherwise
*
*/
uint8_t WaspSD::openFile(const char* filepath, SdFile* file, uint8_t mode)
{
// path index: number of characters to reach
// the parent directory within filepath
int pathidx;
// do the iterative search to look for the file's parent directory
SdFile parentdir = getParentDir(filepath, &pathidx);
filepath += pathidx;
if (! filepath[0])
{
// it was the directory itself!
return 0;
}
// failed to open a subdir!
if (!parentdir.isOpen())
{
return 0;
}
// there is a special case for the Root directory since its a static dir
if (parentdir.isRoot())
{
if ( ! file->open(&root, filepath, mode))
{
// failed to open the file
return 0;
}
// dont close the root!
}
else
{
if ( ! file->open(&parentdir, filepath, mode))
{
return 0;
}
// close the parent
parentdir.close();
}
// Set file pointer to the end of the file
//~ if (mode & (O_APPEND | O_WRITE))
//~ {
//~ file->seekSet(file->fileSize())
//~ }
return 1;
}
/*
* closeFile (file) - closes a file
*
* closes the pointer 'file' which was pointing to a file
* Returns '1' on success, '0' otherwise
*
*/
uint8_t WaspSD::closeFile(SdFile* file)
{
// Close the file
if(!file->close()) return 0;
else return 1;
}
/*
* getFileSize (filepath) - answers the file size for filepath in current folder
*
* answers a longint with the file "filepath" size in the current folder
*
* If the file is not available in the folder, it will answer -1, it will also
* update the DOS.flag to FILE_OPEN_ERROR
*/
int32_t WaspSD::getFileSize(const char* filepath)
{
// Local variable
SdFile file;
uint32_t size;
// Open file
if(!openFile( (char*)filepath, &file, O_RDONLY)) return -1;
// Get file size
size=file.fileSize();
// Close file
file.close();
return size;
}
/*
* cat (filepath, offset, scope)
*
* dumps into the SD.buffer the amount of bytes in 'scope' after 'offset'
* coming from filepath, it will also return it as a string
*
* There is a limitation in size, due to DOS_BUFFER_SIZE. If the data
* read was bigger than that, the function will include the characters
* ">>" at the end and activate the TRUNCATED_DATA value in the SD.flag.
* It is recommened to check this value to assure data integrity.
*
* If there was an error opening the file, the returned string will say
* so and the DOS.flag will show the FILE_OPEN_ERROR bit active
*
* An example of calls to cat(filepath, offset, scope) is:
*
* - SD.cat("hola.txt", 3, 17): will show the 17 characters after
* jumping over 3 in the file "hola.txt"
*
* The information is sent back as a string where each one of the
* characters are printed one after the next, EOL ('\n') will be encoded
* as EOL, and will be accounted as one byte, an example of this would be:
*
* un lugar
* de la man
*
*/
char* WaspSD::cat(const char* filepath, int32_t offset, uint16_t scope)
{
// Local variable
SdFile file;
// check if the card is there or not
if (!isSD())
{
flag = CARD_NOT_PRESENT;
flag |= FILE_OPEN_ERROR;
snprintf(buffer, sizeof(buffer),"%s", CARD_NOT_PRESENT_em);
return buffer;
}
// if scope is zero, then we should make it
// ridiculously big, so that it goes on reading forever
if (scope <= 0) scope = DOS_BUFFER_SIZE;
if (scope > DOS_BUFFER_SIZE) scope = DOS_BUFFER_SIZE;
flag &= ~(TRUNCATED_DATA | FILE_OPEN_ERROR | FILE_SEEKING_ERROR);
// search file in current working directory and open it
// exit if error and modify the general flag with FILE_OPEN_ERROR
if(!openFile((char*)filepath, &file, O_RDONLY))
{
snprintf(buffer, sizeof(buffer), "error opening %s", filepath);
flag |= FILE_OPEN_ERROR;
return buffer;
}
// iterate through the file
// size of the buffer to use when reading
byte maxBuffer = 10;
// buffer so as to store data
uint8_t bufferSD[maxBuffer];
// counter so as not to exceed buffer size
uint32_t cont = 0;
// first jump over the offset
if(!file.seekSet(offset))
{
snprintf(buffer, sizeof(buffer), "error seeking on: %s\n", filepath);
flag |= FILE_SEEKING_ERROR;
file.close();
return buffer;
}
// Read first time from file, 'maxBuffer' bytes
uint8_t readRet = file.read(bufferSD, sizeof(bufferSD));
// second, read the data and store it in the buffer
// Breaks in the case it exceeds its size.
while(readRet > 0 && scope > 0 && cont < DOS_BUFFER_SIZE)
{
// Store data in buffer until scope ends, or
// buffer size limit is exceeded
for(uint8_t i = 0; i < readRet; ++i)
{
buffer[cont++] = bufferSD[i];
scope--;
if( scope <=0 ) break;
if( cont>=DOS_BUFFER_SIZE ) break;
}
// Break in the case the file ends
if( readRet<maxBuffer ) break;
// Read other block of data from SD file
readRet = file.read(bufferSD, sizeof(bufferSD));
}
// In the case the buffer is NOT exceeded, set end of string
if (cont < DOS_BUFFER_SIZE - 1)
{
buffer[cont++] = '\0';
}
else
{
// in case we filled up the whole buffer, we add a
// visual end of buffer indicator and leave the loop
buffer[DOS_BUFFER_SIZE - 4] = '>';
buffer[DOS_BUFFER_SIZE - 3] = '>';
buffer[DOS_BUFFER_SIZE - 2] = '\n';
buffer[DOS_BUFFER_SIZE - 1] = '\0';
flag |= TRUNCATED_DATA;
}
// Close file
file.close();
return buffer;
}
/*
* catBin(filepath, offset, scope)
*
* dumps into the SD.bufferBin the amount of bytes in 'scope' after
* 'offset' coming from filepath, it will also return it.
*
* There is a limitation in size, due to BIN_BUFFER_SIZE. If the data
* read was bigger than that, the function will include the characters
* ">>" at the end and activate the TRUNCATED_DATA value in the SD.flag.
* It is recommended to check this value to assure data integrity.
*
* If there is an error opening the file, 'buffer' is printed with an
* error message and the SD.flag will show the FILE_OPEN_ERROR bit active.
*
*/
uint8_t* WaspSD::catBin(const char* filepath, int32_t offset, uint16_t scope)
{
// Local variable
SdFile file;
// check if the card is there or not
if (!isSD())
{
flag = CARD_NOT_PRESENT;
flag |= FILE_OPEN_ERROR;
snprintf(buffer, sizeof(buffer),"%s", CARD_NOT_PRESENT_em);
USB.println(buffer);
return bufferBin;
}
// if scope is zero, then we should make it
// ridiculously big, so that it goes on reading forever
if (scope <= 0) scope = BIN_BUFFER_SIZE;
if (scope > BIN_BUFFER_SIZE) scope = BIN_BUFFER_SIZE;
flag &= ~(TRUNCATED_DATA | FILE_OPEN_ERROR | FILE_SEEKING_ERROR);
// search file in current working directory and open it
// exit if error and modify the general flag with FILE_OPEN_ERROR
if(!openFile((char*)filepath, &file, O_RDONLY))
{
snprintf(buffer, sizeof(buffer), "error opening %s", filepath);
USB.println(buffer);
flag |= FILE_OPEN_ERROR;
return bufferBin;
}
// iterate through the file
byte maxBuffer = 1; // size of the buffer to use when reading
uint8_t bufferSD[maxBuffer]; // buffer so as to store data
uint32_t cont = 0; // counter so as not to exceed buffer size
// first jump over the offset
if(!file.seekSet(offset))
{
snprintf(buffer, sizeof(buffer), "error seeking on: %s\n", filepath);
USB.println(buffer);
flag |= FILE_SEEKING_ERROR;
file.close();
return bufferBin;
}
// Read first time from file, 'maxBuffer' bytes
uint8_t readRet = file.read(bufferSD, sizeof(bufferSD));
// clear 'bufferBin'
memset(bufferBin, 0x00, sizeof(bufferBin) );
// second, read the data and store it in the buffer
// Breaks in the case it exceeds its size.
while( (readRet > 0) && (scope > 0) && (cont < BIN_BUFFER_SIZE) )
{
// Store data in buffer until scope ends, or
// buffer size limit is exceeded
for(uint8_t i = 0; i < readRet; ++i)
{
bufferBin[cont++] = bufferSD[i];
scope--;
if( scope <=0 ) break;
if( cont>=BIN_BUFFER_SIZE ) break;
}
// Break in the case the file ends
if( readRet<maxBuffer ) break;
// Read other block of data from SD file
readRet = file.read(bufferSD, sizeof(bufferSD));
}
// Close file
file.close();
return bufferBin;
}
/*
* catln (filepath, offset, scope)
*
* dumps into the SD.buffer the amount of lines in 'scope' after 'offset'
* lines coming from filepath, it will also return it as a string.
*
* There is a limitation in size, due to DOS_BUFFER_SIZE. If the data
* read is bigger than that, the function will include the characters
* ">>" at the end and activate the TRUNCATED_DATA value in the SD.flag.
* It is recommened to check this value to assure data integrity.
*
* If there was an error opening the file, the returned string will say
* so and the SD.flag will show the FILE_OPEN_ERROR bit active
*
* An example of calls to catln(filepath, offset, scope) is:
*
* - SD.catln("hola.txt", 10, 5): will show 5 lines following the 10th
* line in the file "hola.txt"
*
* The information is sent back as a string where each one of the file's
* lines are printed in one line, an example of this would be:
*
* en un lugar
* de la mancha de
* cuyo nombre no qui>>
*
* Lines end with EOF ('\n'), this is the symbol used to count the
* amount of lines.
*/
char* WaspSD::catln (const char* filepath, uint32_t offset, uint16_t scope)
{
// Local variables
SdFile file;
uint8_t j=0;
// check if the card is there or not
if (!isSD())
{
flag = CARD_NOT_PRESENT;
flag |= FILE_OPEN_ERROR;
snprintf(buffer, sizeof(buffer),"%s", CARD_NOT_PRESENT_em);
return buffer;
}
// if scope is zero, then we should make it
// ridiculously big, so that it goes on reading forever
if (scope <= 0) scope = DOS_BUFFER_SIZE;
// Limit the maximum size of 'scope'
if (scope > DOS_BUFFER_SIZE) scope = DOS_BUFFER_SIZE;
// Unset any error flag there could be
flag &= ~(TRUNCATED_DATA | FILE_OPEN_ERROR);
// search file in current working directory and open it
// exit if error and modify the general flag with FILE_OPEN_ERROR
if(!openFile((char*)filepath, &file, O_RDONLY))
{
snprintf(buffer, sizeof(buffer), "error opening %s", filepath);
flag |= FILE_OPEN_ERROR;
return buffer;
}
// iterate through the file
byte maxBuffer = 1; // size of the buffer to use when reading
uint8_t bufferSD[maxBuffer];
uint32_t cont = 0;
// Read first byte of the file
uint8_t readRet = file.read(bufferSD, sizeof(bufferSD));
// jump over offset lines (seek number of '\n' characters)
if (offset > 0)
{
// count EOL in order to set the selected 'offset'
j=0;
while( readRet > 0 && offset > 0)
{
for(j = 0; j < readRet; ++j)
{
if (bufferSD[j] == '\n')
offset--;
if( offset <=0 ) break;
}
if(offset>0)
{
// read data from SD file
readRet = file.read(bufferSD, sizeof(bufferSD));
}
}
// do not forget the first buffer
for(uint8_t i = j+1; i < maxBuffer; ++i)
{
buffer[cont++] = bufferSD[i];
if (bufferSD[i] == '\n')
scope--;
}
// read data from SD file
readRet = file.read(bufferSD, sizeof(bufferSD));
}
// add 'scope' lines to buffer
while(readRet > 0 && scope > 0 && cont < DOS_BUFFER_SIZE)
{
// copy data until we count 'scope' lines
for(uint8_t i = 0; i < maxBuffer; ++i)
{
buffer[cont++] = bufferSD[i];
if (bufferSD[i] == '\n')
scope--;
if( scope <=0 ) break;
}
// read data from SD file
if( scope >0 )
readRet = file.read(bufferSD, sizeof(bufferSD));
}
// are we at the end of the buffer yet?
if (cont < DOS_BUFFER_SIZE - 1)
{
// set end of string
buffer[cont++] = '\0';
}
else
{
// in case we filled up the whole buffer, we add a
// visual end of buffer indicator and leave the loop
buffer[DOS_BUFFER_SIZE - 4] = '>';
buffer[DOS_BUFFER_SIZE - 3] = '>';
buffer[DOS_BUFFER_SIZE - 2] = '\n';
buffer[DOS_BUFFER_SIZE - 1] = '\0';
flag |= TRUNCATED_DATA;
}
// close file
file.close();
return buffer;
}
/*
* indexOf ( filepath, pattern, offset ) - search for first occurrence
* of an specific string in a file
*
* Seeks inside 'filepath' file for the first occurrence of the pattern
* after a certain 'offset'. The algorithm will jump over 'offset'
* bytes before starting the search of the pattern. It will return the
* amount of bytes (as an int32_t) to the pattern from the offset
*
* Example, file hola.txt contains:
*
* hola caracola\nhej hej\n hola la[EOF]
*
* The following table shows the results from searching different patterns:
*
* Command Answer
* SD.indexOf("hola.txt", "hola", 0) 0
* SD.indexOf("hola.txt", "hola", 1) 23
* SD.indexOf("hola.txt", "hej", 3) 11
*
* Notes:
* - the special characters like '\n' (EOL) are accounted as one byte
* - files are indexed from 0
*
* If there was an error opening the file, the buffer string will say so
* and the SD.flag will show the FILE_OPEN_ERROR bit active
*/
int32_t WaspSD::indexOf (const char* filepath, const char* pattern, uint32_t offset)
{
// Local variables
SdFile file;
uint8_t exit = 0;
uint32_t cont = 0;
uint8_t readRet;
// check if the card is there or not
if (!isSD())
{
flag = CARD_NOT_PRESENT;
flag |= FILE_OPEN_ERROR;
snprintf(buffer, sizeof(buffer),"%s", CARD_NOT_PRESENT_em);
return -1;
}
// unset any flag error
flag &= ~(FILE_OPEN_ERROR);
// open file in current directory
// exit if error and modify the general flag with FILE_OPEN_ERROR
if(!openFile((char*)filepath, &file, O_RDONLY))
{
snprintf(buffer, sizeof(buffer), "error opening %s", filepath);
flag |= FILE_OPEN_ERROR;
return -2;
}
// get file length
uint32_t limitSize = getFileSize(filepath);
// get pattern length
uint8_t limitPattern = strlen(pattern);
// buffer in order to read bytes from SD file
uint8_t bufferSD[1];
// buffer to store comparison pattern
uint8_t* cmpPattern = (uint8_t*) calloc(limitPattern,sizeof(uint8_t));
if( cmpPattern==NULL )
{
file.close();
return -1;
}
// jump over the 'offset'
if(!file.seekSet(offset))
{
file.close();
free(cmpPattern);
cmpPattern=NULL;
return -1;
}
// fill in the first buffer
readRet = file.read(bufferSD, sizeof(bufferSD));
for(int j=0; j < limitPattern - 1; j++)
{
if (readRet > 0)
{
cmpPattern[j] = bufferSD[0];
readRet = file.read(bufferSD, sizeof(bufferSD));
}
else
exit = 1; // exit if the filesize is smaller than the pattern
}
// to debug the code in the library it is possible to
// use the buffer together with snprintf, e.g.
//~ snprintf(buffer, sizeof(buffer),"%s - %c%c%c%c - %lu - %u -%lu",
//~ pattern,
//~ cmpPattern[0],
//~ cmpPattern[1],
//~ cmpPattern[2],
//~ bufferSD[0],
//~ cont,
//~ limitPattern,
//~ limitSize);
// run inside the buffer
while(readRet > 0 && cont < limitSize && !exit)
{
// take the last position in the buffer
cmpPattern[limitPattern-1] = bufferSD[0];
// compare the strings, exit if found
//if(Utils.strCmp((const char*) pattern, (const char*) cmpPattern, limitPattern) == 0)
if(strncmp((const char*) pattern, (const char*) cmpPattern, limitPattern) == 0)
exit = 1;
// if not exit, increment counter
if (!exit)
cont++;
// shift cmpPattern to the left one position
for(int j = 0; j < limitPattern - 1; j++) cmpPattern[j] = cmpPattern[j+1];
// read the next buffer
readRet = file.read(bufferSD, sizeof(bufferSD));
}
// close file
file.close();
// free dynamic memory
free(cmpPattern);
cmpPattern=NULL;
// in case we checked the whole buffer, we return error
if (cont >= limitSize - limitPattern )
return -1;
// otherwise we return the pattern's location
return cont;
}
/*
* isDir ( dir_entry ) - answers whether a file is a directory or not
*
* Returns 1 if it is a dir, 0 if error, will
* not modify any flags
*/
uint8_t WaspSD::isDir(SdFile* dir)
{
// Check if it is a valid file
if (!dir->isDir())
{
return 0;
}
else return 1;
}
/*
* isDir ( dirpath ) - tests the existence of a directory in the current
* working directory and checks if it is a directory or not
*
* Returns:
* 1 : if it exists and it is a dir,
* 0 : if exists but it is not a dir,
* -1 : if error
* will not modify any flags
*/
int8_t WaspSD::isDir(const char* dirpath)
{
// Local variable
SdFile file;
// try to open the file
if(!openFile( (char*)dirpath, &file, O_RDONLY))
{
return -1;
}
else
{
// File opened. Check if it is a valid file
if (!file.isDir())
{
file.close();
return 0;
}
else file.close();
}
return 1;
}
/*
* del ( filepath ) - delete file
*
* Returns 1 if it is possible to delete "filepath", 0 if error, will
* not modify any flags
*
* This function should not be used to delete the 8.3 version of a
* file that has a long name.
*
*/
boolean WaspSD::del(const char* filepath)
{
return walkPath((char*)filepath, currentDir, callback_remove, NULL);
}
/*
* rmdir ( dirpath ) - delete Directory
*
* returns 1 if it is possible to delete "dirname", 0 if error, will
* not modify any flags
*
* The directory file will be removed only if it is empty and
* is not the root directory. rmDir() follows DOS and Windows and
* ignores the read-only attribute for the directory.
*
* This function should not be used to delete the 8.3 version of a
* file that has a long name.
*
*/
boolean WaspSD::rmdir(const char* dirpath)
{
boolean result = walkPath((char*)dirpath, currentDir, callback_rmdir, NULL);
if(!result)
{
//try to delete a possible "damaged" directory
result = del(dirpath);
}
return result;
}
/*
* rmRfDir ( dirpath ) - delete Directory and all contained files.
*
* returns 1 if it is possible to delete "dirpath", 0 if error, will
* not modify any flags
*
* This function should not be used to delete the 8.3 version of a
* file that has a long name. For example if a file has the long name
*
*/
boolean WaspSD::rmRfDir(const char* dirpath)
{
boolean answer = false;
answer = walkPath((char*)dirpath, currentDir, callback_rmRfdir, NULL);
if(answer == false)
{
// if corrupted when a bad 'rmRfDir' call was done,
// then try to delete the generated corrupted file
if( SD.isFile(dirpath) == true )
{
answer = SD.del(dirpath);
}
}
return answer;
}
/*
* create ( filepath ) - create file called filepath
*
* If filepath is a path, i.e. "/FOLDER/SUBFOLD/file1.txt", the file
* called file1.txt is created inside the subdirectory SUBFOLD always
* the path has been created before using SD.mkdir("/FOLDER/SUBFOLD");
*
* Returns 1 on file creation, 0 if error, will mark the flag with
* FILE_CREATION_ERROR
*/
uint8_t WaspSD::create(const char* filepath)
{
// Local variables
SdFile file;
// set file date
setFileDate();
// check if the card is there or not
if (!isSD())
{
flag = CARD_NOT_PRESENT;
flag |= FILE_CREATION_ERROR;
snprintf(buffer, sizeof(buffer),"%s", CARD_NOT_PRESENT_em);
return 0;
}
// unset any error flag
flag &= ~(FILE_CREATION_ERROR);
// create/open new file. modes:
// O_READ - Open for reading
// O_WRITE - Open for writing
// O_CREAT: create the file if nonexistent
// O_EXCL: If O_CREAT and O_EXCL are set, open shall fail if the file exists
if(!openFile( (char*)filepath, &file, O_READ | O_WRITE | O_CREAT | O_EXCL))
{
flag |= FILE_CREATION_ERROR;
return 0;
}
// close file
file.close();
return 1;
}
/*
* writeSD ( filepath, str, offset ) - write string to file
*
* writes the string 'str' to the file 'filepath' after a certain 'offset'
*
* Returns
* 1 on success,
* 0 if error,
* will mark the flag with FILE_WRITING_ERROR
*/
uint8_t WaspSD::writeSD(const char* filepath, const char* str, int32_t offset)
{
// get "str" length
uint16_t data_len = strlen(str);
return writeSD(filepath, str, offset, data_len);
}
/*
* writeSD ( filepath, str, offset, length ) - write string to file
*
* writes the string "str" to the file "filepath" after a certain "offset"
*
* Returns
* 1 on success,
* 0 if error,
* will mark the flag with FILE_WRITING_ERROR
*/
uint8_t WaspSD::writeSD( const char* filepath,
const char* str,
int32_t offset,
uint16_t length )
{
// Local variables
SdFile file;
// check if the card is there or not
if (!isSD())
{
flag = CARD_NOT_PRESENT;
flag |= FILE_WRITING_ERROR;
snprintf(buffer, sizeof(buffer),"%s", CARD_NOT_PRESENT_em);
return 0;
}
// unset error flag
flag &= ~(FILE_WRITING_ERROR | FILE_SEEKING_ERROR);
// search file in current directory and open it in write mode
if(!openFile(filepath, &file, O_READ | O_WRITE | O_SYNC))
{
snprintf(buffer, sizeof(buffer), "error opening: %s\n", filepath);
flag |= FILE_WRITING_ERROR;
return 0;
}
// jump over the 'offset'
if(!file.seekSet(offset))
{
snprintf(buffer, sizeof(buffer), "error seeking on: %s\n", filepath);
file.close();
flag |= FILE_SEEKING_ERROR;
return 0;
}
// set length properly in case it was not
if(strlen(str)<length)
{
length=strlen(str);
}
// write text to file
if((uint16_t)file.write((uint8_t*) str, length) != length)
{
snprintf(buffer, sizeof(buffer), "error writing to: %s\n", filepath);
file.close();
flag |= FILE_WRITING_ERROR;
return 0;
}
// close file
file.close();
return 1;
}
/*
* writeSD ( filepath, str, offset ) - write numbers to files
*
* writes the array of integers "str" to the file "filepath" after a
* certain "offset". The array MUST end with the following pattern:
* "0xAAAA"
*
* Returns
* 1 on success,
* 0 if error,
* will mark the flag with FILE_WRITING_ERROR
*/
uint8_t WaspSD::writeSD(const char* filepath, uint8_t* str, int32_t offset)
{
// get array length
uint16_t data_len = 0;
while( (str[data_len]!=0xAA) || (str[data_len+1]!=0xAA) ) data_len++;
return writeSD(filepath, str, offset, data_len);
}
/*
* writeSD ( filepath, str, offset, length ) - write numbers to files
*
* writes the array of integers "str" to the file "filepath" after a
* certain "offset". The length of the array is indicated by "length"
*
* Returns
* 1 on success,
* 0 if error,
* will mark the flag with FILE_WRITING_ERROR
*/
uint8_t WaspSD::writeSD(const char* filepath, uint8_t* str, int32_t offset, uint16_t length)
{
// Local variables
SdFile file;
// check if the card is there or not
if (!isSD())
{
flag = CARD_NOT_PRESENT;
flag |= FILE_WRITING_ERROR;
snprintf(buffer, sizeof(buffer),"%s", CARD_NOT_PRESENT_em);
return 0;
}
// unset error flag
flag &= ~(FILE_WRITING_ERROR | FILE_SEEKING_ERROR);
// search file in current directory and open it
if(!openFile(filepath, &file, O_READ | O_WRITE | O_SYNC))
{
snprintf(buffer, sizeof(buffer), "error opening: %s\n", filepath);
flag |= FILE_WRITING_ERROR;
return 0;
}
// jump over the 'offset'
if(!file.seekSet(offset))
{
snprintf(buffer, sizeof(buffer), "error seeking on: %s\n", filepath);
file.close();
flag |= FILE_SEEKING_ERROR;
return 0;
}
// write text to file
if( (uint16_t)file.write((uint8_t*) str, length) != length)
{
snprintf(buffer, sizeof(buffer), "error writing to: %s\n", filepath);
file.close();
flag |= FILE_WRITING_ERROR;
return 0;
}
// close file
file.close();
return 1;
}
/*
* append ( filepath, str ) - write strings at the end of the file
*
* Writes the string "str" at the end of the file "filepath"
*
* Returns
* 1 on success,
* 0 if error,
* will mark the flag with FILE_WRITING_ERROR
*/
uint8_t WaspSD::append(const char* filepath, const char* str)
{
return writeSD(filepath, str, getFileSize(filepath));
}
/*
* append ( filepath, str, length ) - write string at the end of the file
*
* Writes the string "str" at the end of the file "filepath"
*
* \remarks length of string is indicated with "length"
*
* Returns
* 1 on success,
* 0 if error,
* will mark the flag with FILE_WRITING_ERROR
*/
uint8_t WaspSD::append(const char* filepath, const char* str, uint16_t length)
{
return writeSD(filepath, str, getFileSize(filepath), length);
}
/*
* append ( filepath, str ) - write array of numbers at the end of the file
*
* Writes the array of numbers "str" at the end of the file "filepath"
*
* Returns
* 1 on success,
* 0 if error,
* will mark the flag with FILE_WRITING_ERROR
*/
uint8_t WaspSD::append(const char* filepath, uint8_t* str)
{
return writeSD(filepath, str, getFileSize(filepath));
}
/*
* append ( filepath, str, length ) - write array of numbers at the end of the file
*
* Writes the array of numbers "str" at the end of the file "filepath"
* The length of the string "str" is indicated with "length"
*
* Returns
* 1 on success,
* 0 if error,
* will mark the flag with FILE_WRITING_ERROR
*/
uint8_t WaspSD::append(const char* filepath, uint8_t* str, uint16_t length)
{
return writeSD(filepath, str, getFileSize(filepath), length);
}
/*
* appendln ( filepath, str, length ) - write array of numbers at the end of the file
*
* Writes the array of numbers "str" at the end of the file "filepath"
* The length of the string "str" is indicated with "length". End of line is
* added when the first writing is done successfully.
*
* Returns
* 1 on success,
* 0 if error,
* will mark the flag with FILE_WRITING_ERROR
*/
uint8_t WaspSD::appendln(const char* filepath, uint8_t* str, uint16_t length)
{
uint8_t exit = 0;
exit = append(filepath, str, length);
if (exit)
{
exit &= writeEndOfLine(filepath);
}
return exit;
}
/*
* appendln ( filepath, str ) - write strings at the end of files
*
* Writes the string "str" at the end of the file "filepath" adding end
* of line. Depending on the tag FILESYSTEM_LINUX, a '\r' is also
* written to the SD file.
*
* Returns
* 1 on success,
* 0 if error,
* will mark the flag with FILE_WRITING_ERROR
*/
uint8_t WaspSD::appendln(const char* filepath, const char* str)
{
uint8_t exit = 0;
exit = append(filepath, str);
if (exit)
{
exit &= writeEndOfLine(filepath);
}
return exit;
}
/*
* appendln ( filepath, str ) - write array of numbers at the end of the file
*
* Writes the array of numbers "str" at the end of the file "filepath"
* adding end of line. Depending on the tag FILESYSTEM_LINUX, a '\r' is
* also written to the SD file.
*
* Returns
* 1 on success,
* 0 if error,
* will mark the flag with FILE_WRITING_ERROR
*/
uint8_t WaspSD::appendln(const char* filepath, uint8_t* str)
{
uint8_t exit = 0;
exit = append(filepath, str);
if (exit)
{
exit &= writeEndOfLine(filepath);
}
return exit;
}
/*
* numln ( filepath ) - returns the amount of lines in a file
*
* returns the amount of lines in "filepath" that should be in the
* current directory, a negative answer indicates error, zero means no
* lines in the file
*
* This method counts the occurrence of the character '\n' in the file.
* If there was a problem opening it, the FILE_OPEN_ERROR would be
* activated and will return -1
*/
int32_t WaspSD::numln(const char* filepath)
{
// local variables
SdFile file;
byte maxBuffer = 10; // size of the buffer to use when reading
uint8_t bufferSD[maxBuffer]; // buffer to store read data
uint32_t cont = 0; // lines counter
// check if the card is there or not
if (!isSD())
{
flag = CARD_NOT_PRESENT;
flag |= FILE_OPEN_ERROR;
snprintf(buffer, sizeof(buffer),"%s", CARD_NOT_PRESENT_em);
return -1;
}
// unset error flag
flag &= ~(FILE_OPEN_ERROR);
// search file in the current working directory and open it
// exit if error and modify the general flag with FILE_OPEN_ERROR
if(!openFile(filepath, &file, O_READ))
{
snprintf(buffer, sizeof(buffer), "error opening: %s\n", filepath);
flag |= FILE_OPEN_ERROR;
return 0;
}
// count lines by reading '\n' characters
uint8_t readRet = file.read(bufferSD, maxBuffer);
// count '\n' characters while there is available data in SD file
while( readRet > 0)
{
// search '\n' characters
for(uint8_t i = 0; i < readRet; ++i)
{
if (bufferSD[i] == '\n')
cont++;
}
readRet = file.read(bufferSD, maxBuffer);
}
// close file
file.close();
return cont;
}
/*
* cd(dirpath) - changes directory,
*
* Returns: 0=error; 1=ok
*/
uint8_t WaspSD::cd(const char* dirpath)
{
// local variables
int pathidx;
// do the iterative search to look for the path's directory
SdFile newdir = getDir(dirpath, &pathidx);
// check if newdir was correctly found and opened
if (!newdir.isOpen())
{
// failed to open a subdir!
return 0;
}
else
{
// copy object to 'newdir'
memcpy(¤tDir, &newdir, sizeof(SdFile));
}
return 1;
}
/*
* goRoot(path) - go to root directory
*
* Update "currentDir" with "root" attribute by copying the context of the root
* directory in currentDir.
*
* Returns: 0=error; 1=ok
*/
uint8_t WaspSD::goRoot()
{
// Check if currentDir is the root directory
if(currentDir.isRoot())
{
return 1;
}
// close actual directory
if(!currentDir.close())
{
// Can't close actual current directory
return 0;
}
// Update current working directory to 'root' directory
memcpy(¤tDir, &root, sizeof(SdFile));
return 1;
}
/*
* numFiles ( void ) - returns the amount of files in dir
*
* returns the amount of files in the current directory
* a negative answer indicates error, zero means no files in the folder
*/
int8_t WaspSD::numFiles()
{
// set the file's current position to zero
currentDir.rewind();
// check if the card is there or not
if (!isSD())
{
flag = CARD_NOT_PRESENT;
snprintf(buffer, sizeof(buffer),"%s", CARD_NOT_PRESENT_em);
return -1;
}
uint8_t cont = -2;
dir_t dir_entry;
cont=0;
while(currentDir.readDir(&dir_entry))
{
// Don't count TRASH~1 directory
if(!(dir_entry.name[0]=='T' &&
dir_entry.name[1]=='R' &&
dir_entry.name[2]=='A' &&
dir_entry.name[3]=='S' &&
dir_entry.name[4]=='H' ))
{
// increase counter
cont++;
}
}
// set the file's current position to zero
currentDir.rewind();
return cont;
}
/*
* cleanFlags ( void ) - resets all the flags, returns the flags
*/
uint16_t WaspSD::cleanFlags(void)
{
flag = 0;
return flag;
}
/*
* writeEndOfLine -
*
* Write "\r\n" in specified file
*/
uint8_t WaspSD::writeEndOfLine(const char* filepath)
{
uint8_t result = 1;
#ifndef FILESYSTEM_LINUX
if(result)
{
result = append(filepath, "\r\n");
if(!result)
{
result = append(filepath, "\r\n");
}
}
#else
if(result)
{
result = append(filepath, "\n");
if(!result)
{
result = append(filepath, "\n");
}
}
#endif
return result;
}
/*
* format() -
*
* Format SD card erasing all data first
*/
bool WaspSD::format()
{
//! variables:
//---------------------------------------------------------------
uint32_t const ERASE_SIZE = 262144L;
uint32_t cardSizeBlocks;
uint16_t cardCapacityMB;
// cache for SD block
cache_t cache;
// MBR information
uint8_t partType;
uint32_t relSector;
uint32_t partSize;
// Fake disk geometry
uint8_t numberOfHeads;
uint8_t sectorsPerTrack;
// FAT parameters
uint16_t reservedSectors;
uint8_t sectorsPerCluster;
uint32_t fatStart;
uint32_t fatSize;
uint32_t dataStart;
// constants for file system structure
uint16_t const BU16 = 128;
uint16_t const BU32 = 8192;
// strings needed in file system structures
char noName[] = "NO NAME ";
char fat16str[] = "FAT16 ";
char fat32str[] = "FAT32 ";
//---------------------------------------------------------------
//! initialization process
cardSizeBlocks = card.cardSize();
if (cardSizeBlocks == 0)
{
#ifdef SD_DEBUG
PRINTLN_SD(F("error cardSize"));
#endif
return 0;
}
cardCapacityMB = (cardSizeBlocks + 2047)/2048;
#ifdef SD_DEBUG
PRINT_SD(F("Card Size: "));
USB.print(cardCapacityMB);
USB.println(F(" MB, (MB = 1,048,576 bytes)"));
#endif
//! Erasing process
#ifdef SD_DEBUG
PRINTLN_SD(F("\nErasing\n"));
#endif
uint32_t firstBlock = 0;
uint32_t lastBlock;
uint16_t n = 0;
#ifdef SD_DEBUG
PRINT_SD(F(""));
#endif
do {
lastBlock = firstBlock + ERASE_SIZE - 1;
if (lastBlock >= cardSizeBlocks) lastBlock = cardSizeBlocks - 1;
if (!card.erase(firstBlock, lastBlock))
{
#ifdef SD_DEBUG
PRINTLN_SD(F("erase failed"));
#endif
return 0;
}
#ifdef SD_DEBUG
USB.print(F("."));
#endif
if ((n++)%32 == 31) USB.println();
firstBlock += ERASE_SIZE;
} while (firstBlock < cardSizeBlocks);
#ifdef SD_DEBUG
USB.println();
#endif
if (!card.readBlock(0, cache.data))
{
#ifdef SD_DEBUG
PRINTLN_SD(F("error readBlock"));
#endif
return 0;
}
#ifdef SD_DEBUG
PRINT_SD(F("All data set to "));
USB.println(int(cache.data[0]),DEC);
PRINT_SD(F("Erase done\n"));
#endif
//! Formatting process
#ifdef SD_DEBUG
USB.println();
PRINT_SD(F("Formatting\n"));
#endif
// initSizes
if (cardCapacityMB <= 6)
{
#ifdef SD_DEBUG
PRINTLN_SD(F("Card is too small."));
#endif
return 0;
}
else if (cardCapacityMB <= 16) sectorsPerCluster = 2;
else if (cardCapacityMB <= 32) sectorsPerCluster = 4;
else if (cardCapacityMB <= 64) sectorsPerCluster = 8;
else if (cardCapacityMB <= 128) sectorsPerCluster = 16;
else if (cardCapacityMB <= 1024) sectorsPerCluster = 32;
else if (cardCapacityMB <= 32768) sectorsPerCluster = 64;
else{
// SDXC cards
sectorsPerCluster = 128;
}
#ifdef SD_DEBUG
PRINT_SD(F("Blocks/Cluster: "));
USB.println(sectorsPerCluster,DEC);
#endif
// set fake disk geometry
sectorsPerTrack = cardCapacityMB <= 256 ? 32 : 63;
if (cardCapacityMB <= 16) numberOfHeads = 2;
else if (cardCapacityMB <= 32) numberOfHeads = 4;
else if (cardCapacityMB <= 128) numberOfHeads = 8;
else if (cardCapacityMB <= 504) numberOfHeads = 16;
else if (cardCapacityMB <= 1008) numberOfHeads = 32;
else if (cardCapacityMB <= 2016) numberOfHeads = 64;
else if (cardCapacityMB <= 4032) numberOfHeads = 128;
else{
numberOfHeads = 255;
}
if (volume.fatType() == 16)
{
#ifdef SD_DEBUG
PRINT_SD(F("FAT16\n"));
#endif
/*start makeFat16()*/
uint32_t nc;
for (dataStart = 2 * BU16;; dataStart += BU16)
{
nc = (cardSizeBlocks - dataStart)/sectorsPerCluster;
fatSize = (nc + 2 + 255)/256;
uint32_t r = BU16 + 1 + 2 * fatSize + 32;
if (dataStart < r) continue;
relSector = dataStart - r + BU16;
break;
}
// check valid cluster count for FAT16 volume
if (nc < 4085 || nc >= 65525)
{
#ifdef SD_DEBUG
PRINTLN_SD(F("Bad cluster count"));
#endif
return 0;
}
reservedSectors = 1;
fatStart = relSector + reservedSectors;
partSize = nc * sectorsPerCluster + 2 * fatSize + reservedSectors + 32;
if (partSize < 32680) {
partType = 0X01;
} else if (partSize < 65536) {
partType = 0X04;
} else {
partType = 0X06;
}
// write MBR
/*start writeMbr()*/
/*start clearCache(true)*/
memset(&cache, 0, sizeof(cache));
cache.mbr.mbrSig0 = BOOTSIG0;
cache.mbr.mbrSig1 = BOOTSIG1;
/*end clearCache(true)*/
part_t* p = cache.mbr.part;
p->boot = 0;
// get cylinder number for a logical block number
//~ uint16_t c = lbnToCylinder(relSector);
uint16_t c = relSector / (numberOfHeads * sectorsPerTrack);
if (c > 1023)
{
#ifdef SD_DEBUG
PRINTLN_SD(F("error MBR CHS"));
#endif
return 0;
}
p->beginCylinderHigh = c >> 8;
p->beginCylinderLow = c & 0XFF;
//get head number for a logical block number
//~ p->beginHead = lbnToHead(relSector);
p->beginHead = (relSector % (numberOfHeads * sectorsPerTrack)) / sectorsPerTrack;
//get sector number for a logical block number
//~ p->beginSector = lbnToSector(relSector);
p->beginSector = (relSector % sectorsPerTrack) + 1;
p->type = partType;
uint32_t endLbn = relSector + partSize - 1;
//get cylinder number for a logical block number
//~ c = lbnToCylinder(endLbn);
c = endLbn / (numberOfHeads * sectorsPerTrack);
if (c <= 1023) {
p->endCylinderHigh = c >> 8;
p->endCylinderLow = c & 0XFF;
//get head number for a logical block number
//~ p->endHead = lbnToHead(endLbn);
p->endHead = (endLbn % (numberOfHeads * sectorsPerTrack)) / sectorsPerTrack;
//get sector number for a logical block number
//~ p->endSector = lbnToSector(endLbn);
p->endSector = (endLbn % sectorsPerTrack) + 1;
//get sector number for a logical block number
//~ p->endSector = lbnToSector(endLbn);
p->endSector = (endLbn % sectorsPerTrack) + 1;
} else {
// Too big flag, c = 1023, h = 254, s = 63
p->endCylinderHigh = 3;
p->endCylinderLow = 255;
p->endHead = 254;
p->endSector = 63;
}
p->firstSector = relSector;
p->totalSectors = partSize;
//~ if (!writeCache(0))
if (!card.writeBlock(0, cache.data))
{
#ifdef SD_DEBUG
PRINTLN_SD(F("error write MBR"));
#endif
return 0;
}
/*end writeMbr()*/
/*start clearCache(true)*/
memset(&cache, 0, sizeof(cache));
cache.mbr.mbrSig0 = BOOTSIG0;
cache.mbr.mbrSig1 = BOOTSIG1;
/*end clearCache(true)*/
fat_boot_t* pb = &cache.fbs;
pb->jump[0] = 0XEB;
pb->jump[1] = 0X00;
pb->jump[2] = 0X90;
for (uint8_t i = 0; i < sizeof(pb->oemId); i++) {
pb->oemId[i] = ' ';
}
pb->bytesPerSector = 512;
pb->sectorsPerCluster = sectorsPerCluster;
pb->reservedSectorCount = reservedSectors;
pb->fatCount = 2;
pb->rootDirEntryCount = 512;
pb->mediaType = 0XF8;
pb->sectorsPerFat16 = fatSize;
pb->sectorsPerTrack = sectorsPerTrack;
pb->headCount = numberOfHeads;
pb->hidddenSectors = relSector;
pb->totalSectors32 = partSize;
pb->driveNumber = 0X80;
pb->bootSignature = EXTENDED_BOOT_SIG;
//~ pb->volumeSerialNumber = volSerialNumber();
pb->volumeSerialNumber = (cardSizeBlocks << 8) + millis();
memcpy(pb->volumeLabel, noName, sizeof(pb->volumeLabel));
memcpy(pb->fileSystemType, fat16str, sizeof(pb->fileSystemType));
// write partition boot sector
//~ if (!writeCache(relSector))
if (!card.writeBlock(relSector, cache.data))
{
#ifdef SD_DEBUG
PRINTLN_SD(F("FAT16 write PBS failed"));
#endif
return 0;
}
// clear FAT and root directory
/* start clearFatDir(fatStart, dataStart - fatStart);*/
/*start clearCache(false)*/
memset(&cache, 0, sizeof(cache));
/*end clearCache(false)*/
if (!card.writeStart(fatStart, dataStart - fatStart))
{
#ifdef SD_DEBUG
PRINTLN_SD(F("Clear FAT/DIR writeStart failed"));
#endif
return 0;
}
for (uint32_t i = 0; i < (dataStart - fatStart); i++)
{
if ((i & 0XFF) == 0)
{
#ifdef SD_DEBUG
USB.print(F("."));
#endif
}
if (!card.writeData(cache.data))
{
#ifdef SD_DEBUG
USB.println(F("Clear FAT/DIR writeData failed"));
#endif
return 0;
}
}
if (!card.writeStop())
{
#ifdef SD_DEBUG
USB.println(F("Clear FAT/DIR writeStop failed"));
#endif
return 0;
}
#ifdef SD_DEBUG
USB.println();
#endif
/* end clearFatDir(fatStart, dataStart - fatStart);*/
/*start clearCache(false)*/
memset(&cache, 0, sizeof(cache));
/*end clearCache(false)*/
cache.fat16[0] = 0XFFF8;
cache.fat16[1] = 0XFFFF;
// write first block of FAT and backup for reserved clusters
//~ if (!writeCache(fatStart) || !writeCache(fatStart + fatSize)) {
if( !card.writeBlock(fatStart, cache.data) ||
!card.writeBlock(fatStart + fatSize, cache.data) )
{
#ifdef SD_DEBUG
USB.println(F("FAT16 reserve failed"));
#endif
return 0;
}
}
else if (volume.fatType() == 32)
{
#ifdef SD_DEBUG
USB.print(F("FAT32\n"));
#endif
/*start makeFat32()*/
uint32_t nc;
relSector = BU32;
for (dataStart = 2 * BU32;; dataStart += BU32)
{
nc = (cardSizeBlocks - dataStart)/sectorsPerCluster;
fatSize = (nc + 2 + 127)/128;
uint32_t r = relSector + 9 + 2 * fatSize;
if (dataStart >= r) {
break;
}
}
// error if too few clusters in FAT32 volume
if (nc < 65525)
{
#ifdef SD_DEBUG
USB.println(F("Bad cluster count"));
#endif
}
reservedSectors = dataStart - relSector - 2 * fatSize;
fatStart = relSector + reservedSectors;
partSize = nc * sectorsPerCluster + dataStart - relSector;
// type depends on address of end sector
// max CHS has lbn = 16450560 = 1024*255*63
if ((relSector + partSize) <= 16450560) {
// FAT32
partType = 0X0B;
} else {
// FAT32 with INT 13
partType = 0X0C;
}
// write MBR
/*start writeMbr()*/
/*start clearCache(true)*/
memset(&cache, 0, sizeof(cache));
cache.mbr.mbrSig0 = BOOTSIG0;
cache.mbr.mbrSig1 = BOOTSIG1;
/*end clearCache(true)*/
part_t* p = cache.mbr.part;
p->boot = 0;
// get cylinder number for a logical block number
//~ uint16_t c = lbnToCylinder(relSector);
uint16_t c = relSector / (numberOfHeads * sectorsPerTrack);
if (c > 1023)
{
#ifdef SD_DEBUG
USB.println(F("error MBR CHS"));
#endif
return 0;
}
p->beginCylinderHigh = c >> 8;
p->beginCylinderLow = c & 0XFF;
//get head number for a logical block number
//~ p->beginHead = lbnToHead(relSector);
p->beginHead = (relSector % (numberOfHeads * sectorsPerTrack)) / sectorsPerTrack;
//get sector number for a logical block number
//~ p->beginSector = lbnToSector(relSector);
p->beginSector = (relSector % sectorsPerTrack) + 1;
p->type = partType;
uint32_t endLbn = relSector + partSize - 1;
//get cylinder number for a logical block number
//~ c = lbnToCylinder(endLbn);
c = endLbn / (numberOfHeads * sectorsPerTrack);
if (c <= 1023) {
p->endCylinderHigh = c >> 8;
p->endCylinderLow = c & 0XFF;
//get head number for a logical block number
//~ p->endHead = lbnToHead(endLbn);
p->endHead = (endLbn % (numberOfHeads * sectorsPerTrack)) / sectorsPerTrack;
//get sector number for a logical block number
//~ p->endSector = lbnToSector(endLbn);
p->endSector = (endLbn % sectorsPerTrack) + 1;
//get sector number for a logical block number
//~ p->endSector = lbnToSector(endLbn);
p->endSector = (endLbn % sectorsPerTrack) + 1;
} else {
// Too big flag, c = 1023, h = 254, s = 63
p->endCylinderHigh = 3;
p->endCylinderLow = 255;
p->endHead = 254;
p->endSector = 63;
}
p->firstSector = relSector;
p->totalSectors = partSize;
//~ if (!writeCache(0))
if (!card.writeBlock(0, cache.data))
{
#ifdef SD_DEBUG
USB.println(F("error write MBR"));
#endif
return 0;
}
/*start clearCache(true)*/
memset(&cache, 0, sizeof(cache));
cache.mbr.mbrSig0 = BOOTSIG0;
cache.mbr.mbrSig1 = BOOTSIG1;
/*end clearCache(true)*/
fat32_boot_t* pb = &cache.fbs32;
pb->jump[0] = 0XEB;
pb->jump[1] = 0X00;
pb->jump[2] = 0X90;
for (uint8_t i = 0; i < sizeof(pb->oemId); i++) {
pb->oemId[i] = ' ';
}
pb->bytesPerSector = 512;
pb->sectorsPerCluster = sectorsPerCluster;
pb->reservedSectorCount = reservedSectors;
pb->fatCount = 2;
pb->mediaType = 0XF8;
pb->sectorsPerTrack = sectorsPerTrack;
pb->headCount = numberOfHeads;
pb->hidddenSectors = relSector;
pb->totalSectors32 = partSize;
pb->sectorsPerFat32 = fatSize;
pb->fat32RootCluster = 2;
pb->fat32FSInfo = 1;
pb->fat32BackBootBlock = 6;
pb->driveNumber = 0X80;
pb->bootSignature = EXTENDED_BOOT_SIG;
//pb->volumeSerialNumber = volSerialNumber();
pb->volumeSerialNumber = (cardSizeBlocks << 8) + millis();
memcpy(pb->volumeLabel, noName, sizeof(pb->volumeLabel));
memcpy(pb->fileSystemType, fat32str, sizeof(pb->fileSystemType));
// write partition boot sector and backup
//if (!card.writeBlock(0, cache.data) || !writeCache(relSector + 6))
if( !card.writeBlock(relSector, cache.data) ||
!card.writeBlock(relSector + 6, cache.data) )
{
#ifdef SD_DEBUG
USB.println(F("FAT32 write PBS failed"));
#endif
}
/*start clearCache(true)*/
memset(&cache, 0, sizeof(cache));
cache.mbr.mbrSig0 = BOOTSIG0;
cache.mbr.mbrSig1 = BOOTSIG1;
/*end clearCache(true)*/
// write extra boot area and backup
//if (!writeCache(relSector + 2) || !writeCache(relSector + 8))
if( !card.writeBlock(relSector + 2, cache.data) ||
!card.writeBlock(relSector + 8, cache.data) )
{
#ifdef SD_DEBUG
USB.println(F("FAT32 PBS ext failed"));
#endif
}
fat32_fsinfo_t* pf = &cache.fsinfo;
pf->leadSignature = FSINFO_LEAD_SIG;
pf->structSignature = FSINFO_STRUCT_SIG;
pf->freeCount = 0XFFFFFFFF;
pf->nextFree = 0XFFFFFFFF;
// write FSINFO sector and backup
//if (!writeCache(relSector + 1) || !writeCache(relSector + 7))
if( !card.writeBlock(relSector + 1, cache.data) ||
!card.writeBlock(relSector + 7, cache.data) )
{
#ifdef SD_DEBUG
USB.println(F("FAT32 FSINFO failed"));
#endif
}
//clearFatDir(fatStart, 2 * fatSize + sectorsPerCluster);
// clear FAT and root directory
/* start clearFatDir(fatStart, dataStart - fatStart);*/
/*start clearCache(false)*/
memset(&cache, 0, sizeof(cache));
/*end clearCache(false)*/
if (!card.writeStart(fatStart, 2 * fatSize + sectorsPerCluster)) {
#ifdef SD_DEBUG
USB.println(F("Clear FAT/DIR writeStart failed"));
#endif
return 0;
}
for (uint32_t i = 0; i < 2 * fatSize + sectorsPerCluster; i++)
{
if ((i & 0XFF) == 0)
{
#ifdef SD_DEBUG
USB.print(F("."));
#endif
}
if (!card.writeData(cache.data))
{
#ifdef SD_DEBUG
USB.println(F("Clear FAT/DIR writeData failed"));
#endif
return 0;
}
}
if (!card.writeStop())
{
#ifdef SD_DEBUG
USB.println(F("Clear FAT/DIR writeStop failed"));
#endif
return 0;
}
#ifdef SD_DEBUG
USB.println();
#endif
/* end clearFatDir(fatStart, dataStart - fatStart);*/
/*start clearCache(false)*/
memset(&cache, 0, sizeof(cache));
/*end clearCache(false)*/
cache.fat32[0] = 0x0FFFFFF8;
cache.fat32[1] = 0x0FFFFFFF;
cache.fat32[2] = 0x0FFFFFFF;
// write first block of FAT and backup for reserved clusters
//if (!writeCache(fatStart) || !writeCache(fatStart + fatSize))
if( !card.writeBlock(fatStart, cache.data) ||
!card.writeBlock(fatStart + fatSize, cache.data) )
{
#ifdef SD_DEBUG
USB.println(F("FAT32 reserve failed"));
#endif
}
}
// print info
#ifdef SD_DEBUG
USB.print(F("partStart: ")); USB.println(relSector,DEC);
USB.print(F("partSize: ")); USB.println(partSize,DEC);
USB.print(F("reserved: ")); USB.println(reservedSectors,DEC);
USB.print(F("fatStart: ")); USB.println(fatStart,DEC);
USB.print(F("fatSize: ")); USB.println(fatSize,DEC);
USB.print(F("dataStart: ")); USB.println(dataStart,DEC);
USB.print(F("clusterCount: "));USB.println( (relSector + partSize - dataStart)/sectorsPerCluster,DEC);
USB.println();
USB.print(F("Heads: ")); USB.println(int(numberOfHeads),DEC);
USB.print(F("Sectors: ")); USB.println(int(sectorsPerTrack),DEC);
USB.print(F("Cylinders: ")); USB.println(cardSizeBlocks/(numberOfHeads*sectorsPerTrack),DEC);
USB.print(F("Format done\n"));
#endif
return 1;
}
// Private Methods /////////////////////////////////////////////////////////////
/*
* setFileDate() -
*
* Set the proper Date and Time for creating directories and files
*/
void WaspSD::setFileDate()
{
// Get the 5V and 3V3 power supply actual state
bool set5V = WaspRegister & REG_5V;
bool set3V3 = WaspRegister & REG_3V3;
// Get RTC data for creation time and date
// It is necessary to switch on the power supply if any Sensor Board is
// connected to Waspmote so as not to cause intereferences in the I2C bus
PWR.setSensorPower(SENS_5V,SENS_ON);
PWR.setSensorPower(SENS_3V3,SENS_ON);
// update RTC attributes
if (RTC.isON == 0)
{
RTC.ON();
}
RTC.getTime();
if( !set3V3 )
{
PWR.setSensorPower(SENS_3V3,SENS_OFF);
}
if( !set5V )
{
PWR.setSensorPower(SENS_5V,SENS_OFF);
}
// set date time callback function
SdFile::dateTimeCallback(dateTime);
}
/*
* showFile() -
*
* Print out the contents of the whole input file
*/
void WaspSD::showFile(char* filepath)
{
int32_t size = SD.getFileSize(filepath);
int32_t block = 128;
int32_t nL = size / block;
int32_t nR = size % block;
int32_t index = 0;
// show file
USB.println(F("\n-------------------"));
USB.secureBegin();
for(int32_t i=0 ; i<nL ; i++)
{
SD.cat(filepath, index, block);
for (int j = 0; j < block; j++)
{
printByte(SD.buffer[j], 0);
}
index += block ;
}
SD.cat(filepath, index, nR);
for (int j = 0; j < nR; j++)
{
printByte(SD.buffer[j], 0);
}
USB.secureEnd();
USB.println(F("\n-------------------"));
}
/*
* showSD() -
*
* Display the contents of the selected SD card folder o file
*/
void WaspSD::menu(uint32_t timeout)
{
uint32_t previous;
char option;
int i = 0;
char filename[20];
// init SD card
SD.ON();
SD.goRoot();
// check if the card is there or not
if (!SD.isSD())
{
USB.println(F("No SD card inserted"));
return (void)0;
}
// get current time
previous = millis();
do
{
USB.println(F("\r\n------------------------- MENU -------------------------"));
USB.println(F("1: List files in current working directory"));
USB.println(F("2: Show file"));
USB.println(F("3: Change directory"));
USB.println(F("4: Go to Root directory"));
USB.println(F("9: Format SD"));
USB.println(F("--------------------------------------------------------"));
USB.print(F("\n==> Enter numeric option:"));
USB.flush();
// wait for incoming data from keyboard
while (!USB.available() && (millis()-previous < timeout));
// parse incoming bytes
if (USB.available() > 0)
{
previous = millis();
// get option number
option = USB.read();
USB.println(option);
USB.flush();
switch (option)
{
case '1':
SD.ls(LS_DATE | LS_SIZE | LS_R);
previous = millis();
break;
case '2':
// init vars
i = 0;
previous = millis();
memset(filename, 0x00, sizeof(filename));
USB.print(F("==> Enter name of file to read:"));
// wait for incoming data from keyboard
while (!USB.available() && (millis()-previous < timeout));
while (USB.available() > 0)
{
filename[i] = USB.read();
i++;
if (i >= sizeof(filename))
{
break;
}
}
USB.println(filename);
SD.showFile(filename);
previous = millis();
break;
case '3':
// init vars
i = 0;
previous = millis();
memset(filename, 0x00, sizeof(filename));
USB.print(F("==> Enter name of directory to change to:"));
// wait for incoming data from keyboard
while (!USB.available() && (millis()-previous < timeout));
while (USB.available() > 0)
{
filename[i] = USB.read();
i++;
if (i >= sizeof(filename))
{
break;
}
}
USB.println(filename);
SD.cd(filename);
previous = millis();
break;
case '4':
SD.goRoot();
previous = millis();
break;
case '9':
SD.format();
previous = millis();
break;
default:
break;
}
}
// Condition to avoid an overflow (DO NOT REMOVE)
if (millis() < previous) previous = millis();
} while (millis()-previous < timeout);
USB.println();
}
// Preinstantiate Objects //////////////////////////////////////////////////////
WaspSD SD = WaspSD();
| 23.867912 | 127 | 0.650177 | MahendraSondagar |
22fc45d7d1beb4bb0cad838f729daa87e94c159e | 7,108 | cpp | C++ | Samples/Client/DirectxUWP/DirectxClientComponent/Common/DeviceResources.cpp | rozele/3dtoolkit | a15fca73be15f96a165dd18e62180de693a5ab86 | [
"MIT"
] | null | null | null | Samples/Client/DirectxUWP/DirectxClientComponent/Common/DeviceResources.cpp | rozele/3dtoolkit | a15fca73be15f96a165dd18e62180de693a5ab86 | [
"MIT"
] | null | null | null | Samples/Client/DirectxUWP/DirectxClientComponent/Common/DeviceResources.cpp | rozele/3dtoolkit | a15fca73be15f96a165dd18e62180de693a5ab86 | [
"MIT"
] | null | null | null | #include "pch.h"
#include <Collection.h>
#include <windows.graphics.directx.direct3d11.interop.h>
#include "DeviceResources.h"
#include "DirectXHelper.h"
using namespace D2D1;
using namespace Microsoft::WRL;
using namespace Platform;
using namespace Windows::Foundation;
using namespace Windows::Graphics::DirectX::Direct3D11;
using namespace Windows::Graphics::Display;
using namespace Windows::Graphics::Holographic;
using namespace Windows::UI::Core;
// Constructor for DeviceResources.
DX::DeviceResources::DeviceResources() :
m_holographicSpace(nullptr),
m_supportsVprt(false)
{
CreateDeviceIndependentResources();
}
// Configures resources that don't depend on the Direct3D device.
void DX::DeviceResources::CreateDeviceIndependentResources()
{
// Initialize Direct2D resources.
D2D1_FACTORY_OPTIONS options;
ZeroMemory(&options, sizeof(D2D1_FACTORY_OPTIONS));
#if defined(_DEBUG)
// If the project is in a debug build, enable Direct2D debugging via SDK Layers.
options.debugLevel = D2D1_DEBUG_LEVEL_INFORMATION;
#endif
// Initialize the Direct2D Factory.
DX::ThrowIfFailed(
D2D1CreateFactory(
D2D1_FACTORY_TYPE_SINGLE_THREADED,
__uuidof(ID2D1Factory3),
&options,
&m_d2dFactory
)
);
// Initialize the DirectWrite Factory.
DX::ThrowIfFailed(
DWriteCreateFactory(
DWRITE_FACTORY_TYPE_SHARED,
__uuidof(IDWriteFactory3),
&m_dwriteFactory
)
);
}
// Configures the Direct3D device, and stores handles to it and the device context.
void DX::DeviceResources::CreateDeviceResources()
{
// Creates the Direct3D 11 API device object and a corresponding context.
ComPtr<ID3D11Device> device;
ComPtr<ID3D11DeviceContext> context;
// Init device and device context
D3D11CreateDevice(
m_dxgiAdapter.Get(),
D3D_DRIVER_TYPE_HARDWARE,
0,
D3D11_CREATE_DEVICE_BGRA_SUPPORT,
nullptr,
0,
D3D11_SDK_VERSION,
&device,
nullptr,
&context);
device.As(&m_d3dDevice);
context.As(&m_d3dContext);
// Acquires the DXGI interface for the Direct3D device.
ComPtr<IDXGIDevice3> dxgiDevice;
DX::ThrowIfFailed(
m_d3dDevice.As(&dxgiDevice)
);
// Wrap the native device using a WinRT interop object.
m_d3dInteropDevice = CreateDirect3DDevice(dxgiDevice.Get());
// Cache the DXGI adapter.
// This is for the case of no preferred DXGI adapter, or fallback to WARP.
ComPtr<IDXGIAdapter> dxgiAdapter;
DX::ThrowIfFailed(
dxgiDevice->GetAdapter(&dxgiAdapter)
);
DX::ThrowIfFailed(
dxgiAdapter.As(&m_dxgiAdapter)
);
DX::ThrowIfFailed(
m_d2dFactory->CreateDevice(dxgiDevice.Get(), &m_d2dDevice)
);
DX::ThrowIfFailed(
m_d2dDevice->CreateDeviceContext(
D2D1_DEVICE_CONTEXT_OPTIONS_NONE,
&m_d2dContext
)
);
}
void DX::DeviceResources::SetHolographicSpace(HolographicSpace^ holographicSpace)
{
// Cache the holographic space. Used to re-initalize during device-lost scenarios.
m_holographicSpace = holographicSpace;
InitializeUsingHolographicSpace();
}
void DX::DeviceResources::InitializeUsingHolographicSpace()
{
// The holographic space might need to determine which adapter supports
// holograms, in which case it will specify a non-zero PrimaryAdapterId.
LUID id =
{
m_holographicSpace->PrimaryAdapterId.LowPart,
m_holographicSpace->PrimaryAdapterId.HighPart
};
// When a primary adapter ID is given to the app, the app should find
// the corresponding DXGI adapter and use it to create Direct3D devices
// and device contexts. Otherwise, there is no restriction on the DXGI
// adapter the app can use.
if ((id.HighPart != 0) && (id.LowPart != 0))
{
UINT createFlags = 0;
#ifdef DEBUG
if (DX::SdkLayersAvailable())
{
createFlags |= DXGI_CREATE_FACTORY_DEBUG;
}
#endif
// Create the DXGI factory.
ComPtr<IDXGIFactory1> dxgiFactory;
DX::ThrowIfFailed(
CreateDXGIFactory2(
createFlags,
IID_PPV_ARGS(&dxgiFactory)
)
);
ComPtr<IDXGIFactory4> dxgiFactory4;
DX::ThrowIfFailed(dxgiFactory.As(&dxgiFactory4));
// Retrieve the adapter specified by the holographic space.
DX::ThrowIfFailed(
dxgiFactory4->EnumAdapterByLuid(
id,
IID_PPV_ARGS(&m_dxgiAdapter)
)
);
}
else
{
m_dxgiAdapter.Reset();
}
CreateDeviceResources();
m_holographicSpace->SetDirect3D11Device(m_d3dInteropDevice);
// Check for device support for the optional feature that allows setting
// the render target array index from the vertex shader stage.
D3D11_FEATURE_DATA_D3D11_OPTIONS3 options;
m_d3dDevice->CheckFeatureSupport(
D3D11_FEATURE_D3D11_OPTIONS3,
&options,
sizeof(options));
if (options.VPAndRTArrayIndexFromAnyShaderFeedingRasterizer)
{
m_supportsVprt = true;
}
}
// Validates the back buffer for each HolographicCamera and recreates
// resources for back buffers that have changed.
// Locks the set of holographic camera resources until the function exits.
void DX::DeviceResources::EnsureCameraResources(
HolographicFrame^ frame,
HolographicFramePrediction^ prediction)
{
UseHolographicCameraResources<void>([this, frame, prediction](std::map<UINT32, std::unique_ptr<CameraResources>>& cameraResourceMap)
{
for (HolographicCameraPose^ pose : prediction->CameraPoses)
{
HolographicCameraRenderingParameters^ renderingParameters = frame->GetRenderingParameters(pose);
CameraResources* pCameraResources = cameraResourceMap[pose->HolographicCamera->Id].get();
pCameraResources->CreateResourcesForBackBuffer(this, renderingParameters);
}
});
}
// Prepares to allocate resources and adds resource views for a camera.
// Locks the set of holographic camera resources until the function exits.
void DX::DeviceResources::AddHolographicCamera(HolographicCamera^ camera)
{
UseHolographicCameraResources<void>([this, camera](std::map<UINT32, std::unique_ptr<CameraResources>>& cameraResourceMap)
{
cameraResourceMap[camera->Id] = std::make_unique<CameraResources>(camera);
});
m_d3dRenderTargetSize = camera->RenderTargetSize;
}
// Deallocates resources for a camera and removes the camera from the set.
// Locks the set of holographic camera resources until the function exits.
void DX::DeviceResources::RemoveHolographicCamera(HolographicCamera^ camera)
{
UseHolographicCameraResources<void>([this, camera](std::map<UINT32, std::unique_ptr<CameraResources>>& cameraResourceMap)
{
CameraResources* pCameraResources = cameraResourceMap[camera->Id].get();
if (pCameraResources != nullptr)
{
pCameraResources->ReleaseResourcesForBackBuffer(this);
cameraResourceMap.erase(camera->Id);
}
});
}
// Present the contents of the swap chain to the screen.
// Locks the set of holographic camera resources until the function exits.
void DX::DeviceResources::Present(HolographicFrame^ frame)
{
// By default, this API waits for the frame to finish before it returns.
// Holographic apps should wait for the previous frame to finish before
// starting work on a new frame. This allows for better results from
// holographic frame predictions.
HolographicFramePresentResult presentResult = frame->PresentUsingCurrentPrediction(HolographicFramePresentWaitBehavior::DoNotWaitForFrameToFinish);
}
| 29.131148 | 148 | 0.770962 | rozele |
fe033aa598dc17ae2171f63cc50814b2ca3d56c1 | 1,394 | cpp | C++ | soj/4315.cpp | huangshenno1/project_euler | 8a3c91fd11bcb6a6a830e963b1d5aed3f5ff787d | [
"MIT"
] | null | null | null | soj/4315.cpp | huangshenno1/project_euler | 8a3c91fd11bcb6a6a830e963b1d5aed3f5ff787d | [
"MIT"
] | null | null | null | soj/4315.cpp | huangshenno1/project_euler | 8a3c91fd11bcb6a6a830e963b1d5aed3f5ff787d | [
"MIT"
] | null | null | null | #include <cstdio>
#include <cstring>
#include <cstdlib>
#include <ctime>
#include <climits>
#include <cmath>
#include <cassert>
#include <iostream>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <list>
#include <queue>
#include <stack>
#include <deque>
#include <algorithm>
using namespace std;
#define ll long long
#define pii pair<int, int>
#define fr first
#define sc second
#define mp make_pair
#define FOR(i,j,k) for(int i=j;i<=(k);i++)
#define FORD(i,j,k) for(int i=j;i>=(k);i--)
#define REP(i,n) for(int i=0;i<(n);i++)
const int maxn = 100005;
int n, a[maxn];
int dp[2][32][2];
int main()
{
while (scanf("%d", &n) == 1)
{
for (int i=1;i<=n;i++) scanf("%d", &a[i]);
bool flag = 0;
memset(dp[flag], 0, sizeof(dp[flag]));
ll ans = 0;
for (int i=1;i<=n;i++)
{
flag ^= 1;
memset(dp[flag], 0, sizeof(dp[flag]));
for (int j=0;j<32;j++)
for (int k=0;k<2;k++)
{
if ((a[i]>>j)&1) dp[flag][j][k^1] += dp[flag^1][j][k];
else dp[flag][j][k] += dp[flag^1][j][k];
}
for (int j=0;j<32;j++)
dp[flag][j][(a[i]>>j)&1]++;
for (int j=0;j<32;j++)
ans += (ll)dp[flag][j][1] << j;
}
printf("%lld\n", ans);
}
return 0;
}
| 23.233333 | 74 | 0.484218 | huangshenno1 |
fe03caba543e551b40eb40cb515eb6588cde5c41 | 1,603 | cpp | C++ | src/HighQueue/Message.cpp | dale-wilson/HSQueue | 04d01ed42707069d28e81b5494aba61904e6e591 | [
"BSD-3-Clause"
] | 2 | 2015-12-29T17:33:25.000Z | 2021-12-20T02:30:44.000Z | src/HighQueue/Message.cpp | dale-wilson/HighQueue | 04d01ed42707069d28e81b5494aba61904e6e591 | [
"BSD-3-Clause"
] | null | null | null | src/HighQueue/Message.cpp | dale-wilson/HighQueue | 04d01ed42707069d28e81b5494aba61904e6e591 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2014 Object Computing, Inc.
// All rights reserved.
// See the file license.txt for licensing information.
#include <Common/HighQueuePch.hpp>
#include "Message.hpp"
#include <HighQueue/details/HQMemoryBlockPool.hpp>
using namespace HighQueue;
Message::~Message()
{
try{
release();
}
catch(...)
{
//ignore this (sorry!)
}
}
void Message::set(HQMemoryBlockPool * container, size_t capacity, size_t offset, size_t used)
{
container_ = reinterpret_cast<byte_t *>(container);
capacity_ = (capacity == 0) ? used : capacity;
offset_ = offset;
used_ = used;
}
byte_t * Message::getContainer()const
{
return container_;
}
size_t Message::getOffset()const
{
return offset_;
}
void Message::release()
{
if(container_ != 0)
{
auto pool = reinterpret_cast<HQMemoryBlockPool *>(container_);
pool->release(*this);
}
}
void Message::reset()
{
container_ = 0;
capacity_ = 0;
offset_ = 0;
used_ = 0;
}
namespace
{
const char * messageTypeNames[] = {
"Unused",
"Shutdown",
"Heartbeat",
"MulticastPacket",
"Gap",
"MockMessage",
"LocalType0", "LocalType1", "LocalType2", "LocalType3",
"LocalType4", "LocalType5", "LocalType6", "LocalType7",
"ExtraTypeBase"
};
}
const char * Message::toText(Message::MessageType type)
{
auto index = size_t(type);
if(index, sizeof(messageTypeNames) / sizeof(messageTypeNames[0]))
{
return messageTypeNames[index];
}
return "MessageTypeOutOfRange";
}
| 19.54878 | 93 | 0.622583 | dale-wilson |
fe094de6b61b8f744ba80583d38cb3c435fd166f | 103 | hpp | C++ | libng/core/src/libng_core/net/packet.hpp | gapry/libng | 8fbf927e5bb73f105bddbb618430d3e1bf2cf877 | [
"MIT"
] | null | null | null | libng/core/src/libng_core/net/packet.hpp | gapry/libng | 8fbf927e5bb73f105bddbb618430d3e1bf2cf877 | [
"MIT"
] | null | null | null | libng/core/src/libng_core/net/packet.hpp | gapry/libng | 8fbf927e5bb73f105bddbb618430d3e1bf2cf877 | [
"MIT"
] | null | null | null | #pragma once
namespace libng {
class packet_header;
class packet {
public:
};
} // namespace libng
| 8.583333 | 20 | 0.708738 | gapry |
fe0e474b85c6744928713cb3c16d8dfb8b3b8a58 | 609 | cpp | C++ | Visual Studio 2010/Projects/bjarneStroustrupC++PartIV/bjarneStroustrupC++PartIV/Chapter25Exercise7.cpp | Ziezi/Programming-Principles-and-Practice-Using-C-by-Bjarne-Stroustrup- | 6fd64801863e883508f15d16398744405f4f9e34 | [
"Unlicense"
] | 9 | 2018-10-24T15:16:47.000Z | 2021-12-14T13:53:50.000Z | Visual Studio 2010/Projects/bjarneStroustrupC++PartIV/bjarneStroustrupC++PartIV/Chapter25Exercise7.cpp | ChrisBKirov/Programming-Principles-and-Practice-Using-C-by-Bjarne-Stroustrup- | 6fd64801863e883508f15d16398744405f4f9e34 | [
"Unlicense"
] | null | null | null | Visual Studio 2010/Projects/bjarneStroustrupC++PartIV/bjarneStroustrupC++PartIV/Chapter25Exercise7.cpp | ChrisBKirov/Programming-Principles-and-Practice-Using-C-by-Bjarne-Stroustrup- | 6fd64801863e883508f15d16398744405f4f9e34 | [
"Unlicense"
] | 7 | 2018-10-29T15:30:37.000Z | 2021-01-18T15:15:09.000Z | /*
TITLE Hex values in a range Chapter25Exercise7.cpp
COMMENT
Objective: Write out the hexadecimal values from 0 to 400;
and from -200 to 200.
Input: -
Output: -
Author: Chris B. Kirov
Date: 13.05.2017
*/
#include <iostream>
void print_hex(int from, int to)
{
for (int i = from; i < to; ++i)
{
std::cout << std::hex << i <<' ';
if(i % 8 == 0 && i != 0)
{
std::cout <<'\n';
}
}
std::cout <<'\n';
}
int main()
{
try
{
print_hex(0, 400);
print_hex(-200, 200);
}
catch(std::exception& e)
{
std::cerr << e.what();
exit(1);
}
getchar();
} | 14.853659 | 61 | 0.53202 | Ziezi |
fe0fd0786ef956959d2a7cbcf871208a3d1e55f6 | 1,158 | cpp | C++ | src/systems/EventLogger.cpp | pladams9/thirteenth-floor | d5a3c2733b1a6d767dd7d6b2fe8cf468f0f1f5ec | [
"MIT"
] | null | null | null | src/systems/EventLogger.cpp | pladams9/thirteenth-floor | d5a3c2733b1a6d767dd7d6b2fe8cf468f0f1f5ec | [
"MIT"
] | null | null | null | src/systems/EventLogger.cpp | pladams9/thirteenth-floor | d5a3c2733b1a6d767dd7d6b2fe8cf468f0f1f5ec | [
"MIT"
] | null | null | null | /*
* EventLogger.h
*
* Created on: Sep 24, 2019
* Author: pladams9
*/
#include <engine/Events.h>
#include <systems/EventLogger.h>
/* INCLUDES */
#include <sstream>
#include "Logger.h"
namespace TF
{
namespace Sys
{
/* METHOD DEFINITIONS */
EventLogger::EventLogger(Engine* eng) : System(eng)
{
this->_engine->RegisterFrameStartCallback
(
[this]() { this->Step(); }
);
this->_eventQueue.Listen("KEY_DOWN");
this->_eventQueue.Listen("KEY_UP");
this->_eventQueue.Listen("MOUSE_DOWN");
this->_eventQueue.Listen("MOUSE_UP");
}
void EventLogger::Step()
{
Event e;
while(this->_eventQueue.PollEvents(e))
{
std::stringstream log_msg;
if(e.GetEventType() == "KEY_DOWN") log_msg << "KEY_DOWN, Keycode: " << e.GetStringData("keycode");
if(e.GetEventType() == "KEY_UP") log_msg << "KEY_UP, Keycode: " << e.GetStringData("keycode");
if(e.GetEventType() == "MOUSE_DOWN") log_msg << "MOUSE_DOWN, x, y: " << e.GetStringData("x") << ", " << e.GetStringData("y");
if(e.GetEventType() == "MOUSE_UP") log_msg << "MOUSE_UP, x, y: " << e.GetStringData("x") << ", " << e.GetStringData("y");
LOGGER().Log(INFO, log_msg.str());
}
}
}
}
| 21.849057 | 127 | 0.642487 | pladams9 |
fe11fc1ec25703833a65d495c42cf0f0f78363e1 | 4,291 | hpp | C++ | examples/smith_waterman/smith_waterman.hpp | drichmond/HOPS | 9684c0c9ebe5511fe0c202219a0bcd51fbf61079 | [
"BSD-3-Clause"
] | 10 | 2018-10-03T09:19:48.000Z | 2021-09-15T14:46:32.000Z | examples/smith_waterman/smith_waterman.hpp | drichmond/HOPS | 9684c0c9ebe5511fe0c202219a0bcd51fbf61079 | [
"BSD-3-Clause"
] | 1 | 2019-09-24T17:38:25.000Z | 2019-09-24T17:38:25.000Z | examples/smith_waterman/smith_waterman.hpp | drichmond/HOPS | 9684c0c9ebe5511fe0c202219a0bcd51fbf61079 | [
"BSD-3-Clause"
] | null | null | null | // ----------------------------------------------------------------------
// Copyright (c) 2018, The Regents of the University of California 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 The Regents of the University of California
// 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 REGENTS OF THE
// UNIVERSITY OF CALIFORNIA 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.
// ----------------------------------------------------------------------
#ifndef __SMITH_WATERMAN_HPP
#define __SMITH_WATERMAN_HPP
#include <stdio.h>
#include <array>
#define MATCH 2
#define ALPHA 2
#define BETA 1
#define REF_LENGTH 32
#define READ_LENGTH 16
#define SW_HIST 2
typedef char base;
#ifdef BIT_ACCURATE
#include "ap_int.h"
typedef ap_uint<2> hw_base;
#else
typedef char hw_base;
#endif
template<typename T>
base randtobase(T IN){
switch(IN >> (8*sizeof(IN)-3)){
case 0:return 'a';
case 1:return 'c';
case 2:return 't';
case 3:return 'g';
default: return 'x';
}
}
struct toHwBase{
hw_base operator()(base const& IN) const{
#ifdef BIT_ACCURATE
switch(IN){
case 'a':
return 0;
case 'c':
return 1;
case 't':
return 2;
case 'g':
return 3;
default:
return 0;
}
#else
return IN;
#endif
}
} to_hw_base;
struct toSwBase{
base operator()(hw_base const& IN) const{
#ifdef BIT_ACCURATE
switch(IN){
case 0:
return 'a';
case 1:
return 'c';
case 2:
return 't';
case 3:
return 'g';
default:
return 'x';
}
#else
return IN;
#endif
}
} to_sw_base;
struct score{
char v, e, f;
};
struct sw_ref{
hw_base b;
bool last;
};
template<std::size_t LEN>
void print_top(char const& matid, std::array<char, LEN> const& top){
printf("%c", matid);
for (auto t : top) {
printf("%3c ", t);
}
printf("\n");
}
template<std::size_t LEN>
void print_top(char const& matid, std::array<sw_ref, LEN> const& top){
printf("%c", matid);
for (auto t : top) {
printf("%3c ", to_sw_base(t.b));
}
printf("\n");
}
template<std::size_t LEN>
void print_row(char const& matid, base const& lbase, std::array<score, LEN> const& row){
printf("%c", lbase);
for (auto r : row) {
switch(matid) {
case 'E':
printf("%3d ", r.e);
break;
case 'F':
printf("%3d ", r.f);
break;
case 'V':
printf("%3d ", r.v);
break;
default:
break;
}
}
printf("\n");
}
template<std::size_t SW, std::size_t W, std::size_t H, typename T>
void print_mat(char matid, std::array<base, H> left, std::array<T, W> top, matrix<score, SW, H> smatrix){
print_top(matid, top);
for(int j = 0; j < H; ++j){
print_row(matid, left[j], smatrix[j]);
}
printf("\n");
}
template<std::size_t SW, std::size_t W, std::size_t H, typename T>
void print_state(std::array<base, H> left, std::array<T, W> top, matrix<score, SW, H> smatrix){
print_mat('E', left, top, smatrix);
print_mat('F', left, top, smatrix);
print_mat('V', left, top, smatrix);
}
#endif //__SMITH_WATERMAN_HPP
| 24.380682 | 105 | 0.656024 | drichmond |
fe27f1eff0b3f4ba7dfe9da78c7ef5a79cc161b1 | 1,038 | cpp | C++ | command/remote/lib/light.cpp | Jeonghum/hfdpcpp11 | 5864973163991b58b89efa50ddfd75b201af2bed | [
"AFL-3.0"
] | 3 | 2018-12-18T03:44:23.000Z | 2019-11-20T20:45:43.000Z | command/remote/lib/light.cpp | Jeonghum/hfdpcpp11 | 5864973163991b58b89efa50ddfd75b201af2bed | [
"AFL-3.0"
] | 2 | 2018-04-07T06:36:23.000Z | 2018-04-08T13:35:38.000Z | command/remote/lib/light.cpp | Jeonghum/hfdpcpp11 | 5864973163991b58b89efa50ddfd75b201af2bed | [
"AFL-3.0"
] | 2 | 2018-05-30T11:14:14.000Z | 2021-04-18T22:38:48.000Z | //===--- light.cpp - --------------------------------------------*- C++ -*-===//
//
// Head First Design Patterns
//
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief
///
//===----------------------------------------------------------------------===//
//https://google.github.io/styleguide/cppguide.html#Names_and_Order_of_Includes
//dir2 / foo2.h.
#include "light.hpp"
//C system files.
//C++ system files.
#include <iostream>
//Other libraries' .h files.
//Your project's .h files.
namespace headfirst {
Light::Light( const std::string location) :
location_( location )
{
std::cout << "Light::Light" << std::endl;
}
void Light::TurnOn() const
{
std::cout << "Light::on" << std::endl;
std::cout << location_.c_str() << " light is on" << std::endl;
}
void Light::TurnOff() const
{
std::cout << "Light::off" << std::endl;
std::cout << location_.c_str() << " light is off" << std::endl;
}
} //namespace headfirst
| 24.139535 | 80 | 0.460501 | Jeonghum |
fe2a6ca2df3e22095a79de8b89077db32c9681c3 | 2,004 | cpp | C++ | test/IteratorMapTerminalOperationTest.cpp | cyr62110/fmpcxx | 6ff9433ffc7677cad59eb5601ab656f33c914199 | [
"Apache-2.0"
] | 1 | 2016-09-17T20:35:20.000Z | 2016-09-17T20:35:20.000Z | test/IteratorMapTerminalOperationTest.cpp | cyr62110/fmpcxx | 6ff9433ffc7677cad59eb5601ab656f33c914199 | [
"Apache-2.0"
] | 4 | 2016-10-05T10:33:14.000Z | 2016-10-06T18:31:09.000Z | test/IteratorMapTerminalOperationTest.cpp | cyr62110/fmpcxx | 6ff9433ffc7677cad59eb5601ab656f33c914199 | [
"Apache-2.0"
] | null | null | null | #include "catch.hpp"
#include "util/LightTestObject.h"
#include <fmrcxx/fmrcxx.h>
using namespace fmrcxx;
TEST_CASE( "check toMap with std::map", "[IteratorMapTerminalOperation]" ) {
LightTestObject::resetCounters();
std::map<std::string, int> map;
map["hello"] = 1;
map["world"] = 2;
std::map<std::string, LightTestObject> items = iterateOverMap(map)
.map<Tuple<std::string, LightTestObject>>([](Tuple<const std::string&, int&> value) {
return Tuple<std::string, LightTestObject>(value.getKey(), LightTestObject(value.getValue()));
})
.toMap<std::map>();
REQUIRE ( (*items.find("hello")).second.getValue() == 1 );
REQUIRE ( (*items.find("world")).second.getValue() == 2 );
REQUIRE ( items.size() == 2 );
REQUIRE ( LightTestObject::nbTimeMoveConstructorCalled >= 2 );
}
TEST_CASE( "check copy to map with std::map using raw pointer", "[IteratorMapTerminalOperation]" ) {
std::map<std::string, LightTestObject> map;
map.emplace("hello", 1);
map.emplace("world", 2);
LightTestObject::resetCounters();
auto items = iterateOverMap(map)
.copyToMap<std::map>();
REQUIRE ( (*items.find("hello")).second->getValue() == 1 );
REQUIRE ( (*items.find("hello")).second != &(*map.find("hello")).second );
REQUIRE ( items.size() == 2 );
REQUIRE ( LightTestObject::nbTimeCopyConstructorCalled == 2 );
REQUIRE ( LightTestObject::nbTimeMoveConstructorCalled == 0 );
REQUIRE ( LightTestObject::nbTimeDestructorCalled == 0 );
for (auto it = items.begin(); it != items.end(); it++) {
delete it->second;
}
}
/* FIXME Not working
TEST_CASE( "check copy to map with std::map using unique pointer", "[IteratorMapTerminalOperation]" ) {
std::map<std::string, LightTestObject> map;
map.emplace("hello", 1);
map.emplace("world", 2);
LightTestObject::resetCounters();
auto items = std::move(iterateOverMap(map)
.copyToMap<std::map, std::unique_ptr<LightTestObject>>());
REQUIRE ( (*items.find("hello")).second->getValue() == 1 );
REQUIRE ( items.size() == 2 );
}
*/
| 30.363636 | 103 | 0.676148 | cyr62110 |
fe32c4992d606789e6375a257615f9a50ab47a28 | 5,627 | cpp | C++ | c/meterpreter/source/extensions/mimikatz/modules/mod_hash.cpp | vaginessa/metasploit-payloads | 863414b652a98ab12ae15d90e6deed568d1b4030 | [
"PSF-2.0"
] | 264 | 2015-01-02T10:15:42.000Z | 2022-03-31T06:59:13.000Z | c/meterpreter/source/extensions/mimikatz/modules/mod_hash.cpp | vaginessa/metasploit-payloads | 863414b652a98ab12ae15d90e6deed568d1b4030 | [
"PSF-2.0"
] | 112 | 2015-01-02T01:26:38.000Z | 2021-11-21T02:07:21.000Z | c/meterpreter/source/extensions/mimikatz/modules/mod_hash.cpp | vaginessa/metasploit-payloads | 863414b652a98ab12ae15d90e6deed568d1b4030 | [
"PSF-2.0"
] | 130 | 2015-01-02T05:29:46.000Z | 2022-03-18T19:50:39.000Z | /* Benjamin DELPY `gentilkiwi`
http://blog.gentilkiwi.com
benjamin@gentilkiwi.com
Licence : http://creativecommons.org/licenses/by/3.0/fr/
*/
#include "mod_hash.h"
PSYSTEM_FUNCTION_006 mod_hash::SystemFunction006 = reinterpret_cast<PSYSTEM_FUNCTION_006>(GetProcAddress(GetModuleHandle(L"advapi32"), "SystemFunction006"));
PSYSTEM_FUNCTION_007 mod_hash::SystemFunction007 = reinterpret_cast<PSYSTEM_FUNCTION_007>(GetProcAddress(GetModuleHandle(L"advapi32"), "SystemFunction007"));
PRTL_UPCASE_UNICODE_STRING_TO_OEM_STRING mod_hash::RtlUpcaseUnicodeStringToOemString = reinterpret_cast<PRTL_UPCASE_UNICODE_STRING_TO_OEM_STRING>(GetProcAddress(GetModuleHandle(L"ntdll"), "RtlUpcaseUnicodeStringToOemString"));
PRTL_INIT_UNICODESTRING mod_hash::RtlInitUnicodeString = reinterpret_cast<PRTL_INIT_UNICODESTRING>(GetProcAddress(GetModuleHandle(L"ntdll"), "RtlInitUnicodeString"));
PRTL_FREE_OEM_STRING mod_hash::RtlFreeOemString = reinterpret_cast<PRTL_FREE_OEM_STRING>(GetProcAddress(GetModuleHandle(L"ntdll"), "RtlFreeOemString"));
bool mod_hash::lm(wstring * chaine, wstring * hash)
{
bool status = false;
UNICODE_STRING maChaine;
OEM_STRING maDestination;
BYTE monTab[16];
RtlInitUnicodeString(&maChaine, chaine->c_str());
if(NT_SUCCESS(RtlUpcaseUnicodeStringToOemString(&maDestination, &maChaine, TRUE)))
{
if(status = NT_SUCCESS(SystemFunction006(maDestination.Buffer, monTab)))
hash->assign(mod_text::stringOfHex(monTab, sizeof(monTab)));
RtlFreeOemString(&maDestination);
}
return status;
}
bool mod_hash::ntlm(wstring * chaine, wstring * hash)
{
bool status = false;
UNICODE_STRING maChaine;
BYTE monTab[16];
RtlInitUnicodeString(&maChaine, chaine->c_str());
if(status = NT_SUCCESS(SystemFunction007(&maChaine, monTab)))
hash->assign(mod_text::stringOfHex(monTab, sizeof(monTab)));
return status;
}
void mod_hash::getBootKeyFromKey(BYTE bootkey[0x10], BYTE key[0x10])
{
BYTE permut[] = {0x0b, 0x06, 0x07, 0x01, 0x08, 0x0a, 0x0e, 0x00, 0x03, 0x05, 0x02, 0x0f, 0x0d, 0x09, 0x0c, 0x04};
for(unsigned int i = 0; i < 0x10; i++)
bootkey[i] = key[permut[i]];
}
bool mod_hash::getHbootKeyFromBootKeyAndF(BYTE hBootKey[0x10], BYTE bootKey[0x10], BYTE * AccountsF)
{
bool reussite = false;
unsigned char qwe[] = "!@#$%^&*()qwertyUIOPAzxcvbnmQQQQQQQQQQQQ)(*@&%";
unsigned char num[] = "0123456789012345678901234567890123456789";
HCRYPTPROV hCryptProv = NULL;
HCRYPTHASH hHash = NULL;
if(CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
{
BYTE md5hash[0x10] = {0};
DWORD dwHashDataLen = sizeof(md5hash);
CryptCreateHash(hCryptProv, CALG_MD5, 0, 0, &hHash);
CryptHashData(hHash, AccountsF + 0x70, 0x10, 0);
CryptHashData(hHash, qwe, sizeof(qwe), 0);
CryptHashData(hHash, bootKey, 0x10, 0);
CryptHashData(hHash, num, sizeof(num), 0);
CryptGetHashParam(hHash, HP_HASHVAL, md5hash, &dwHashDataLen, 0);
CryptDestroyHash(hHash);
CryptReleaseContext(hCryptProv, 0);
reussite = mod_crypto::genericDecrypt(AccountsF + 0x80, 0x10, md5hash, 0x10, CALG_RC4, hBootKey, 0x10);
}
return reussite;
}
bool mod_hash::decryptHash(wstring * hash, BYTE * hBootKey, USER_V * userV, SAM_ENTRY * encHash, DWORD rid, bool isNtlm)
{
bool reussite = false;
unsigned char ntpassword[] = "NTPASSWORD";
unsigned char lmpassword[] = "LMPASSWORD";
BYTE obfkey[0x10];
BYTE mes2CleDES[0x10];
if(encHash->lenght == 0x10 + 4)
{
HCRYPTPROV hCryptProv = NULL;
HCRYPTHASH hHash = NULL;
if(CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
{
BYTE md5hash[0x10] = {0};
DWORD dwHashDataLen = 0x10;
CryptCreateHash(hCryptProv, CALG_MD5, 0, 0, &hHash);
CryptHashData(hHash, hBootKey, 0x10, 0);
CryptHashData(hHash, (BYTE *) &rid, sizeof(rid), 0);
CryptHashData(hHash, isNtlm ? ntpassword : lmpassword, isNtlm ? sizeof(ntpassword) : sizeof(lmpassword), 0);
CryptGetHashParam(hHash, HP_HASHVAL, md5hash, &dwHashDataLen, 0);
CryptDestroyHash(hHash);
CryptReleaseContext(hCryptProv, 0);
if(mod_crypto::genericDecrypt(&(userV->datas) + encHash->offset + 4, 0x10, md5hash, 0x10, CALG_RC4, obfkey, 0x10))
{
sid_to_key1(rid, mes2CleDES);
sid_to_key2(rid, mes2CleDES + 8);
reussite = mod_crypto::genericDecrypt(obfkey + 0, sizeof(obfkey) / 2, mes2CleDES + 0, sizeof(mes2CleDES) / 2, CALG_DES) &&
mod_crypto::genericDecrypt(obfkey + 8, sizeof(obfkey) / 2, mes2CleDES + 8, sizeof(mes2CleDES) / 2, CALG_DES);
}
}
}
hash->assign(reussite ? mod_text::stringOfHex(obfkey, sizeof(obfkey)) : L"");
return reussite;
}
void mod_hash::str_to_key(BYTE *str, BYTE *key)
{
key[0] = str[0] >> 1;
key[1] = ((str[0] & 0x01) << 6) | (str[1] >> 2);
key[2] = ((str[1] & 0x03) << 5) | (str[2] >> 3);
key[3] = ((str[2] & 0x07) << 4) | (str[3] >> 4);
key[4] = ((str[3] & 0x0f) << 3) | (str[4] >> 5);
key[5] = ((str[4] & 0x1f) << 2) | (str[5] >> 6);
key[6] = ((str[5] & 0x3f) << 1) | (str[6] >> 7);
key[7] = str[6] & 0x7f;
for (DWORD i = 0; i < 8; i++)
key[i] = (key[i] << 1);
}
void mod_hash::sid_to_key1(DWORD sid, BYTE deskey[8])
{
unsigned char s[7];
s[0] = s[4] = (unsigned char)((sid) & 0xff);
s[1] = s[5] = (unsigned char)((sid >> 8) & 0xff);
s[2] = s[6] = (unsigned char)((sid >>16) & 0xff);
s[3] = (unsigned char)((sid >>24) & 0xff);
str_to_key(s, deskey);
}
void mod_hash::sid_to_key2(DWORD sid, BYTE deskey[8])
{
unsigned char s[7];
s[0] = s[4] = (unsigned char)((sid >>24) & 0xff);
s[1] = s[5] = (unsigned char)((sid) & 0xff);
s[2] = s[6] = (unsigned char)((sid >> 8) & 0xff);
s[3] = (unsigned char)((sid >>16) & 0xff);
str_to_key(s, deskey);
}
| 37.264901 | 226 | 0.699662 | vaginessa |
fe36edc8d951d0a12f1b404f7c462eda01361e43 | 2,506 | cc | C++ | media/base/unaligned_shared_memory_unittest.cc | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | media/base/unaligned_shared_memory_unittest.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | media/base/unaligned_shared_memory_unittest.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright 2018 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.
#include "media/base/unaligned_shared_memory.h"
#include <stdint.h>
#include <string.h>
#include <limits>
#include "base/logging.h"
#include "base/macros.h"
#include "base/memory/shared_memory.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace media {
namespace {
const uint8_t kUnalignedData[] = "XXXhello";
const size_t kUnalignedDataSize = arraysize(kUnalignedData);
const off_t kUnalignedOffset = 3;
const uint8_t kData[] = "hello";
const size_t kDataSize = arraysize(kData);
base::SharedMemoryHandle CreateHandle(const uint8_t* data, size_t size) {
base::SharedMemory shm;
EXPECT_TRUE(shm.CreateAndMapAnonymous(size));
memcpy(shm.memory(), data, size);
return shm.TakeHandle();
}
} // namespace
TEST(UnalignedSharedMemoryTest, CreateAndDestroy) {
auto handle = CreateHandle(kData, kDataSize);
UnalignedSharedMemory shm(handle, true);
}
TEST(UnalignedSharedMemoryTest, CreateAndDestroy_InvalidHandle) {
base::SharedMemoryHandle handle;
UnalignedSharedMemory shm(handle, true);
}
TEST(UnalignedSharedMemoryTest, Map) {
auto handle = CreateHandle(kData, kDataSize);
UnalignedSharedMemory shm(handle, true);
ASSERT_TRUE(shm.MapAt(0, kDataSize));
EXPECT_EQ(0, memcmp(shm.memory(), kData, kDataSize));
}
TEST(UnalignedSharedMemoryTest, Map_Unaligned) {
auto handle = CreateHandle(kUnalignedData, kUnalignedDataSize);
UnalignedSharedMemory shm(handle, true);
ASSERT_TRUE(shm.MapAt(kUnalignedOffset, kDataSize));
EXPECT_EQ(0, memcmp(shm.memory(), kData, kDataSize));
}
TEST(UnalignedSharedMemoryTest, Map_InvalidHandle) {
base::SharedMemoryHandle handle;
UnalignedSharedMemory shm(handle, true);
ASSERT_FALSE(shm.MapAt(1, kDataSize));
EXPECT_EQ(shm.memory(), nullptr);
}
TEST(UnalignedSharedMemoryTest, Map_NegativeOffset) {
auto handle = CreateHandle(kData, kDataSize);
UnalignedSharedMemory shm(handle, true);
ASSERT_FALSE(shm.MapAt(-1, kDataSize));
}
TEST(UnalignedSharedMemoryTest, Map_SizeOverflow) {
auto handle = CreateHandle(kData, kDataSize);
UnalignedSharedMemory shm(handle, true);
ASSERT_FALSE(shm.MapAt(1, std::numeric_limits<size_t>::max()));
}
TEST(UnalignedSharedMemoryTest, UnmappedIsNullptr) {
auto handle = CreateHandle(kData, kDataSize);
UnalignedSharedMemory shm(handle, true);
ASSERT_EQ(shm.memory(), nullptr);
}
} // namespace media
| 28.804598 | 73 | 0.765363 | zipated |
fe397a962c6043d59cfceca626689e137d9d311d | 194 | cxx | C++ | Applications/ParaView/Documentation/ParaViewDocumentationInitializer.cxx | mathstuf/ParaView | e867e280545ada10c4ed137f6a966d9d2f3db4cb | [
"Apache-2.0"
] | 2 | 2019-09-27T08:04:34.000Z | 2019-10-16T22:30:54.000Z | Applications/ParaView/Documentation/ParaViewDocumentationInitializer.cxx | mathstuf/ParaView | e867e280545ada10c4ed137f6a966d9d2f3db4cb | [
"Apache-2.0"
] | null | null | null | Applications/ParaView/Documentation/ParaViewDocumentationInitializer.cxx | mathstuf/ParaView | e867e280545ada10c4ed137f6a966d9d2f3db4cb | [
"Apache-2.0"
] | 5 | 2016-04-14T13:42:37.000Z | 2021-05-22T04:59:42.000Z | #include "ParaViewDocumentationInitializer.h"
#include "vtkPVConfig.h"
#include <QObject>
#include <QtPlugin>
void PARAVIEW_DOCUMENTATION_INIT()
{
Q_INIT_RESOURCE(paraview_documentation);
}
| 17.636364 | 45 | 0.804124 | mathstuf |
fe3a669389e59c38d2010261d65786853a9c3950 | 33 | hpp | C++ | include/BESSCore/src/Renderer/Renderer.hpp | shivang51/BESS | 8c53c5cb13863fd05574ebf20bf57624d83b0d25 | [
"MIT"
] | null | null | null | include/BESSCore/src/Renderer/Renderer.hpp | shivang51/BESS | 8c53c5cb13863fd05574ebf20bf57624d83b0d25 | [
"MIT"
] | null | null | null | include/BESSCore/src/Renderer/Renderer.hpp | shivang51/BESS | 8c53c5cb13863fd05574ebf20bf57624d83b0d25 | [
"MIT"
] | null | null | null | #pragma once
#include "Quad.hpp" | 11 | 19 | 0.727273 | shivang51 |
fe3aa498e736eb6385f47787de0ffaada3844c92 | 29,671 | hpp | C++ | include/NP-Engine/Graphics/RHI/Vulkan/VulkanPipeline.hpp | naphipps/NP-Engine | 0cac8b2d5e76c839b96f2061bf57434bdc37915e | [
"MIT"
] | null | null | null | include/NP-Engine/Graphics/RHI/Vulkan/VulkanPipeline.hpp | naphipps/NP-Engine | 0cac8b2d5e76c839b96f2061bf57434bdc37915e | [
"MIT"
] | null | null | null | include/NP-Engine/Graphics/RHI/Vulkan/VulkanPipeline.hpp | naphipps/NP-Engine | 0cac8b2d5e76c839b96f2061bf57434bdc37915e | [
"MIT"
] | null | null | null | //##===----------------------------------------------------------------------===##//
//
// Author: Nathan Phipps 12/8/21
//
//##===----------------------------------------------------------------------===##//
#ifndef NP_ENGINE_VULKAN_PIPELINE_HPP
#define NP_ENGINE_VULKAN_PIPELINE_HPP
#include "NP-Engine/Filesystem/Filesystem.hpp"
#include "NP-Engine/Vendor/VulkanInclude.hpp"
#include "NP-Engine/Vendor/GlfwInclude.hpp"
#include "VulkanInstance.hpp"
#include "VulkanSurface.hpp"
#include "VulkanDevice.hpp"
#include "VulkanSwapchain.hpp"
#include "VulkanShader.hpp"
#include "VulkanVertex.hpp"
namespace np::graphics::rhi
{
class VulkanPipeline
{
private:
constexpr static siz MAX_FRAMES = 2;
VulkanSwapchain _swapchain;
container::vector<VulkanVertex> _vertices;
VkBuffer _vertex_buffer;
VkDeviceMemory _vertex_buffer_memory;
VulkanShader _vertex_shader;
VulkanShader _fragment_shader;
VkRenderPass _render_pass;
VkPipelineLayout _pipeline_layout;
VkPipeline _pipeline;
bl _rebuild_swapchain;
container::vector<VkFramebuffer> _framebuffers;
VkCommandPool _command_pool;
container::vector<VkCommandBuffer> _command_buffers;
siz _current_frame;
container::vector<VkSemaphore> _image_available_semaphores;
container::vector<VkSemaphore> _render_finished_semaphores;
container::vector<VkFence> _fences;
container::vector<VkFence> _image_fences;
static void WindowResizeCallback(void* pipeline, ui32 width, ui32 height)
{
((VulkanPipeline*)pipeline)->SetRebuildSwapchain();
((VulkanPipeline*)pipeline)->Draw(time::DurationMilliseconds(0));
}
VkPipelineShaderStageCreateInfo CreatePipelineShaderStageInfo()
{
VkPipelineShaderStageCreateInfo info{};
info.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
return info;
}
VkPipelineVertexInputStateCreateInfo CreatePipelineVertexInputStateInfo()
{
VkPipelineVertexInputStateCreateInfo info{};
info.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
return info;
}
VkPipelineInputAssemblyStateCreateInfo CreatePipelineInputAssemblyStateInfo()
{
VkPipelineInputAssemblyStateCreateInfo info{};
info.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
info.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
info.primitiveRestartEnable = VK_FALSE;
// TODO: it's possible to break up lines and triangles in the _STRIP topology modes by using a special index of
// 0xFFFF or 0xFFFFFFFF.
return info;
}
VkViewport CreateViewport()
{
VkViewport viewport{};
viewport.x = 0.0f;
viewport.y = 0.0f;
viewport.width = (flt)Swapchain().Extent().width;
viewport.height = (flt)Swapchain().Extent().height;
viewport.minDepth = 0.0f;
viewport.maxDepth = 1.0f;
return viewport;
}
VkRect2D CreateScissor()
{
VkRect2D scissor{};
scissor.offset = {0, 0};
scissor.extent = Swapchain().Extent();
return scissor;
}
VkPipelineViewportStateCreateInfo CreatePipelineViewportStateInfo()
{
VkPipelineViewportStateCreateInfo info{};
info.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
return info;
}
VkPipelineRasterizationStateCreateInfo CreatePipelineRasterizationStateInfo()
{
VkPipelineRasterizationStateCreateInfo info{};
info.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
/*
//TODO:
If depthClampEnable is set to VK_TRUE, then fragments that are beyond the near and far planes
are clamped to them as opposed to discarding them. This is useful in some special cases like
shadow maps. Using this requires enabling a GPU feature.
*/
info.depthClampEnable = VK_FALSE;
info.rasterizerDiscardEnable = VK_FALSE;
info.polygonMode = VK_POLYGON_MODE_FILL; // TODO: or VK_POLYGON_MODE_LINE or VK_POLYGON_MODE_POINT
info.lineWidth = 1.0f; // TODO: any larger value required enabling wideLines GPU feature
info.cullMode = VK_CULL_MODE_BACK_BIT;
info.frontFace = VK_FRONT_FACE_CLOCKWISE;
/*
//TODO:
The rasterizer can alter the depth values by adding a constant value or biasing them based on
a fragment's slope. This is sometimes used for shadow mapping, but we won't be using it.
Just set depthBiasEnable to VK_FALSE.
*/
info.depthBiasEnable = VK_FALSE;
info.depthBiasConstantFactor = 0.0f; // Optional
info.depthBiasClamp = 0.0f; // Optional
info.depthBiasSlopeFactor = 0.0f; // Optional
return info;
}
VkPipelineMultisampleStateCreateInfo CreatePipelineMultisampleStateInfo()
{
VkPipelineMultisampleStateCreateInfo info{};
info.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
info.sampleShadingEnable = VK_FALSE;
info.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
info.minSampleShading = 1.0f; // Optional
info.pSampleMask = nullptr; // Optional
info.alphaToCoverageEnable = VK_FALSE; // Optional
info.alphaToOneEnable = VK_FALSE; // Optional
return info;
}
VkPipelineColorBlendAttachmentState CreatePipelineColorBlendAttachmentState()
{
VkPipelineColorBlendAttachmentState state{};
state.colorWriteMask =
VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
state.blendEnable = VK_FALSE;
state.srcColorBlendFactor = VK_BLEND_FACTOR_ONE; // Optional
state.dstColorBlendFactor = VK_BLEND_FACTOR_ZERO; // Optional
state.colorBlendOp = VK_BLEND_OP_ADD; // Optional
state.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE; // Optional
state.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO; // Optional
state.alphaBlendOp = VK_BLEND_OP_ADD; // Optional
return state;
/*
//TODO:
The most common way to use color blending is to implement alpha blending, where we want
the new color to be blended with the old color based on its opacity
finalColor.rgb = newAlpha * newColor + (1 - newAlpha) * oldColor;
finalColor.a = newAlpha.a;
colorBlendAttachment.blendEnable = VK_TRUE;
colorBlendAttachment.srcColorBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA;
colorBlendAttachment.dstColorBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
colorBlendAttachment.colorBlendOp = VK_BLEND_OP_ADD;
colorBlendAttachment.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE;
colorBlendAttachment.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO;
colorBlendAttachment.alphaBlendOp = VK_BLEND_OP_ADD;
*/
}
VkPipelineColorBlendStateCreateInfo CreatePipelineColorBlendStateInfo()
{
VkPipelineColorBlendStateCreateInfo info{};
info.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
info.logicOpEnable = VK_FALSE;
info.logicOp = VK_LOGIC_OP_COPY; // Optional
info.blendConstants[0] = 0.0f; // Optional
info.blendConstants[1] = 0.0f; // Optional
info.blendConstants[2] = 0.0f; // Optional
info.blendConstants[3] = 0.0f; // Optional
return info;
}
container::vector<VkDynamicState> CreateDynamicStates()
{
return {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_LINE_WIDTH};
}
VkPipelineDynamicStateCreateInfo CreatePipelineDynamicStateInfo()
{
VkPipelineDynamicStateCreateInfo info{};
info.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
info.dynamicStateCount = 2;
// info.pDynamicStates = dynamicStates;
return info;
}
VkAttachmentDescription CreateAttachmentDescription()
{
VkAttachmentDescription desc{};
desc.format = Device().SurfaceFormat().format;
desc.samples = VK_SAMPLE_COUNT_1_BIT; // TODO: multisampling
// TODO: The loadOp and storeOp determine what to do with the data in the
// attachment before rendering and after rendering
desc.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
desc.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
// TODO: we don't do anything with the stencil buffer
desc.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
desc.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
desc.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
desc.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
return desc;
}
VkAttachmentReference CreateAttachmentReference()
{
VkAttachmentReference ref{};
ref.attachment = 0;
ref.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
return ref;
}
VkSubpassDescription CreateSubpassDescription()
{
VkSubpassDescription desc{};
desc.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
return desc;
}
VkRenderPassCreateInfo CreateRenderPassInfo()
{
VkRenderPassCreateInfo info{};
info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
return info;
}
VkGraphicsPipelineCreateInfo CreateGraphicsPipelineInfo()
{
VkGraphicsPipelineCreateInfo info{};
info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
return info;
}
container::vector<VkPipelineShaderStageCreateInfo> CreateShaderStages()
{
container::vector<VkPipelineShaderStageCreateInfo> stages;
VkPipelineShaderStageCreateInfo vertex_stage = CreatePipelineShaderStageInfo();
vertex_stage.stage = VK_SHADER_STAGE_VERTEX_BIT;
vertex_stage.module = _vertex_shader;
vertex_stage.pName = _vertex_shader.Entrypoint().c_str();
stages.emplace_back(vertex_stage);
VkPipelineShaderStageCreateInfo fragment_stage = CreatePipelineShaderStageInfo();
fragment_stage.stage = VK_SHADER_STAGE_FRAGMENT_BIT;
fragment_stage.module = _fragment_shader;
fragment_stage.pName = _fragment_shader.Entrypoint().c_str();
stages.emplace_back(fragment_stage);
return stages;
}
VkPipelineLayoutCreateInfo CreatePipelineLayoutInfo()
{
VkPipelineLayoutCreateInfo info{};
info.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
info.setLayoutCount = 0; // Optional
info.pSetLayouts = nullptr; // Optional
info.pushConstantRangeCount = 0; // Optional
info.pPushConstantRanges = nullptr; // Optional
return info;
}
VkFramebufferCreateInfo CreateFramebufferInfo()
{
VkFramebufferCreateInfo info{};
info.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
info.width = Swapchain().Extent().width;
info.height = Swapchain().Extent().height;
info.layers = 1;
return info;
}
VkCommandPoolCreateInfo CreateCommandPoolInfo()
{
VkCommandPoolCreateInfo info{};
info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
info.queueFamilyIndex = Device().QueueFamilyIndices().graphics.value();
info.flags = 0; // Optional
return info;
}
VkCommandBufferAllocateInfo CreateCommandBufferAllocateInfo()
{
VkCommandBufferAllocateInfo info{};
info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
info.commandPool = _command_pool;
info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
return info;
}
VkCommandBufferBeginInfo CreateCommandBufferBeginInfo()
{
VkCommandBufferBeginInfo info{};
info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
info.flags = 0; // Optional
info.pInheritanceInfo = nullptr; // Optional
return info;
}
VkRenderPassBeginInfo CreateRenderPassBeginInfo()
{
VkRenderPassBeginInfo info{};
info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
info.renderPass = _render_pass;
info.renderArea.offset = {0, 0};
info.renderArea.extent = Swapchain().Extent();
return info;
}
container::vector<VkClearValue> CreateClearValues()
{
container::vector<VkClearValue> values;
VkClearValue clear_color = {{{0.0f, 0.0f, 0.0f, 1.0f}}};
values.emplace_back(clear_color);
return values;
}
container::vector<VkSubpassDependency> CreateSubpassDependencies()
{
container::vector<VkSubpassDependency> dependencies{};
VkSubpassDependency dependency{};
dependency.srcSubpass = VK_SUBPASS_EXTERNAL;
dependency.dstSubpass = 0;
dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
dependency.srcAccessMask = 0;
dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
dependencies.emplace_back(dependency);
return dependencies;
}
VkBufferCreateInfo CreateBufferInfo()
{
VkBufferCreateInfo info{};
info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
info.usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT;
info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
return info;
}
VkMemoryAllocateInfo CreateMemoryAllocateInfo()
{
VkMemoryAllocateInfo info{};
info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
return info;
}
ui32 ChooseMemoryTypeIndex(ui32 type_filter, VkMemoryPropertyFlags property_flags)
{
VkPhysicalDeviceMemoryProperties memory_properties;
vkGetPhysicalDeviceMemoryProperties(Device().PhysicalDevice(), &memory_properties);
bl found = false;
ui32 memory_type_index = 0;
for (ui32 i = 0; i < memory_properties.memoryTypeCount; i++)
{
if ((type_filter & (1 << i)) &&
(memory_properties.memoryTypes[i].propertyFlags & property_flags) == property_flags)
{
found = true;
memory_type_index = i;
}
}
return found ? memory_type_index : -1;
}
VkRenderPass CreateRenderPass()
{
VkRenderPass render_pass = nullptr;
container::vector<VkAttachmentReference> attachment_references = {CreateAttachmentReference()};
VkSubpassDescription subpass_description = CreateSubpassDescription();
subpass_description.colorAttachmentCount = attachment_references.size();
subpass_description.pColorAttachments = attachment_references.data();
container::vector<VkSubpassDescription> subpass_descriptions = {subpass_description};
container::vector<VkAttachmentDescription> attachment_descriptions = {CreateAttachmentDescription()};
container::vector<VkSubpassDependency> subpass_dependencies = CreateSubpassDependencies();
VkRenderPassCreateInfo render_pass_info = CreateRenderPassInfo();
render_pass_info.attachmentCount = attachment_descriptions.size();
render_pass_info.pAttachments = attachment_descriptions.data();
render_pass_info.subpassCount = subpass_descriptions.size();
render_pass_info.pSubpasses = subpass_descriptions.data();
render_pass_info.dependencyCount = subpass_dependencies.size();
render_pass_info.pDependencies = subpass_dependencies.data();
if (vkCreateRenderPass(Device(), &render_pass_info, nullptr, &render_pass) != VK_SUCCESS)
{
render_pass = nullptr;
}
return render_pass;
}
VkPipelineLayout CreatePipelineLayout()
{
VkPipelineLayout pipeline_layout = nullptr;
VkPipelineLayoutCreateInfo pipeline_layout_info = CreatePipelineLayoutInfo();
if (vkCreatePipelineLayout(Device(), &pipeline_layout_info, nullptr, &pipeline_layout) != VK_SUCCESS)
{
pipeline_layout = nullptr;
}
return pipeline_layout;
}
VkPipeline CreatePipeline()
{
VkPipeline pipeline = nullptr;
if (_pipeline_layout != nullptr && _render_pass != nullptr)
{
container::vector<VkVertexInputBindingDescription> vertex_binding_descs = VulkanVertex::BindingDescriptions();
container::array<VkVertexInputAttributeDescription, 2> vertex_attribute_descs =
VulkanVertex::AttributeDescriptions();
VkPipelineVertexInputStateCreateInfo vertex_input_state_info = CreatePipelineVertexInputStateInfo();
vertex_input_state_info.vertexBindingDescriptionCount = (ui32)vertex_binding_descs.size();
vertex_input_state_info.pVertexBindingDescriptions = vertex_binding_descs.data();
vertex_input_state_info.vertexAttributeDescriptionCount = (ui32)vertex_attribute_descs.size();
vertex_input_state_info.pVertexAttributeDescriptions = vertex_attribute_descs.data();
container::vector<VkPipelineShaderStageCreateInfo> shader_stages = CreateShaderStages();
VkPipelineInputAssemblyStateCreateInfo input_assembly_state_info = CreatePipelineInputAssemblyStateInfo();
container::vector<VkViewport> viewports = {CreateViewport()};
container::vector<VkRect2D> scissors = {CreateScissor()};
VkPipelineViewportStateCreateInfo viewport_state_info = CreatePipelineViewportStateInfo();
viewport_state_info.viewportCount = viewports.size();
viewport_state_info.pViewports = viewports.data();
viewport_state_info.scissorCount = scissors.size();
viewport_state_info.pScissors = scissors.data();
VkPipelineRasterizationStateCreateInfo rasterization_state_info = CreatePipelineRasterizationStateInfo();
VkPipelineMultisampleStateCreateInfo multisample_state_info = CreatePipelineMultisampleStateInfo();
container::vector<VkPipelineColorBlendAttachmentState> color_blend_attachment_states = {
CreatePipelineColorBlendAttachmentState()};
VkPipelineColorBlendStateCreateInfo color_blend_state_info = CreatePipelineColorBlendStateInfo();
color_blend_state_info.attachmentCount = color_blend_attachment_states.size();
color_blend_state_info.pAttachments = color_blend_attachment_states.data();
VkGraphicsPipelineCreateInfo pipeline_info = CreateGraphicsPipelineInfo();
pipeline_info.stageCount = shader_stages.size();
pipeline_info.pStages = shader_stages.data();
pipeline_info.pVertexInputState = &vertex_input_state_info;
pipeline_info.pInputAssemblyState = &input_assembly_state_info;
pipeline_info.pViewportState = &viewport_state_info;
pipeline_info.pRasterizationState = &rasterization_state_info;
pipeline_info.pMultisampleState = &multisample_state_info;
pipeline_info.pDepthStencilState = nullptr; // Optional
pipeline_info.pColorBlendState = &color_blend_state_info;
pipeline_info.pDynamicState = nullptr; // Optional
pipeline_info.layout = _pipeline_layout;
pipeline_info.renderPass = _render_pass;
pipeline_info.subpass = 0;
pipeline_info.basePipelineHandle = VK_NULL_HANDLE; // Optional
pipeline_info.basePipelineIndex = -1; // Optional
if (vkCreateGraphicsPipelines(Device(), nullptr, 1, &pipeline_info, nullptr, &pipeline) != VK_SUCCESS)
{
pipeline = nullptr;
}
}
return pipeline;
}
container::vector<VkFramebuffer> CreateFramebuffers()
{
container::vector<VkFramebuffer> framebuffers(Swapchain().ImageViews().size());
for (siz i = 0; i < Swapchain().ImageViews().size(); i++)
{
container::vector<VkImageView> image_views = {Swapchain().ImageViews()[i]};
VkFramebufferCreateInfo framebuffer_info = CreateFramebufferInfo();
framebuffer_info.renderPass = _render_pass;
framebuffer_info.attachmentCount = image_views.size();
framebuffer_info.pAttachments = image_views.data();
if (vkCreateFramebuffer(Device(), &framebuffer_info, nullptr, &framebuffers[i]) != VK_SUCCESS)
{
framebuffers[i] = nullptr;
}
}
return framebuffers;
}
VkCommandPool CreateCommandPool()
{
VkCommandPool command_pool = nullptr;
VkCommandPoolCreateInfo command_pool_info = CreateCommandPoolInfo();
if (vkCreateCommandPool(Device(), &command_pool_info, nullptr, &command_pool) != VK_SUCCESS)
{
command_pool = nullptr;
}
return command_pool;
}
container::vector<VkCommandBuffer> CreateCommandBuffers()
{
container::vector<VkCommandBuffer> command_buffers(_framebuffers.size());
VkCommandBufferAllocateInfo command_buffer_allocate_info = CreateCommandBufferAllocateInfo();
command_buffer_allocate_info.commandBufferCount = (ui32)command_buffers.size();
if (vkAllocateCommandBuffers(Device(), &command_buffer_allocate_info, command_buffers.data()) != VK_SUCCESS)
{
command_buffers.clear();
}
for (siz i = 0; i < command_buffers.size(); i++)
{
VkCommandBufferBeginInfo command_buffer_begin_info = CreateCommandBufferBeginInfo();
if (vkBeginCommandBuffer(command_buffers[i], &command_buffer_begin_info) != VK_SUCCESS)
{
command_buffers.clear();
break;
}
container::vector<VkClearValue> clear_values = CreateClearValues();
VkRenderPassBeginInfo render_pass_begin_info = CreateRenderPassBeginInfo();
render_pass_begin_info.framebuffer = _framebuffers[i];
render_pass_begin_info.clearValueCount = clear_values.size();
render_pass_begin_info.pClearValues = clear_values.data();
container::vector<VkBuffer> vertex_buffers{_vertex_buffer};
container::vector<VkDeviceSize> offsets{0};
vkCmdBeginRenderPass(command_buffers[i], &render_pass_begin_info, VK_SUBPASS_CONTENTS_INLINE);
vkCmdBindPipeline(command_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, _pipeline);
vkCmdBindVertexBuffers(command_buffers[i], 0, (ui32)vertex_buffers.size(), vertex_buffers.data(),
offsets.data());
vkCmdDraw(command_buffers[i], (ui32)_vertices.size(), 1, 0, 0);
vkCmdEndRenderPass(command_buffers[i]);
if (vkEndCommandBuffer(command_buffers[i]) != VK_SUCCESS)
{
command_buffers.clear();
break;
}
}
return command_buffers;
}
container::vector<VkSemaphore> CreateSemaphores(siz count)
{
container::vector<VkSemaphore> semaphores(count);
for (siz i = 0; i < count; i++)
{
VkSemaphoreCreateInfo semaphore_info{};
semaphore_info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
if (vkCreateSemaphore(Device(), &semaphore_info, nullptr, &semaphores[i]) != VK_SUCCESS)
{
semaphores.clear();
break;
}
}
return semaphores;
}
container::vector<VkFence> CreateFences(siz count, bl initialize = true)
{
container::vector<VkFence> fences(count, nullptr);
if (initialize)
{
for (siz i = 0; i < count; i++)
{
VkFenceCreateInfo fence_info{};
fence_info.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
fence_info.flags = VK_FENCE_CREATE_SIGNALED_BIT;
if (vkCreateFence(Device(), &fence_info, nullptr, &fences[i]) != VK_SUCCESS)
{
fences.clear();
break;
}
}
}
return fences;
}
VkBuffer CreateVertexBuffer()
{
VkBuffer buffer = nullptr;
VkBufferCreateInfo buffer_info = CreateBufferInfo();
buffer_info.size = sizeof(_vertices[0]) * _vertices.size();
if (vkCreateBuffer(Device(), &buffer_info, nullptr, &buffer) != VK_SUCCESS)
{
buffer = nullptr;
}
return buffer;
}
VkDeviceMemory CreateVertexBufferMemory()
{
VkDeviceMemory buffer_memory = nullptr;
VkMemoryRequirements requirements;
vkGetBufferMemoryRequirements(Device(), _vertex_buffer, &requirements);
VkMemoryAllocateInfo allocate_info = CreateMemoryAllocateInfo();
allocate_info.allocationSize = requirements.size;
allocate_info.memoryTypeIndex = ChooseMemoryTypeIndex(
requirements.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
if (vkAllocateMemory(Device(), &allocate_info, nullptr, &buffer_memory) != VK_SUCCESS)
{
buffer_memory = nullptr;
}
else
{
vkBindBufferMemory(Device(), _vertex_buffer, buffer_memory, 0);
}
return buffer_memory;
}
void RebuildSwapchain()
{
SetRebuildSwapchain(false);
vkDeviceWaitIdle(Device());
vkFreeCommandBuffers(Device(), _command_pool, (ui32)_command_buffers.size(), _command_buffers.data());
for (auto framebuffer : _framebuffers)
vkDestroyFramebuffer(Device(), framebuffer, nullptr);
vkDestroyPipeline(Device(), _pipeline, nullptr);
vkDestroyPipelineLayout(Device(), _pipeline_layout, nullptr);
vkDestroyRenderPass(Device(), _render_pass, nullptr);
_swapchain.Rebuild();
_render_pass = CreateRenderPass();
_pipeline_layout = CreatePipelineLayout();
_pipeline = CreatePipeline();
_framebuffers = CreateFramebuffers();
_command_buffers = CreateCommandBuffers();
}
public:
VulkanPipeline(VulkanDevice& device):
_swapchain(device),
_vertices(3),
_vertex_buffer(CreateVertexBuffer()),
_vertex_buffer_memory(CreateVertexBufferMemory()),
_vertex_shader(Device(), fs::append(fs::append("Vulkan", "shaders"), "vertex.glsl"), VulkanShader::Type::VERTEX),
_fragment_shader(Device(), fs::append(fs::append("Vulkan", "shaders"), "fragment.glsl"),
VulkanShader::Type::FRAGMENT),
_render_pass(CreateRenderPass()),
_pipeline_layout(CreatePipelineLayout()),
_pipeline(CreatePipeline()),
_framebuffers(CreateFramebuffers()), // TODO: can we put this in a VulkanFramebuffer? I don't think so
_command_pool(CreateCommandPool()), // TODO: can we put this in a VulkanCommand_____?? maybe....?
_command_buffers(CreateCommandBuffers()),
_current_frame(0),
_image_available_semaphores(CreateSemaphores(MAX_FRAMES)),
_render_finished_semaphores(CreateSemaphores(MAX_FRAMES)),
_fences(CreateFences(MAX_FRAMES)),
_image_fences(CreateFences(Swapchain().Images().size(), false)),
_rebuild_swapchain(false)
{
Surface().Window().SetResizeCallback(this, WindowResizeCallback);
const container::vector<Vertex> vertices = {
{{0.0f, -0.5f}, {1.0f, 0.0f, 1.0f}}, {{0.5f, 0.5f}, {1.0f, 1.0f, 0.0f}}, {{-0.5f, 0.5f}, {0.0f, 1.0f, 1.0f}}};
siz data_size = sizeof(_vertices[0]) * _vertices.size();
void* data;
vkMapMemory(device, _vertex_buffer_memory, 0, data_size, 0, &data);
memcpy(data, vertices.data(), data_size);
vkUnmapMemory(device, _vertex_buffer_memory);
}
~VulkanPipeline()
{
vkDeviceWaitIdle(Device());
vkDestroyBuffer(Device(), _vertex_buffer, nullptr);
vkFreeMemory(Device(), _vertex_buffer_memory, nullptr);
for (VkSemaphore& semaphore : _render_finished_semaphores)
vkDestroySemaphore(Device(), semaphore, nullptr);
for (VkSemaphore& semaphore : _image_available_semaphores)
vkDestroySemaphore(Device(), semaphore, nullptr);
for (VkFence& fence : _fences)
vkDestroyFence(Device(), fence, nullptr);
vkDestroyCommandPool(Device(), _command_pool, nullptr);
for (auto framebuffer : _framebuffers)
vkDestroyFramebuffer(Device(), framebuffer, nullptr);
vkDestroyPipeline(Device(), _pipeline, nullptr);
vkDestroyPipelineLayout(Device(), _pipeline_layout, nullptr);
vkDestroyRenderPass(Device(), _render_pass, nullptr);
}
VulkanInstance& Instance() const
{
return _swapchain.Instance();
}
VulkanSurface& Surface() const
{
return _swapchain.Surface();
}
VulkanDevice& Device() const
{
return _swapchain.Device();
}
const VulkanSwapchain& Swapchain() const
{
return _swapchain;
}
const VulkanShader& VertexShader() const
{
return _vertex_shader;
}
const VulkanShader& FragmentShader() const
{
return _fragment_shader;
}
void SetRebuildSwapchain(bl rebuild_swapchain = true)
{
_rebuild_swapchain = rebuild_swapchain;
}
void Draw(time::DurationMilliseconds time_delta)
{
i32 width = 0;
i32 height = 0;
glfwGetFramebufferSize((GLFWwindow*)Surface().Window().GetNativeWindow(), &width, &height);
if (width == 0 || height == 0)
{
return;
}
vkWaitForFences(Device(), 1, &_fences[_current_frame], VK_TRUE, UI64_MAX);
ui32 image_index;
VkResult acquire_result = vkAcquireNextImageKHR(Device(), Swapchain(), UI64_MAX,
_image_available_semaphores[_current_frame], nullptr, &image_index);
if (acquire_result == VK_ERROR_OUT_OF_DATE_KHR)
{
RebuildSwapchain();
return;
}
else if (acquire_result != VK_SUCCESS && acquire_result != VK_SUBOPTIMAL_KHR)
{
NP_ASSERT(false, "vkAcquireNextImageKHR error");
}
// Check if a previous frame is using this image (i.e. there is its fence to wait on)
if (_image_fences[image_index] != nullptr)
{
vkWaitForFences(Device(), 1, &_image_fences[image_index], VK_TRUE, UI64_MAX);
}
// Mark the image as now being in use by this frame
_image_fences[image_index] = _fences[_current_frame];
container::vector<VkSemaphore> wait_semaphores{_image_available_semaphores[_current_frame]};
container::vector<VkPipelineStageFlags> wait_stages{VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT};
container::vector<VkSemaphore> signal_semaphores{_render_finished_semaphores[_current_frame]};
container::vector<VkSwapchainKHR> swapchains{Swapchain()};
VkSubmitInfo submit_info{};
submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submit_info.waitSemaphoreCount = wait_semaphores.size();
submit_info.pWaitSemaphores = wait_semaphores.data();
submit_info.pWaitDstStageMask = wait_stages.data();
submit_info.commandBufferCount = 1; // _command_buffers.size();
submit_info.pCommandBuffers = &_command_buffers[image_index];
submit_info.signalSemaphoreCount = signal_semaphores.size();
submit_info.pSignalSemaphores = signal_semaphores.data();
vkResetFences(Device(), 1, &_fences[_current_frame]);
if (vkQueueSubmit(Device().GraphicsDeviceQueue(), 1, &submit_info, _fences[_current_frame]) != VK_SUCCESS)
{
NP_ASSERT(false, "failed to submit draw command buffer!");
}
VkPresentInfoKHR present_info{};
present_info.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
present_info.waitSemaphoreCount = signal_semaphores.size();
present_info.pWaitSemaphores = signal_semaphores.data();
present_info.swapchainCount = swapchains.size();
present_info.pSwapchains = swapchains.data();
present_info.pImageIndices = &image_index;
present_info.pResults = nullptr; // Optional
VkResult present_result = vkQueuePresentKHR(Device().PresentDeviceQueue(), &present_info);
if (present_result == VK_ERROR_OUT_OF_DATE_KHR || present_result == VK_SUBOPTIMAL_KHR || _rebuild_swapchain)
{
RebuildSwapchain();
}
else if (present_result != VK_SUCCESS)
{
NP_ASSERT(false, "vkQueuePresentKHR error");
}
vkQueueWaitIdle(Device().PresentDeviceQueue());
_current_frame = (_current_frame + 1) % MAX_FRAMES;
}
operator VkPipeline() const
{
return _pipeline;
}
};
} // namespace np::graphics::rhi
#endif /* NP_ENGINE_VULKAN_PIPELINE_HPP */ | 33.64059 | 116 | 0.753497 | naphipps |
fe3d6f9a3c7e2fe50ec9304877198771bee83a2c | 2,026 | cpp | C++ | offline5/160101048_OA5_2.cpp | nitinkedia7/CS210-Data-Structures | 9e79d7f5fc7e11b02ca80ee8ab40f1343b428fe8 | [
"MIT"
] | null | null | null | offline5/160101048_OA5_2.cpp | nitinkedia7/CS210-Data-Structures | 9e79d7f5fc7e11b02ca80ee8ab40f1343b428fe8 | [
"MIT"
] | null | null | null | offline5/160101048_OA5_2.cpp | nitinkedia7/CS210-Data-Structures | 9e79d7f5fc7e11b02ca80ee8ab40f1343b428fe8 | [
"MIT"
] | 2 | 2020-08-31T14:25:42.000Z | 2020-08-31T19:06:43.000Z | // 160101048_OA5_2.cpp: Nitin Kedia
// Description: Calculation of number of inversions in array S using mergeSort
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
// Utility function for copying part to source array to dest array;
int *copyArray(int *src, int i, int j, int *dest) {
dest = new int[j-i+2]; // last element will be INT_MAX, so length is one more than required
int k;
for (k = i; k <= j; k++) {
dest[k-i] = src[k];
}
dest[k-i] = INT_MAX; // to simplify mergeArray, else we have to impose appropriate boundary conditions
return dest;
}
// mergeArray merges two sorted daughter arrays into a single sorted array
// we are passing inv (counter for inversion pairs) by reference
void mergeArray(int *array, int l, int p, int u, int *pInv) {
int *left, *right;
left = copyArray(array, l, p, left); // copying daughter arrays to be eventually copied back to parent array in proper order
right = copyArray(array, p+1, u, right);
int j = 0, k = 0;
for (int i = l; i <= u; i++) {
if (left[j] > right[k]) {
array[i] = right[k++];
(*pInv) += (p+1-l)-j; // each time a element x from right array is copied to main array instead of all other elements of left array
// we get n unique inversion pairs where n = number of remaining elements in left array
}
else array[i] = left[j++];
}
}
// mergeSort uses divide and conquer steps
void mergeSort(int *array, int l, int u, int *pInv) {
if (l < u) {
int p = (l+u)/2;
mergeSort(array, p+1, u, pInv); // recursively sort right part
mergeSort(array, l, p, pInv); // recursively sort left part
mergeArray(array, l, p, u, pInv); // merge left and right part
}
}
int main() {
cout << "Enter input:" << endl;
int n;
cin >> n;
if (n <= 0) return 0;
int array[n];
for (int i = 0; i < n; i++) {
cin >> array[i];
}
int inv = 0; // initialise number of inversions with 0 and pass it by reference to merge steps
mergeSort(array, 0, n-1, &inv);
cout << inv << endl; // print number of inversions
} | 33.766667 | 134 | 0.652024 | nitinkedia7 |
fe3d9919a750669b1b6838020b96b55eed484d4c | 4,650 | cpp | C++ | la-test.cpp | busysteve/la | bcd53b1676ef91d93ba6a1e606b5098a5712a293 | [
"MIT"
] | 1 | 2020-05-25T05:28:10.000Z | 2020-05-25T05:28:10.000Z | la-test.cpp | busysteve/dsp | 1a80f719c7af38beafdf7656f19690783ae5b00e | [
"Apache-2.0"
] | null | null | null | la-test.cpp | busysteve/dsp | 1a80f719c7af38beafdf7656f19690783ae5b00e | [
"Apache-2.0"
] | null | null | null |
#include <iostream>
#include <fstream>
#include <vector>
#include <complex>
#include <string>
#include <cstring>
#include <cmath>
#include <float.h>
#include "tnt/tnt.h"
#include <initializer_list>
#include "Signal.h"
#include "la.h"
template <typename T> int VectorTest()
{
const double PI = 3.141592653589793238463;
const double PI2 = PI * 2.0;
{
cout << "Vector tests:" << endl;
Vector<T> v1( { (T)13.0, (T)-12.0, (T)2.0 } );
Vector<T> v2( { (T)14.0, (T)15.0, (T)-3.0 } );
T s1 = (T)23.0;
cout << v1 << " dot " << v2 << " = " << v1.dot( v2 ) << endl;
cout << v1 << " mul " << v2 << " = " << v1.mul( v2 ) << endl;
cout << v1 << " div " << v2 << " = " << v1.div( v2 ) << endl;
cout << v1 << " add " << v2 << " = " << v1.add( v2 ) << endl;
cout << v1 << " sub " << v2 << " = " << v1.sub( v2 ) << endl;
cout << v1 << " mul " << s1 << " = " << v1.mul( s1 ) << endl;
cout << v1 << " div " << s1 << " = " << v1.div( s1 ) << endl;
cout << v1 << " add " << s1 << " = " << v1.add( s1 ) << endl;
cout << v1 << " sub " << s1 << " = " << v1.sub( s1 ) << endl;
cout << v1 << " * " << v2 << " = " << v1 * v2 << endl;
cout << s1 << " * " << v2 << " = " << s1 * v2 << endl;
cout << v1 << " * " << s1 << " = " << v1 * s1 << endl;
cout << v1 << " / " << v2 << " = " << v1 / v2 << endl;
cout << s1 << " / " << v2 << " = " << s1 / v2 << endl;
cout << v1 << " / " << s1 << " = " << v1 / s1 << endl;
cout << v1 << " + " << v2 << " = " << v1 + v2 << endl;
cout << s1 << " + " << v2 << " = " << s1 + v2 << endl;
cout << v1 << " + " << s1 << " = " << v1 + s1 << endl;
cout << v1 << " - " << v2 << " = " << v1 - v2 << endl;
cout << s1 << " - " << v2 << " = " << s1 - v2 << endl;
cout << v1 << " - " << s1 << " = " << v1 - s1 << endl;
cout << v1 << " negated = " << -v1 << endl;
Vector<T> v3( 3, (T)1.0 );
Vector<T> v4( 4, (T)2.0 );
cout << v3.dot( v4 ) << endl;
}
{
cout << endl << "Matrix * Matrix tests:" << endl;
Matrix<T> mA( { { 5.0, 34.0, -28.0 },
{ 8.0, -83.4, 71.7 },
{ 92.6, 23.3, 9.2 } }
);
Matrix<T> mB( { { 56.0, 26.0, 4.3 },
{ 6.5, 33.4, 5.6 },
{ 8.4, 1.9, 2.3 } }
);
Matrix<T> mC( { { 5.0, 34.0, -28.0 },
{ 8.0, -83.4, 71.7 },
{ 83.4, 4.3, 71.7 },
{ 92.6, 23.3, 9.2 } }
);
try{
cout << mA << " + " << mC << " = " << mA + mC << endl << endl;
} catch ( linear_algebra_error e )
{
cerr << endl << e.what() << endl;
}
Matrix<T> m3( { { 5.0, 34.0, -28.0 },
{ 8.0, -83.4, 71.7 },
{ 83.4, 4.3, 71.7 },
{ 92.6, 23.3, 9.2 } }
);
Matrix<T> m4( { { 56.0, 26.0 },
{ 6.5, 33.4 },
{ 8.4, 1.9 } }
);
cout << m3 << " * " << m4 << " = " << m3 * m4 << endl;
Matrix<T> m1( { { 34.0, -28.0 },
{ -83.4, 71.7 },
{ 83.4, 71.7 },
{ 92.6, 23.3 } }
);
Matrix<T> m2( { { 56.0, 26.0 },
{ 8.4, 1.9 } }
);
cout << m1 << " * " << m2 << " = " << m1 * m2 << endl;
m3.print() << endl;
m3.transpose();
m3.print() << endl;
//cout << m1 << " / " << m2 << " = " << m1 / m2 << endl;
cout << endl << "Matrix * Vector tests:" << endl;
Matrix<T> m5( { { 34.0, -28.0 },
{ -83.4, 71.7 },
{ 92.6, 23.3 } }
);
Vector<T> v1( { 23.4, 45.6 } );
Vector<T> v2( { 23.4, 45.6, 77.0 } );
try
{
cout << m5 << " * " << v1 << " = " << m5 * v1 << endl << endl;
cout << m5 << " * " << v2 << " = " << m5 * v2 << endl << endl;
}
catch( linear_algebra_error e )
{
cerr << endl << e.what() << endl;
}
Matrix<T> a( {{2,3},{4,5},{4,5}} );
Vector<T> b( {6,7} );
cout << endl << a << " * " << b << " = " << a * b << endl;
double framerate = 11025.0;
Vector<T> amps( {0.6,0.25,0.1,0.05} );
Vector<T> fs( {300.0,400.0,500.0,600.0} );
Vector<T> ts;
for( double t=0.0; t <1.0; t += 1.0/framerate)
ts.push_back(t);
cout << endl << amps << " * " << fs << " = " << amps * fs << endl;
//cout << endl << ts << endl;
//cout << endl << ts << " * " << fs << " = " << ts * fs << endl;
auto args = ts.outer(fs);
auto M = args;
M.func( [&]( T x ){ return std::cos( PI2 * x); } );
cout << endl << M << endl;
auto ys = M * amps;
cout << endl << ys << endl << ys.size() << endl;
cout << endl << ys[1000] << endl << endl;
Wave wav( framerate, 16 );
wav.setsignal(ys, 100.0);
wav.write( "quad-tone.wav" );
std::complex<T> c1( 0, 1 );
auto z = std::exp( c1 * 1.5 );
std::cout << z << std::endl;
}
return 0;
}
int main()
{
VectorTest<double>();
return 0;
}
| 21.933962 | 68 | 0.389032 | busysteve |
fe3fa1da32bf3d13e13d1cabf783ce4bb74c1cc5 | 805 | cc | C++ | content/browser/child_process_launcher_browsertest.cc | kjthegod/chromium | cf940f7f418436b77e15b1ea23e6fa100ca1c91a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2019-11-28T10:46:52.000Z | 2019-11-28T10:46:52.000Z | content/browser/child_process_launcher_browsertest.cc | kjthegod/chromium | cf940f7f418436b77e15b1ea23e6fa100ca1c91a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | content/browser/child_process_launcher_browsertest.cc | kjthegod/chromium | cf940f7f418436b77e15b1ea23e6fa100ca1c91a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2015-03-27T11:15:39.000Z | 2016-08-17T14:19:56.000Z | // Copyright 2014 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.
#include "base/command_line.h"
#include "content/public/common/content_switches.h"
#include "content/public/test/content_browser_test.h"
#include "content/public/test/content_browser_test_utils.h"
namespace content {
typedef ContentBrowserTest ChildProcessLauncherBrowserTest;
class StatsTableBrowserTest : public ChildProcessLauncherBrowserTest {
public:
void SetUpCommandLine(base::CommandLine* command_line) override {
command_line->AppendSwitch(switches::kEnableStatsTable);
}
};
IN_PROC_BROWSER_TEST_F(StatsTableBrowserTest, StartWithStatTable) {
NavigateToURL(shell(), GURL("about:blank"));
}
} // namespace content
| 30.961538 | 73 | 0.797516 | kjthegod |
fe4335c2f43990f89ab3b3b4137f1d35ca8cae3f | 5,472 | cpp | C++ | examples/livelocation.cpp | Sil3ntStorm/libtelegram | a0c52ba4aac5519a3031dba506ad4a64cd8fca83 | [
"MIT"
] | 118 | 2016-10-02T10:49:02.000Z | 2022-03-23T14:32:05.000Z | examples/livelocation.cpp | Sil3ntStorm/libtelegram | a0c52ba4aac5519a3031dba506ad4a64cd8fca83 | [
"MIT"
] | 21 | 2017-04-21T13:34:36.000Z | 2021-12-08T17:00:40.000Z | examples/livelocation.cpp | Sil3ntStorm/libtelegram | a0c52ba4aac5519a3031dba506ad4a64cd8fca83 | [
"MIT"
] | 35 | 2016-06-08T15:31:03.000Z | 2022-03-23T16:43:28.000Z | /// This example demonstrates a bot that accepts two locations, and then sends
/// a live location interpolating smoothly between the two.
/// As this is a very simple example, it does not keep track of multiple users,
/// so should only be used by one user at a time.
/// It could be extended to support multiple users by tracking each user's
/// status along with user ID, with a separate thread running to update the live
/// locations for each.
#include <libtelegram/libtelegram.h>
auto main()->int {
std::string const token("123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11");
telegram::sender sender(token);
telegram::listener::poll listener(sender);
auto lerp = [](float from, float to, float coefficient){ // helper function to linearly interpolate
return from + coefficient * (to - from);
};
std::optional<telegram::types::location> first_location; // cache our first location, when it arrives
std::optional<telegram::types::location> second_location; // cache our second location, when it arrives
listener.set_callback_message([&](telegram::types::message const &message){
auto const message_chat_id = message.chat.id;
if(!first_location) { // we haven't received any locations yet from the user
if(!message.location) { // early exit if this message doesn't contain a location
sender.send_message(message_chat_id, "Send me the first location.");
return;
}
first_location = message.location; // cache the first location
sender.send_message(message_chat_id,
"Interpolating from " +
std::to_string(first_location->latitude) + ", " +
std::to_string(first_location->longitude) + ".\n"
"Send me the second location.");
} else { // we already received the first location, so we want the second
if(!message.location) { // early exit if this message doesn't contain a location
sender.send_message(message_chat_id, "Send me the second location.");
return;
}
second_location = message.location; // cache the second location
sender.send_message(message_chat_id,
"Interpolating from " +
std::to_string(first_location->latitude) + ", " +
std::to_string(first_location->longitude) + " to " +
std::to_string(second_location->latitude) + ", " +
std::to_string(second_location->longitude) + "...\n");
unsigned int constexpr const live_location_period = 60; // time in seconds
unsigned int constexpr const seconds_per_update = 2; // don't flood with updates too frequently
auto const location_message = sender.send_location(message_chat_id, // send the initial location first, we'll then update it. This function returns the message we sent, we'll need its id to update it
*first_location,
live_location_period); // minimum 60, maximum 86400
if(!location_message || !location_message->location) { // error checking: make sure we got back a message with a correctly sent location
sender.send_message(message_chat_id, "Something went wrong - unable to send back that first location!");
return;
}
auto sent_message_id = location_message->message_id; // this is the message id of the location message we're updating
unsigned int constexpr const steps = live_location_period / seconds_per_update;
for(unsigned int step = 0; step != steps; ++step) {
float coefficient = static_cast<float>(step) / steps;
telegram::types::location const interpolated_location{
lerp(first_location->latitude, second_location->latitude, coefficient),
lerp(first_location->longitude, second_location->longitude, coefficient)
};
std::cout << "DEBUG: updating message id " << sent_message_id << std::endl;
auto const updated_message = sender.edit_message_live_location(message_chat_id, // update the live location - we need both the chat id and...
sent_message_id, // ...the message id we're updating
interpolated_location);
//sent_message_id = updated_message->message_id;
using namespace std::chrono_literals; // to let us use the "seconds" literal
std::this_thread::sleep_for(1s * seconds_per_update); // sleep this thread until it's time to send the next message
}
}
});
listener.set_num_threads(1); // run single-threaded
listener.run(); // launch the listener - this call blocks until interrupted
return EXIT_SUCCESS;
};
| 64.376471 | 212 | 0.572917 | Sil3ntStorm |
1cfb6e5ac6be776790882c66d9bfdc5e29489ab2 | 21,294 | cpp | C++ | src/mplfe/bc_input/src/bc_class.cpp | MapleSystem/OpenArkCompiler | fc250857642ca38ac8b83ae7486513fadf3ab742 | [
"MulanPSL-1.0"
] | 5 | 2019-09-02T04:44:52.000Z | 2021-11-08T12:23:51.000Z | src/mplfe/bc_input/src/bc_class.cpp | MapleSystem/OpenArkCompiler | fc250857642ca38ac8b83ae7486513fadf3ab742 | [
"MulanPSL-1.0"
] | 2 | 2020-07-21T01:22:01.000Z | 2021-12-06T08:07:16.000Z | src/mplfe/bc_input/src/bc_class.cpp | MapleSystem/OpenArkCompiler | fc250857642ca38ac8b83ae7486513fadf3ab742 | [
"MulanPSL-1.0"
] | 4 | 2019-09-02T04:46:52.000Z | 2020-09-10T11:30:03.000Z | /*
* Copyright (c) [2020-2021] Huawei Technologies Co.,Ltd.All rights reserved.
*
* OpenArkCompiler is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR
* FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "bc_class.h"
#include "global_tables.h"
#include "fe_utils_java.h"
#include "fe_utils.h"
#include "fe_manager.h"
#include "fe_options.h"
namespace maple {
namespace bc {
// ========== BCClassElem ==========
BCClassElem::BCClassElem(const BCClass &klassIn, uint32 acc, const std::string &nameIn, const std::string &descIn)
: klass(klassIn),
accessFlag(acc),
name(nameIn),
descriptor(descIn) {}
const std::string &BCClassElem::GetName() const {
return name;
}
const std::string &BCClassElem::GetDescription() const {
return descriptor;
}
uint32 BCClassElem::GetItemIdx() const {
return GetItemIdxImpl();
}
uint32 BCClassElem::GetIdx() const {
return GetIdxImpl();
}
uint32 BCClassElem::GetAccessFlag() const {
return accessFlag;
}
bool BCClassElem::IsStatic() const {
return IsStaticImpl();
}
const std::string &BCClassElem::GetClassName() const {
return klass.GetClassName(false);
}
GStrIdx BCClassElem::GetClassNameMplIdx() const {
return klass.GetClassNameMplIdx();
}
const BCClass &BCClassElem::GetBCClass() const {
return klass;
}
// ========== BCTryInfo ==========
void BCTryInfo::DumpTryCatchInfo(const std::unique_ptr<std::list<std::unique_ptr<BCTryInfo>>> &tryInfos) {
DEBUG_STMT(
for (const auto &tryInfo : *tryInfos) {
LogInfo::MapleLogger(kLlDbg) << "tryBlock: [" << std::hex << "0x" << tryInfo->GetStartAddr() << ", 0x" <<
tryInfo->GetEndAddr() << ")";
LogInfo::MapleLogger(kLlDbg) << " handler: ";
for (const auto &e : (*tryInfo->GetCatches())) {
LogInfo::MapleLogger(kLlDbg) << "0x" << e->GetHandlerAddr() << " ";
}
LogInfo::MapleLogger(kLlDbg) << std::endl;
})
}
// ========== BCClassMethod ==========
void BCClassMethod::SetMethodInstOffset(const uint16 *pos) {
instPos = pos;
}
void BCClassMethod::SetRegisterTotalSize(uint16 size) {
registerTotalSize = size;
}
uint16 BCClassMethod::GetRegisterTotalSize() const{
return registerTotalSize;
}
void BCClassMethod::SetCodeOff(uint32 off) {
codeOff = off;
}
uint32 BCClassMethod::GetCodeOff() const {
return codeOff;
}
void BCClassMethod::SetRegisterInsSize(uint16 size) {
registerInsSize = size;
}
bool BCClassMethod::IsVirtual() const {
return IsVirtualImpl();
}
bool BCClassMethod::IsNative() const {
return IsNativeImpl();
}
bool BCClassMethod::IsInit() const {
return IsInitImpl();
}
bool BCClassMethod::IsClinit() const {
return IsClinitImpl();
}
std::string BCClassMethod::GetFullName() const {
return GetClassName() + "|" + GetName() + "|" + GetDescription();
}
void BCClassMethod::SetSrcPosInfo() {
#ifdef DEBUG
if ((FEOptions::GetInstance().IsDumpComment() || FEOptions::GetInstance().IsDumpLOC()) &&
pSrcPosInfo != nullptr) {
uint32 srcPos = 0;
for (auto &[pos, inst] : *pcBCInstructionMap) {
auto it = pSrcPosInfo->find(pos);
if (it != pSrcPosInfo->end()) {
srcPos = it->second; // when pSrcPosInfo is valid, update srcPos
}
inst->SetSrcPositionInfo(klass.GetSrcFileIdx(), srcPos);
}
}
#endif
}
void BCClassMethod::ProcessInstructions() {
if (pcBCInstructionMap->empty()) {
return;
}
// some instructions depend on exception handler, so we process try-catch info first
ProcessTryCatch();
visitedPcSet.emplace(pcBCInstructionMap->begin()->first);
GStrIdx methodIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(namemangler::EncodeName(GetFullName()));
for (auto itor = pcBCInstructionMap->begin(); itor != pcBCInstructionMap->end();) {
BCInstruction *inst = itor->second;
inst->SetFuncNameIdx(methodIdx);
inst->Parse(*this);
++itor;
if (inst->IsConditionBranch() || inst->IsGoto() || inst->IsSwitch()) {
std::vector<uint32> targets = inst->GetTargets();
for (uint32 target : targets) {
auto it = pcBCInstructionMap->find(target);
CHECK_FATAL(it != pcBCInstructionMap->end(), "Invalid branch target 0x%x in method: %s",
target, GetFullName().c_str());
it->second->SetInstructionKind(kTarget);
if (visitedPcSet.emplace(target).second == false) {
multiInDegreeSet.emplace(target);
}
}
if (inst->IsSwitch() && itor != pcBCInstructionMap->end()) {
itor->second->SetInstructionKind(kTarget);
inst->SetDefaultTarget(itor->second);
}
}
if (itor == pcBCInstructionMap->end()) {
continue;
}
if (inst->IsFallThru()) {
if (visitedPcSet.emplace(itor->first).second == false) {
multiInDegreeSet.emplace(itor->first);
}
}
if (itor->second->IsReturn()) {
inst->SetReturnInst(itor->second);
}
}
SetSrcPosInfo();
if (FEOptions::GetInstance().GetTypeInferKind() == FEOptions::kLinearScan) {
TypeInfer();
}
}
void BCClassMethod::ProcessTryCatch() {
if (tryInfos == nullptr) {
return;
}
for (const auto &e : *tryInfos) {
uint32 tryStart = e->GetStartAddr();
uint32 tryEnd = e->GetEndAddr();
auto it = pcBCInstructionMap->find(tryStart);
CHECK_FATAL(it != pcBCInstructionMap->end(), "Invalid try start pos 0x%x in method: %s", tryStart,
GetFullName().c_str());
it->second->SetInstructionKind(kTryStart);
BCInstruction *inst = it->second;
auto it1 = pcBCInstructionMap->find(tryEnd);
if (tryStart == tryEnd) {
it->second->SetInstructionKind(kTryEnd);
} else if (it1 != pcBCInstructionMap->end()) {
--it1;
it1->second->SetInstructionKind(kTryEnd);
} else {
// behind the last instruction
pcBCInstructionMap->rbegin()->second->SetInstructionKind(kTryEnd);
}
// Calculate catchable instructions
std::list<BCInstruction*> catchableInsts;
while (it->second->GetPC() < tryEnd) {
it->second->SetCatchable();
if (it->second->IsCatchable()) {
catchableInsts.emplace_back(it->second);
}
++it;
if (it == pcBCInstructionMap->end()) {
break;
}
}
for (const auto &handler: *(e->GetCatches())) {
uint32 handlerPc = handler->GetHandlerAddr();
auto elem = pcBCInstructionMap->find(handlerPc);
CHECK_FATAL(elem != pcBCInstructionMap->end(), "Invalid catch pos 0x%x in method: %s", handlerPc,
GetFullName().c_str());
elem->second->SetInstructionKind(kCatch);
elem->second->SetExceptionType(handler->GetExceptionNameIdx());
inst->AddHandler(elem->second);
for (auto catchableInst : catchableInsts) {
catchableInst->AddHandlerTarget(handlerPc);
if (visitedPcSet.emplace(handlerPc).second == false) {
multiInDegreeSet.emplace(handlerPc);
}
}
}
}
}
// Use linear scan with SSA
// We insert phi behind the def in a edge before the dominance if the reg is alive under this dominance.
// A reg is default dead at its definition, we mark a reg alive only when it was used.
// And insert the reg def-type into `used alive types` if it is defined in a determinate type.
// We transfer reg live info through shared memory, record live-interval in dominancesMap and BCRegType::livesBegins.
// After a multi-in pos, we create a new TypeInferItem for a new live range.
// Insert `in-edge` into dominance `prevs`, for record complete reg use in circles by one pass.
void BCClassMethod::TypeInfer() {
std::set<uint32> visitedSet;
// [pc, [regNum, TypeInferItem*]]
std::list<std::pair<uint32, std::vector<TypeInferItem*>>> pcDefedRegsList;
// [pc, [regNum, TypeInferItem*]]
std::vector<std::vector<TypeInferItem*>> dominances((*pcBCInstructionMap).rbegin()->first + 1);
std::vector<TypeInferItem*> regTypeMap(registerTotalSize, nullptr);
for (auto ® : argRegs) {
regTypeMap[reg->regNum] = ConstructTypeInferItem(allocator, 0, reg.get(), nullptr);
regTypes.emplace_back(reg->regType);
}
visitedSet.emplace(0);
if (multiInDegreeSet.find(0) != multiInDegreeSet.end()) {
std::vector<TypeInferItem*> typeMap = ConstructNewRegTypeMap(allocator, 1, regTypeMap);
pcDefedRegsList.emplace_front(0, typeMap);
dominances[0] = typeMap;
} else {
pcDefedRegsList.emplace_front(0, regTypeMap);
}
Traverse(pcDefedRegsList, dominances, visitedSet);
PrecisifyRegType();
}
void BCClassMethod::Traverse(std::list<std::pair<uint32, std::vector<TypeInferItem*>>> &pcDefedRegsList,
std::vector<std::vector<TypeInferItem*>> &dominances, std::set<uint32> &visitedSet) {
while (!pcDefedRegsList.empty()) {
auto head = pcDefedRegsList.front();
pcDefedRegsList.pop_front();
BCInstruction *currInst = (*pcBCInstructionMap)[head.first];
std::vector<TypeInferItem*> nextRegTypeMap = head.second;
auto usedRegs = currInst->GetUsedRegs();
for (auto usedReg : *usedRegs) {
auto defedItem = nextRegTypeMap[usedReg->regNum];
CHECK_FATAL(defedItem != nullptr && defedItem->reg != nullptr,
"Cannot find Reg%u defination at 0x%x:0x%x in method %s",
usedReg->regNum, head.first, currInst->GetOpcode(), GetFullName().c_str());
usedReg->regValue = defedItem->reg->regValue;
usedReg->regType = defedItem->reg->regType;
currInst->SetRegTypeInTypeInfer();
// Make the reg alive when it used, live range [defPos, usePos]
usedReg->regTypeItem->SetPos(currInst->GetPC());
defedItem->InsertUniqueAliveType(nullptr, usedReg->regTypeItem);
}
auto defedRegs = currInst->GetDefedRegs();
auto exHandlerTargets = currInst->GetHandlerTargets();
uint32 next = currInst->GetPC() + currInst->GetWidth();
for (auto exHandlerTarget : exHandlerTargets) {
if (visitedSet.emplace(exHandlerTarget).second == false) {
auto &domIt = dominances[exHandlerTarget];
InsertPhi(domIt, nextRegTypeMap);
continue;
}
if ((multiInDegreeSet.find(exHandlerTarget) != multiInDegreeSet.end())) {
std::vector<TypeInferItem*> typeMap = ConstructNewRegTypeMap(allocator, exHandlerTarget + 1, nextRegTypeMap);
pcDefedRegsList.emplace_front(exHandlerTarget, typeMap);
dominances[exHandlerTarget] = typeMap;
} else {
pcDefedRegsList.emplace_front(exHandlerTarget, nextRegTypeMap);
}
Traverse(pcDefedRegsList, dominances, visitedSet);
}
for (auto defedReg : *defedRegs) {
TypeInferItem *item = ConstructTypeInferItem(allocator, currInst->GetPC() + 1, defedReg, nullptr);
nextRegTypeMap[defedReg->regNum] = item;
defedReg->regType->SetPos(currInst->GetPC());
regTypes.emplace_back(defedReg->regType);
}
if (currInst->IsFallThru() && next <= pcBCInstructionMap->rbegin()->first) {
if (visitedSet.emplace(next).second == false) {
auto &domIt = dominances[next];
InsertPhi(domIt, nextRegTypeMap);
} else {
if (multiInDegreeSet.find(next) != multiInDegreeSet.end()) {
std::vector<TypeInferItem*> typeMap = ConstructNewRegTypeMap(allocator, next + 1, nextRegTypeMap);
pcDefedRegsList.emplace_front(next, typeMap);
dominances[next] = typeMap;
} else {
pcDefedRegsList.emplace_front(next, nextRegTypeMap);
}
// Use stack to replace recursive call, avoid `call stack` overflow in long `fallthru` code.
// And `fallthu` instructions can not disrupt visit order.
if (currInst->IsConditionBranch() || currInst->IsSwitch()) {
Traverse(pcDefedRegsList, dominances, visitedSet);
}
}
}
auto normalTargets = currInst->GetTargets();
for (auto normalTarget : normalTargets) {
if (visitedSet.emplace(normalTarget).second == false) {
auto &domIt = dominances[normalTarget];
InsertPhi(domIt, nextRegTypeMap);
continue;
}
if (multiInDegreeSet.find(normalTarget) != multiInDegreeSet.end()) {
std::vector<TypeInferItem*> typeMap = ConstructNewRegTypeMap(allocator, normalTarget + 1, nextRegTypeMap);
pcDefedRegsList.emplace_front(normalTarget, typeMap);
dominances[normalTarget] = typeMap;
} else {
pcDefedRegsList.emplace_front(normalTarget, nextRegTypeMap);
}
Traverse(pcDefedRegsList, dominances, visitedSet);
}
}
}
void BCClassMethod::InsertPhi(const std::vector<TypeInferItem*> &dom, std::vector<TypeInferItem*> &src) {
for (auto &d : dom) {
if (d == nullptr) {
continue;
}
auto srcItem = src[d->reg->regNum];
if (srcItem == d) {
continue;
}
if (d->RegisterInPrevs(srcItem) == false) {
continue;
}
if (d->isAlive == false) {
continue;
}
CHECK_FATAL(srcItem != nullptr, "ByteCode RA error.");
for (auto ty : *(d->aliveUsedTypes)) {
ty->SetDom(true);
}
srcItem->InsertUniqueAliveTypes(d, d->aliveUsedTypes);
}
}
TypeInferItem *BCClassMethod::ConstructTypeInferItem(
MapleAllocator &alloc, uint32 pos, BCReg *bcReg, TypeInferItem *prev) {
TypeInferItem *item = alloc.GetMemPool()->New<TypeInferItem>(alloc, pos, bcReg, prev);
return item;
}
std::vector<TypeInferItem*> BCClassMethod::ConstructNewRegTypeMap(MapleAllocator &alloc, uint32 pos,
const std::vector<TypeInferItem*> ®TypeMap) {
std::vector<TypeInferItem*> res(regTypeMap.size(), nullptr);
size_t i = 0;
for (const auto &elem : regTypeMap) {
if (elem != nullptr) {
res[i] = ConstructTypeInferItem(alloc, pos, elem->reg, elem);
}
++i;
}
return res;
}
std::list<UniqueFEIRStmt> BCClassMethod::GenReTypeStmtsThroughArgs() const {
std::list<UniqueFEIRStmt> stmts;
for (const auto &argReg : argRegs) {
std::list<UniqueFEIRStmt> stmts0 = argReg->GenRetypeStmtsAfterDef();
for (auto &stmt : stmts0) {
stmts.emplace_back(std::move(stmt));
}
}
return stmts;
}
void BCClassMethod::PrecisifyRegType() {
for (auto elem : regTypes) {
elem->PrecisifyTypes();
}
}
std::list<UniqueFEIRStmt> BCClassMethod::EmitInstructionsToFEIR() const {
std::list<UniqueFEIRStmt> stmts;
if (!HasCode()) {
return stmts; // Skip abstract and native method, not emit it to mpl but mplt.
}
if (IsStatic() && GetName().compare("<clinit>") != 0) { // Not insert JAVA_CLINIT_CHECK in <clinit>
GStrIdx containerNameIdx = GetClassNameMplIdx();
uint32 typeID = UINT32_MAX;
if (FEOptions::GetInstance().IsAOT()) {
const std::string &mplClassName = GetBCClass().GetClassName(true);
int32 dexFileHashCode = GetBCClass().GetBCParser().GetFileNameHashId();
typeID = FEManager::GetTypeManager().GetTypeIDFromMplClassName(mplClassName, dexFileHashCode);
}
UniqueFEIRStmt stmt =
std::make_unique<FEIRStmtIntrinsicCallAssign>(INTRN_JAVA_CLINIT_CHECK,
std::make_unique<FEIRTypeDefault>(PTY_ref, containerNameIdx),
nullptr, typeID);
stmts.emplace_back(std::move(stmt));
}
std::map<uint32, FEIRStmtPesudoLabel2*> targetFEIRStmtMap;
std::list<FEIRStmtGoto2*> gotoFEIRStmts;
std::list<FEIRStmtSwitch2*> switchFEIRStmts;
std::list<UniqueFEIRStmt> retypeStmts = GenReTypeStmtsThroughArgs();
for (auto &stmt : retypeStmts) {
stmts.emplace_back(std::move(stmt));
}
for (const auto &elem : *pcBCInstructionMap) {
std::list<UniqueFEIRStmt> instStmts = elem.second->EmitToFEIRStmts();
for (auto &e : instStmts) {
if (e->GetKind() == kStmtPesudoLabel) {
targetFEIRStmtMap.emplace(static_cast<FEIRStmtPesudoLabel2*>(e.get())->GetPos(),
static_cast<FEIRStmtPesudoLabel2*>(e.get()));
}
if (e->GetKind() == kStmtGoto || e->GetKind() == kStmtCondGoto) {
gotoFEIRStmts.emplace_back(static_cast<FEIRStmtGoto2*>(e.get()));
}
if (e->GetKind() == kStmtSwitch) {
switchFEIRStmts.emplace_back(static_cast<FEIRStmtSwitch2*>(e.get()));
}
stmts.emplace_back(std::move(e));
}
}
LinkJumpTarget(targetFEIRStmtMap, gotoFEIRStmts, switchFEIRStmts); // Link jump target
return stmts;
}
void BCClassMethod::LinkJumpTarget(const std::map<uint32, FEIRStmtPesudoLabel2*> &targetFEIRStmtMap,
const std::list<FEIRStmtGoto2*> &gotoFEIRStmts,
const std::list<FEIRStmtSwitch2*> &switchFEIRStmts) {
for (auto &e : gotoFEIRStmts) {
auto target = targetFEIRStmtMap.find(e->GetTarget());
CHECK_FATAL(target != targetFEIRStmtMap.end(), "Cannot find the target for goto/condGoto");
e->SetStmtTarget(*(target->second));
}
for (auto &e : switchFEIRStmts) {
uint32 label = e->GetDefaultLabelIdx();
if (label != UINT32_MAX) {
auto defaultTarget = targetFEIRStmtMap.find(label);
CHECK_FATAL(defaultTarget != targetFEIRStmtMap.end(), "Cannot find the default target for Switch");
e->SetDefaultTarget(defaultTarget->second);
}
for (const auto &valueLabel : e->GetMapValueLabelIdx()) {
auto target = targetFEIRStmtMap.find(valueLabel.second);
CHECK_FATAL(target != targetFEIRStmtMap.end(), "Cannot find the target for Switch");
e->AddTarget(valueLabel.first, target->second);
}
}
}
void BCClassMethod::DumpBCInstructionMap() const {
// Only used in DEBUG manually
DEBUG_STMT(
uint32 idx = 0;
for (const auto &[pos, instPtr] : *pcBCInstructionMap) {
LogInfo::MapleLogger(kLlDbg) << "index: " << std::dec << idx++ << " pc: 0x" << std::hex << pos <<
" opcode: 0x" << instPtr->GetOpcode() << std::endl;
});
}
const uint16 *BCClassMethod::GetInstPos() const {
return instPos;
}
std::vector<std::unique_ptr<FEIRVar>> BCClassMethod::GenArgVarList() const {
return GenArgVarListImpl();
}
void BCClassMethod::GenArgRegs() {
return GenArgRegsImpl();
}
// ========== BCCatchInfo ==========
BCCatchInfo::BCCatchInfo(uint32 handlerAddrIn, const GStrIdx &argExceptionNameIdx, bool iscatchAllIn)
: handlerAddr(handlerAddrIn),
exceptionNameIdx(argExceptionNameIdx),
isCatchAll(iscatchAllIn) {}
// ========== BCClass ==========
void BCClass::SetSrcFileInfo(const std::string &name) {
srcFileNameIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(name);
srcFileIdx = FEManager::GetManager().RegisterSourceFileIdx(srcFileNameIdx);
}
void BCClass::SetSuperClasses(const std::list<std::string> &names) {
if (names.empty()) {
return; // No parent class
}
superClassNameList = names;
}
void BCClass::SetInterface(const std::string &name) {
interfaces.push_back(name);
}
void BCClass::SetAccFlag(uint32 flag) {
accFlag = flag;
}
void BCClass::SetField(std::unique_ptr<BCClassField> field) {
fields.push_back(std::move(field));
}
void BCClass::SetMethod(std::unique_ptr<BCClassMethod> method) {
std::lock_guard<std::mutex> lock(bcClassMtx);
methods.push_back(std::move(method));
}
void BCClass::InsertFinalStaticStringID(uint32 stringID) {
finalStaticStringID.push_back(stringID);
}
void BCClass::SetClassName(const std::string &classNameOrin) {
classNameOrinIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(classNameOrin);
classNameMplIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(namemangler::EncodeName(classNameOrin));
}
const std::unique_ptr<BCAnnotationsDirectory> &BCClass::GetAnnotationsDirectory() const {
return annotationsDirectory;
}
void BCClass::SetAnnotationsDirectory(std::unique_ptr<BCAnnotationsDirectory> annotationsDirectoryIn) {
annotationsDirectory = std::move(annotationsDirectoryIn);
}
std::vector<MIRConst*> BCClass::GetStaticFieldsConstVal() const {
return staticFieldsConstVal;
}
void BCClass::InsertStaticFieldConstVal(MIRConst *cst) {
staticFieldsConstVal.push_back(cst);
}
const std::string &BCClass::GetClassName(bool mapled) const {
return mapled ? GlobalTables::GetStrTable().GetStringFromStrIdx(classNameMplIdx) :
GlobalTables::GetStrTable().GetStringFromStrIdx(classNameOrinIdx);
}
const std::list<std::string> &BCClass::GetSuperClassNames() const {
return superClassNameList;
}
const std::vector<std::string> &BCClass::GetSuperInterfaceNames() const {
return interfaces;
}
std::string BCClass::GetSourceFileName() const {
return GlobalTables::GetStrTable().GetStringFromStrIdx(srcFileNameIdx);
}
GStrIdx BCClass::GetIRSrcFileSigIdx() const {
return irSrcFileSigIdx;
}
int32 BCClass::GetFileNameHashId() const {
return parser.GetFileNameHashId();
}
uint32 BCClass::GetAccessFlag() const {
return accFlag;
}
const std::vector<std::unique_ptr<BCClassField>> &BCClass::GetFields() const {
return fields;
}
std::vector<std::unique_ptr<BCClassMethod>> &BCClass::GetMethods() {
return methods;
}
} // namespace bc
} // namespace maple
| 35.372093 | 117 | 0.676435 | MapleSystem |
1cfee9f4d7acfd474e6662a128ee9c82f29fd60c | 7,667 | cpp | C++ | GlowWormEngine/src/gwBoxMesh.cpp | Flugschildkrote/GEII-Robot-Simulation | 2756e693fbc5ccba431b21224f9361705207b438 | [
"MIT"
] | null | null | null | GlowWormEngine/src/gwBoxMesh.cpp | Flugschildkrote/GEII-Robot-Simulation | 2756e693fbc5ccba431b21224f9361705207b438 | [
"MIT"
] | null | null | null | GlowWormEngine/src/gwBoxMesh.cpp | Flugschildkrote/GEII-Robot-Simulation | 2756e693fbc5ccba431b21224f9361705207b438 | [
"MIT"
] | null | null | null | #include "gwBoxMesh.h"
using namespace gwe;
gwe::gwBoxMesh::gwBoxMesh(const std::string &name, float width, float height, float depth) : gwPrimitiveShape(name), mWidth(width), mHeight(height), mDepth(depth)
{
}
gwe::gwBoxMesh::~gwBoxMesh()
{
}
float gwe::gwBoxMesh::getWidth(void) const { return mWidth; }
float gwe::gwBoxMesh::getHeight(void) const { return mHeight; }
float gwe::gwBoxMesh::getDepth(void) const { return mDepth; }
void gwe::gwBoxMesh::generateShape(void)
{
mVertices = new float[108];
mVerticesSize = 108;
mVerticesCount = 36;
mVerticesBytes = 108*sizeof(float);
float X = mWidth/2.0f; float Y = mHeight/2.0f; float Z = mDepth/2.0f;
mVertices[0] = -X; mVertices[1] = -Y; mVertices[2] = Z;
mVertices[3] = X; mVertices[4] = -Y; mVertices[5] = Z;
mVertices[6] = X; mVertices[7] = Y; mVertices[8] = Z;
mVertices[9] = -X; mVertices[10] = -Y; mVertices[11] = Z;
mVertices[12]= -X; mVertices[13] = Y; mVertices[14] = Z;
mVertices[15]= X; mVertices[16] = Y; mVertices[17] = Z;
mVertices[18] = X; mVertices[19] = -Y; mVertices[20] = Z;
mVertices[21] = X; mVertices[22] = -Y; mVertices[23] = -Z;
mVertices[24] = X; mVertices[25] = Y; mVertices[26] = -Z;
mVertices[27] = X; mVertices[28] = -Y; mVertices[29] = Z;
mVertices[30] = X; mVertices[31] = Y; mVertices[32] = Z;
mVertices[33] = X; mVertices[34] = Y; mVertices[35] = -Z;
mVertices[36] = X; mVertices[37] = -Y; mVertices[38] = -Z;
mVertices[39] = -X; mVertices[40] = -Y; mVertices[41] = -Z;
mVertices[42] = -X; mVertices[43] = Y; mVertices[44] = -Z;
mVertices[45] = X; mVertices[46] = -Y; mVertices[47] = -Z;
mVertices[48] = X; mVertices[49] = Y; mVertices[50] = -Z;
mVertices[51] = -X; mVertices[52] = Y; mVertices[53] = -Z;
mVertices[54] = -X; mVertices[55] = -Y; mVertices[56] = -Z;
mVertices[57] = -X; mVertices[58] = -Y; mVertices[59] = Z;
mVertices[60] = -X; mVertices[61] = Y; mVertices[62] = Z;
mVertices[63] = -X; mVertices[64] = -Y; mVertices[65] = -Z;
mVertices[66] = -X; mVertices[67] = Y; mVertices[68] = -Z;
mVertices[69] = -X; mVertices[70] = Y; mVertices[71] = Z;
mVertices[72] = -X; mVertices[73] = Y; mVertices[74] = Z;
mVertices[75] = X; mVertices[76] = Y; mVertices[77] = Z;
mVertices[78] = X; mVertices[79] = Y; mVertices[80] = -Z;
mVertices[81] = -X; mVertices[82] = Y; mVertices[83] = Z;
mVertices[84] = -X; mVertices[85] = Y; mVertices[86] = -Z;
mVertices[87] = X; mVertices[88] = Y; mVertices[89] = -Z;
mVertices[90] = X; mVertices[91] = -Y; mVertices[92] = Z;
mVertices[93] = -X; mVertices[94] = -Y; mVertices[95] = Z;
mVertices[96] = -X; mVertices[97] = -Y; mVertices[98] = -Z;
mVertices[99] = X; mVertices[100] = -Y; mVertices[101] = Z;
mVertices[102] = X; mVertices[103] = -Y; mVertices[104] = -Z;
mVertices[105] = -X; mVertices[106] = -Y; mVertices[107] = -Z;
mNormals = new float[108]; mNormalsSize = 108; mNormalsBytes = 108*sizeof(float);
mNormals[0] = 0; mNormals[1] = 0; mNormals[2] = 1;
mNormals[3] = 0; mNormals[4] = 0; mNormals[5] = 1;
mNormals[6] = 0; mNormals[7] = 0; mNormals[8] = 1;
mNormals[9] = 0; mNormals[10] = 0; mNormals[11] = 1;
mNormals[12] = 0; mNormals[13] = 0; mNormals[14] = 1;
mNormals[15] = 0; mNormals[16] = 0; mNormals[17] = 1;
mNormals[18] = 1; mNormals[19] = 0; mNormals[20] = 0;
mNormals[21] = 1; mNormals[22] = 0; mNormals[23] = 0;
mNormals[24] = 1; mNormals[25] = 0; mNormals[26] = 0;
mNormals[27] = 1; mNormals[28] = 0; mNormals[29] = 0;
mNormals[30] = 1; mNormals[31] = 0; mNormals[32] = 0;
mNormals[33] = 1; mNormals[34] = 0; mNormals[35] = 0;
mNormals[36] = 0; mNormals[37] = 0; mNormals[38] = -1;
mNormals[39] = 0; mNormals[40] = 0; mNormals[41] = -1;
mNormals[42] = 0; mNormals[43] = 0; mNormals[44] = -1;
mNormals[45] = 0; mNormals[46] = 0; mNormals[47] = -1;
mNormals[48] = 0; mNormals[49] = 0; mNormals[50] = -1;
mNormals[51] = 0; mNormals[52] = 0; mNormals[53] = -1;
mNormals[54] = -1; mNormals[55] = 0; mNormals[56] = 0;
mNormals[57] = -1; mNormals[58] = 0; mNormals[59] = 0;
mNormals[60] = -1; mNormals[61] = 0; mNormals[62] = 0;
mNormals[63] = -1; mNormals[64] = 0; mNormals[65] = 0;
mNormals[66] = -1; mNormals[67] = 0; mNormals[68] = 0;
mNormals[69] = -1; mNormals[70] = 0; mNormals[71] = 0;
mNormals[72] = 0; mNormals[73] = 1; mNormals[74] = 0;
mNormals[75] = 0; mNormals[76] = 1; mNormals[77] = 0;
mNormals[78] = 0; mNormals[79] = 1; mNormals[80] = 0;
mNormals[81] = 0; mNormals[82] = 1; mNormals[83] = 0;
mNormals[84] = 0; mNormals[85] = 1; mNormals[86] = 0;
mNormals[87] = 0; mNormals[88] = 1; mNormals[89] = 0;
mNormals[90] = 0; mNormals[91] = -1; mNormals[92] = 0;
mNormals[93] = 0; mNormals[94] = -1; mNormals[95] = 0;
mNormals[96] = 0; mNormals[97] = -1; mNormals[98] = 0;
mNormals[99] = 0; mNormals[100] = -1; mNormals[101] = 0;
mNormals[102] = 0; mNormals[103] = -1; mNormals[104] = 0;
mNormals[105] = 0; mNormals[106] = -1; mNormals[107] = 0;
mTCoords = new float[72]; mTCoordsSize = 72; mTCoordsBytes = 72*sizeof(float);
mTCoords[0] = 0; mTCoords[1] = 0;
mTCoords[2] = 1; mTCoords[3] = 0;
mTCoords[4] = 1; mTCoords[5] = 1;
mTCoords[6] = 0; mTCoords[7] = 0;
mTCoords[8] = 0; mTCoords[9] = 1;
mTCoords[10] = 1; mTCoords[11] = 1;
mTCoords[12] = 0; mTCoords[13] = 0;
mTCoords[14] = 1; mTCoords[15] = 0;
mTCoords[16] = 1; mTCoords[17] = 1;
mTCoords[18] = 0; mTCoords[19] = 0;
mTCoords[20] = 0; mTCoords[21] = 1;
mTCoords[22] = 1; mTCoords[23] = 1;
mTCoords[24] = 0; mTCoords[25] = 0;
mTCoords[26] = 1; mTCoords[27] = 0;
mTCoords[28] = 1; mTCoords[29] = 1;
mTCoords[30] = 0; mTCoords[31] = 0;
mTCoords[32] = 0; mTCoords[33] = 1;
mTCoords[34] = 1; mTCoords[35] = 1;
mTCoords[36] = 0; mTCoords[37] = 0;
mTCoords[38] = 1; mTCoords[39] = 0;
mTCoords[40] = 1; mTCoords[41] = 1;
mTCoords[42] = 0; mTCoords[43] = 0;
mTCoords[44] = 0; mTCoords[45] = 1;
mTCoords[46] = 1; mTCoords[47] = 1;
mTCoords[48] = 0; mTCoords[49] = 0;
mTCoords[50] = 1; mTCoords[51] = 0;
mTCoords[52] = 1; mTCoords[53] = 1;
mTCoords[54] = 0; mTCoords[55] = 0;
mTCoords[56] = 0; mTCoords[57] = 1;
mTCoords[58] = 1; mTCoords[59] = 1;
mTCoords[60] = 0; mTCoords[61] = 0;
mTCoords[62] = 1; mTCoords[63] = 0;
mTCoords[64] = 1; mTCoords[65] = 1;
mTCoords[66] = 0; mTCoords[67] = 0;
mTCoords[68] = 0; mTCoords[69] = 1;
mTCoords[70] = 1; mTCoords[71] = 1;
}
| 48.525316 | 162 | 0.503456 | Flugschildkrote |
e801cf78ee5c87cd11cabbc31fbd35e9a65100e9 | 2,767 | hpp | C++ | src/concurrent/blocking_queue.hpp | ifplusor/rocketmq-client-cpp | fd301f4b064d5035fc72261023a396e2c9126c53 | [
"Apache-2.0"
] | 5 | 2019-04-24T13:37:05.000Z | 2021-01-29T16:37:55.000Z | src/concurrent/blocking_queue.hpp | ifplusor/rocketmq-client-cpp | fd301f4b064d5035fc72261023a396e2c9126c53 | [
"Apache-2.0"
] | null | null | null | src/concurrent/blocking_queue.hpp | ifplusor/rocketmq-client-cpp | fd301f4b064d5035fc72261023a396e2c9126c53 | [
"Apache-2.0"
] | 1 | 2021-02-03T03:11:03.000Z | 2021-02-03T03:11:03.000Z | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ROCKETMQ_CONCURRENT_BLOCKINGQUEUE_HPP_
#define ROCKETMQ_CONCURRENT_BLOCKINGQUEUE_HPP_
#include <chrono>
#include <condition_variable>
#include <deque>
#include <mutex>
#include "time.hpp"
namespace rocketmq {
template <typename T>
class blocking_queue {
public:
// types:
typedef T value_type;
virtual ~blocking_queue() = default;
bool empty() {
std::lock_guard<std::mutex> lock(mutex_);
return queue_.empty();
}
size_t size() {
std::lock_guard<std::mutex> lock(mutex_);
return queue_.size();
}
template <typename E,
typename std::enable_if<std::is_same<typename std::decay<E>::type, value_type>::value, int>::type = 0>
void push_back(E&& v) {
std::unique_lock<std::mutex> lock(mutex_);
queue_.emplace_back(new value_type(std::forward<E>(v)));
cv_.notify_one();
}
template <class E, typename std::enable_if<std::is_convertible<E, value_type*>::value, int>::type = 0>
void push_back(E v) {
std::unique_lock<std::mutex> lock(mutex_);
queue_.emplace_back(v);
cv_.notify_one();
}
std::unique_ptr<value_type> pop_front() {
std::unique_lock<std::mutex> lock(mutex_);
if (queue_.empty()) {
cv_.wait(lock, [&] { return !queue_.empty(); });
}
auto v = std::move(queue_.front());
queue_.pop_front();
return v;
}
std::unique_ptr<value_type> pop_front(long timeout, time_unit unit) {
auto deadline = until_time_point(timeout, unit);
std::unique_lock<std::mutex> lock(mutex_);
if (queue_.empty()) {
cv_.wait_until(lock, deadline, [&] { return !queue_.empty(); });
}
if (!queue_.empty()) {
auto v = std::move(queue_.front());
queue_.pop_front();
return v;
}
return std::unique_ptr<value_type>();
}
private:
std::deque<std::unique_ptr<value_type>> queue_;
std::mutex mutex_;
std::condition_variable cv_;
};
} // namespace rocketmq
#endif // ROCKETMQ_CONCURRENT_BLOCKINGQUEUE_HPP_
| 29.126316 | 114 | 0.68811 | ifplusor |
e8054ed8bad581e4c6ee7f22377ba4aef07865b2 | 278 | cpp | C++ | 171-Excel_Sheet_Column_Number.cpp | elsdrium/LeetCode-practice | a3b1fa5dd200155a636d36cd570e2454f7194e10 | [
"MIT"
] | null | null | null | 171-Excel_Sheet_Column_Number.cpp | elsdrium/LeetCode-practice | a3b1fa5dd200155a636d36cd570e2454f7194e10 | [
"MIT"
] | null | null | null | 171-Excel_Sheet_Column_Number.cpp | elsdrium/LeetCode-practice | a3b1fa5dd200155a636d36cd570e2454f7194e10 | [
"MIT"
] | null | null | null | class Solution {
public:
int titleToNumber(string s) {
int result = 0, base = 1;
char c = char('A' - 1);
for ( int i=s.size()-1; i>=0; --i ) {
result += (s[i] - c) * base;
base *= 26;
}
return result;
}
};
| 21.384615 | 45 | 0.413669 | elsdrium |
e805a0b69441342f27e658a29c15531e039b4208 | 270 | cpp | C++ | esphome/components/light/light_output.cpp | OttoWinter/esphomeyaml | 6a85259e4d6d1b0a0f819688b8e555efcb99ecb0 | [
"MIT"
] | 249 | 2018-04-07T12:04:11.000Z | 2019-01-25T01:11:34.000Z | esphome/components/light/light_output.cpp | OttoWinter/esphomeyaml | 6a85259e4d6d1b0a0f819688b8e555efcb99ecb0 | [
"MIT"
] | 243 | 2018-04-11T16:37:11.000Z | 2019-01-25T16:50:37.000Z | esphome/components/light/light_output.cpp | OttoWinter/esphomeyaml | 6a85259e4d6d1b0a0f819688b8e555efcb99ecb0 | [
"MIT"
] | 40 | 2018-04-10T05:50:14.000Z | 2019-01-25T15:20:36.000Z | #include "light_output.h"
#include "transformers.h"
namespace esphome {
namespace light {
std::unique_ptr<LightTransformer> LightOutput::create_default_transition() {
return make_unique<LightTransitionTransformer>();
}
} // namespace light
} // namespace esphome
| 20.769231 | 76 | 0.77037 | OttoWinter |
e80a0766fae30180bbe8f8067cc989fcb0d7cd68 | 1,022 | cpp | C++ | leetcode/236.cpp | Moonshile/MyAlgorithmCandy | e1ab006a5abe7d2749ae564ad2bffc4a628ed31b | [
"Apache-2.0"
] | 2 | 2016-11-26T02:56:35.000Z | 2019-06-17T04:09:02.000Z | leetcode/236.cpp | Moonshile/MyAlgorithmCandy | e1ab006a5abe7d2749ae564ad2bffc4a628ed31b | [
"Apache-2.0"
] | null | null | null | leetcode/236.cpp | Moonshile/MyAlgorithmCandy | e1ab006a5abe7d2749ae564ad2bffc4a628ed31b | [
"Apache-2.0"
] | 3 | 2016-07-18T14:13:20.000Z | 2019-06-17T04:08:32.000Z | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
private:
bool findPath(TreeNode *root, TreeNode *node, vector<TreeNode*> &res) {
if (root) {
res.push_back(root);
if (root == node || findPath(root->left, node, res) || findPath(root->right, node, res)) {
return true;
}
res.pop_back();
}
return false;
}
public:
TreeNode* lowestCommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q) {
vector<TreeNode*> p_path, q_path;
if (findPath(root, p, p_path) && findPath(root, q, q_path)) {
for (int i = 0, n = min(p_path.size(), q_path.size()); i <= n; ++i) {
if (i == n || p_path[i] != q_path[i]) {
return p_path[i - 1];
}
}
}
return nullptr;
}
};
| 28.388889 | 102 | 0.489237 | Moonshile |
e80aa5242d47f19ebea8dd15b83ecdb140dd48c4 | 14,146 | cpp | C++ | test/JSONSettingsRESTAPITest/Tests/SettingsSetValueEndpointTest.cpp | systelab/cpp-json-settings | d9283ea97ea31bd2730127f996b6d7b1f91cf8a2 | [
"MIT"
] | null | null | null | test/JSONSettingsRESTAPITest/Tests/SettingsSetValueEndpointTest.cpp | systelab/cpp-json-settings | d9283ea97ea31bd2730127f996b6d7b1f91cf8a2 | [
"MIT"
] | 2 | 2020-06-11T12:58:00.000Z | 2020-06-11T18:15:55.000Z | test/JSONSettingsRESTAPITest/Tests/SettingsSetValueEndpointTest.cpp | systelab/cpp-json-settings | d9283ea97ea31bd2730127f996b6d7b1f91cf8a2 | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "SettingsEndpointBaseTest.h"
#include "JSONSettingsRESTAPI/Endpoints/SettingsSetValueEndpoint.h"
#include "RESTAPICore/Endpoint/EndpointRequestData.h"
#include "WebServerAdapterInterface/Model/Reply.h"
#include "JSONAdapterTestUtilities/JSONAdapterUtilities.h"
using namespace testing;
using namespace systelab::json::test_utility;
namespace systelab { namespace setting { namespace rest_api { namespace unit_test {
class SettingsSetValueEndpointTest : public SettingsEndpointBaseTest
{
public:
void SetUp()
{
SettingsEndpointBaseTest::SetUp();
}
void TearDown()
{
SettingsEndpointBaseTest::TearDown();
}
std::unique_ptr<systelab::rest_api_core::IEndpoint> buildEndpoint(const SettingsFile& file)
{
auto settingsService = std::make_unique<systelab::setting::SettingsService>(m_encryptionAdapter);
return std::make_unique<SettingsSetValueEndpoint>(file, std::move(settingsService), m_jsonAdapter);
}
std::unique_ptr<systelab::rest_api_core::IEndpoint> buildEndpointWithoutEncryptionAdapter(const SettingsFile& file)
{
auto settingsService = std::make_unique<systelab::setting::SettingsService>();
return std::make_unique<SettingsSetValueEndpoint>(file, std::move(settingsService), m_jsonAdapter);
}
rest_api_core::EndpointRequestData buildHappyPathEndpointRequestData(int settingId, const std::string& newSettingValue)
{
std::stringstream ss;
ss << "{";
ss << " \"newValue\": \"" << newSettingValue << "\"";
ss << "}";
return buildEndpointRequestData(settingId, ss.str());
}
rest_api_core::EndpointRequestData buildEndpointRequestData(int settingId, const std::string& requestContent)
{
rest_api_core::EndpointRequestData endpointRequestData;
endpointRequestData.setParameters(rest_api_core::EndpointRequestParams({}, { {"id", settingId} }));
endpointRequestData.setContent(requestContent);
return endpointRequestData;
}
std::string buildSettingExpectedContent(int settingId, const std::string& path,
const std::string& typeName, bool useCache,
const std::string& defaultValue,
const std::string& currentValue)
{
std::stringstream expectedContentStream;
expectedContentStream << "{" << std::endl;
expectedContentStream << " \"id\": " << settingId << "," << std::endl;
expectedContentStream << " \"path\": \"" << path << "\"," << std::endl;
expectedContentStream << " \"type\": \"" << typeName << "\"," << std::endl;
expectedContentStream << " \"useCache\": " << (useCache ? "true" : "false") << "," << std::endl;
expectedContentStream << " \"defaultValue\": \"" << defaultValue << "\"," << std::endl;
expectedContentStream << " \"currentValue\": \"" << currentValue << "\"" << std::endl;
expectedContentStream << "}" << std::endl;
return expectedContentStream.str();
}
};
// Integer setting
TEST_F(SettingsSetValueEndpointTest, testExecuteForIntSettingAndValidValueReturnsOKReply)
{
auto endpoint = buildEndpoint(MySettingsFile::FILENAME);
auto reply = endpoint->execute(buildHappyPathEndpointRequestData(1, "9876")); // Integer setting has id=1
ASSERT_TRUE(reply != nullptr);
EXPECT_EQ(systelab::web_server::Reply::OK, reply->getStatus());
EXPECT_EQ("application/json", reply->getHeader("Content-Type"));
EXPECT_TRUE(compareJSONs(buildSettingExpectedContent(1, "IntSettingCache", "integer", true, "1234", "9876"),
reply->getContent(), m_jsonAdapter));
}
TEST_F(SettingsSetValueEndpointTest, testExecuteForIntSettingAndValidValueWritesValueInMySettingsFile)
{
auto endpoint = buildEndpoint(MySettingsFile::FILENAME);
endpoint->execute(buildHappyPathEndpointRequestData(1, "9876")); // Integer setting has id=1
std::string expectedSettingsFileContent = "{ \"IntSettingCache\": \"9876\" }";
EXPECT_TRUE(compareJSONs(expectedSettingsFileContent, *readSettingsFile(MySettingsFile::FILENAME), m_jsonAdapter));
}
TEST_F(SettingsSetValueEndpointTest, testExecuteForIntSettingAndInvalidValueReturnsBadRequestReply)
{
auto endpoint = buildEndpoint(MySettingsFile::FILENAME);
auto reply = endpoint->execute(buildHappyPathEndpointRequestData(1, "ThisIsNotAnInteger")); // Integer setting has id=1
ASSERT_TRUE(reply != nullptr);
EXPECT_EQ(systelab::web_server::Reply::BAD_REQUEST, reply->getStatus());
EXPECT_EQ("application/json", reply->getHeader("Content-Type"));
EXPECT_TRUE(compareJSONs(buildExpectedMessageReplyContent("New setting value not valid."),
reply->getContent(), m_jsonAdapter));
ASSERT_FALSE(readSettingsFile(MySettingsFile::FILENAME));
}
// Double setting
TEST_F(SettingsSetValueEndpointTest, testExecuteForDblSettingAndValidValueReturnsOKReply)
{
auto endpoint = buildEndpoint(MySettingsFile::FILENAME);
auto reply = endpoint->execute(buildHappyPathEndpointRequestData(2, "98.7")); // Double setting has id=2
ASSERT_TRUE(reply != nullptr);
EXPECT_EQ(systelab::web_server::Reply::OK, reply->getStatus());
EXPECT_EQ("application/json", reply->getHeader("Content-Type"));
EXPECT_TRUE(compareJSONs(buildSettingExpectedContent(2, "DblSettingNoCache", "double", false, "5.678", "98.7"),
reply->getContent(), m_jsonAdapter));
}
TEST_F(SettingsSetValueEndpointTest, testExecuteForDblSettingAndValidValueWritesValueInMySettingsFile)
{
auto endpoint = buildEndpoint(MySettingsFile::FILENAME);
endpoint->execute(buildHappyPathEndpointRequestData(2, "98.7")); // Double setting has id=2
std::string expectedSettingsFileContent = "{ \"DblSettingNoCache\": \"98.7\" }";
EXPECT_TRUE(compareJSONs(expectedSettingsFileContent, *readSettingsFile(MySettingsFile::FILENAME), m_jsonAdapter));
}
TEST_F(SettingsSetValueEndpointTest, testExecuteForDblSettingAndInvalidValueReturnsBadRequestReply)
{
auto endpoint = buildEndpoint(MySettingsFile::FILENAME);
auto reply = endpoint->execute(buildHappyPathEndpointRequestData(2, "ThisIsNotADouble")); // Double setting has id=2
ASSERT_TRUE(reply != nullptr);
EXPECT_EQ(systelab::web_server::Reply::BAD_REQUEST, reply->getStatus());
EXPECT_EQ("application/json", reply->getHeader("Content-Type"));
EXPECT_TRUE(compareJSONs(buildExpectedMessageReplyContent("New setting value not valid."),
reply->getContent(), m_jsonAdapter));
ASSERT_FALSE(readSettingsFile(MySettingsFile::FILENAME));
}
// String setting
TEST_F(SettingsSetValueEndpointTest, testExecuteForStrSettingAndValidValueReturnsOKReply)
{
auto endpoint = buildEndpoint(MySettingsFile::FILENAME);
auto reply = endpoint->execute(buildHappyPathEndpointRequestData(3, "MySuperNewValue")); // String setting has id=3
ASSERT_TRUE(reply != nullptr);
EXPECT_EQ(systelab::web_server::Reply::OK, reply->getStatus());
EXPECT_EQ("application/json", reply->getHeader("Content-Type"));
EXPECT_TRUE(compareJSONs(buildSettingExpectedContent(3, "Section.StrSettingCache", "string", true, "ba", "MySuperNewValue"),
reply->getContent(), m_jsonAdapter));
}
TEST_F(SettingsSetValueEndpointTest, testExecuteForStrSettingAndValidValueWritesValueInMySettingsFile)
{
auto endpoint = buildEndpoint(MySettingsFile::FILENAME);
endpoint->execute(buildHappyPathEndpointRequestData(3, "MySuperNewValue")); // String setting has id=3
std::string expectedSettingsFileContent = "{ \"Section\": { \"StrSettingCache\": \"MySuperNewValue\" } }";
EXPECT_TRUE(compareJSONs(expectedSettingsFileContent, *readSettingsFile(MySettingsFile::FILENAME), m_jsonAdapter));
}
// Boolean setting
TEST_F(SettingsSetValueEndpointTest, testExecuteForBoolSettingAndValidValueReturnsOKReply)
{
auto endpoint = buildEndpoint(MySettingsFile::FILENAME);
auto reply = endpoint->execute(buildHappyPathEndpointRequestData(4, "true")); // Boolean setting has id=4
ASSERT_TRUE(reply != nullptr);
EXPECT_EQ(systelab::web_server::Reply::OK, reply->getStatus());
EXPECT_EQ("application/json", reply->getHeader("Content-Type"));
EXPECT_TRUE(compareJSONs(buildSettingExpectedContent(4, "Section.Subsection.BoolSettingNoCache", "boolean", false, "false", "true"),
reply->getContent(), m_jsonAdapter));
}
TEST_F(SettingsSetValueEndpointTest, testExecuteForBoolSettingAndValidValueWritesValueInMySettingsFile)
{
auto endpoint = buildEndpoint(MySettingsFile::FILENAME);
endpoint->execute(buildHappyPathEndpointRequestData(4, "true")); // Boolean setting has id=4
std::string expectedSettingsFileContent = "{ \"Section\": { \"Subsection\": { \"BoolSettingNoCache\": \"true\" } } }";
EXPECT_TRUE(compareJSONs(expectedSettingsFileContent, *readSettingsFile(MySettingsFile::FILENAME), m_jsonAdapter));
}
TEST_F(SettingsSetValueEndpointTest, testExecuteForBoolSettingAndInvalidValueReturnsBadRequestReply)
{
auto endpoint = buildEndpoint(MySettingsFile::FILENAME);
auto reply = endpoint->execute(buildHappyPathEndpointRequestData(4, "NotABoolean")); // Boolean setting has id=4
ASSERT_TRUE(reply != nullptr);
EXPECT_EQ(systelab::web_server::Reply::BAD_REQUEST, reply->getStatus());
EXPECT_EQ("application/json", reply->getHeader("Content-Type"));
EXPECT_TRUE(compareJSONs(buildExpectedMessageReplyContent("New setting value not valid."),
reply->getContent(), m_jsonAdapter));
ASSERT_FALSE(readSettingsFile(MySettingsFile::FILENAME));
}
// Encrypted setting
TEST_F(SettingsSetValueEndpointTest, testExecuteForEncryptedSettingAndValidValueReturnsOKReply)
{
auto endpoint = buildEndpoint(EncryptedSettingsFile::FILENAME);
auto reply = endpoint->execute(buildHappyPathEndpointRequestData(1, "5555"));
ASSERT_TRUE(reply != nullptr);
EXPECT_EQ(systelab::web_server::Reply::OK, reply->getStatus());
EXPECT_EQ("application/json", reply->getHeader("Content-Type"));
EXPECT_TRUE(compareJSONs(buildSettingExpectedContent(1, "Section.IntSettingCache", "integer", true, "9999", "5555"),
reply->getContent(), m_jsonAdapter));
}
TEST_F(SettingsSetValueEndpointTest, testExecuteForEncryptedSettingAndValidValueWritesValueInEncryptedSettingsFile)
{
auto endpoint = buildEndpoint(EncryptedSettingsFile::FILENAME);
endpoint->execute(buildHappyPathEndpointRequestData(1, "5555"));
std::string expectedSettingsFileContent = "{ \"Section\": { \"IntSettingCache\": \"5555\" } }";
EXPECT_TRUE(compareJSONs(expectedSettingsFileContent, *readSettingsFile(EncryptedSettingsFile::FILENAME, EncryptedSettingsFile::ENCRYPTION_KEY), m_jsonAdapter));
}
// Error cases
TEST_F(SettingsSetValueEndpointTest, testExecuteForNotDefinedSettingsFileReturnsNotFoundReply)
{
auto endpoint = buildEndpoint("NotExistingFile");
auto reply = endpoint->execute(buildHappyPathEndpointRequestData(1, "9876"));
ASSERT_TRUE(reply != nullptr);
EXPECT_EQ(systelab::web_server::Reply::NOT_FOUND, reply->getStatus());
EXPECT_EQ("application/json", reply->getHeader("Content-Type"));
EXPECT_TRUE(compareJSONs("{}", reply->getContent(), m_jsonAdapter));
}
TEST_F(SettingsSetValueEndpointTest, testExecuteForNotExistingSettingInSettingsFileReturnsNotFoundReply)
{
unsigned int notExistingSettingId = 666;
auto endpoint = buildEndpoint(MySettingsFile::FILENAME);
auto reply = endpoint->execute(buildHappyPathEndpointRequestData(notExistingSettingId, "9876"));
ASSERT_TRUE(reply != nullptr);
EXPECT_EQ(systelab::web_server::Reply::NOT_FOUND, reply->getStatus());
EXPECT_EQ("application/json", reply->getHeader("Content-Type"));
EXPECT_TRUE(compareJSONs("{}", reply->getContent(), m_jsonAdapter));
}
TEST_F(SettingsSetValueEndpointTest, testExecuteForEncryptedFileWithoutEncryptionAdapterReturnsInternalServerErrorReply)
{
auto endpoint = buildEndpointWithoutEncryptionAdapter(EncryptedSettingsFile::FILENAME);
auto reply = endpoint->execute(buildHappyPathEndpointRequestData(1, "9876"));
ASSERT_TRUE(reply != nullptr);
EXPECT_EQ(systelab::web_server::Reply::INTERNAL_SERVER_ERROR, reply->getStatus());
EXPECT_EQ("application/json", reply->getHeader("Content-Type"));
EXPECT_TRUE(compareJSONs(buildExpectedMessageReplyContent("Unable to access encrypted settings file when no encryption adapter provided."),
reply->getContent(), m_jsonAdapter));
}
TEST_F(SettingsSetValueEndpointTest, testExecuteForRequestThatDoesNotHaveIdNumericParameterReturnsInternalServerErrorReply)
{
auto endpoint = buildEndpoint(MySettingsFile::FILENAME);
auto reply = endpoint->execute(rest_api_core::EndpointRequestData());
ASSERT_TRUE(reply != nullptr);
EXPECT_EQ(systelab::web_server::Reply::INTERNAL_SERVER_ERROR, reply->getStatus());
EXPECT_EQ("application/json", reply->getHeader("Content-Type"));
EXPECT_TRUE(compareJSONs(buildExpectedMessageReplyContent("Configured endpoint route lacks 'id' numeric parameter."),
reply->getContent(), m_jsonAdapter));
}
TEST_F(SettingsSetValueEndpointTest, testExecuteForRequestWhoseContentIsNotAValidJSONReturnsBadRequestReply)
{
auto endpoint = buildEndpointWithoutEncryptionAdapter(EncryptedSettingsFile::FILENAME);
auto reply = endpoint->execute(buildEndpointRequestData(1, "This is not a JSON content"));
ASSERT_TRUE(reply != nullptr);
EXPECT_EQ(systelab::web_server::Reply::BAD_REQUEST, reply->getStatus());
EXPECT_EQ("application/json", reply->getHeader("Content-Type"));
EXPECT_TRUE(compareJSONs(buildExpectedMessageReplyContent("Request content not in JSON format."),
reply->getContent(), m_jsonAdapter));
}
TEST_F(SettingsSetValueEndpointTest, testExecuteForRequestWhoseContentDoesNotSatisfyJSONSchemaReturnsBadRequestReply)
{
auto endpoint = buildEndpointWithoutEncryptionAdapter(EncryptedSettingsFile::FILENAME);
auto reply = endpoint->execute(buildEndpointRequestData(1, "{ \"anotherField\": 23 }"));
ASSERT_TRUE(reply != nullptr);
EXPECT_EQ(systelab::web_server::Reply::BAD_REQUEST, reply->getStatus());
EXPECT_EQ("application/json", reply->getHeader("Content-Type"));
EXPECT_TRUE(compareJSONs(buildExpectedMessageReplyContent("Request content does not statisfy JSON schema: "
"Invalid schema: # Invalid keyword: required Invalid document: #"),
reply->getContent(), m_jsonAdapter));
}
}}}}
| 45.194888 | 163 | 0.765517 | systelab |
e80acbdb590acad486f57b22858631f77fa9b758 | 1,410 | cc | C++ | resonance_audio/utils/sum_and_difference_processor_test.cc | seba10000/resonance-audio | e1923fe6fe733ae4d3c8460ff883c87e2ad05d6b | [
"Apache-2.0"
] | 396 | 2018-03-14T09:55:52.000Z | 2022-03-27T14:58:38.000Z | resonance_audio/utils/sum_and_difference_processor_test.cc | seba10000/resonance-audio | e1923fe6fe733ae4d3c8460ff883c87e2ad05d6b | [
"Apache-2.0"
] | 46 | 2018-04-18T17:14:29.000Z | 2022-02-19T21:35:57.000Z | resonance_audio/utils/sum_and_difference_processor_test.cc | seba10000/resonance-audio | e1923fe6fe733ae4d3c8460ff883c87e2ad05d6b | [
"Apache-2.0"
] | 96 | 2018-03-14T17:20:50.000Z | 2022-03-03T01:12:37.000Z | /*
Copyright 2018 Google Inc. 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 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 "utils/sum_and_difference_processor.h"
#include "third_party/googletest/googletest/include/gtest/gtest.h"
namespace vraudio {
// Tests Process method.
TEST(SumAndDifferenceProcessor, TestProcessMethod) {
static const std::vector<std::vector<float>> kTestVector = {
{0.0f, 1.0f, 2.0f}, {3.0f, 4.0f, 5.0f}};
AudioBuffer audio_buffer(kTestVector.size(), kTestVector[0].size());
audio_buffer = kTestVector;
SumAndDifferenceProcessor processor(audio_buffer.num_frames());
processor.Process(&audio_buffer);
for (size_t frame = 0; frame < kTestVector[0].size(); ++frame) {
EXPECT_EQ(kTestVector[0][frame] + kTestVector[1][frame],
audio_buffer[0][frame]);
EXPECT_EQ(kTestVector[0][frame] - kTestVector[1][frame],
audio_buffer[1][frame]);
}
}
} // namespace vraudio
| 32.790698 | 72 | 0.734043 | seba10000 |
e813de0a7669a25f03aaac77f5df1c74f9434dce | 6,033 | cpp | C++ | Data/Juliet-C/Juliet-C-v102/testcases/CWE620_Unverified_Password_Change/main.cpp | b19e93n/PLC-Pyramid | 6d5b57be6995a94ef7402144cee965862713b031 | [
"MIT"
] | null | null | null | Data/Juliet-C/Juliet-C-v102/testcases/CWE620_Unverified_Password_Change/main.cpp | b19e93n/PLC-Pyramid | 6d5b57be6995a94ef7402144cee965862713b031 | [
"MIT"
] | null | null | null | Data/Juliet-C/Juliet-C-v102/testcases/CWE620_Unverified_Password_Change/main.cpp | b19e93n/PLC-Pyramid | 6d5b57be6995a94ef7402144cee965862713b031 | [
"MIT"
] | null | null | null | /* NOTE - eventually this file will be automatically updated using a Perl script that understand
* the naming of test case files, functions, and namespaces.
*/
#include <time.h> /* for time() */
#include <stdlib.h> /* for srand() */
#include "std_testcase.h"
#include "testcases.h"
int main(int argc, char * argv[]) {
/* seed randomness */
srand( (unsigned)time(NULL) );
global_argc = argc;
global_argv = argv;
#ifndef OMITGOOD
/* Calling C good functions */
/* BEGIN-AUTOGENERATED-C-GOOD-FUNCTION-CALLS */
printLine("Calling CWE620_Unverified_Password_Change__w32_01_good();");
CWE620_Unverified_Password_Change__w32_01_good();
printLine("Calling CWE620_Unverified_Password_Change__w32_02_good();");
CWE620_Unverified_Password_Change__w32_02_good();
printLine("Calling CWE620_Unverified_Password_Change__w32_03_good();");
CWE620_Unverified_Password_Change__w32_03_good();
printLine("Calling CWE620_Unverified_Password_Change__w32_04_good();");
CWE620_Unverified_Password_Change__w32_04_good();
printLine("Calling CWE620_Unverified_Password_Change__w32_05_good();");
CWE620_Unverified_Password_Change__w32_05_good();
printLine("Calling CWE620_Unverified_Password_Change__w32_06_good();");
CWE620_Unverified_Password_Change__w32_06_good();
printLine("Calling CWE620_Unverified_Password_Change__w32_07_good();");
CWE620_Unverified_Password_Change__w32_07_good();
printLine("Calling CWE620_Unverified_Password_Change__w32_08_good();");
CWE620_Unverified_Password_Change__w32_08_good();
printLine("Calling CWE620_Unverified_Password_Change__w32_09_good();");
CWE620_Unverified_Password_Change__w32_09_good();
printLine("Calling CWE620_Unverified_Password_Change__w32_10_good();");
CWE620_Unverified_Password_Change__w32_10_good();
printLine("Calling CWE620_Unverified_Password_Change__w32_11_good();");
CWE620_Unverified_Password_Change__w32_11_good();
printLine("Calling CWE620_Unverified_Password_Change__w32_12_good();");
CWE620_Unverified_Password_Change__w32_12_good();
printLine("Calling CWE620_Unverified_Password_Change__w32_13_good();");
CWE620_Unverified_Password_Change__w32_13_good();
printLine("Calling CWE620_Unverified_Password_Change__w32_14_good();");
CWE620_Unverified_Password_Change__w32_14_good();
printLine("Calling CWE620_Unverified_Password_Change__w32_15_good();");
CWE620_Unverified_Password_Change__w32_15_good();
printLine("Calling CWE620_Unverified_Password_Change__w32_16_good();");
CWE620_Unverified_Password_Change__w32_16_good();
printLine("Calling CWE620_Unverified_Password_Change__w32_17_good();");
CWE620_Unverified_Password_Change__w32_17_good();
printLine("Calling CWE620_Unverified_Password_Change__w32_18_good();");
CWE620_Unverified_Password_Change__w32_18_good();
printLine("Calling CWE620_Unverified_Password_Change__w32_19_good();");
CWE620_Unverified_Password_Change__w32_19_good();
/* END-AUTOGENERATED-C-GOOD-FUNCTION-CALLS */
#ifdef __cplusplus
/* Calling C++ good functions */
/* BEGIN-AUTOGENERATED-CPP-GOOD-FUNCTION-CALLS */
/* END-AUTOGENERATED-CPP-GOOD-FUNCTION-CALLS */
#endif /* __cplusplus */
#endif /* OMITGOOD */
#ifndef OMITBAD
/* Calling C bad functions */
/* BEGIN-AUTOGENERATED-C-BAD-FUNCTION-CALLS */
printLine("Calling CWE620_Unverified_Password_Change__w32_01_bad();");
CWE620_Unverified_Password_Change__w32_01_bad();
printLine("Calling CWE620_Unverified_Password_Change__w32_02_bad();");
CWE620_Unverified_Password_Change__w32_02_bad();
printLine("Calling CWE620_Unverified_Password_Change__w32_03_bad();");
CWE620_Unverified_Password_Change__w32_03_bad();
printLine("Calling CWE620_Unverified_Password_Change__w32_04_bad();");
CWE620_Unverified_Password_Change__w32_04_bad();
printLine("Calling CWE620_Unverified_Password_Change__w32_05_bad();");
CWE620_Unverified_Password_Change__w32_05_bad();
printLine("Calling CWE620_Unverified_Password_Change__w32_06_bad();");
CWE620_Unverified_Password_Change__w32_06_bad();
printLine("Calling CWE620_Unverified_Password_Change__w32_07_bad();");
CWE620_Unverified_Password_Change__w32_07_bad();
printLine("Calling CWE620_Unverified_Password_Change__w32_08_bad();");
CWE620_Unverified_Password_Change__w32_08_bad();
printLine("Calling CWE620_Unverified_Password_Change__w32_09_bad();");
CWE620_Unverified_Password_Change__w32_09_bad();
printLine("Calling CWE620_Unverified_Password_Change__w32_10_bad();");
CWE620_Unverified_Password_Change__w32_10_bad();
printLine("Calling CWE620_Unverified_Password_Change__w32_11_bad();");
CWE620_Unverified_Password_Change__w32_11_bad();
printLine("Calling CWE620_Unverified_Password_Change__w32_12_bad();");
CWE620_Unverified_Password_Change__w32_12_bad();
printLine("Calling CWE620_Unverified_Password_Change__w32_13_bad();");
CWE620_Unverified_Password_Change__w32_13_bad();
printLine("Calling CWE620_Unverified_Password_Change__w32_14_bad();");
CWE620_Unverified_Password_Change__w32_14_bad();
printLine("Calling CWE620_Unverified_Password_Change__w32_15_bad();");
CWE620_Unverified_Password_Change__w32_15_bad();
printLine("Calling CWE620_Unverified_Password_Change__w32_16_bad();");
CWE620_Unverified_Password_Change__w32_16_bad();
printLine("Calling CWE620_Unverified_Password_Change__w32_17_bad();");
CWE620_Unverified_Password_Change__w32_17_bad();
printLine("Calling CWE620_Unverified_Password_Change__w32_18_bad();");
CWE620_Unverified_Password_Change__w32_18_bad();
printLine("Calling CWE620_Unverified_Password_Change__w32_19_bad();");
CWE620_Unverified_Password_Change__w32_19_bad();
/* END-AUTOGENERATED-C-BAD-FUNCTION-CALLS */
#ifdef __cplusplus
/* Calling C++ bad functions */
/* BEGIN-AUTOGENERATED-CPP-BAD-FUNCTION-CALLS */
/* END-AUTOGENERATED-CPP-BAD-FUNCTION-CALLS */
#endif /* __cplusplus */
#endif /* OMITBAD */
return 0;
}
| 34.084746 | 97 | 0.802917 | b19e93n |
e819cde9d0c5b65887b08a125a144e40513fe00f | 430 | cpp | C++ | Simple_Problem/BOJ(9095).cpp | kkkHoon/algorithm_study | b16ab6118511059d28e77c1807f3e8fabb13e5f0 | [
"MIT"
] | null | null | null | Simple_Problem/BOJ(9095).cpp | kkkHoon/algorithm_study | b16ab6118511059d28e77c1807f3e8fabb13e5f0 | [
"MIT"
] | null | null | null | Simple_Problem/BOJ(9095).cpp | kkkHoon/algorithm_study | b16ab6118511059d28e77c1807f3e8fabb13e5f0 | [
"MIT"
] | null | null | null | #include <iostream>
#include <algorithm>
#include <queue>
#include <functional>
using namespace std;
int n, num, cnt;
void calculate(int num);
int main()
{
cin >> n;
for (int i = 0; i < n; i++) {
cin >> num;
cnt = 0;
calculate(num);
cout << cnt << endl;
}
return 0;
}
void calculate(int num)
{
if (num <= 0) {
if (num == 0)
cnt++;
return;
}
calculate(num - 1);
calculate(num - 2);
calculate(num - 3);
} | 13.030303 | 30 | 0.574419 | kkkHoon |
e81ad576080bb897a8df9fc83debde671fd663ed | 845 | cpp | C++ | TPP/TBB/material/actividad2.cpp | zhonskate/MCPD | 14e8f41c5b9317dc5c4ccbddba95e6db69087d29 | [
"MIT"
] | null | null | null | TPP/TBB/material/actividad2.cpp | zhonskate/MCPD | 14e8f41c5b9317dc5c4ccbddba95e6db69087d29 | [
"MIT"
] | null | null | null | TPP/TBB/material/actividad2.cpp | zhonskate/MCPD | 14e8f41c5b9317dc5c4ccbddba95e6db69087d29 | [
"MIT"
] | null | null | null |
/* El código desarrollado en la Actividad 2 debe funcionar con el siguiente programa principal */
/* donde getN es el método que permite obtener la dimensión de la Tabla */
/* Si el código está correcto mostrará lo siguiente */
/* Tabla 1: [ 83 86 77 15 93 35 86 92 49 21 ] */
/* Tabla 2: [ 62 27 90 59 63 ] */
/* Tabla 3: [ 62 27 90 59 63 ] */
/* Tabla 4: [ 83 86 77 15 93 35 86 92 49 21 ] */
/*int main() {
Tabla t1;
Tabla t2(5);
for( int i=0; i<t1.getN(); i++ ) {
t1[i] = rand() % 100;
}
cout << "Tabla 1: " << t1;
for( int i=0; i<t2.getN(); i++ ) {
t2[i] = rand() % 100;
}
cout << "Tabla 2: " << t2;
Tabla t3(t2);
cout << "Tabla 3: " << t3;
Tabla t4(5);
t4 = t1;
cout << "Tabla 4: " << t4;
}
*/
| 26.40625 | 97 | 0.47574 | zhonskate |
e81aebed47e6eb18ed58f218cee4be929d85bbbe | 6,460 | hpp | C++ | models/epidemic/epidemic.hpp | pvelesko/warped2-models | e0afe5119374c9e2191c946f70510bb6d7558f44 | [
"MIT"
] | 4 | 2015-04-13T17:22:51.000Z | 2018-01-16T14:54:33.000Z | models/epidemic/epidemic.hpp | pvelesko/warped2-models | e0afe5119374c9e2191c946f70510bb6d7558f44 | [
"MIT"
] | 3 | 2017-08-14T21:41:32.000Z | 2020-08-21T08:21:14.000Z | models/epidemic/epidemic.hpp | pvelesko/warped2-models | e0afe5119374c9e2191c946f70510bb6d7558f44 | [
"MIT"
] | 8 | 2015-09-28T08:25:34.000Z | 2020-04-01T12:25:15.000Z | #ifndef EPIDEMIC_HPP
#define EPIDEMIC_HPP
#include <string>
#include <vector>
#include <map>
#include <random>
#include "memory.hpp"
#include "warped.hpp"
#include "Person.hpp"
#include "DiseaseModel.hpp"
#include "DiffusionNetwork.hpp"
WARPED_DEFINE_LP_STATE_STRUCT(LocationState) {
LocationState() {
current_population_ = std::make_shared<std::map <unsigned long, std::shared_ptr<Person>>>();
}
LocationState(const LocationState& other) {
current_population_ = std::make_shared<std::map <unsigned long, std::shared_ptr<Person>>>();
for (auto it = other.current_population_->begin();
it != other.current_population_->end(); it++) {
auto person = it->second;
auto new_person =
std::make_shared<Person>( person->pid_,
person->susceptibility_,
person->vaccination_status_,
person->infection_state_,
person->loc_arrival_timestamp_,
person->prev_state_change_timestamp_ );
current_population_->insert(current_population_->begin(),
std::pair <unsigned long, std::shared_ptr<Person>> (person->pid_, new_person));
}
};
std::shared_ptr<std::map <unsigned long, std::shared_ptr<Person>>> current_population_;
};
enum event_type_t {
DISEASE_UPDATE_TRIGGER,
DIFFUSION_TRIGGER,
DIFFUSION
};
class EpidemicEvent : public warped::Event {
public:
EpidemicEvent() = default;
EpidemicEvent(const std::string receiver_name, unsigned int timestamp,
std::shared_ptr<Person> person, event_type_t event_type)
: receiver_name_(receiver_name), loc_arrival_timestamp_(timestamp),
event_type_(event_type) {
if (person != nullptr) {
pid_ = person->pid_;
susceptibility_ = person->susceptibility_;
vaccination_status_ = person->vaccination_status_;
infection_state_ = person->infection_state_;
prev_state_change_timestamp_ = person->prev_state_change_timestamp_;
}
}
const std::string& receiverName() const { return receiver_name_; }
unsigned int timestamp() const { return loc_arrival_timestamp_; }
unsigned int size() const {
return receiver_name_.length() +
sizeof(pid_) +
sizeof(susceptibility_) +
sizeof(vaccination_status_) +
sizeof(infection_state_) +
sizeof(loc_arrival_timestamp_) +
sizeof(prev_state_change_timestamp_) +
sizeof(event_type_);
}
std::string receiver_name_;
unsigned long pid_;
double susceptibility_;
bool vaccination_status_;
infection_state_t infection_state_;
unsigned int loc_arrival_timestamp_;
unsigned int prev_state_change_timestamp_;
event_type_t event_type_;
WARPED_REGISTER_SERIALIZABLE_MEMBERS(cereal::base_class<warped::Event>(this),
receiver_name_, pid_, susceptibility_, vaccination_status_, infection_state_,
loc_arrival_timestamp_, prev_state_change_timestamp_, event_type_)
};
class Location : public warped::LogicalProcess {
public:
Location(const std::string& name, float transmissibility, unsigned int latent_dwell_interval,
unsigned int incubating_dwell_interval, unsigned int infectious_dwell_interval,
unsigned int asympt_dwell_interval, float latent_infectivity,
float incubating_infectivity, float infectious_infectivity,
float asympt_infectivity, float prob_ulu, float prob_ulv, float prob_urv,
unsigned int loc_state_refresh_interval,
unsigned int loc_diffusion_trig_interval,
std::vector<std::shared_ptr<Person>> population,
unsigned int travel_time_to_hub, unsigned int index)
: LogicalProcess(name), state_(), location_name_(name),
location_state_refresh_interval_(loc_state_refresh_interval),
location_diffusion_trigger_interval_(loc_diffusion_trig_interval),
rng_(new std::default_random_engine(index)) {
state_ = std::make_shared<LocationState>();
disease_model_ =
std::make_shared<DiseaseModel>(
transmissibility, latent_dwell_interval, incubating_dwell_interval,
infectious_dwell_interval, asympt_dwell_interval, latent_infectivity,
incubating_infectivity, infectious_infectivity, asympt_infectivity,
prob_ulu, prob_ulv, prob_urv);
diffusion_network_ =
std::make_shared<DiffusionNetwork>(travel_time_to_hub, rng_);
for (auto& person : population) {
state_->current_population_->insert(state_->current_population_->begin(),
std::pair <unsigned long, std::shared_ptr<Person>> (person->pid_, person));
}
}
virtual warped::LPState& getState() override { return *state_; }
virtual std::vector<std::shared_ptr<warped::Event>> initializeLP() override;
virtual std::vector<std::shared_ptr<warped::Event>> receiveEvent(const warped::Event& event) override;
void populateTravelDistances(std::map<std::string, unsigned int> travel_chart) {
diffusion_network_->populateTravelChart(travel_chart);
}
void statistics ( unsigned long *population_size,
unsigned long *affected_cnt ) {
auto population_map = *state_->current_population_;
*population_size = population_map.size();
*affected_cnt = 0;
for (auto& entry : population_map) {
auto person = *entry.second;
if (person.isAffected()) (*affected_cnt)++;
}
}
std::string getLocationName() {
return location_name_;
}
protected:
std::shared_ptr<LocationState> state_;
std::string location_name_;
std::shared_ptr<DiseaseModel> disease_model_;
std::shared_ptr<DiffusionNetwork> diffusion_network_;
unsigned int location_state_refresh_interval_;
unsigned int location_diffusion_trigger_interval_;
std::shared_ptr<std::default_random_engine> rng_;
};
#endif
| 38.224852 | 106 | 0.644582 | pvelesko |
e81c23115fc18d2098aad9d464d36b3d17d027d9 | 352 | hpp | C++ | include/LevelSettings.hpp | vyorkin/asteroids | 870256e338eefb07466af27735d5b8df0c5c7d42 | [
"MIT"
] | 1 | 2015-03-13T10:09:54.000Z | 2015-03-13T10:09:54.000Z | include/LevelSettings.hpp | vyorkin-personal/asteroids | 870256e338eefb07466af27735d5b8df0c5c7d42 | [
"MIT"
] | null | null | null | include/LevelSettings.hpp | vyorkin-personal/asteroids | 870256e338eefb07466af27735d5b8df0c5c7d42 | [
"MIT"
] | null | null | null | #pragma once
#include "Base.hpp"
enum LevelDifficulty { Easy, Normal, Hard };
struct LevelSettings {
LevelSettings();
LevelSettings(const LevelSettings&) = default;
LevelSettings(const LevelDifficulty difficulty, const int numAsteroids);
LevelDifficulty difficulty;
int numAsteroids;
static const LevelSettings initial;
};
| 20.705882 | 76 | 0.741477 | vyorkin |
e8267e60757fdd2e5eda623f9d6321b427be89c7 | 4,428 | cpp | C++ | ros/src/sensing/fusion/packages/calibration_camera_lidar/nodes/calibration_test/scan_window.cpp | filiperinaldi/Autoware | 9fae6cc7cb8253586578dbb62a2f075b52849e6e | [
"Apache-2.0"
] | 4 | 2019-04-22T10:18:26.000Z | 2019-05-20T05:16:03.000Z | ros/src/sensing/fusion/packages/calibration_camera_lidar/nodes/calibration_test/scan_window.cpp | filiperinaldi/Autoware | 9fae6cc7cb8253586578dbb62a2f075b52849e6e | [
"Apache-2.0"
] | 1 | 2019-03-05T05:52:41.000Z | 2019-03-05T05:52:41.000Z | ros/src/sensing/fusion/packages/calibration_camera_lidar/nodes/calibration_test/scan_window.cpp | filiperinaldi/Autoware | 9fae6cc7cb8253586578dbb62a2f075b52849e6e | [
"Apache-2.0"
] | 2 | 2019-06-23T18:08:04.000Z | 2019-07-04T14:14:59.000Z | /*
* Copyright 2015-2019 Autoware Foundation. 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 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 "scan_window.h"
void plot_vertical_line(IplImage* image, int line_division_num, int window_width, int window_height)
{
CvPoint line_start, line_end;
for (int i = 0; i < line_division_num; i++) {
line_start.x = 0;
line_start.y = window_height / line_division_num * (i + 1);
line_end.x = window_width;
line_end.y = window_height / line_division_num * (i + 1);
cvLine(image, line_start, line_end, CV_RGB (120, 120, 120), 1, 8, 0);
}
}
void plot_horizontal_line(IplImage* image, int window_width, int window_height)
{
CvPoint line_start, line_end;
line_start.x = window_width / 2;
line_start.y = 0;
line_end.x = window_width /2;
line_end.y = window_height;
cvLine(image, line_start, line_end, CV_RGB (120, 120, 120), 1, 8, 0);
}
void plot_center_pt_line(IplImage *image, CvPoint center_pt, int chess_size, int pat_col, int margin, int window_width, int window_height, int scale)
{
CvPoint line_start, line_end;
/* chessboard horizontal line */
line_start.x = window_width / 2 - ((chess_size / 1000) * (pat_col + 1) + (margin /1000)) * scale / 2;
line_start.y = center_pt.y;
line_end.x = window_width /2 + ((chess_size / 1000) * (pat_col + 1) + (margin /1000)) * scale / 2;
line_end.y = center_pt.y;
cvLine(image, line_start, line_end, CV_RGB (255, 255, 0), 1, 8, 0);
/* chessboard vertical line */
// left line
line_start.x = window_width/2 - ((chess_size/1000.0) * (pat_col+1) + (margin/1000.0)) * scale / 2;
line_start.y = 0;
line_end.x = window_width/2 - ((chess_size/1000.0) * (pat_col+1) + (margin/1000.0)) * scale / 2;
line_end.y = window_height;
cvLine(image, line_start, line_end, CV_RGB (255, 255, 0), 1, 8, 0);
// right line
line_start.x = window_width/2 + (((float)chess_size/1000.0) * (pat_col+1) + ((float)margin/1000.0)) * scale / 2;
line_start.y = 0;
line_end.x = window_width/2 + (((float)chess_size/1000.0) * (pat_col+1) + ((float)margin/1000.0)) * scale / 2;
line_end.y = window_height;
cvLine(image, line_start, line_end, CV_RGB (255, 255, 0), 1, 8, 0);
}
CvPoint get_center_pt(int window_width, Three_dimensional_vector* scan, int scale)
{
CvPoint center_pt;
center_pt.x = scan->x[scan->x.size() / 2] * scale + (window_width / 2);
center_pt.y = scan->z[scan->x.size() / 2] * scale;
return center_pt;
}
void plot_string(IplImage* image, const char* text, int thickness, int x, int y, CvScalar color)
{
CvFont dfont;
float hscale = 1.0f;
float vscale = 1.0f;
float italicscale = 0.0f;
cvInitFont (&dfont, CV_FONT_HERSHEY_SIMPLEX , hscale, vscale, italicscale, thickness, CV_AA);
cvPutText(image, text, cvPoint(x, y), &dfont, color);
}
void plot_string_on_buttun(IplImage* image, const char* text, int thickness, int x, int y, bool on_mouse)
{
if (on_mouse)
plot_string(image, text, thickness, x, y, CV_RGB(250, 250, 250));
else
plot_string(image, text, thickness, x, y, CV_RGB(150, 150, 150));
}
void plot_scan_image(IplImage* image, Two_dimensional_vector* scan_image)
{
CvSeq *points;
CvPoint pt;
CvMemStorage *storage = cvCreateMemStorage (0);
points = cvCreateSeq (CV_SEQ_ELTYPE_POINT, sizeof (CvSeq), sizeof (CvPoint), storage);
for (int i = 0; i < (int)scan_image->x.size(); i++) {
if(0 > scan_image->x[i] || scan_image->x[i] > 639) {
continue;
}
if(0 > scan_image->y[i] || scan_image->y[i] > 479) {
continue;
}
pt.x = scan_image->x[i];
pt.y = scan_image->y[i];
cvSeqPush (points, &pt);
cvCircle(image, pt, 2, CV_RGB (0, 255, 0), CV_FILLED, 8, 0);
}
cvClearSeq(points);
cvReleaseMemStorage(&storage);
}
| 36.9 | 149 | 0.651536 | filiperinaldi |
e826be4a7e76bd740d4f56a76693422e6828e30d | 4,274 | hpp | C++ | test/verify_r1cs_scheme.hpp | skywinder/crypto3-blueprint | c2b033eaaff1a19ab5332b9f49a32bb4fdd1dc20 | [
"MIT"
] | 6 | 2021-05-27T04:52:42.000Z | 2022-01-23T23:33:40.000Z | test/verify_r1cs_scheme.hpp | skywinder/crypto3-blueprint | c2b033eaaff1a19ab5332b9f49a32bb4fdd1dc20 | [
"MIT"
] | 12 | 2020-12-08T15:17:00.000Z | 2022-03-17T22:19:43.000Z | test/verify_r1cs_scheme.hpp | skywinder/crypto3-blueprint | c2b033eaaff1a19ab5332b9f49a32bb4fdd1dc20 | [
"MIT"
] | 5 | 2021-05-20T20:02:17.000Z | 2022-01-14T12:26:24.000Z | //---------------------------------------------------------------------------//
// Copyright (c) 2018-2021 Mikhail Komarov <nemo@nil.foundation>
// Copyright (c) 2020-2021 Nikita Kaskov <nbering@nil.foundation>
//
// MIT License
//
// 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.
//---------------------------------------------------------------------------//
#ifndef CRYPTO3_ZK_BLUEPRINT_VERIFY_R1CS_SCHEME_COMPONENT_TEST_HPP
#define CRYPTO3_ZK_BLUEPRINT_VERIFY_R1CS_SCHEME_COMPONENT_TEST_HPP
#include <boost/test/unit_test.hpp>
#include <nil/crypto3/zk/snark/algorithms/generate.hpp>
#include <nil/crypto3/zk/snark/algorithms/verify.hpp>
#include <nil/crypto3/zk/snark/algorithms/prove.hpp>
#include <nil/crypto3/zk/snark/schemes/ppzksnark/r1cs_gg_ppzksnark.hpp>
#include <nil/crypto3/zk/components/blueprint.hpp>
#include <nil/crypto3/algebra/curves/edwards.hpp>
using namespace nil::crypto3;
using namespace nil::crypto3::zk;
using namespace nil::crypto3::algebra;
template<typename CurveType,
typename SchemeType = snark::r1cs_gg_ppzksnark<CurveType>>
bool verify_component(components::blueprint<typename CurveType::scalar_field_type> bp){
if (bp.num_variables() == 0x00){
std::cout << "Empty blueprint!" << std::endl;
return false;
}
using field_type = typename CurveType::scalar_field_type;
using scheme_type = SchemeType;
const snark::r1cs_constraint_system<field_type> constraint_system = bp.get_constraint_system();
auto begin = std::chrono::high_resolution_clock::now();
const typename scheme_type::keypair_type keypair = snark::generate<scheme_type>(constraint_system);
auto end = std::chrono::high_resolution_clock::now();
auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin);
std::cout << "Key generation finished, time: " << elapsed.count() * 1e-9 << std::endl;
begin = std::chrono::high_resolution_clock::now();
const typename scheme_type::proof_type proof = snark::prove<scheme_type>(keypair.first, bp.primary_input(), bp.auxiliary_input());
end = std::chrono::high_resolution_clock::now();
elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin);
std::cout << "Proving finished, time: " << elapsed.count() * 1e-9 << std::endl;
begin = std::chrono::high_resolution_clock::now();
bool verified = snark::verify<scheme_type>(keypair.second, bp.primary_input(), proof);
end = std::chrono::high_resolution_clock::now();
elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin);
std::cout << "Number of R1CS constraints: " << constraint_system.num_constraints() << std::endl;
std::cout << "Verification finished, time: " << elapsed.count() * 1e-9 << std::endl;
std::cout << "Verification status: " << verified << std::endl;
return verified;
}
template<>
bool verify_component<curves::edwards<183>,
snark::r1cs_gg_ppzksnark<curves::edwards<183>>>(components::blueprint<typename curves::edwards<183>::scalar_field_type> bp){
std::cout << "Warning! r1cs_gg_ppzksnark for Edwards-183 is not implemented yet" << std::endl;
return false;
}
#endif // CRYPTO3_ZK_BLUEPRINT_VERIFY_R1CS_SCHEME_COMPONENT_TEST_HPP
| 46.967033 | 146 | 0.710108 | skywinder |
e829eb40a826947ae467322d8d56f897a0e6b444 | 541 | cpp | C++ | 2579/2579.cpp14.cpp | isac322/BOJ | 35959dd1a63d75ebca9ed606051f7a649d5c0c7b | [
"MIT"
] | 14 | 2017-05-02T02:00:42.000Z | 2021-11-16T07:25:29.000Z | 2579/2579.cpp14.cpp | isac322/BOJ | 35959dd1a63d75ebca9ed606051f7a649d5c0c7b | [
"MIT"
] | 1 | 2017-12-25T14:18:14.000Z | 2018-02-07T06:49:44.000Z | 2579/2579.cpp14.cpp | isac322/BOJ | 35959dd1a63d75ebca9ed606051f7a649d5c0c7b | [
"MIT"
] | 9 | 2016-03-03T22:06:52.000Z | 2020-04-30T22:06:24.000Z | #include <cstdio>
#include <algorithm>
using namespace std;
int v[301] = {0};
int dp[301][2] = {0};
int solve(int n, bool is_prev_stepped) {
int &p = dp[n][is_prev_stepped];
if (p != -1) return p;
int a = is_prev_stepped ? 0 : solve(n - 1, true);
int b = solve(n - 2, false);
return p = max(a, b) + v[n];
}
int main() {
int t;
scanf("%d", &t);
for (int i = 1; i <= t; i++) {
scanf("%d", v + i);
dp[i][0] = dp[i][1] = -1;
}
dp[1][0] = dp[1][1] = v[1];
dp[2][0] = v[1] + v[2];
printf("%d\n", solve(t, false));
} | 16.393939 | 50 | 0.502773 | isac322 |
e82aaa5af5b4eaaca57de857ffb8e12bfb29f08d | 10,138 | cpp | C++ | Viewer/ecflowUI/src/LimitEditor.cpp | ecmwf/ecflow | 2498d0401d3d1133613d600d5c0e0a8a30b7b8eb | [
"Apache-2.0"
] | 11 | 2020-08-07T14:42:45.000Z | 2021-10-21T01:59:59.000Z | Viewer/ecflowUI/src/LimitEditor.cpp | CoollRock/ecflow | db61dddc84d3d2c7dd6af95fd799d717c6bc2a6d | [
"Apache-2.0"
] | 10 | 2020-08-07T14:36:27.000Z | 2022-02-22T06:51:24.000Z | Viewer/ecflowUI/src/LimitEditor.cpp | CoollRock/ecflow | db61dddc84d3d2c7dd6af95fd799d717c6bc2a6d | [
"Apache-2.0"
] | 6 | 2020-08-07T14:34:38.000Z | 2022-01-10T12:06:27.000Z | //============================================================================
// Copyright 2009-2020 ECMWF.
// This software is licensed under the terms of the Apache Licence version 2.0
// which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
// In applying this licence, ECMWF does not waive the privileges and immunities
// granted to it by virtue of its status as an intergovernmental organisation
// nor does it submit to any jurisdiction.
//
//============================================================================
#include "LimitEditor.hpp"
#include <QItemSelectionModel>
#include <QMessageBox>
#include <QSettings>
#include <QStringListModel>
#include "Aspect.hpp"
#include "AttributeEditorFactory.hpp"
#include "CommandHandler.hpp"
#include "MainWindow.hpp"
#include "VAttribute.hpp"
#include "VAttributeType.hpp"
#include "VLimitAttr.hpp"
#include "SessionHandler.hpp"
#include "ServerHandler.hpp"
#include "VNode.hpp"
LimitEditorWidget::LimitEditorWidget(QWidget* parent) : QWidget(parent)
{
setupUi(this);
removeTb_->setDefaultAction(actionRemove_);
removeAllTb_->setDefaultAction(actionRemoveAll_);
killTb_->setDefaultAction(actionKill_);
//pathView_->addAction(actionRemove_);
QFont f=actionLookUp_->font();
f.setBold(true);
actionLookUp_->setFont(f);
pathView_->addAction(actionLookUp_);
auto* sep = new QAction(this);
sep->setSeparator(true);
pathView_->addAction(sep);
pathView_->addAction(actionRemove_);
pathView_->addAction(actionKill_);
pathView_->setSelectionMode(QAbstractItemView::ExtendedSelection);
pathView_->setContextMenuPolicy(Qt::ActionsContextMenu);
}
LimitEditor::LimitEditor(VInfo_ptr info,QWidget* parent) :
AttributeEditor(info,"limit",parent),
model_(nullptr)
{
w_=new LimitEditorWidget(this);
addForm(w_);
VAttribute* a=info_->attribute();
Q_ASSERT(a);
Q_ASSERT(a->type());
Q_ASSERT(a->type()->name() == "limit");
QStringList aData=a->data();
if(aData.count() < 4)
return;
QString name=aData[1];
oriVal_=aData[2].toInt();
oriMax_=aData[3].toInt();
w_->nameLabel_->setText(name);
w_->valueLabel_->setText(QString::number(oriVal_));
w_->maxSpin_->setRange(0,10000000);
w_->maxSpin_->setValue(oriMax_);
w_->maxSpin_->setFocus();
if(aData[2].isEmpty() || aData[3].isEmpty())
{
w_->actionRemove_->setEnabled(false);
w_->actionRemoveAll_->setEnabled(false);
w_->actionKill_->setEnabled(false);
return;
}
buildList(a);
connect(w_->maxSpin_,SIGNAL(valueChanged(int)),
this,SLOT(slotMaxChanged(int)));
connect(w_->actionRemove_,SIGNAL(triggered()),
this,SLOT(slotRemove()));
connect(w_->actionRemoveAll_,SIGNAL(triggered()),
this,SLOT(slotRemoveAll()));
connect(w_->actionKill_,SIGNAL(triggered()),
this,SLOT(slotKill()));
connect(w_->actionLookUp_,SIGNAL(triggered()),
this,SLOT(slotLookUp()));
connect(w_->pathView_->selectionModel(),
SIGNAL(selectionChanged(const QItemSelection&, const QItemSelection&)),
this,SLOT(slotSelection(const QItemSelection&, const QItemSelection&)));
connect(w_->pathView_,SIGNAL(doubleClicked(const QModelIndex&)),
this,SLOT(slotDoubleClicked(const QModelIndex&)));
header_->setInfo(QString::fromStdString(info_->path()),"Limit");
checkButtonStatus();
readSettings();
//No reset button is allowed because we can perform irreversible changes!
doNotUseReset();
}
LimitEditor::~LimitEditor()
{
writeSettings();
}
void LimitEditor::buildList(VAttribute *a)
{
auto* lim=static_cast<VLimitAttr*>(a);
Q_ASSERT(lim);
model_=new QStringListModel(this);
w_->pathView_->setModel(model_);
//Update the model(=node list)
setModelData(lim->paths());
}
void LimitEditor::apply()
{
int intVal=w_->valueLabel_->text().toInt();
int intMax=w_->maxSpin_->value();
std::string val=QString::number(intVal).toStdString();
std::string max=QString::number(intMax).toStdString();
std::string name=w_->nameLabel_->text().toStdString();
std::vector<std::string> valCmd;
VAttribute::buildAlterCommand(valCmd,"change","limit_value",name,val);
std::vector<std::string> maxCmd;
VAttribute::buildAlterCommand(maxCmd,"change","limit_max",name,max);
if(oriVal_ != intVal && oriMax_ != intMax)
{
if(intVal < oriMax_)
{
CommandHandler::run(info_,valCmd);
CommandHandler::run(info_,maxCmd);
}
else
{
CommandHandler::run(info_,maxCmd);
CommandHandler::run(info_,valCmd);
}
}
else if(oriVal_ != intVal)
{
CommandHandler::run(info_,valCmd);
}
else if(oriMax_ != intMax)
{
CommandHandler::run(info_,maxCmd);
}
}
void LimitEditor::resetValue()
{
}
void LimitEditor::slotMaxChanged(int)
{
checkButtonStatus();
}
bool LimitEditor::isValueChanged()
{
return (oriMax_ != w_->maxSpin_->value());
}
void LimitEditor::slotRemove()
{
remove(false);
}
void LimitEditor::slotRemoveAll()
{
remove(true);
}
void LimitEditor::remove(bool all)
{
if(!info_)
return;
//We cannot cancel the setting after remove is callled
disableCancel();
Q_ASSERT(model_);
VAttribute* a=info_->attribute();
Q_ASSERT(a);
auto* lim=static_cast<VLimitAttr*>(a);
Q_ASSERT(lim);
if(all)
{
std::vector<std::string> valCmd;
VAttribute::buildAlterCommand(valCmd,"change","limit_value",a->strName(),"0");
CommandHandler::run(info_,valCmd);
}
else
{
std::vector<std::string> paths;
Q_FOREACH(QModelIndex idx,w_->pathView_->selectionModel()->selectedRows())
{
std::vector<std::string> valCmd;
VAttribute::buildAlterCommand(valCmd,"delete","limit_path",a->strName(),
model_->data(idx,Qt::DisplayRole).toString().toStdString());
CommandHandler::run(info_,valCmd);
}
}
//Updating the gui with the new state will happen later
//because command() is asynchronous
}
void LimitEditor::slotKill()
{
if(!info_)
return;
Q_ASSERT(model_);
VAttribute* a=info_->attribute();
Q_ASSERT(a);
auto* lim=static_cast<VLimitAttr*>(a);
Q_ASSERT(lim);
std::vector<VNode*> items;
Q_FOREACH(QModelIndex idx,w_->pathView_->selectionModel()->selectedRows())
{
std::string p = model_->data(idx,Qt::DisplayRole).toString().toStdString();
if (VNode* n=info_->server()->vRoot()->find(p))
if(n->isNode())
items.push_back(n);
}
if(items.empty())
return;
if(CommandHandler::kill(items, true))
{
//We cannot cancel the setting after kill is callled
disableCancel();
}
//Updating the gui with the new state will happen later
//because command() is asynchronous
}
void LimitEditor::nodeChanged(const std::vector<ecf::Aspect::Type>& aspect)
{
bool limitCh=(std::find(aspect.begin(),aspect.end(),ecf::Aspect::LIMIT) != aspect.end());
if(limitCh && info_)
{
VAttribute* a=info_->attribute();
Q_ASSERT(a);
auto* lim=static_cast<VLimitAttr*>(a);
Q_ASSERT(lim);
QStringList aData=a->data();
if(aData.count() < 4)
return;
oriVal_=aData[2].toInt();
w_->valueLabel_->setText(QString::number(oriVal_));
oriMax_=aData[3].toInt();
w_->maxSpin_->setValue(oriMax_);
//Update the model (=node list)
setModelData(lim->paths());
}
}
void LimitEditor::setModelData(QStringList lst)
{
Q_ASSERT(model_);
bool hadData=(modelData_.isEmpty() == false);
modelData_=lst;
model_->setStringList(modelData_);
if(!modelData_.isEmpty())
{
if(!hadData)
{
w_->pathView_->setCurrentIndex(model_->index(0,0));
w_->pathView_->setFocus(Qt::MouseFocusReason);
}
w_->actionRemove_->setEnabled(true);
w_->actionRemoveAll_->setEnabled(true);
}
else
{
w_->actionRemove_->setEnabled(false);
w_->actionRemoveAll_->setEnabled(false);
}
}
void LimitEditor::slotSelection(const QItemSelection& /*selected*/, const QItemSelection& /*deselected*/)
{
bool st = w_->pathView_->selectionModel()->selectedIndexes().count() > 0;
w_->actionRemove_->setEnabled(st);
w_->actionKill_->setEnabled(st);
}
//Lookup in tree
void LimitEditor::slotLookUp()
{
QModelIndex idx=w_->pathView_->currentIndex();
lookup(idx);
}
void LimitEditor::slotDoubleClicked(const QModelIndex &index)
{
lookup(index);
}
void LimitEditor::lookup(const QModelIndex &idx)
{
if(!info_)
return;
Q_ASSERT(model_);
std::string nodePath=
model_->data(idx,Qt::DisplayRole).toString().toStdString();
VInfo_ptr ni=VInfo::createFromPath(info_->server(),nodePath);
if(ni)
{
MainWindow::lookUpInTree(ni);
}
}
void LimitEditor::writeSettings()
{
SessionItem* cs=SessionHandler::instance()->current();
Q_ASSERT(cs);
QSettings settings(QString::fromStdString(cs->qtSettingsFile("LimitEditor")),
QSettings::NativeFormat);
//We have to clear it so that should not remember all the previous values
settings.clear();
settings.beginGroup("main");
settings.setValue("size",size());
settings.endGroup();
}
void LimitEditor::readSettings()
{
SessionItem* cs=SessionHandler::instance()->current();
Q_ASSERT(cs);
QSettings settings(QString::fromStdString(cs->qtSettingsFile("LimitEditor")),
QSettings::NativeFormat);
settings.beginGroup("main");
if(settings.contains("size"))
{
resize(settings.value("size").toSize());
}
else
{
resize(QSize(420,400));
}
settings.endGroup();
}
static AttributeEditorMaker<LimitEditor> makerStr("limit");
| 25.665823 | 105 | 0.633951 | ecmwf |
e82b49954587ce2af6d6688c086789f562529784 | 812 | cpp | C++ | coj.uci.cu/FirstvsSecond.cpp | facug91/OJ-Solutions | 9aa55be066ce5596e4e64737c28cd3ff84e092fe | [
"Apache-2.0"
] | 6 | 2016-09-10T03:16:34.000Z | 2020-04-07T14:45:32.000Z | coj.uci.cu/FirstvsSecond.cpp | facug91/OJ-Solutions | 9aa55be066ce5596e4e64737c28cd3ff84e092fe | [
"Apache-2.0"
] | null | null | null | coj.uci.cu/FirstvsSecond.cpp | facug91/OJ-Solutions | 9aa55be066ce5596e4e64737c28cd3ff84e092fe | [
"Apache-2.0"
] | 2 | 2018-08-11T20:55:35.000Z | 2020-01-15T23:23:11.000Z | /*
By: facug91
From: http://coj.uci.cu/24h/problem.xhtml?pid=2691
Name: First vs Second
Date: 05/04/2015
*/
#include <bits/stdc++.h>
#define EPS 1e-9
#define DEBUG(x) cerr << "#" << (#x) << ": " << (x) << endl
const double PI = 2.0*acos(0.0);
#define INF 1000000000
//#define MOD 1000000
//#define MAXN 1000005
using namespace std;
typedef long long ll;
typedef pair<int, int> ii; typedef pair<int, ii> iii;
typedef vector<int> vi; typedef vector<ii> vii;
int n, m, s[2], t;
int main () {
ios_base::sync_with_stdio(0); cin.tie(0);
int i;
cin>>n>>m;
s[0] = s[1] = 0;
for (i=0; i<n; i++) cin>>t, s[0] += t;
for (i=0; i<m; i++) cin>>t, s[1] += t;
if (s[0] > s[1]) cout<<"first win\n";
else if (s[0] < s[1]) cout<<"second win\n";
else cout<<"tie\n";
return 0;
}
| 21.368421 | 59 | 0.565271 | facug91 |
e82d2cb5dcf66a271197b6dc5b78044987cfe354 | 599 | cpp | C++ | avs/vis_avs/g_unkn.cpp | semiessessi/vis_avs | e99a3803e9de9032e0e6759963b2c2798f3443ef | [
"BSD-3-Clause"
] | 18 | 2020-07-30T11:55:23.000Z | 2022-02-25T02:39:15.000Z | avs/vis_avs/g_unkn.cpp | semiessessi/vis_avs | e99a3803e9de9032e0e6759963b2c2798f3443ef | [
"BSD-3-Clause"
] | 34 | 2021-01-13T02:02:12.000Z | 2022-03-23T12:09:55.000Z | avs/vis_avs/g_unkn.cpp | semiessessi/vis_avs | e99a3803e9de9032e0e6759963b2c2798f3443ef | [
"BSD-3-Clause"
] | 3 | 2021-03-18T12:53:58.000Z | 2021-10-02T20:24:41.000Z | #include "g__lib.h"
#include "g__defs.h"
#include "c_unkn.h"
#include "resource.h"
#include <windows.h>
int win32_dlgproc_unknown(HWND hwndDlg, UINT uMsg, WPARAM, LPARAM)
{
C_UnknClass* g_this = (C_UnknClass*)g_current_render;
switch (uMsg)
{
case WM_INITDIALOG:
{
char s[512]="";
if (g_this->idString[0]) wsprintf(s,"APE: %s\r\n",g_this->idString);
else wsprintf(s,"Built-in ID: %d\r\n",g_this->id);
wsprintf(s+strlen(s),"Config size: %d\r\n",g_this->configdata_len);
SetDlgItemText(hwndDlg,IDC_EDIT1,s);
}
return 1;
}
return 0;
}
| 23.038462 | 76 | 0.63606 | semiessessi |
e82d366ad09f8a438f44b4123bdd65819ad0d51f | 5,774 | cpp | C++ | src/renderer/surface_smoothing_pass.cpp | gustavo4passos/opengl-fluidrendering | 572a84760b4338559e16dbca4865931e5062d34a | [
"MIT"
] | 2 | 2019-10-23T09:54:18.000Z | 2020-02-05T23:05:33.000Z | src/renderer/surface_smoothing_pass.cpp | gustavo4passos/opengl-fluidrendering | 572a84760b4338559e16dbca4865931e5062d34a | [
"MIT"
] | null | null | null | src/renderer/surface_smoothing_pass.cpp | gustavo4passos/opengl-fluidrendering | 572a84760b4338559e16dbca4865931e5062d34a | [
"MIT"
] | null | null | null | #include "surface_smoothing_pass.h"
#include "../utils/logger.h"
#include "../utils/glcall.h"
#include <assert.h>
namespace fluidity
{
SurfaceSmoothingPass::SurfaceSmoothingPass(
const unsigned bufferWidth,
const unsigned bufferHeight,
const unsigned kernelRadius,
const unsigned nIterations)
: m_bufferWidth(bufferWidth),
m_bufferHeight(bufferHeight),
m_kernelRadius(kernelRadius),
m_nIterations(nIterations),
m_fbo(0),
m_unfilteredSurfaces(0),
m_currentWorkingSurfaces(0),
m_smoothedSurfaces(0),
m_bilateralFilter(nullptr)
{ }
auto SurfaceSmoothingPass::Init() -> bool
{
GLfloat screenQuadVertices[] =
{
-1.f, 1.f, 0.f, 1.f,
1.f, 1.f, 1.f, 1.f,
-1.f, -1.f, 0.f, 0.f,
1.f, 1.f, 1.f, 1.f,
-1.f, -1.f, 0.f, 0.f,
1.f, -1.f, 1.f, 0.f
};
GLCall(glGenBuffers(1, &m_screenQuadVbo));
GLCall(glGenVertexArrays(1, &m_screenQuadVao));
GLCall(glBindVertexArray(m_screenQuadVao));
GLCall(glBindBuffer(GL_ARRAY_BUFFER, m_screenQuadVbo));
GLCall(glBufferData(
GL_ARRAY_BUFFER,
sizeof(screenQuadVertices),
screenQuadVertices,
GL_STATIC_DRAW));
GLCall(glVertexAttribPointer(
0,
2,
GL_FLOAT,
GL_FALSE,
sizeof(GLfloat) * 4,
(const GLvoid*)0));
GLCall(glEnableVertexAttribArray(0));
GLCall(glVertexAttribPointer(
1,
2,
GL_FLOAT,
GL_FALSE,
sizeof(GLfloat) * 4,
(const GLvoid*)(2 * sizeof(GLfloat))));
GLCall(glEnableVertexAttribArray(1));
GLCall(glBindVertexArray(0));
GLCall(glBindBuffer(GL_ARRAY_BUFFER, 0));
GLCall(glGenFramebuffers(1, &m_fbo));
GLCall(glBindFramebuffer(GL_FRAMEBUFFER, m_fbo));
GLCall(glGenTextures(1, &m_currentWorkingSurfaces));
GLCall(glBindTexture(GL_TEXTURE_2D, m_currentWorkingSurfaces));
GLCall(glTexImage2D(
GL_TEXTURE_2D,
0,
GL_RGBA32F,
m_bufferWidth,
m_bufferHeight,
0,
GL_RGBA,
GL_FLOAT,
nullptr));
GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST));
GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST));
GLCall(glGenTextures(1, &m_smoothedSurfaces));
GLCall(glBindTexture(GL_TEXTURE_2D, m_smoothedSurfaces));
GLCall(glTexImage2D(
GL_TEXTURE_2D,
0,
GL_RGBA32F,
m_bufferWidth,
m_bufferHeight,
0,
GL_RGBA,
GL_FLOAT,
nullptr));
GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST));
GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST));
// GLCall(glFramebufferTexture2D(
// GL_FRAMEBUFFER,
// GL_COLOR_ATTACHMENT0,
// GL_TEXTURE_2D,
// m_smoothedSurfaces,
// 0));
// if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
// {
// LOG_ERROR("Framebuffer is not complete.");
// return false;
// }
unsigned attachments[2] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 };
GLCall(glDrawBuffers(1, attachments));
GLCall(glBindFramebuffer(GL_FRAMEBUFFER, 0));
m_bilateralFilter = new Shader(
"../../shaders/texture_rendering.vert",
"../../shaders/bilateral_filter.frag");
return true;
}
auto SurfaceSmoothingPass::SetUnfilteredSurfaces(const GLuint unfilteredSurfaces) -> void
{
m_unfilteredSurfaces = unfilteredSurfaces;
}
auto SurfaceSmoothingPass::Render() -> void
{
assert(m_bilateralFilter != nullptr);
GLCall(glBindFramebuffer(GL_FRAMEBUFFER, m_fbo));
m_bilateralFilter->Bind();
m_bilateralFilter->SetInt("kernelRadius", m_kernelRadius);
GLCall(glBindVertexArray(m_screenQuadVao));
GLCall(glActiveTexture(GL_TEXTURE0));
glBindTexture(GL_TEXTURE_2D, m_unfilteredSurfaces);
GLCall(glFramebufferTexture2D(
GL_FRAMEBUFFER,
GL_COLOR_ATTACHMENT0,
GL_TEXTURE_2D,
m_smoothedSurfaces,
0));
for(unsigned i = 0; i < m_nIterations; i++)
{
GLCall(glDrawArrays(GL_TRIANGLES, 0, 6));
glBindTexture(GL_TEXTURE_2D, 0);
GLCall(glFramebufferTexture2D(
GL_FRAMEBUFFER,
GL_COLOR_ATTACHMENT0,
GL_TEXTURE_2D,
0,
0));
InvertWorkingAndSmoothedSurfaces();
GLCall(glBindTexture(GL_TEXTURE_2D, m_currentWorkingSurfaces));
GLCall(glFramebufferTexture2D(
GL_FRAMEBUFFER,
GL_COLOR_ATTACHMENT0,
GL_TEXTURE_2D,
m_smoothedSurfaces,
0));
}
InvertWorkingAndSmoothedSurfaces();
GLCall(glBindTexture(GL_TEXTURE_2D, 0));
GLCall(glBindVertexArray(0));
m_bilateralFilter->Unbind();
GLCall(glBindFramebuffer(GL_FRAMEBUFFER, 0));
}
auto SurfaceSmoothingPass::InvertWorkingAndSmoothedSurfaces() -> void
{
GLuint tempTex = m_currentWorkingSurfaces;
m_currentWorkingSurfaces = m_smoothedSurfaces;
m_smoothedSurfaces = tempTex;
}
}; | 31.380435 | 93 | 0.579841 | gustavo4passos |
e82f09d5ce4b9de3e9f6c2bb9579fd7ffdbab01f | 4,686 | cpp | C++ | tests/DocTest_Tests/CombinationTests.cpp | ExternalRepositories/ApprovalTests.cpp | 04fcc5b7345288d043d88ed6ffc08e2f69123284 | [
"Apache-2.0"
] | 259 | 2017-12-19T08:18:13.000Z | 2022-03-22T08:05:30.000Z | tests/DocTest_Tests/CombinationTests.cpp | ExternalRepositories/ApprovalTests.cpp | 04fcc5b7345288d043d88ed6ffc08e2f69123284 | [
"Apache-2.0"
] | 179 | 2018-02-01T11:20:38.000Z | 2022-02-28T09:40:21.000Z | tests/DocTest_Tests/CombinationTests.cpp | ExternalRepositories/ApprovalTests.cpp | 04fcc5b7345288d043d88ed6ffc08e2f69123284 | [
"Apache-2.0"
] | 55 | 2017-11-27T18:56:47.000Z | 2022-03-17T09:06:24.000Z | #include "doctest/doctest.h"
#include <vector>
#include <string>
#include "ApprovalTests/core/ApprovalException.h"
#include "ApprovalTests/reporters/BlockingReporter.h"
#include "ApprovalTests/CombinationApprovals.h"
#include "reporters/FakeReporter.h"
using namespace ApprovalTests;
TEST_CASE("YouCanVerifyCombinationsOf1")
{
std::vector<std::string> words{"hello", "world"};
CombinationApprovals::verifyAllCombinations(
[](const std::string& s) { return s + "!"; }, words);
}
FrontLoadedReporterDisposer clearFrontLoadedReporter()
{
return Approvals::useAsFrontLoadedReporter(
BlockingReporter::onMachineNamed("safadfasdfas"));
}
TEST_CASE("YouCanVerifyCombinationsOf1Reports")
{
auto d = clearFrontLoadedReporter();
std::vector<std::string> words{"hello", "world"};
FakeReporter reporter;
try
{
CombinationApprovals::verifyAllCombinations(
Options(reporter), [](const std::string& s) { return s + "!"; }, words);
}
catch (const ApprovalException&)
{
// ignore
}
REQUIRE(reporter.called == true);
}
TEST_CASE("YouCanVerifyCombinationsOf9")
{
std::vector<std::string> letters{"a", "b"};
CombinationApprovals::verifyAllCombinations(
[](const std::string& s1,
const std::string& s2,
const std::string& s3,
const std::string& s4,
const std::string& s5,
const std::string& s6,
const std::string& s7,
const std::string& s8,
const std::string& s9) { return s1 + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9; },
letters,
letters,
letters,
letters,
letters,
letters,
letters,
letters,
letters);
}
TEST_CASE("YouCanVerifyCombinationsOf9Reports")
{
auto d = clearFrontLoadedReporter();
FakeReporter reporter;
try
{
std::vector<std::string> letters{"a", "b"};
CombinationApprovals::verifyAllCombinations(
Options(reporter),
[](const std::string& s1,
const std::string& s2,
const std::string& s3,
const std::string& s4,
const std::string& s5,
const std::string& s6,
const std::string& s7,
const std::string& s8,
const std::string& s9) {
return s1 + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9;
},
letters,
letters,
letters,
letters,
letters,
letters,
letters,
letters,
letters);
}
catch (const ApprovalException&)
{
// ignore
}
REQUIRE(reporter.called == true);
}
TEST_CASE("YouCanVerifyCombinationsOf10")
{
std::vector<std::string> letters{"a", "b"};
CombinationApprovals::verifyAllCombinations(
[](const std::string& s1,
const std::string& s2,
const std::string& s3,
const std::string& s4,
const std::string& s5,
const std::string& s6,
const std::string& s7,
const std::string& s8,
const std::string& s9,
const std::string& s10) {
return s1 + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9 + s10;
},
letters,
letters,
letters,
letters,
letters,
letters,
letters,
letters,
letters,
letters);
}
TEST_CASE("CombinationsApiWithHeadersAndOptions")
{
std::vector<std::string> letters{"a", "b"};
auto converter = [](const std::string& s1,
const std::string& s2,
const std::string& s3) { return s1 + s2 + s3; };
SUBCASE("Without Header")
{
CombinationApprovals::verifyAllCombinations(converter, letters, letters, letters);
CombinationApprovals::verifyAllCombinations(
Options(), converter, letters, letters, letters);
}
SUBCASE("With Header")
{
// without Options - both char* and std::string for header
CombinationApprovals::verifyAllCombinations(
"TITLE", converter, letters, letters, letters);
CombinationApprovals::verifyAllCombinations(
std::string("TITLE"), converter, letters, letters, letters);
// with Options - both char* and std::string for header
CombinationApprovals::verifyAllCombinations(
Options(), "TITLE", converter, letters, letters, letters);
CombinationApprovals::verifyAllCombinations(
Options(), std::string("TITLE"), converter, letters, letters, letters);
}
}
| 29.658228 | 90 | 0.573197 | ExternalRepositories |
e830a64d4feda6e6919727636b138853ffdfe68b | 3,268 | cpp | C++ | src/Cylinder.cpp | Dav-v/Rha | 77fa838ea0830bd1f335349dd88d0a7005b4a921 | [
"Apache-2.0"
] | null | null | null | src/Cylinder.cpp | Dav-v/Rha | 77fa838ea0830bd1f335349dd88d0a7005b4a921 | [
"Apache-2.0"
] | null | null | null | src/Cylinder.cpp | Dav-v/Rha | 77fa838ea0830bd1f335349dd88d0a7005b4a921 | [
"Apache-2.0"
] | null | null | null | /*
* Author: Davide Viero - dviero42@gmail.com
* Rha raytracer
* 2019
* License: see LICENSE file
*
*/
#define GLM_ENABLE_EXPERIMENTAL
#include "cylinder.h"
#include "gtx/transform.hpp"
#include <iostream>
using namespace glm;
Cylinder::Cylinder(std::string name,
vec3 pos,
vec3 scale,
vec3 col,
float ka,
float kd,
float ks,
float kr,
float n)
{
this->name = name;
coefficients.ka = ka;
coefficients.kd = kd;
coefficients.ks = ks;
coefficients.kr = kr;
coefficients.n = n;
color = col;
//transform = mat4(1.0f);
transform = translate(transform,pos);
transform = glm::scale(transform,scale);
transform = rotate(transform, 90.0f, vec3(1.0, 0.0f,0.0f));
for(int i = 0; i < 4; i++){
std::cout<<"\n";
for(int k = 0; k < 4; k++)
std::cout<<transform[k][i]<<"\t";
}
normalsTransform = transpose(transform);
invTransform = inverse(transform);
invNormalsTransform = transpose(invTransform);
}
vec3 Cylinder::computeNormal(vec3 point)
{
vec3 invNormal;
vec3 localSpacePoint = vec3(invTransform * vec4(point, 1.0f));
if (localSpacePoint.z > 0.49 && localSpacePoint.z < 0.51)
invNormal = vec3(0.0f,0.0f,1.0f);
else if (localSpacePoint.z > -0.51 && localSpacePoint.z < -0.49)
invNormal = vec3(0.0f, 0.0f, -1.0f);
else
invNormal = normalize(vec3(localSpacePoint.x,localSpacePoint.y, 0.0f));
vec3 normal = normalize(vec3(invNormalsTransform * vec4(invNormal, 0.0f)));
return normal;
}
std::tuple<bool, std::vector<float>> Cylinder::intersections(Ray r)
{
// transformed direction in cylinder space
vec3 c1 = vec3(invTransform * vec4(r.getDirectionVector(), 0.0f));
// transformed point in cylinder space
vec3 s1 = vec3(invTransform * vec4(r.getOriginVector(), 1.0f));
/*
Equation for a ray intersection a cylinder :
t^2 (dot(cd,cd)) + 2*t (dot(cd,sd)) + (dot(sd,sd) -1) = 0
where cd = vec2(c1.x,c1.y) sd = vec2(s1.x,s1.y)
z must be -0.5<= z <= 0.5
*/
vec2 cd = vec2(c1);
vec2 sd = vec2(s1);
float a = dot(cd, cd);
float b = dot(sd, cd);
float c = (dot(sd, sd) - 1.0f);
float d = pow(b, 2.0f) - a * c;
if (d < 0.0f)
return std::make_tuple(false, std::vector<float>{0.0f});
float t0 = (-b + sqrt(d)) / a;
float t1 = (-b - sqrt(d)) / a;
bool intersected = false;
vec3 p0 = c1 * t0 +s1;
vec3 p1 = c1 * t1 +s1;
std::vector<float> intersectionsT;
if(p0.z >= -0.5 && p0.z <= 0.5)
{
intersected = true;
intersectionsT.push_back(t0);
}
if (p1.z >= -0.5 && p1.z <= 0.5)
{
intersected = true;
intersectionsT.push_back(t1);
}
float t2 = (0.5f-s1.z) / c1.z;
float t3 = (-0.5f-s1.z) / c1.z;
float x = c1.x * t2 + s1.x;
float y = c1.y * t2 + s1.y;
if(pow(x,2)+pow(y,2) <= 1.0f)
{
intersected = true;
intersectionsT.push_back(t2);
}
x = c1.x * t3 + s1.x;
y = c1.y * t3 + s1.y;
if(pow(x,2)+pow(y,2) <= 1.0f)
{
intersected = true;
intersectionsT.push_back(t3);
}
/*
if(t0>0.0001f || t1>0.0001f) return std::make_tuple(true, intersectionsT);
else return std::make_tuple(false, intersectionsT);
*/
return std::make_tuple(intersected, intersectionsT);
} | 25.333333 | 77 | 0.596389 | Dav-v |
e83299e1f2750c578e2c66549ae886f37be633c1 | 903 | cpp | C++ | 500-600/587.cpp | Thomaw/Project-Euler | bcad5d8a1fd3ebaa06fa52d92d286607e9372a8d | [
"MIT"
] | null | null | null | 500-600/587.cpp | Thomaw/Project-Euler | bcad5d8a1fd3ebaa06fa52d92d286607e9372a8d | [
"MIT"
] | null | null | null | 500-600/587.cpp | Thomaw/Project-Euler | bcad5d8a1fd3ebaa06fa52d92d286607e9372a8d | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
typedef double flt;
const flt pi = acos(-1.0), eps = 1e-9;
flt k;
flt calc(flt x) {
flt y = 1 - sqrt(1 - (x - 1) * (x - 1));
return std::min(y, k * x);
}
flt simpson(flt a, flt b) {
flt c = (a + b) * 0.5;
return (calc(a) + 4 * calc(c) + calc(b)) * (b -a) / 6;
}
flt asr(flt a, flt b, flt eps, flt A) {
flt c = (a + b) * 0.5;
flt L = simpson(a, c), R = simpson(c, b);
if (fabs(A - L - R) <= 15 * eps) return L + R + (A - L - R) / 15;
return asr(a, c, eps / 2, L) + asr(c, b, eps / 2, R);
}
flt asr(flt a, flt b, flt eps) {
return asr(a, b, eps, simpson(a, b));
}
int main() {
flt S = 1 - pi / 4;
for (int n = 2; ; ++n) {
k = 1.0 / n;
flt now = asr(0, 1, 1e-9);
if (now / S < 0.001) {
std::cout << n << std::endl;
break;
}
}
return 0;
}
| 21.5 | 68 | 0.419712 | Thomaw |
e8329c11566599a4077900a8f21b72554f741107 | 1,222 | cpp | C++ | 02.autocomplete-template/binary_search_deluxe.cpp | MrHakimov/CPP-COURSE | 7abd5251b153c7024a294bdcf92dd2671130748a | [
"MIT"
] | null | null | null | 02.autocomplete-template/binary_search_deluxe.cpp | MrHakimov/CPP-COURSE | 7abd5251b153c7024a294bdcf92dd2671130748a | [
"MIT"
] | null | null | null | 02.autocomplete-template/binary_search_deluxe.cpp | MrHakimov/CPP-COURSE | 7abd5251b153c7024a294bdcf92dd2671130748a | [
"MIT"
] | null | null | null | #include "binary_search_deluxe.hpp"
int binary_search_deluxe::first_index_of(const std::vector<term> &a, const term &key,
const std::function<bool(const term &left,
const term &right)> &comparator) {
int leftBorder = -1;
int rightBorder = a.size() - 1;
while (rightBorder - leftBorder > 1) {
int middle = (leftBorder + rightBorder) / 2;
if (comparator(a[middle], key)) {
leftBorder = middle;
} else {
rightBorder = middle;
}
}
return rightBorder;
}
int binary_search_deluxe::last_index_of(const std::vector<term> &a, const term &key,
const std::function<bool(const term &left,
const term &right)> &comparator) {
int leftBorder = 0;
int rightBorder = a.size();
while (rightBorder - leftBorder > 1) {
int middle = (leftBorder + rightBorder) / 2;
if (!comparator(key, a[middle])) {
leftBorder = middle;
} else {
rightBorder = middle;
}
}
return leftBorder;
}
| 35.941176 | 100 | 0.501637 | MrHakimov |
e836c767dab22097db382c4364e130cb44e5b488 | 48 | cpp | C++ | chapter_2/ex_2.32.cpp | YasserKa/Cpp_Primer | 198b10255fd67e31c15423a5e44b7f02abb8bdc2 | [
"MIT"
] | null | null | null | chapter_2/ex_2.32.cpp | YasserKa/Cpp_Primer | 198b10255fd67e31c15423a5e44b7f02abb8bdc2 | [
"MIT"
] | null | null | null | chapter_2/ex_2.32.cpp | YasserKa/Cpp_Primer | 198b10255fd67e31c15423a5e44b7f02abb8bdc2 | [
"MIT"
] | null | null | null | /**
* int null = 0, *p = null; it's legal
*/
| 9.6 | 38 | 0.4375 | YasserKa |
e8391600bbf2026275e2b2631d9938ab48d8308b | 1,495 | hpp | C++ | include/gl/primitives/plane.hpp | scholli/unvox | 879e06f45a40963527e0a895d742f7be6fb3d490 | [
"MIT"
] | null | null | null | include/gl/primitives/plane.hpp | scholli/unvox | 879e06f45a40963527e0a895d742f7be6fb3d490 | [
"MIT"
] | null | null | null | include/gl/primitives/plane.hpp | scholli/unvox | 879e06f45a40963527e0a895d742f7be6fb3d490 | [
"MIT"
] | 1 | 2019-10-30T09:35:35.000Z | 2019-10-30T09:35:35.000Z | //******************************************************************************
// Module: UnVox
// Author: Sebastian Thiele / Andre Schollmeyer
//
// Copyright 2019
// All rights reserved
//******************************************************************************
#ifndef UNVOX_GL_PLANE_HPP
#define UNVOX_GL_PLANE_HPP
#include <gl/glpp.hpp>
#include <gl/arraybuffer.hpp>
#include <gl/vertexarrayobject.hpp>
#include <glm/glm.hpp>
namespace unvox { namespace gl {
class UNVOX_GL plane
{
public :
plane ( GLint vertexattrib_index, GLint normalattrib_index, GLint texcoordattrib_index );
~plane ( );
plane(plane const& other) = delete;
plane operator=(plane const& other) = delete;
public :
void size ( float width, float height );
void texcoords ( glm::vec4 const& a,
glm::vec4 const& b,
glm::vec4 const& c,
glm::vec4 const& d);
void normal ( glm::vec4 const& n );
void attrib_location ( GLint vertexattrib_index,
GLint normalattrib_index,
GLint texcoordattrib_index );
void draw ( );
private :
arraybuffer _vertices;
arraybuffer _normals;
arraybuffer _texcoords;
vertexarrayobject _vao;
};
} } // namespace unvox / namespace gl
#endif // UNVOX_GL_PLANE_HPP
| 25.338983 | 111 | 0.506355 | scholli |
e83bc97b368b34510632f4702e0282cbd32d4cde | 1,206 | hpp | C++ | Hardware/Sensor/IMU/mpu9150.hpp | SaurusQ/FoamPilot | 562acfc50feb19d1216a0fabe6b85cf2f85057e4 | [
"MIT"
] | null | null | null | Hardware/Sensor/IMU/mpu9150.hpp | SaurusQ/FoamPilot | 562acfc50feb19d1216a0fabe6b85cf2f85057e4 | [
"MIT"
] | null | null | null | Hardware/Sensor/IMU/mpu9150.hpp | SaurusQ/FoamPilot | 562acfc50feb19d1216a0fabe6b85cf2f85057e4 | [
"MIT"
] | null | null | null |
#ifndef MPU9150_HPP
#define MPU9150_HPP
#include "hwSelect.hpp"
#ifdef SELECT_MPU9150
#include "imu.hpp"
#include "I2cBus.hpp"
#define MPU9150_I2C_ADDR 0x68
#define MPU9150_GYRO_CONFIG 0x27
#define MPU9150_ACCEL_CONFIG 0x28
#define MPU9150_ACCEL_XOUT_H 0x3B
#define MPU9150_PWR_MGMT_1 0x6B
// compass
#define MPU9150_MAG_I2C_ADDR 0x0C
#define MPU9150_MAG_XOUT_L 0x03
#define MPU9150_INT_PIN_CFG 0x37
enum AccelSens {
FS_2 = 0x00,
FS_4 = 0x01,
FS_8 = 0x02,
FS_16 = 0x03,
};
enum GyroSens {
FS_250 = 0x00,
FS_500 = 0x01,
FS_1000 = 0x02,
FS_2000 = 0x03,
};
class MPU9150 : public Imu
{
public:
MPU9150();
virtual ~MPU9150() {}
virtual void init();
virtual void reset();
virtual void calibrate();
virtual void update();
virtual void isHealhty();
virtual void setAccelSens(AccelSens sens);
virtual void setGyroSens(GyroSens sens);
virtual void setSleepEnabled(bool enabled);
protected:
I2cBus* pI2cBus_;
float accSensMult_;
float gyroSensMult_;
float compSensMult_;
};
#endif
#endif
| 19.451613 | 51 | 0.635158 | SaurusQ |
e83c1f860b03d287c74fb377b04d55131ea06345 | 465 | cpp | C++ | UVa 11958 - Coming Home/sample/11958 - Coming Home.cpp | tadvi/uva | 0ac0cbdf593879b4fb02a3efc09adbb031cb47d5 | [
"MIT"
] | 1 | 2020-11-24T03:17:21.000Z | 2020-11-24T03:17:21.000Z | UVa 11958 - Coming Home/sample/11958 - Coming Home.cpp | tadvi/uva | 0ac0cbdf593879b4fb02a3efc09adbb031cb47d5 | [
"MIT"
] | null | null | null | UVa 11958 - Coming Home/sample/11958 - Coming Home.cpp | tadvi/uva | 0ac0cbdf593879b4fb02a3efc09adbb031cb47d5 | [
"MIT"
] | 1 | 2021-04-11T16:22:31.000Z | 2021-04-11T16:22:31.000Z | #include <stdio.h>
int main() {
int t, cases = 0;
scanf("%d", &t);
while(t--) {
int n, H, M;
scanf("%d %d:%d", &n, &H, &M);
int mn = 0xfffffff, h, m, c;
H = H*60+M;
while(n--) {
scanf("%d:%d %d", &h, &m, &c);
h = h*60+m;
if(h < H) h += 1440;
h += c;
if(mn > h) mn = h;
}
printf("Case %d: %d\n", ++cases, mn-H);
}
return 0;
}
| 21.136364 | 47 | 0.324731 | tadvi |
e83d9cfcb45faf934945b047f904ca93c2f1c934 | 470 | cxx | C++ | athena/Simulation/ISF/ISF_FastCaloSim/ISF_FastCaloSimEvent/src/TFCSEnergyParametrization.cxx | atif4461/FCS-GPU | 181865f55d299287873f99c777aad2ef9404e961 | [
"Apache-2.0"
] | 2 | 2022-01-25T20:32:53.000Z | 2022-02-16T01:15:47.000Z | athena/Simulation/ISF/ISF_FastCaloSim/ISF_FastCaloSimEvent/src/TFCSEnergyParametrization.cxx | atif4461/FCS-GPU | 181865f55d299287873f99c777aad2ef9404e961 | [
"Apache-2.0"
] | null | null | null | athena/Simulation/ISF/ISF_FastCaloSim/ISF_FastCaloSimEvent/src/TFCSEnergyParametrization.cxx | atif4461/FCS-GPU | 181865f55d299287873f99c777aad2ef9404e961 | [
"Apache-2.0"
] | 1 | 2022-02-11T15:54:10.000Z | 2022-02-11T15:54:10.000Z | /*
Copyright (C) 2002-2018 CERN for the benefit of the ATLAS collaboration
*/
#include "ISF_FastCaloSimEvent/TFCSEnergyParametrization.h"
#include "ISF_FastCaloSimEvent/FastCaloSim_CaloCell_ID.h"
//=============================================
//======= TFCSEnergyParametrization =========
//=============================================
TFCSEnergyParametrization::TFCSEnergyParametrization(const char* name, const char* title):TFCSParametrization(name,title)
{
}
| 29.375 | 121 | 0.621277 | atif4461 |
e83e7037bc2eca8708f055dd79642d02c5c6967a | 5,623 | cpp | C++ | indra/newview/fsfloaterprotectedfolders.cpp | SaladDais/LLUDP-Encryption | 8a426cd0dd154e1a10903e0e6383f4deb2a6098a | [
"ISC"
] | 1 | 2022-01-29T07:10:03.000Z | 2022-01-29T07:10:03.000Z | indra/newview/fsfloaterprotectedfolders.cpp | bloomsirenix/Firestorm-manikineko | 67e1bb03b2d05ab16ab98097870094a8cc9de2e7 | [
"Unlicense"
] | null | null | null | indra/newview/fsfloaterprotectedfolders.cpp | bloomsirenix/Firestorm-manikineko | 67e1bb03b2d05ab16ab98097870094a8cc9de2e7 | [
"Unlicense"
] | 1 | 2021-10-01T22:22:27.000Z | 2021-10-01T22:22:27.000Z | /**
* @file fsfloaterprotectedfolders.cpp
* @brief Class for the protected folders floater
*
* $LicenseInfo:firstyear=2020&license=viewerlgpl$
* Phoenix Firestorm Viewer Source Code
* Copyright (c) 2020 Ansariel Hiller @ Second Life
*
* 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;
* version 2.1 of the License only.
*
* 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
*
* The Phoenix Firestorm Project, Inc., 1831 Oakwood Drive, Fairmont, Minnesota 56031-3225 USA
* http://www.firestormviewer.org
* $/LicenseInfo$
*/
#include "llviewerprecompiledheaders.h"
#include "fsfloaterprotectedfolders.h"
#include "fscommon.h"
#include "llbutton.h"
#include "llfiltereditor.h"
#include "llinventoryfunctions.h"
#include "llinventorymodel.h"
#include "llscrolllistctrl.h"
#include "llviewercontrol.h" // for gSavedSettings
#include "rlvactions.h"
FSFloaterProtectedFolders::FSFloaterProtectedFolders(const LLSD& key)
: LLFloater(key),
mFolderList(NULL),
mFilterSubString(LLStringUtil::null),
mFilterSubStringOrig(LLStringUtil::null),
mProtectedCategoriesChangedCallbackConnection(),
mInitialized(false)
{
}
FSFloaterProtectedFolders::~FSFloaterProtectedFolders()
{
if (mProtectedCategoriesChangedCallbackConnection.connected())
{
mProtectedCategoriesChangedCallbackConnection.disconnect();
}
}
//virtual
BOOL FSFloaterProtectedFolders::postBuild()
{
mFolderList = getChild<LLScrollListCtrl>("folder_list");
mFolderList->setFilterColumn(0);
mFolderList->setDoubleClickCallback(boost::bind(&FSFloaterProtectedFolders::onDoubleClick, this));
mRemoveFolderBtn = getChild<LLButton>("remove_btn");
mRemoveFolderBtn->setCommitCallback(boost::bind(&FSFloaterProtectedFolders::handleRemove, this));
mFilterEditor = getChild<LLFilterEditor>("filter_input");
mFilterEditor->setCommitCallback(boost::bind(&FSFloaterProtectedFolders::onFilterEdit, this, _2));
return TRUE;
}
//virtual
void FSFloaterProtectedFolders::onOpen(const LLSD& /*info*/)
{
if (!mInitialized)
{
if (!gInventory.isInventoryUsable())
{
return;
}
mProtectedCategoriesChangedCallbackConnection = gSavedPerAccountSettings.getControl("FSProtectedFolders")->getCommitSignal()->connect(boost::bind(&FSFloaterProtectedFolders::updateList, this));
updateList();
mInitialized = true;
}
}
//virtual
void FSFloaterProtectedFolders::draw()
{
LLFloater::draw();
mRemoveFolderBtn->setEnabled(mFolderList->getNumSelected() > 0);
}
//virtual
BOOL FSFloaterProtectedFolders::handleKeyHere(KEY key, MASK mask)
{
if (FSCommon::isFilterEditorKeyCombo(key, mask))
{
mFilterEditor->setFocus(TRUE);
return TRUE;
}
return LLFloater::handleKeyHere(key, mask);
}
void FSFloaterProtectedFolders::updateList()
{
bool needs_sort = mFolderList->isSorted();
mFolderList->setNeedsSort(false);
mFolderList->clearRows();
LLSD protected_folders = gSavedPerAccountSettings.getLLSD("FSProtectedFolders");
for (LLSD::array_const_iterator it = protected_folders.beginArray(); it != protected_folders.endArray(); ++it)
{
LLUUID id = (*it).asUUID();
LLViewerInventoryCategory* cat = gInventory.getCategory(id);
LLSD row_data;
row_data["value"] = id;
row_data["columns"][0]["column"] = "name";
row_data["columns"][0]["value"] = cat ? cat->getName() : getString("UnknownFolder");
LLScrollListItem* row = mFolderList->addElement(row_data);
if (!cat)
{
LLScrollListText* name_column = (LLScrollListText*)row->getColumn(0);
name_column->setFontStyle(LLFontGL::NORMAL | LLFontGL::ITALIC);
}
}
mFolderList->setNeedsSort(needs_sort);
mFolderList->updateSort();
}
void FSFloaterProtectedFolders::handleRemove()
{
uuid_set_t selected_ids;
std::vector<LLScrollListItem*> selected_items = mFolderList->getAllSelected();
for (std::vector<LLScrollListItem*>::iterator it = selected_items.begin(); it != selected_items.end(); ++it)
{
selected_ids.insert((*it)->getUUID());
}
LLSD protected_folders = gSavedPerAccountSettings.getLLSD("FSProtectedFolders");
LLSD new_protected_folders;
for (LLSD::array_const_iterator it = protected_folders.beginArray(); it != protected_folders.endArray(); ++it)
{
if (selected_ids.find((*it).asUUID()) == selected_ids.end())
{
new_protected_folders.append(*it);
}
}
gSavedPerAccountSettings.setLLSD("FSProtectedFolders", new_protected_folders);
}
void FSFloaterProtectedFolders::onFilterEdit(const std::string& search_string)
{
mFilterSubStringOrig = search_string;
LLStringUtil::trimHead(mFilterSubStringOrig);
// Searches are case-insensitive
std::string search_upper = mFilterSubStringOrig;
LLStringUtil::toUpper(search_upper);
if (mFilterSubString == search_upper)
{
return;
}
mFilterSubString = search_upper;
// Apply new filter.
mFolderList->setFilterString(mFilterSubStringOrig);
}
void FSFloaterProtectedFolders::onDoubleClick()
{
LLUUID selected_item_id = mFolderList->getStringUUIDSelectedItem();
if (selected_item_id.notNull() && (!RlvActions::isRlvEnabled() || !RlvActions::hasBehaviour(RLV_BHVR_SHOWINV)))
{
show_item_original(selected_item_id);
}
}
| 29.439791 | 195 | 0.764183 | SaladDais |
e84aad78cb7c40555ddc41b8a8e2a6a6d231abe4 | 13,788 | cpp | C++ | src/common/motion_model/test/test_differential_motion_model.cpp | ruvus/auto | 25ae62d6e575cae40212356eed43ec3e76e9a13e | [
"Apache-2.0"
] | 19 | 2021-05-28T06:14:21.000Z | 2022-03-10T10:03:08.000Z | src/common/motion_model/test/test_differential_motion_model.cpp | ruvus/auto | 25ae62d6e575cae40212356eed43ec3e76e9a13e | [
"Apache-2.0"
] | 222 | 2021-10-29T22:00:27.000Z | 2022-03-29T20:56:34.000Z | src/common/motion_model/test/test_differential_motion_model.cpp | ruvus/auto | 25ae62d6e575cae40212356eed43ec3e76e9a13e | [
"Apache-2.0"
] | 14 | 2021-05-29T14:59:17.000Z | 2022-03-10T10:03:09.000Z | // Copyright 2021 Apex.AI, 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.
//
// Developed by Apex.AI, Inc.
#include <motion_model/differential_drive_motion_model.hpp>
#include <state_vector/common_states.hpp>
#include <gtest/gtest.h>
#include <array>
#include <chrono>
#include <cmath>
using autoware::common::motion_model::CatrMotionModel32;
using autoware::common::motion_model::CvtrMotionModel32;
using autoware::common::state_vector::variable::X;
using autoware::common::state_vector::variable::Y;
using autoware::common::state_vector::variable::YAW;
using autoware::common::state_vector::variable::YAW_CHANGE_RATE;
using autoware::common::state_vector::variable::XY_VELOCITY;
using autoware::common::state_vector::variable::XY_ACCELERATION;
using autoware::common::types::float32_t;
using std::sqrt;
using std::sin;
using std::cos;
namespace
{
constexpr auto kEpsilon = 1.0e-6F;
} // namespace
/// @test Make sure a static object stays static.
TEST(CvtrMotionModelTest, PredictStaticObject) {
CvtrMotionModel32 model;
CvtrMotionModel32::State initial_state{CvtrMotionModel32::State{}};
initial_state.at<X>() = 42.0F;
initial_state.at<Y>() = 42.0F;
initial_state.at<YAW>() = 1.0F;
EXPECT_EQ(
initial_state, model.predict(initial_state, std::chrono::milliseconds{100LL}));
}
/// @test Make sure a static object stays static.
TEST(CatrMotionModelTest, PredictStaticObject) {
CatrMotionModel32 model;
CatrMotionModel32::State initial_state{CatrMotionModel32::State{}};
initial_state.at<X>() = 42.0F;
initial_state.at<Y>() = 42.0F;
initial_state.at<YAW>() = 1.0F;
EXPECT_EQ(
initial_state, model.predict(initial_state, std::chrono::milliseconds{100LL}));
}
/// @test Check that the Jacobian matches one computed symbolically when turn rate is not zero.
TEST(CvtrMotionModelTest, TestJacobianNonZeroTurnRate) {
CvtrMotionModel32::State state{CvtrMotionModel32::State{}};
state.at<X>() = 42.0F;
state.at<Y>() = 23.0F;
state.at<YAW>() = 0.5F;
state.at<XY_VELOCITY>() = 2.0F;
state.at<YAW_CHANGE_RATE>() = 2.0F;
// Computed with SymPy.
CvtrMotionModel32::State::Matrix expected_jacobian{(CvtrMotionModel32::State::Matrix{} <<
1.0F, 0.0F, -0.112740374605884F, 0.082396074316744F, -0.00591185558829518F,
0.0F, 1.0F, 0.164792148633488F, 0.0563701873029421F, 0.00805158142082696F,
0.0F, 0.0F, 1.0F, 0.0F, 0.0F,
0.0F, 0.0F, 0.0F, 1.0F, 0.1F,
0.0F, 0.0F, 0.0F, 0.0F, 1.0F).finished()};
CvtrMotionModel32 model;
const auto jacobian = model.jacobian(state, std::chrono::milliseconds{100LL});
EXPECT_TRUE(expected_jacobian.isApprox(jacobian, kEpsilon)) <<
"Jacobians don't match: \nExpected:\n" << expected_jacobian << "\nActual:\n" << jacobian;
}
/// @test Check that the Jacobian matches one computed symbolically when turn rate is not zero.
TEST(CatrMotionModelTest, TestJacobianNonZeroTurnRate) {
CatrMotionModel32::State state{CatrMotionModel32::State{}};
state.at<X>() = 42.0F;
state.at<Y>() = 23.0F;
state.at<YAW>() = 0.5F;
state.at<XY_VELOCITY>() = 2.0F;
state.at<YAW_CHANGE_RATE>() = 2.0F;
state.at<XY_ACCELERATION>() = 2.0F;
// Computed with SymPy.
CatrMotionModel32::State::Matrix expected_jacobian{(CatrMotionModel32::State::Matrix{} <<
1.0F, 0.0F, -0.1186522F, 0.0823960F, -0.0063150F, 0.0040257F,
0.0F, 1.0F, 0.1728437F, 0.0563701F, 0.0085819F, 0.0029559277F,
0.0F, 0.0F, 1.0F, 0.0F, 0.1F, 0.0F,
0.0F, 0.0F, 0.0F, 1.0F, 0.0F, 0.1F,
0.0F, 0.0F, 0.0F, 0.0F, 1.0F, 0.0F,
0.0F, 0.0F, 0.0F, 0.0F, 0.0F, 1.0F).finished()};
CatrMotionModel32 model;
const auto jacobian = model.jacobian(state, std::chrono::milliseconds{100LL});
EXPECT_TRUE(expected_jacobian.isApprox(jacobian, kEpsilon)) <<
"Jacobians don't match: \nExpected:\n" << expected_jacobian << "\nActual:\n" << jacobian;
}
/// @test Check that the Jacobian matches one computed symbolically when turn rate is zero.
TEST(CvtrMotionModelTest, TestJacobianZeroTurnRate) {
CvtrMotionModel32::State state{CvtrMotionModel32::State{}};
state.at<X>() = 42.0F;
state.at<Y>() = 23.0F;
state.at<YAW>() = 0.5F;
state.at<XY_VELOCITY>() = 2.0F;
state.at<YAW_CHANGE_RATE>() = 0.0F;
// Computed with SymPy.
CvtrMotionModel32::State::Matrix expected_jacobian{(CvtrMotionModel32::State::Matrix{} <<
1.0F, 0.0F, -0.0958851077208406F, 0.0877582561890373F, -0.00958851077208406F,
0.0F, 1.0F, 0.175516512378075F, 0.0479425538604203F, 0.0175516512378075F,
0.0F, 0.0F, 1.0F, 0.0F, 0.0F,
0.0F, 0.0F, 0.0F, 1.0F, 0.0F,
0.0F, 0.0F, 0.0F, 0.0F, 1.0F).finished()};
CvtrMotionModel32 model;
const auto jacobian = model.jacobian(state, std::chrono::milliseconds{100LL});
EXPECT_TRUE(expected_jacobian.isApprox(jacobian, kEpsilon)) <<
"Jacobians don't match: \nExpected:\n" << expected_jacobian << "\nActual:\n" << jacobian;
}
/// @test Check that the Jacobian matches one computed symbolically when turn rate is zero.
TEST(CatrMotionModelTest, TestJacobianZeroTurnRate) {
CatrMotionModel32::State state{CatrMotionModel32::State{}};
state.at<X>() = 42.0F;
state.at<Y>() = 23.0F;
state.at<YAW>() = 0.5F;
state.at<XY_VELOCITY>() = 2.0F;
state.at<YAW_CHANGE_RATE>() = 0.0F;
state.at<XY_ACCELERATION>() = 2.0F;
// Computed with SymPy.
CatrMotionModel32::State::Matrix expected_jacobian{(CatrMotionModel32::State::Matrix{} <<
1.0F, 0.0F, -0.1006793F, 0.0877582F, -0.0100679F, 0.0043879F,
0.0F, 1.0F, 0.1842923F, 0.0479425F, 0.0184292F, 0.0023971F,
0.0F, 0.0F, 1.0F, 0.0F, 0.0F, 0.0F,
0.0F, 0.0F, 0.0F, 1.0F, 0.0F, 0.1F,
0.0F, 0.0F, 0.0F, 0.0F, 1.0F, 0.0F,
0.0F, 0.0F, 0.0F, 0.0F, 0.0F, 1.0F).finished()};
CatrMotionModel32 model;
const auto jacobian = model.jacobian(state, std::chrono::milliseconds{100LL});
EXPECT_TRUE(expected_jacobian.isApprox(jacobian, kEpsilon)) <<
"Jacobians don't match: \nExpected:\n" << expected_jacobian << "\nActual:\n" << jacobian;
}
/// @test Predict the linear movement with zero turn rate.
TEST(CvtrMotionModelTest, PredictLinearMovementWithZeroTurnRate) {
CvtrMotionModel32 model;
CvtrMotionModel32::State initial_state{};
// Movement in X direction.
initial_state = CvtrMotionModel32::State{};
initial_state.at<XY_VELOCITY>() = 1.0F;
CvtrMotionModel32::State expected_state{initial_state};
expected_state.at<X>() += 1.0F;
EXPECT_EQ(expected_state, model.predict(initial_state, std::chrono::seconds{1LL}));
// Movement in negative X direction.
initial_state = CvtrMotionModel32::State{};
initial_state.at<XY_VELOCITY>() = -1.0F;
expected_state = initial_state;
expected_state.at<X>() -= 1.0F;
EXPECT_EQ(expected_state, model.predict(initial_state, std::chrono::seconds{1LL}));
// Movement in Y direction.
initial_state = CvtrMotionModel32::State{};
initial_state.at<XY_VELOCITY>() = 1.0F;
initial_state.at<YAW>() = 0.5F * M_PIf32;
expected_state = initial_state;
expected_state.at<Y>() += 1.0F;
EXPECT_EQ(expected_state, model.predict(initial_state, std::chrono::seconds{1LL}));
// Movement in negative Y direction.
initial_state = CvtrMotionModel32::State{};
initial_state.at<XY_VELOCITY>() = 1.0F;
initial_state.at<YAW>() = -0.5F * M_PIf32;
expected_state = initial_state;
expected_state.at<Y>() -= 1.0F;
EXPECT_EQ(expected_state, model.predict(initial_state, std::chrono::seconds{1LL}));
// Movement in XY direction.
initial_state = CvtrMotionModel32::State{};
initial_state.at<XY_VELOCITY>() = 1.0F;
initial_state.at<YAW>() = 0.25F * M_PIf32;
expected_state = initial_state;
expected_state.at<X>() += 0.5F * sqrt(2.0F);
expected_state.at<Y>() += 0.5F * sqrt(2.0F);
EXPECT_EQ(expected_state, model.predict(initial_state, std::chrono::seconds{1LL}));
// Movement in negative XY direction.
initial_state = CvtrMotionModel32::State{};
initial_state.at<XY_VELOCITY>() = 1.0F;
initial_state.at<YAW>() = -0.75F * M_PIf32;
expected_state = initial_state;
expected_state.at<X>() -= 0.5F * sqrt(2.0F);
expected_state.at<Y>() -= 0.5F * sqrt(2.0F);
EXPECT_EQ(expected_state, model.predict(initial_state, std::chrono::seconds{1LL}));
}
/// @test Predict the linear movement with zero turn rate.
TEST(CatrMotionModelTest, PredictLinearMovementWithZeroTurnRate) {
CatrMotionModel32 model;
CatrMotionModel32::State initial_state{};
// Movement in X direction.
initial_state = CatrMotionModel32::State{};
initial_state.at<XY_VELOCITY>() = 1.0F;
initial_state.at<XY_ACCELERATION>() = 1.0F;
const auto time_difference{std::chrono::seconds{1LL}};
const auto dt{std::chrono::duration<float32_t>{time_difference}.count()};
CatrMotionModel32::State expected_state{initial_state};
expected_state.at<X>() +=
dt * initial_state.at<XY_VELOCITY>() + 0.5F * dt * dt * initial_state.at<XY_ACCELERATION>();
expected_state.at<XY_VELOCITY>() += dt * initial_state.at<XY_ACCELERATION>();
EXPECT_EQ(expected_state, model.predict(initial_state, time_difference));
// Movement in negative X direction.
initial_state = CatrMotionModel32::State{};
initial_state.at<XY_VELOCITY>() = -1.0F;
initial_state.at<XY_ACCELERATION>() = -1.0F;
expected_state = initial_state;
expected_state.at<X>() +=
dt * initial_state.at<XY_VELOCITY>() + 0.5F * dt * dt * initial_state.at<XY_ACCELERATION>();
expected_state.at<XY_VELOCITY>() += dt * initial_state.at<XY_ACCELERATION>();
EXPECT_EQ(expected_state, model.predict(initial_state, time_difference));
// Movement in Y direction.
initial_state = CatrMotionModel32::State{};
initial_state.at<XY_VELOCITY>() = 1.0F;
initial_state.at<XY_ACCELERATION>() = 1.0F;
initial_state.at<YAW>() = 0.5F * M_PIf32;
expected_state = initial_state;
expected_state.at<Y>() +=
dt * initial_state.at<XY_VELOCITY>() + 0.5F * dt * dt * initial_state.at<XY_ACCELERATION>();
expected_state.at<XY_VELOCITY>() += dt * initial_state.at<XY_ACCELERATION>();
EXPECT_EQ(expected_state, model.predict(initial_state, time_difference));
// Movement in negative Y direction.
initial_state = CatrMotionModel32::State{};
initial_state.at<XY_VELOCITY>() = 1.0F;
initial_state.at<XY_ACCELERATION>() = 1.0F;
initial_state.at<YAW>() = -0.5F * M_PIf32;
expected_state = initial_state;
expected_state.at<Y>() -=
dt * initial_state.at<XY_VELOCITY>() + 0.5F * dt * dt * initial_state.at<XY_ACCELERATION>();
expected_state.at<XY_VELOCITY>() += dt * initial_state.at<XY_ACCELERATION>();
EXPECT_EQ(expected_state, model.predict(initial_state, time_difference));
// Movement in XY direction.
initial_state = CatrMotionModel32::State{};
initial_state.at<XY_VELOCITY>() = 1.0F;
initial_state.at<XY_ACCELERATION>() = 1.0F;
initial_state.at<YAW>() = 0.25F * M_PIf32;
expected_state = initial_state;
const auto distance =
dt * initial_state.at<XY_VELOCITY>() + 0.5F * dt * dt * initial_state.at<XY_ACCELERATION>();
expected_state.at<X>() += sqrt(0.5F * distance * distance);
expected_state.at<Y>() += sqrt(0.5F * distance * distance);
expected_state.at<XY_VELOCITY>() += dt * initial_state.at<XY_ACCELERATION>();
EXPECT_EQ(expected_state, model.predict(initial_state, time_difference));
// Movement in negative XY direction.
initial_state = CatrMotionModel32::State{};
initial_state.at<XY_VELOCITY>() = 1.0F;
initial_state.at<XY_ACCELERATION>() = 1.0F;
initial_state.at<YAW>() = -0.75F * M_PIf32;
expected_state = initial_state;
expected_state.at<X>() -= sqrt(0.5F * distance * distance);
expected_state.at<Y>() -= sqrt(0.5F * distance * distance);
expected_state.at<XY_VELOCITY>() += dt * initial_state.at<XY_ACCELERATION>();
EXPECT_EQ(expected_state, model.predict(initial_state, time_difference));
}
/// @test Predict the linear movement with non-zero turn rate.
TEST(CvtrMotionModelTest, PredictLinearMovementWithNonzeroTurnRate) {
CvtrMotionModel32 model;
CvtrMotionModel32::State initial_state{};
initial_state.at<X>() = 42.0F;
initial_state.at<Y>() = 23.0F;
initial_state.at<YAW>() = 0.5F;
initial_state.at<XY_VELOCITY>() = 2.0F;
initial_state.at<YAW_CHANGE_RATE>() = 2.0F;
CvtrMotionModel32::State expected_state{initial_state};
// Values computed from a symbolic math derivation.
expected_state.at<X>() = 42.1647921486335F;
expected_state.at<Y>() = 23.1127403746059F;
expected_state.at<YAW>() = 0.7F;
EXPECT_EQ(expected_state, model.predict(initial_state, std::chrono::milliseconds{100LL}));
}
/// @test Predict the linear movement with non-zero turn rate.
TEST(CatrMotionModelTest, PredictLinearMovementWithNonzeroTurnRate) {
CatrMotionModel32 model;
CatrMotionModel32::State initial_state{};
initial_state.at<X>() = 42.0F;
initial_state.at<Y>() = 23.0F;
initial_state.at<YAW>() = 0.5F;
initial_state.at<XY_VELOCITY>() = 2.0F;
initial_state.at<YAW_CHANGE_RATE>() = 2.0F;
initial_state.at<XY_ACCELERATION>() = 2.0F;
CatrMotionModel32::State expected_state{initial_state};
// Values computed from a symbolic math derivation.
expected_state.at<X>() = 42.1728437300543F;
expected_state.at<Y>() = 23.1186522301942F;
expected_state.at<YAW>() = 0.7F;
expected_state.at<XY_VELOCITY>() = 2.2F;
EXPECT_EQ(expected_state, model.predict(initial_state, std::chrono::milliseconds{100LL}));
}
| 42.819876 | 96 | 0.715912 | ruvus |
e84bd307a0b127644bc42956a19244650e5e8920 | 3,065 | cpp | C++ | aws-cpp-sdk-cloudformation/source/model/StackDriftDetectionStatus.cpp | curiousjgeorge/aws-sdk-cpp | 09b65deba03cfbef9a1e5d5986aa4de71bc03cd8 | [
"Apache-2.0"
] | 2 | 2019-03-11T15:50:55.000Z | 2020-02-27T11:40:27.000Z | aws-cpp-sdk-cloudformation/source/model/StackDriftDetectionStatus.cpp | curiousjgeorge/aws-sdk-cpp | 09b65deba03cfbef9a1e5d5986aa4de71bc03cd8 | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-cloudformation/source/model/StackDriftDetectionStatus.cpp | curiousjgeorge/aws-sdk-cpp | 09b65deba03cfbef9a1e5d5986aa4de71bc03cd8 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 <aws/cloudformation/model/StackDriftDetectionStatus.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>
using namespace Aws::Utils;
namespace Aws
{
namespace CloudFormation
{
namespace Model
{
namespace StackDriftDetectionStatusMapper
{
static const int DETECTION_IN_PROGRESS_HASH = HashingUtils::HashString("DETECTION_IN_PROGRESS");
static const int DETECTION_FAILED_HASH = HashingUtils::HashString("DETECTION_FAILED");
static const int DETECTION_COMPLETE_HASH = HashingUtils::HashString("DETECTION_COMPLETE");
StackDriftDetectionStatus GetStackDriftDetectionStatusForName(const Aws::String& name)
{
int hashCode = HashingUtils::HashString(name.c_str());
if (hashCode == DETECTION_IN_PROGRESS_HASH)
{
return StackDriftDetectionStatus::DETECTION_IN_PROGRESS;
}
else if (hashCode == DETECTION_FAILED_HASH)
{
return StackDriftDetectionStatus::DETECTION_FAILED;
}
else if (hashCode == DETECTION_COMPLETE_HASH)
{
return StackDriftDetectionStatus::DETECTION_COMPLETE;
}
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
overflowContainer->StoreOverflow(hashCode, name);
return static_cast<StackDriftDetectionStatus>(hashCode);
}
return StackDriftDetectionStatus::NOT_SET;
}
Aws::String GetNameForStackDriftDetectionStatus(StackDriftDetectionStatus enumValue)
{
switch(enumValue)
{
case StackDriftDetectionStatus::DETECTION_IN_PROGRESS:
return "DETECTION_IN_PROGRESS";
case StackDriftDetectionStatus::DETECTION_FAILED:
return "DETECTION_FAILED";
case StackDriftDetectionStatus::DETECTION_COMPLETE:
return "DETECTION_COMPLETE";
default:
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
}
return {};
}
}
} // namespace StackDriftDetectionStatusMapper
} // namespace Model
} // namespace CloudFormation
} // namespace Aws
| 34.829545 | 104 | 0.679935 | curiousjgeorge |
e84f306d88c484e88a6b89bfcadf2b5bea567ef6 | 4,540 | hpp | C++ | inc/phi_BLR.hpp | rchan26/hierarchicalFusion | 20cb965526b47ae8f0373bdbdcbdb76d99ab8618 | [
"CC-BY-4.0"
] | 1 | 2021-09-27T15:32:50.000Z | 2021-09-27T15:32:50.000Z | inc/phi_BLR.hpp | rchan26/hierarchicalFusion | 20cb965526b47ae8f0373bdbdcbdb76d99ab8618 | [
"CC-BY-4.0"
] | null | null | null | inc/phi_BLR.hpp | rchan26/hierarchicalFusion | 20cb965526b47ae8f0373bdbdcbdb76d99ab8618 | [
"CC-BY-4.0"
] | 1 | 2021-12-09T03:22:51.000Z | 2021-12-09T03:22:51.000Z | #ifndef PHI_BLR
#define PHI_BLR
#include <RcppArmadillo.h>
arma::vec log_BLR_gradient(const arma::vec &beta,
const arma::vec &y_labels,
const arma::mat &X,
const arma::vec &X_beta,
const arma::vec &count,
const arma::vec &prior_means,
const arma::vec &prior_variances,
const double &C);
arma::mat log_BLR_hessian(const arma::mat &X,
const arma::vec &X_beta,
const arma::vec &count,
const arma::vec &prior_variances,
const double &C);
Rcpp::List ea_phi_BLR_DL_vec(const arma::vec &beta,
const arma::vec &y_labels,
const arma::mat &X,
const arma::vec &count,
const arma::vec &prior_means,
const arma::vec &prior_variances,
const double &C,
const arma::mat &precondition_mat);
Rcpp::List ea_phi_BLR_DL_matrix(const arma::mat &beta,
const arma::vec &y_labels,
const arma::mat &X,
const arma::vec &count,
const arma::vec &prior_means,
const arma::vec &prior_variances,
const double &C,
const arma::mat &precondition_mat);
double spectral_radius_BLR(const arma::vec &beta,
const int &dim,
const arma::mat &X,
const arma::vec &count,
const arma::vec &prior_variances,
const double &C,
const arma::mat &Lambda);
Rcpp::List obtain_hypercube_centre_BLR(const Rcpp::List &bessel_layers,
const arma::mat &transform_to_X,
const arma::vec &y_labels,
const arma::mat &X,
const arma::vec &count,
const arma::vec &prior_means,
const arma::vec &prior_variances,
const double &C);
Rcpp::List spectral_radius_bound_BLR_Z(const int &dim,
const arma::mat &V,
const arma::mat &X,
const arma::vec &count,
const arma::vec &prior_variances,
const double &C,
const arma::mat &sqrt_Lambda);
Rcpp::List spectral_radius_global_bound_BLR_Z(const int &dim,
const arma::mat &X,
const arma::vec &count,
const arma::vec &prior_variances,
const double &C,
const arma::mat &sqrt_Lambda);
Rcpp::List ea_phi_BLR_DL_bounds(const arma::vec &beta_hat,
const arma::vec &grad_log_hat,
const int &dim,
const arma::mat &X,
const arma::vec &count,
const arma::vec &prior_variances,
const double &C,
const Rcpp::List &transform_mats,
const Rcpp::List &hypercube_vertices,
const bool &local_bounds);
double gamma_NB_BLR(const arma::vec ×,
const double &h,
const arma::vec &x0,
const arma::vec &y,
const double &s,
const double &t,
const arma::vec &y_labels,
const arma::mat &X,
const arma::vec &count,
const arma::vec &prior_means,
const arma::vec &prior_variances,
const double &C,
const arma::mat &precondition_mat);
#endif | 47.291667 | 79 | 0.396035 | rchan26 |
e850145eff970058bfbda746530cd3ee98a51fcd | 9,709 | cpp | C++ | OpenGL_GLFW_Project/GeometryShaderExplosion.cpp | millerf1234/OpenGL_Windows_Projects | 26161ba3c820df366a83baaf6e2a275d874c6acd | [
"MIT"
] | null | null | null | OpenGL_GLFW_Project/GeometryShaderExplosion.cpp | millerf1234/OpenGL_Windows_Projects | 26161ba3c820df366a83baaf6e2a275d874c6acd | [
"MIT"
] | null | null | null | OpenGL_GLFW_Project/GeometryShaderExplosion.cpp | millerf1234/OpenGL_Windows_Projects | 26161ba3c820df366a83baaf6e2a275d874c6acd | [
"MIT"
] | null | null | null | //See header file for details
//This file will most likely closely resemble the file "RenderProject1.cpp"
#include "GeometryShaderExplosion.h"
void GeometryShaderExplosion::initialize() {
error = false;
window = nullptr;
frameNumber = 0ull;
frameUnpaused = 0ull;
frameOfMostRecentColorRecording = 0ull;
counter = 0.0f;
zRotation = 0.0f;
//Set initial background color
backgroundColor = glm::vec3(0.25f, 0.5f, 0.75f);
glEnable(GL_PROGRAM_POINT_SIZE);
}
GeometryShaderExplosion::GeometryShaderExplosion(std::shared_ptr<MonitorData> screenInfo) {
initialize();
//Make sure we have a monitor to render to
if (!screenInfo || !screenInfo->activeMonitor) {
error = true;
return;
}
//Make sure the context is set to this monitor (and this thread [see glfw documentation])
if (glfwGetCurrentContext() != screenInfo->activeMonitor) {
std::ostringstream warning;
warning << "\nWARNING!\n[In GeometryShaderExplosion's constructor]\n" <<
"GeometryShaderExplosion detected that the glfw active context was set" <<
"\nto a different monitor or different execution-thread then\n" <<
"the one passed to GeometryShaderExplosion's contructor!\n";
warning << "This means that running GeometryShaderExplosion will invalidate\n" <<
"the previoud context by replacing it with this one, which\n" <<
"could lead to errors! Please ensure that the correct context is\n" <<
"being passed to GeometryShaderExplosion in the application code!\n";
fprintf(WRNLOG, warning.str().c_str());
glfwMakeContextCurrent(screenInfo->activeMonitor);
}
window = screenInfo->activeMonitor;
}
GeometryShaderExplosion::~GeometryShaderExplosion() {
}
void GeometryShaderExplosion::run() {
if (error) {
fprintf(ERRLOG, "An error occured while loading GeometryShaderExplosion\n");
return;
}
fprintf(MSGLOG, "\nGeometryShaderExplosion demo project has loaded and will begin running!\n");
fprintf(MSGLOG, "\n\tDemo Starting...!\n");
fprintf(MSGLOG, "\nEntering Render Loop...\n");
renderLoop();
}
void GeometryShaderExplosion::loadAssets() {
loadShaders(); //load the GLSL shader code
loadTeapot(); //have the GL context load the Teapot vertices to video memory
}
void GeometryShaderExplosion::loadShaders() {
fprintf(MSGLOG, "\nInitializing Shaders!\n");
sceneShader = std::make_unique<ShaderProgram>();
//There is just 1 pipeline here to build. Here is the pipeline
//---------------------------
// (VERTEX STAGE)
// Attach a helper shader with just some useful functions
fprintf(MSGLOG, "\nAttaching secondary helper vertex shader!\n");
std::unique_ptr<ShaderInterface::VertexShader> vertHelper = std::make_unique<ShaderInterface::VertexShader>("VertMath.vert");
if (!vertHelper)
return;
vertHelper->makeSecondary();
sceneShader->attachSecondaryVert(vertHelper.get());
//Attach the primary vertex shader
fprintf(MSGLOG, "\nAttaching main vertex shader!\n");
sceneShader->attachVert("GeometryShaderExplosion.vert");
//---------------------------
//---------------------------
// (Geometry Stage)
// Attach the primary geometry shader to the pipeline. (This is where the explosion happens)
fprintf(MSGLOG, "\nAttaching geometry shader!\n");
sceneShader->attachGeom("GeometryShaderExplosion.geom");
//--------------------------
//--------------------------
// (Fragment Stage)
// Attach the primary Fragment Shader to the pipeline
fprintf(MSGLOG, "\nAttaching fragment shader!\n");
sceneShader->attachFrag("GeometryShaderExplosion.frag");
fprintf(MSGLOG, "\nAttempting to link program!\n");
//---------------------------
// AT THIS POINT, ALL OF THE PIPELINE STAGES HAVE BEEN ATTACHED, SO LINK THE PIPELINE AND CHECK FOR ERRORS
sceneShader->link();
if (sceneShader->checkIfLinked()) {
fprintf(MSGLOG, "Program Successfully linked!\n");
}
else {
fprintf(ERRLOG, "Shader Program was not successfully linked!\n");
fprintf(MSGLOG, "\t[Press 'ENTER' to attempt to continue program execution]\n");
std::cin.get(); //Hold the window open if there was an error
}
}
void GeometryShaderExplosion::loadTeapot() {
fprintf(MSGLOG, "\nLoading Teapot Vertices\n");
std::vector<GLfloat> teapotVertices;
for (int i = 0; i < teapot_count; i++) {
teapotVertices.push_back(static_cast<GLfloat>(teapot[i]));
}
fprintf(MSGLOG, "\nTeapot vertices loaded to application.\n"
"Application will now load teapot vertices to video memory on GPU.\n");
//Make a vertex attribute set to handle organizing the data for the graphics context
vertexAttributes = std::make_unique<GenericVertexAttributeSet>(1);
if (!vertexAttributes)
return;
vertexAttributes->sendDataToVertexBuffer(0, teapotVertices, 3, 0);
fprintf(MSGLOG, "\nTeapot Has Been Successfully Loaded To Video Memory!\n");
}
void GeometryShaderExplosion::renderLoop() {
while (glfwWindowShouldClose(window) == GLFW_FALSE) {
if (checkToSeeIfShouldCloseWindow()) {
glfwSetWindowShouldClose(window, GLFW_TRUE);
continue; //Skip the rest of this loop iteration to close window quickly
}
if (checkIfShouldPause()) {
pause();
continue;
}
if (checkIfShouldRecordColor())
recordColorToLog();
if (checkIfShouldReset())
reset();
updateFrameClearColor();
updateUniforms();
drawVerts();
counter += 0.00125f;
glfwSwapBuffers(window);
glfwPollEvents();
frameNumber++; //Increment the frame counter
prepareGLContextForNextFrame();
}
}
bool GeometryShaderExplosion::checkToSeeIfShouldCloseWindow() const {
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) {
return true;
}
return false;
}
bool GeometryShaderExplosion::checkIfShouldPause() const {
if ((frameNumber >= (frameUnpaused + DELAY_LENGTH_OF_PAUSE_CHECKING_AFTER_UNPAUSE))
&& (glfwGetKey(window, GLFW_KEY_SPACE) == GLFW_PRESS)) {
return true;
}
return false;
}
bool GeometryShaderExplosion::checkIfShouldRecordColor() const {
if ((frameNumber >= (frameOfMostRecentColorRecording +
DELAY_BETWEEN_SCREEN_COLOR_RECORDINGS_IN_RENDER_PROJECTS))
&& (glfwGetKey(window, GLFW_KEY_P) == GLFW_PRESS)) {
return true;
}
return false;
}
bool GeometryShaderExplosion::checkIfShouldReset() const {
if (glfwGetKey(window, GLFW_KEY_R) == GLFW_PRESS)
return true;
return false;
}
void GeometryShaderExplosion::pause() {
auto begin = std::chrono::high_resolution_clock::now(); //Time measurement
auto end = std::chrono::high_resolution_clock::now();
fprintf(MSGLOG, "PAUSED!\n");
while (std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin).count() < 300000000) {
std::this_thread::sleep_for(std::chrono::nanoseconds(2000000));
end = std::chrono::high_resolution_clock::now();
}
//Enter an infinite loop checking for the unpaused key to be pressed
while (true) {
glfwPollEvents();
if (glfwGetKey(window, GLFW_KEY_SPACE) == GLFW_PRESS) {
frameUnpaused = frameNumber;
fprintf(MSGLOG, "UNPAUSED!\n");
return;
}
else if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) {
glfwSetWindowShouldClose(window, GLFW_TRUE);
return;
}
else { //wait for a little bit before polling again
std::this_thread::sleep_for(std::chrono::nanoseconds(3333333));
}
}
}
void GeometryShaderExplosion::recordColorToLog() {
frameOfMostRecentColorRecording = frameNumber;
int colorDigits = 6; //Digits to print out for each color
//Syntax Note: With '%*f', the '*' means that the width will be provided as an additional parameter
fprintf(MSGLOG, "\nThe background color of frame %llu is:\n\tRed: %*f,\tGreen: %*f,\tBlue: %*f\n",
frameNumber, colorDigits, backgroundColor.r, colorDigits, backgroundColor.g, colorDigits, backgroundColor.b);
}
void GeometryShaderExplosion::reset() {
fprintf(MSGLOG, "\nReseting Demo...\n");
counter = 0.0f; //Reset time to 0
zRotation = 0.0f; //Reset rotation
backgroundColor = glm::vec3(0.0f, 0.5f, 0.75f);
frameNumber = 0ull;
}
void GeometryShaderExplosion::updateFrameClearColor() {
//To look into:
//GL_UseProgram_Stages
float * red = &(backgroundColor.x);
float * green = &(backgroundColor.y);
float * blue = &(backgroundColor.z);
*red = glm::min(1.0f, (*red + *green + *blue) / 3.0f);
//*green = glm::abs(sin(glm::min(1.0f, (*red) + ((*blue) * (*blue) / (*red)))));
*blue = 0.5f + 0.25f*cos(counter);
//static bool sleep = false;
if (abs(ceilf(counter) - counter) < 0.0049f) {
float temp = *red;
*red = *green;
*green = *blue;
*blue = temp;
//sleep = true;
}
glClearColor(*red, *green, *blue, 1.0f);
}
void GeometryShaderExplosion::updateUniforms() {
sceneShader->use();
//Update uniform locations
sceneShader->uniforms->updateUniform1f("zoom", 1.0f);
sceneShader->uniforms->updateUniform1f("time", counter);
//Uniforms for the geometry shader effect
sceneShader->uniforms->updateUniform1i("level", 2); //tweak this value as needed
sceneShader->uniforms->updateUniform1f("gravity", -9.81f); //tweak this value as needed
sceneShader->uniforms->updateUniform1f("velocityScale", 3.0f); //tweak this value as needed
zRotation += 0.005f;
//fprintf(MSGLOG, "zRot is %f\n", zRotation);
//sceneShader->uniforms->updateUniform1f("xRotation", 0.0f);
//sceneShader->uniforms->updateUniform1f("yRotation", 0.0f*zRotation * 4.0f);
sceneShader->uniforms->updateUniform1f("zRotation", zRotation);
}
void GeometryShaderExplosion::drawVerts() {
if (sceneShader)
sceneShader->use();
if (vertexAttributes)
vertexAttributes->use();
/*glDrawArrays(GL_TRIANGLES, 0, 3);*/
glDrawArrays(GL_TRIANGLES, 0, teapot_count / 3);
}
void GeometryShaderExplosion::prepareGLContextForNextFrame() {
glBindVertexArray(0);
glUseProgram(0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
| 29.782209 | 126 | 0.712947 | millerf1234 |
e854014f23a145200dc306d02dfdc052063084a5 | 591 | cpp | C++ | ace/examples/corba/client.cpp | tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective | 1b0172cdb78757fd17898503aaf6ce03d940ef28 | [
"Apache-1.1"
] | 46 | 2015-12-04T17:12:58.000Z | 2022-03-11T04:30:49.000Z | ace/examples/corba/client.cpp | tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective | 1b0172cdb78757fd17898503aaf6ce03d940ef28 | [
"Apache-1.1"
] | null | null | null | ace/examples/corba/client.cpp | tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective | 1b0172cdb78757fd17898503aaf6ce03d940ef28 | [
"Apache-1.1"
] | 23 | 2016-10-24T09:18:14.000Z | 2022-02-25T02:11:35.000Z | // client.cpp,v 4.3 1998/07/31 22:55:09 gonzo Exp
#include "Test.hh"
ACE_RCSID(CORBA, client, "client.cpp,v 4.3 1998/07/31 22:55:09 gonzo Exp")
int
main (int argc, char *argv[])
{
char *host = argc == 2 ? argv[1] : ACE_DEFAULT_SERVER_HOST;
Test_var my_test;
TRY {
my_test = Test::_bind ("", host, IT_X);
my_test->method (5);
} CATCHANY {
cerr << IT_X << endl;
return -1;
} ENDTRY;
ACE_DEBUG ((LM_DEBUG, "everything works!\n"));
// Memory for my_test is automatically released by destructor of
// smart pointer.
return 0;
}
| 21.107143 | 75 | 0.605753 | tharindusathis |
e858c316154a7c9e1f62b57de38d96608393a30b | 14,735 | cpp | C++ | setup.cpp | jessexm/dbgutils | 149e5ee1a49ff87861601ea992918d1d56873bc2 | [
"BSD-3-Clause"
] | 2 | 2019-12-28T10:33:42.000Z | 2020-04-02T01:53:33.000Z | setup.cpp | jessexm/dbgutils | 149e5ee1a49ff87861601ea992918d1d56873bc2 | [
"BSD-3-Clause"
] | null | null | null | setup.cpp | jessexm/dbgutils | 149e5ee1a49ff87861601ea992918d1d56873bc2 | [
"BSD-3-Clause"
] | null | null | null | /* Copyright (C) 2002, 2003, 2004 Zilog, Inc.
*
* $Id: setup.cpp,v 1.6 2005/10/20 18:39:37 jnekl Exp $
*
* This file initializes the debugger enviroment by reading
* settings from a config file and by parsing command-line
* options.
*/
#include <string.h>
#include <stdio.h>
#include <assert.h>
#include <sys/stat.h>
#include <readline/readline.h>
#include <readline/history.h>
#include "xmalloc.h"
#include "ez8dbg.h"
#include "ocd_serial.h"
#include "ocd_parport.h"
#include "ocd_tcpip.h"
#include "server.h"
#include "cfg.h"
#include "md5.h"
/**************************************************************/
#ifndef CFGFILE
#define CFGFILE "ez8mon.cfg"
#endif
#ifndef _WIN32
#define DIRSEP '/'
#else
#define DIRSEP '\\'
#endif
/**************************************************************/
const char *serialports[] =
#if (!defined _WIN32) && (defined __sun__)
/* solaris */
{ "/dev/ttya", "/dev/ttyb", NULL };
#elif (!defined _WIN32)
/* linux */
{ "/dev/ttyS0", "/dev/ttyS1", "/dev/ttyS2", "/dev/ttyS3", NULL };
#else
/* windows */
{ "com1", "com2", "com3", "com4", NULL };
#endif
char *progname;
int verbose;
/**************************************************************/
#define str(x) _str(x)
#define _str(x) #x
#ifndef DEFAULT_CONNECTION
#define DEFAULT_CONNECTION serial
#endif
#ifndef DEFAULT_DEVICE
#define DEFAULT_DEVICE auto
#endif
#ifndef DEFAULT_BAUDRATE
#define DEFAULT_BAUDRATE 57600
#endif
#ifndef ALT_BAUDRATE
#define ALT_BAUDRATE 4800
#endif
#ifndef DEFAULT_MTU
#define DEFAULT_MTU 4096
#endif
#ifndef DEFAULT_SYSCLK
#define DEFAULT_SYSCLK 20MHz
#endif
/**************************************************************
* Our debugger object.
*/
static ez8dbg _ez8;
ez8dbg *ez8 = &_ez8;
/**************************************************************/
rl_command_func_t *tab_function = rl_insert;
static char *connection = NULL;
static char *device = NULL;
static char *baudrate = NULL;
static char *sysclk = NULL;
static char *mtu = NULL;
static char *server = NULL;
static FILE *log_proto = NULL;
static int invoke_server = 0;
static int disable_cache = 0;
static int unlock_ocd = 0;
int repeat = 0x40;
int show_times = 0;
int esc_key = 0;
int testmenu = 0;
char *tcl_script = NULL;
/* option values to load upon reset */
struct option_t {
uint8_t addr;
uint8_t value;
struct option_t *next;
} *options = NULL;
/**************************************************************
* The ESC key is bound to this function.
*
* This function will terminate any readline call. It is
* used to abort a command.
*/
int esc_function(int count, int key)
{
esc_key = 1;
rl_done = 1;
return 0;
}
/**************************************************************
* This initializes the readline library.
*/
int readline_init(void)
{
int err;
err = rl_bind_key(ESC, esc_function);
if(err) {
return -1;
}
err = rl_bind_key('\t', *tab_function);
if(err) {
return -1;
}
return 0;
}
/**************************************************************
* This will search for a config file.
*
* It will first look in the current directory. If it doesn't
* find one there, it will then look in the directory pointed
* to by the HOME environment variable.
*/
cfgfile *find_cfgfile(void)
{
char *filename, *home, *ptr;
struct stat mystat;
cfgfile *cfg;
if(stat(CFGFILE, &mystat) == 0) {
cfg = new cfgfile();
cfg->open(CFGFILE);
return cfg;
}
home = getenv("HOME");
if(!home) {
return NULL;
}
filename = (char *)xmalloc(strlen(home) + 1 + sizeof(CFGFILE));
strcpy(filename, home);
ptr = strchr(filename, '\0');
*ptr++ = DIRSEP;
*ptr = '\0';
strcat(filename, CFGFILE);
if(stat(filename, &mystat) == 0) {
cfg = new cfgfile();
cfg->open(filename);
free(filename);
return cfg;
}
free(filename);
return NULL;
}
/**************************************************************
* This function will get parameters from the config file.
*/
int load_config(void)
{
char *ptr;
cfgfile *cfg;
cfg = find_cfgfile();
if(!cfg) {
return 1;
}
ptr = cfg->get("connection");
if(ptr) {
connection = xstrdup(ptr);
}
ptr = cfg->get("device");
if(ptr) {
device = xstrdup(ptr);
}
ptr = cfg->get("baudrate");
if(ptr) {
baudrate = xstrdup(ptr);
}
ptr = cfg->get("mtu");
if(ptr) {
mtu = xstrdup(ptr);
}
ptr = cfg->get("clock");
if(ptr) {
sysclk = xstrdup(ptr);
}
ptr = cfg->get("server");
if(ptr) {
server = xstrdup(ptr);
invoke_server = 1;
}
ptr = cfg->get("cache");
if(ptr) {
if(!strcasecmp(ptr, "disabled")) {
disable_cache = 1;
}
}
ptr = cfg->get("testmenu");
if(ptr) {
if(!strcasecmp(ptr, "enabled")) {
testmenu = 1;
}
}
ptr = cfg->get("repeat");
if(ptr) {
char *tail;
repeat = strtol(ptr, &tail, 0);
if(!tail || *tail || tail == ptr) {
fprintf(stderr, "Invalid repeat = %s\n", ptr);
return -1;
}
}
delete cfg;
return 0;
}
/**************************************************************
* display_md5hash()
*
* This routine computes and displays the md5 hash of a text
* string. This is useful for generating password hashes.
*/
void display_md5hash(char *s)
{
int i;
uint8_t hash[16];
MD5_CTX context;
assert(s != NULL);
MD5Init(&context);
MD5Update(&context, (unsigned char *)s, strlen(s));
MD5Final(hash, &context);
printf("text = %s\n", s);
printf("md5hash = ");
for(i=0; i<16; i++) {
printf("%02x", hash[i]);
}
printf("\n");
return;
}
/**************************************************************
* usage()
*
* This function displays command-line usage info.
*/
void usage(void)
{
extern char *build;
printf("%s - build %s\n", progname, build);
printf("Usage: %s [OPTIONS]\n", progname);
printf("Z8 Encore! command line debugger.\n\n");
printf(" -h show this help\n");
printf(" -p DEVICE connect to specified serial port device\n");
printf(" -b BAUDRATE connect using specified baudrate\n");
printf(" -l list valid baudrates\n");
printf(" -t MTU set maximum packet size\n");
printf(" (used to prevent receive overrun errors)\n");
printf(" -c FREQUENCY use specified clock frequency for flash\n");
printf(" program/erase oprations\n");
printf(" -s [:PORT] run as tcp/ip server\n");
printf(" -n [SERVER][:PORT] connect to tcp/ip server\n");
printf(" -m TEXT calculate and display md5hash of text\n");
printf(" -d dump raw ocd communication\n");
printf(" -D disable memory cache\n");
printf(" -T display diagnostic run times\n");
printf(" -S SCRIPT run tcl script\n");
printf(" -u issue OCD unlock sequence for 8-pin device\n");
printf("\n");
return;
}
/**************************************************************
* parse_options()
*
* This routine handles command line options.
*/
void parse_options(int argc, char **argv)
{
int c;
const struct baudvalue *b;
char *s;
progname = *argv;
s = strrchr(progname, '/');
if(s) {
progname = s+1;
}
s = strrchr(progname, '\\');
if(s) {
progname = s+1;
}
while((c = getopt(argc, argv, "hldDTp:b:t:c:snm:vS:u")) != EOF) {
switch(c) {
case '?':
printf("Try '%s -h' for more information.\n",
progname);
exit(EXIT_FAILURE);
break;
case 'h':
usage();
exit(EXIT_SUCCESS);
break;
case 'l':
b = baudrates;
while(b->value) {
printf("%d\n", b->value);
b++;
}
exit(EXIT_SUCCESS);
break;
case 'p':
connection = xstrdup("serial");
if(device) {
free(device);
}
device = xstrdup(optarg);
break;
case 'b':
if(baudrate) {
free(baudrate);
}
baudrate = xstrdup(optarg);
break;
case 't':
if(mtu) {
free(mtu);
}
mtu = xstrdup(optarg);
break;
case 'c':
if(sysclk) {
free(sysclk);
}
sysclk = xstrdup(optarg);
break;
case 's':
invoke_server = 1;
break;
case 'n':
connection = xstrdup("tcpip");
if(device) {
free(device);
device = NULL;
}
break;
case 'd':
log_proto = stdout;
break;
case 'D':
disable_cache = 1;
break;
case 'T':
show_times = 1;
break;
case 'm':
display_md5hash(optarg);
exit(EXIT_SUCCESS);
break;
case 'v':
verbose++;
break;
case 'S':
tcl_script = optarg;
break;
case 'u':
unlock_ocd = 1;
break;
default:
abort();
}
}
if(invoke_server) {
if(optind + 1 == argc) {
if(server) {
free(server);
}
server = xstrdup(argv[optind]);
}
optind++;
}
if(connection && !strcasecmp(connection, "tcpip")) {
if(optind + 1 == argc) {
if(device) {
free(device);
}
device = xstrdup(argv[optind]);
}
optind++;
}
if(!tcl_script && optind < argc) {
printf("%s: too many arguments.\n", progname);
printf("Try '%s -h' for more information.\n", progname);
exit(EXIT_FAILURE);
}
return;
}
/**************************************************************
* connect()
*
* This routine will connect to the on-chip debugger using
* the configured interface.
*/
int connect(void)
{
int i, value, clk, baud;
char *tail;
double clock;
if(log_proto) {
ez8->log_proto = log_proto;
}
if(mtu) {
value = strtol(mtu, &tail, 0);
if(!tail || *tail || tail == mtu) {
fprintf(stderr, "Invalid mtu \"%s\"\n", mtu);
return -1;
}
ez8->mtu = value;
}
if(sysclk) {
clock = strtod(sysclk, &tail);
if(tail == NULL || tail == sysclk) {
fprintf(stderr, "Invalid clock \"%s\"\n", sysclk);
return -1;
}
while(*tail && strchr(" \t", *tail)) {
tail++;
}
if(*tail == 'k' || *tail == 'K') {
clock *= 1000;
tail++;
} else if(*tail == 'M') {
clock *= 1000000;
tail++;
}
if(*tail != '\0' && strcasecmp(tail, "Hz")) {
fprintf(stderr, "Invalid clock suffix \"%s\"\n",
tail);
return -1;
}
} else {
fprintf(stderr, "Unknown system clock.\n");
return -1;
}
clk = (int)clock;
if(clk < 32000 || clk > 20000000) {
fprintf(stderr, "Clock %d out of range\n", clk);
return -1;
}
ez8->set_sysclk(clk);
if(disable_cache) {
ez8->memcache_enabled = 0;
}
if(connection == NULL) {
fprintf(stderr, "Unknown connection type.\n");
return -1;
} else if(!strcasecmp(connection, "serial")) {
if(!device) {
fprintf(stderr, "Unknown communication device.\n");
return -1;
}
if(!baudrate) {
baud = DEFAULT_BAUDRATE;
} else {
baud = strtol(baudrate, &tail, 0);
if(!tail || *tail || tail == baudrate) {
fprintf(stderr, "Invalid baudrate \"%s\"\n",
baudrate);
return -1;
}
}
if(!strcasecmp(device, "auto")) {
bool found = 0;
printf("Auto-searching for device ...\n");
for(i=0; serialports[i]; i++) {
device = xstrdup(serialports[i]);
printf("Trying %s ... ", device);
fflush(stdout);
try {
ez8->connect_serial(device, baud, unlock_ocd);
} catch(char *err) {
printf("fail\n");
continue;
}
try {
ez8->reset_link();
} catch(char *err) {
printf("timeout\n");
ez8->disconnect();
continue;
}
printf("ok\n");
found = 1;
break;
}
if(!found) {
printf(
"Could not find dongle during autosearch.\n");
return -1;
}
try {
ez8->rd_revid();
} catch(char *err) {
baud = ALT_BAUDRATE;
ez8->set_baudrate(baud);
ez8->reset_link();
try {
ez8->rd_revid();
} catch(char *err) {
printf(
"Found dongle, but did not receive response from device.\n");
return -1;
}
}
if(ez8->cached_reload() &&
ez8->cached_sysclk() > 115200*8) {
baud = 115200;
ez8->set_baudrate(baud);
ez8->reset_link();
}
} else {
try {
ez8->connect_serial(device, baud, unlock_ocd);
} catch(char *err) {
fprintf(stderr, "%s", err);
return -1;
}
try {
ez8->reset_link();
} catch(char *err) {
printf("Failed connecting to %s\n", device);
fprintf(stderr, "%s", err);
ez8->disconnect();
return -1;
}
}
printf("Connected to %s @ %d\n", device, baud);
} else if(!strcasecmp(connection, "parport")) {
if(!device) {
fprintf(stderr, "Unknown device");
return -1;
}
try {
ez8->connect_parport(device);
} catch(char *err) {
printf("Parallel port connection failed\n");
fprintf(stderr, "%s", err);
return -1;
}
try {
ez8->reset_link();
} catch(char *err) {
printf("IEEE1284 negotiation failed\n");
fprintf(stderr, "%s", err);
ez8->disconnect();
return -1;
}
} else if(!strcasecmp(connection, "tcpip")) {
try {
ez8->connect_tcpip(device);
} catch(char *err) {
printf("Connection failed\n");
fprintf(stderr, "%s", err);
return -1;
}
try {
ez8->reset_link();
} catch(char *err) {
printf("Remote reset failed\n");
fprintf(stderr, "%s", err);
ez8->disconnect();
return -1;
}
} else {
printf("Invalid connection type \"%s\"\n",
connection);
return -1;
}
return 0;
}
/**************************************************************
* init()
*
* This routine sets up and connects to the on-chip debugger.
*/
int init(int argc, char **argv)
{
int err;
tab_function = rl_insert;
rl_startup_hook = readline_init;
connection = xstrdup(str(DEFAULT_CONNECTION));
device = xstrdup(str(DEFAULT_DEVICE));
baudrate = xstrdup(str(DEFAULT_BAUDRATE));
sysclk = xstrdup(str(DEFAULT_SYSCLK));
mtu = xstrdup(str(DEFAULT_MTU));
err = load_config();
if(err < 0) {
return -1;
}
parse_options(argc, argv);
err = connect();
if(err) {
return -1;
}
if(invoke_server) {
err = run_server(ez8->iflink(), server);
ez8->disconnect();
if(err) {
exit(EXIT_FAILURE);
} else {
exit(EXIT_SUCCESS);
}
}
#ifdef TEST
try {
extern void check_config(void);
check_config();
} catch(char *err) {
fprintf(stderr, "%s", err);
return -1;
}
#endif
try {
ez8->stop();
} catch(char *err) {
fprintf(stderr, "%s", err);
return -1;
}
return 0;
}
/**************************************************************
* finish()
*
* This does the opposite of init(), it terminates a
* connection. It will remove any breakpoints that are
* set and put the part into "run" mode when finished.
*/
int finish(void)
{
try {
int addr;
while(ez8->get_num_breakpoints() > 0) {
addr = ez8->get_breakpoint(0);
ez8->remove_breakpoint(addr);
}
ez8->run();
ez8->disconnect();
} catch(char *err) {
fprintf(stderr, "%s", err);
return -1;
}
return 0;
}
/**************************************************************/
| 19.111543 | 84 | 0.55134 | jessexm |
e8591699457d2855917c3569dd261352061e7df4 | 4,730 | hpp | C++ | inc/Matrixes.hpp | KPO-2020-2021/zad5_2-delipl | b4bd2e673c8b7e92e85aed10919427a6704353ca | [
"Unlicense"
] | 1 | 2022-03-08T03:16:48.000Z | 2022-03-08T03:16:48.000Z | inc/Matrixes.hpp | KPO-2020-2021/zad5_2-delipl | b4bd2e673c8b7e92e85aed10919427a6704353ca | [
"Unlicense"
] | null | null | null | inc/Matrixes.hpp | KPO-2020-2021/zad5_2-delipl | b4bd2e673c8b7e92e85aed10919427a6704353ca | [
"Unlicense"
] | null | null | null | /**
* @file Matrixes.hpp
* @author Delicat Jakub (delicat.kuba@gmail.com)
* @brief File describes implemetations for template class Matrix.
* Instantiation of template class Matrix like Matrix4x4, Matrix3x3, Matrix2x2 and MatrixRot.
* @version 0.1
* @date 2021-06-23
*
* @copyright Copyright (c) 2021
*
*/
#ifndef __MATRIXROT_H__
#define __MATRIXROT_H__
#include "Vectors.hpp"
#include "Matrix.hpp"
/**
* @file
*/
#ifndef MIN_DIFF
/**
* @brief Minimal difference between two double numbers. It might be included from config.hpp
*/
#define MIN_DIFF 0.000000001
#endif // !MIN_DIFF
/**
* @brief Square Matrix with double values and comare with MIN_DIFF
* @tparam dim
*/
template<std::size_t dim>
class dMatrixSqr: public Matrix<double, dim, dim>{
public:
/**
* @brief Construct a new d Matrix Sqr object
*/
dMatrixSqr(): Matrix<double, dim, dim>() {}
/**
* @brief Construct a new d Matrix Sqr object
* @param list of inserted values
*/
dMatrixSqr(const std::initializer_list<Vector<double, dim>> &list): Matrix<double, dim, dim>(list) {}
/**
* @brief Construct a new d Matrix Sqr object
* @param M copied Matrix
*/
dMatrixSqr(const Matrix<double, dim, dim> &M): Matrix<double, dim, dim>(M){}
/**
* @brief Checks if every diffrence is bigger than MIN_DIFF
* @param v compared dMatrixSqe
* @return true if is lower
* @return false if is bigger
*/
bool operator==(const dMatrixSqr &v) const{
for (std::size_t i = 0; i < dim; ++i)
for (std::size_t j = 0; j < dim; ++j)
if (abs(this->vector[i][j] - v[i][j]) > MIN_DIFF)
return false;
return true;
}
/**
* @brief Checks if every diffrence is bigger than MIN_DIFF
* @param v compared dMatrixSqe
* @return true if is bigger
* @return false if is less
*/
bool operator!=(const dMatrixSqr &v) const{
for (std::size_t i = 0; i < dim; ++i)
for (std::size_t j = 0; j < dim; ++j)
if (abs(this->vector[i][j] - v[i][j]) <= MIN_DIFF)
return false;
return true;
}
/**
* @brief Checks if every value is lower than MIN_DIFF
* @param v compared dMatrixSqe
* @return true if is lower
* @return false if is bigger
*/
bool operator!() const{
for (std::size_t i = 0; i < dim; ++i)
for (std::size_t j = 0; j < dim; ++j)
if (abs(this->vector[i][j]) >= MIN_DIFF)
return false;
return true;
}
};
/**
* @brief four dimentional square double Matrix
*/
typedef dMatrixSqr<4> Matrix4x4;
/**
* @brief three dimentional square double Matrix
*/
typedef dMatrixSqr<3> Matrix3x3;
/**
* @brief two dimentional square double Matrix
*/
typedef dMatrixSqr<2> Matrix2x2;
class MatrixRot: public Matrix3x3{
public:
/**
* @brief Construct a new Matrix Rot object and fill like unit Matrix
*/
MatrixRot();
/**
* @brief Construct a new Matrix Rot object and copy
* @param M Copieied Matrix
*/
MatrixRot(const Matrix3x3 &M): Matrix3x3(M){}
/**
* @brief Construct a new Matrix Rot object and copy
* @param M Copieied Matrix
*/
MatrixRot(const Matrix<double, 3, 3> &M): Matrix3x3(M){}
/**
* @brief Construct a new Matrix Rot object and fill with rotating values
* @param angle angle of rotation
* @param axis of rotation ex. \p VectorZ , \p VectorX , \p VectorY
*/
MatrixRot(double angle, const Vector3 &axis);
};
/**
* @brief Transform Matrix 4x4 which collects translation, rotation and scale
*/
class MatrixTransform: public Matrix4x4{
public:
/**
* @brief Construct a new MatrixTransform object and fill like unit Matrix
*/
MatrixTransform();
/**
* @brief Construct a new MatrixTransform object and copy
* @param M Copieied Matrix
*/
MatrixTransform(const Matrix4x4 &M) : Matrix4x4(M) {}
/**
* @brief Construct a new Matrix Transform object
* @param translate translate Vector3 to move bodies
* @param angles Vector3 of 3 angles in 3 axis
* @param scale Vector3 of scale in every dimention
*/
MatrixTransform(const Vector3 &translate, const Vector3 &angles, const Vector3 &scale);
};
#endif // __MATRIXROT_H__ | 29.018405 | 109 | 0.572939 | KPO-2020-2021 |
e859f22bdab86a51b4ab7ca4786ef6bf0bad2939 | 25,353 | cpp | C++ | AviSynthPlus/plugins/Shibatch/ssrc.cpp | wurui1994/AviSynth | d318f4b455c49a8864c30b3cce84925ebb16c002 | [
"MIT"
] | 1 | 2018-09-27T09:37:42.000Z | 2018-09-27T09:37:42.000Z | AviSynthPlus/plugins/Shibatch/ssrc.cpp | wurui1994/AviSynth | d318f4b455c49a8864c30b3cce84925ebb16c002 | [
"MIT"
] | null | null | null | AviSynthPlus/plugins/Shibatch/ssrc.cpp | wurui1994/AviSynth | d318f4b455c49a8864c30b3cce84925ebb16c002 | [
"MIT"
] | null | null | null | /******************************************************
A fast and high quality sampling rate converter SSRC
written by Naoki Shibata
Homepage : http://shibatch.sourceforge.net/
e-mail : shibatch@users.sourceforge.net
Some changes are:
Copyright (c) 2001-2003, Peter Pawlowski
All rights reserved.
*******************************************************/
#include "ssrc.h"
#include <avs/alignment.h>
#include <cassert>
#pragma warning(disable:4244)
template<class REAL>
class Resampler_i_base : public Resampler_base
{
protected:
Resampler_i_base(const Resampler_base::CONFIG & c) : Resampler_base(c) {}
void make_outbuf(int nsmplwrt2, REAL* outbuf, int& delay2);
void make_inbuf(int nsmplread, int inbuflen, REAL_inout* rawinbuf, REAL* inbuf, int toberead);
};
#define M 15
#ifndef M_PI
#define M_PI 3.1415926535897932384626433832795028842
#endif
#define RANDBUFLEN 65536
#define RINT(x) ((x) >= 0 ? ((int)((x) + 0.5)) : ((int)((x) - 0.5)))
extern "C"
{
extern double dbesi0(double);
}
static double alpha(double a)
{
if (a <= 21) return 0;
if (a <= 50) return 0.5842*pow(a-21,0.4)+0.07886*(a-21);
return 0.1102*(a-8.7);
}
static double win(double n,int len,double alp,double iza)
{
return dbesi0(alp*sqrt(1-4*n*n/(((double)len-1)*((double)len-1))))/iza;
}
static double sinc(double x)
{
return x == 0 ? 1 : sin(x)/x;
}
static double hn_lpf(int n,double lpf,double fs)
{
double t = 1/fs;
double omega = 2*M_PI*lpf;
return 2*lpf*t*sinc(n*omega*t);
}
static int gcd(int x, int y)
{
int t;
while (y != 0) {
t = x % y; x = y; y = t;
}
return x;
}
int CanResample(int sfrq,int dfrq)
{
if (sfrq==dfrq) return 1;
int frqgcd = gcd(sfrq,dfrq);
if (dfrq>sfrq)
{
int fs1 = sfrq / frqgcd * dfrq;
if (fs1/dfrq == 1) return 1;
else if (fs1/dfrq % 2 == 0) return 1;
else if (fs1/dfrq % 3 == 0) return 1;
else return 0;
}
else
{
if (dfrq/frqgcd == 1) return 1;
else if (dfrq/frqgcd % 2 == 0) return 1;
else if (dfrq/frqgcd % 3 == 0) return 1;
else return 0;
}
}
void Buffer::Read(int size)
{
if (size)
{
if (buf_data==size) buf_data=0;
else
{
mem_ops<REAL_inout>::move(buffer,buffer+size,buf_data-size);
buf_data-=size;
}
}
}
void Buffer::Write(const REAL_inout * ptr,int size)
{
buffer.check_size(buf_data + size);
mem_ops<REAL_inout>::copy(buffer+buf_data,ptr,size);
buf_data+=size;
}
void Resampler_base::bufloop(int finish)
{
int s;
REAL_inout * ptr = in.GetBuffer(&s);
int done=0;
while(done<s)
{
int d=Resample(ptr,s-done,finish);
if (d==0) break;
done+=d;
ptr+=d;
}
in.Read(done);
}
void Resampler_base::Write(const REAL_inout * input,int size)
{
in.Write(input,size);
bufloop(0);
}
template<class REAL>
void Resampler_i_base<REAL>::make_inbuf(int nsmplread, int inbuflen, REAL_inout* rawinbuf, REAL* inbuf, int toberead)
{
const int MaxLoop = nsmplread * nch;
const int InbufBase = inbuflen * nch;
for(int i = 0; i < MaxLoop; i++) {
inbuf[InbufBase + i] = rawinbuf[i];
}
size_t ClearSize = toberead - nsmplread;
if(ClearSize) {
memset(inbuf + InbufBase + MaxLoop, 0, ClearSize * nch * sizeof REAL);
}
}
template<class REAL>
void Resampler_i_base<REAL>::make_outbuf(int nsmplwrt2, REAL* outbuf, int& delay2)
{
const int MaxLoop = nsmplwrt2 * nch;
for(int i = 0; i < MaxLoop; i++) {
REAL s = outbuf[i] * gain;
if(s > 1.0) {
peak = peak < s ? s : peak;
// s = 1.0;
} else if(s < -1.0) {
peak = peak < -s ? -s : peak;
// s = -1.0;
}
__output((REAL_inout)s,delay2);
}
}
#ifdef WIN32
extern "C" {_declspec(dllimport) int _stdcall MulDiv(int nNumber,int nNumerator,int nDenominator);}
#else
#define MulDiv(x,y,z) ((x)*(y)/(z))
#endif
unsigned int Resampler_base::GetLatency()
{
return MulDiv(in.Size(),1000,sfrq*nch) + MulDiv(out.Size(),1000,dfrq*nch);
}
template<class REAL>
class Upsampler : public Resampler_i_base<REAL>
{
using Resampler_i_base<REAL>::FFTFIRLEN;
using Resampler_i_base<REAL>::peak;
using Resampler_i_base<REAL>::sfrq;
using Resampler_i_base<REAL>::dfrq;
using Resampler_i_base<REAL>::nch;
using Resampler_i_base<REAL>::DF;
using Resampler_i_base<REAL>::AA;
using Resampler_i_base<REAL>::make_outbuf;
using Resampler_i_base<REAL>::make_inbuf;
__int64 fs1;
int frqgcd,osf,fs2;
REAL **stage1,*stage2;
int n1,n1x,n1y,n2,n2b;
int filter2len;
int *f1order,*f1inc;
int *fft_ip;// = NULL;
REAL *fft_w;// = NULL;
//unsigned char *rawinbuf,*rawoutbuf;
REAL *inbuf,*outbuf;
REAL **buf1,**buf2;
int spcount;
int i,j;
int n2b2;//=n2b/2;
int rp; // keep the location of the next samples to read in inbuf at fs1.
int ds; // number of samples to dispose next in sfrq.
int nsmplwrt1; // actually number of samples to send stage2 filters .
int nsmplwrt2; // actually number of samples to send stage2 filters .
int s1p; // the reminder obtained by dividing the samples output from stage1 filter by n1y*osf.
int init;
unsigned int sumread,sumwrite;
int osc;
REAL *ip,*ip_backup;
int s1p_backup,osc_backup;
int p;
int inbuflen;
int delay;// = 0;
int delay2;
public:
Upsampler(const Resampler_base::CONFIG & c);
unsigned int Resample(REAL_inout * rawinbuf, unsigned int in_size, int ending);
~Upsampler();
};
template<class REAL>
Upsampler<REAL>::Upsampler(const Resampler_base::CONFIG & c) : Resampler_i_base<REAL>(c)
{
fft_ip = NULL;
fft_w = NULL;
peak = 0;
spcount = 0;
filter2len = FFTFIRLEN; /* stage 2 filter length */
/* Make stage 1 filter */
{
double aa = AA; /* stop band attenuation(dB) */
double lpf, delta, d, df, alp, iza;
double guard = 2;
frqgcd = gcd(sfrq, dfrq);
fs1 = (__int64)(sfrq / frqgcd) * (__int64)dfrq;
if (fs1 / dfrq == 1) osf = 1;
else if (fs1 / dfrq % 2 == 0) osf = 2;
else if (fs1 / dfrq % 3 == 0) osf = 3;
else {
// fprintf(stderr,"Resampling from %dHz to %dHz is not supported.\n",sfrq,dfrq);
// fprintf(stderr,"%d/gcd(%d,%d)=%d must be divided by 2 or 3.\n",sfrq,sfrq,dfrq,fs1/dfrq);
// exit(-1);
return;
}
df = (dfrq*osf / 2 - sfrq / 2) * 2 / guard;
lpf = sfrq / 2 + (dfrq*osf / 2 - sfrq / 2) / guard;
delta = pow(10.0, -aa / 20);
if (aa <= 21) d = 0.9222; else d = (aa - 7.95) / 14.36;
n1 = fs1 / df * d + 1;
if (n1 % 2 == 0) n1++;
alp = alpha(aa);
iza = dbesi0(alp);
//printf("iza = %g\n",iza);
n1y = fs1 / sfrq;
n1x = n1 / n1y + 1;
f1order = (int*)avs_malloc(sizeof(int)*n1y*osf, 64);
for (i = 0; i<n1y*osf; i++) {
f1order[i] = fs1 / sfrq - (i*(fs1 / (dfrq*osf))) % (fs1 / sfrq);
if (f1order[i] == fs1 / sfrq) f1order[i] = 0;
}
f1inc = (int*)avs_malloc(sizeof(int)*n1y*osf, 64);
for (i = 0; i<n1y*osf; i++) {
f1inc[i] = f1order[i] < fs1 / (dfrq*osf) ? nch : 0;
if (f1order[i] == fs1 / sfrq) f1order[i] = 0;
}
stage1 = (REAL**)avs_malloc(sizeof(REAL *)*n1y, 64);
stage1[0] = (REAL*)avs_malloc(sizeof(REAL)*n1x*n1y, 64);
for (i = 1; i<n1y; i++) {
stage1[i] = &(stage1[0][n1x*i]);
for (j = 0; j<n1x; j++) stage1[i][j] = 0;
}
for (i = -(n1 / 2); i <= n1 / 2; i++)
{
stage1[(i + n1 / 2) % n1y][(i + n1 / 2) / n1y] = win(i, n1, alp, iza)*hn_lpf(i, lpf, fs1)*fs1 / sfrq;
}
}
/* Make stage 2 filter */
{
double aa = AA; /* stop band attenuation(dB) */
double lpf, delta, d, df, alp, iza;
int ipsize, wsize;
delta = pow(10.0, -aa / 20);
if (aa <= 21) d = 0.9222; else d = (aa - 7.95) / 14.36;
fs2 = dfrq * osf;
for (i = 1;; i = i * 2)
{
n2 = filter2len * i;
if (n2 % 2 == 0) n2--;
df = (fs2*d) / (n2 - 1);
lpf = sfrq / 2;
if (df < DF) break;
}
alp = alpha(aa);
iza = dbesi0(alp);
for (n2b = 1; n2b<n2; n2b *= 2);
n2b *= 2;
stage2 = (REAL*)avs_malloc(sizeof(REAL)*n2b, 64);
for (i = 0; i<n2b; i++) stage2[i] = 0;
for (i = -(n2 / 2); i <= n2 / 2; i++) {
stage2[i + n2 / 2] = win(i, n2, alp, iza)*hn_lpf(i, lpf, fs2) / n2b * 2;
}
ipsize = 2 + sqrt((double)n2b);
fft_ip = (int*)avs_malloc(sizeof(int)*ipsize, 64);
fft_ip[0] = 0;
wsize = n2b / 2;
fft_w = (REAL*)avs_malloc(sizeof(REAL)*wsize, 64);
fft<REAL>::rdft(n2b, 1, stage2, fft_ip, fft_w);
}
// delay=0;
n2b2 = n2b / 2;
buf1 = (REAL**)avs_malloc(sizeof(REAL *)*nch, 64);
for (i = 0; i<nch; i++)
{
buf1[i] = (REAL*)avs_malloc(sizeof(REAL)*(n2b2 / osf + 1), 64);
for (j = 0; j<(n2b2 / osf + 1); j++) buf1[i][j] = 0;
}
buf2 = (REAL**)avs_malloc(sizeof(REAL *)*nch, 64);
for (i = 0; i<nch; i++) buf2[i] = (REAL*)avs_malloc(sizeof(REAL)*n2b, 64);
inbuf = (REAL*)avs_malloc(nch*(n2b2 + n1x) * sizeof(REAL), 64);
outbuf = (REAL*)avs_malloc(sizeof(REAL)*nch*(n2b2 / osf + 1), 64);
s1p = 0;
rp = 0;
ds = 0;
osc = 0;
init = 1;
inbuflen = n1 / 2 / (fs1 / sfrq) + 1;
delay = (double)n2 / 2 / (fs2 / dfrq);
delay2 = delay * nch;
sumread = sumwrite = 0;
}
template<class REAL>
unsigned int Upsampler<REAL>::Resample(REAL_inout * rawinbuf, unsigned int in_size, int ending)
{
/* Apply filters */
int nsmplread, toberead, toberead2;
unsigned int rv = 0;
int ch;
toberead2 = toberead = floor((double)n2b2*sfrq / (dfrq*osf)) + 1 + n1x - inbuflen;
if (!ending)
{
rv = nch * toberead;
if (in_size<rv) return 0;
nsmplread = toberead;
}
else
{
nsmplread = in_size / nch;
rv = nsmplread * nch;
}
make_inbuf(nsmplread, inbuflen, rawinbuf, inbuf, toberead);
inbuflen += toberead2;
sumread += nsmplread;
//nsmplwrt1 = ((rp-1)*sfrq/fs1+inbuflen-n1x)*dfrq*osf/sfrq;
//if (nsmplwrt1 > n2b2) nsmplwrt1 = n2b2;
nsmplwrt1 = n2b2;
// apply stage 1 filter
ip = &inbuf[((sfrq*(rp - 1) + fs1) / fs1)*nch];
s1p_backup = s1p;
ip_backup = ip;
osc_backup = osc;
for (ch = 0; ch<nch; ch++)
{
REAL *op = &outbuf[ch];
int fdo = fs1 / (dfrq*osf), no = n1y * osf;
s1p = s1p_backup; ip = ip_backup + ch;
switch (n1x)
{
case 7:
for (p = 0; p<nsmplwrt1; p++)
{
int s1o = f1order[s1p];
buf2[ch][p] =
stage1[s1o][0] * *(ip + 0 * nch) +
stage1[s1o][1] * *(ip + 1 * nch) +
stage1[s1o][2] * *(ip + 2 * nch) +
stage1[s1o][3] * *(ip + 3 * nch) +
stage1[s1o][4] * *(ip + 4 * nch) +
stage1[s1o][5] * *(ip + 5 * nch) +
stage1[s1o][6] * *(ip + 6 * nch);
ip += f1inc[s1p];
s1p++;
if (s1p == no) s1p = 0;
}
break;
case 9:
for (p = 0; p<nsmplwrt1; p++)
{
int s1o = f1order[s1p];
buf2[ch][p] =
stage1[s1o][0] * *(ip + 0 * nch) +
stage1[s1o][1] * *(ip + 1 * nch) +
stage1[s1o][2] * *(ip + 2 * nch) +
stage1[s1o][3] * *(ip + 3 * nch) +
stage1[s1o][4] * *(ip + 4 * nch) +
stage1[s1o][5] * *(ip + 5 * nch) +
stage1[s1o][6] * *(ip + 6 * nch) +
stage1[s1o][7] * *(ip + 7 * nch) +
stage1[s1o][8] * *(ip + 8 * nch);
ip += f1inc[s1p];
s1p++;
if (s1p == no) s1p = 0;
}
break;
default:
for (p = 0; p<nsmplwrt1; p++)
{
REAL tmp = 0;
REAL *ip2 = ip;
int s1o = f1order[s1p];
for (i = 0; i<n1x; i++)
{
tmp += stage1[s1o][i] * *ip2;
ip2 += nch;
}
buf2[ch][p] = tmp;
ip += f1inc[s1p];
s1p++;
if (s1p == no) s1p = 0;
}
break;
}
osc = osc_backup;
// apply stage 2 filter
for (p = nsmplwrt1; p<n2b; p++) buf2[ch][p] = 0;
//for(i=0;i<n2b2;i++) printf("%d:%g ",i,buf2[ch][i]);
fft<REAL>::rdft(n2b, 1, buf2[ch], fft_ip, fft_w);
buf2[ch][0] = stage2[0] * buf2[ch][0];
buf2[ch][1] = stage2[1] * buf2[ch][1];
for (i = 1; i<n2b / 2; i++)
{
REAL re, im;
re = stage2[i * 2] * buf2[ch][i * 2] - stage2[i * 2 + 1] * buf2[ch][i * 2 + 1];
im = stage2[i * 2 + 1] * buf2[ch][i * 2] + stage2[i * 2] * buf2[ch][i * 2 + 1];
//printf("%d : %g %g %g %g %g %g\n",i,stage2[i*2],stage2[i*2+1],buf2[ch][i*2],buf2[ch][i*2+1],re,im);
buf2[ch][i * 2] = re;
buf2[ch][i * 2 + 1] = im;
}
fft<REAL>::rdft(n2b, -1, buf2[ch], fft_ip, fft_w);
for (i = osc, j = 0; i<n2b2; i += osf, j++)
{
REAL f = (buf1[ch][j] + buf2[ch][i]);
op[j*nch] = f;
}
nsmplwrt2 = j;
osc = i - n2b2;
for (j = 0; i<n2b; i += osf, j++)
buf1[ch][j] = buf2[ch][i];
}
rp += nsmplwrt1 * (sfrq / frqgcd) / osf;
make_outbuf(nsmplwrt2, outbuf, delay2);
if (!init) {
if (ending) {
if ((double)sumread*dfrq / sfrq + 2 > sumwrite + nsmplwrt2) {
sumwrite += nsmplwrt2;
}
else {
}
}
else {
sumwrite += nsmplwrt2;
}
}
else {
if (nsmplwrt2 < delay) {
delay -= nsmplwrt2;
}
else {
if (ending) {
if ((double)sumread*dfrq / sfrq + 2 > sumwrite + nsmplwrt2 - delay) {
sumwrite += nsmplwrt2 - delay;
}
else {
}
}
else {
sumwrite += nsmplwrt2 - delay;
init = 0;
}
}
}
{
int ds = (rp - 1) / (fs1 / sfrq);
assert(inbuflen >= ds);
mem_ops<REAL>::move(inbuf, inbuf + nch * ds, nch*(inbuflen - ds));
inbuflen -= ds;
rp -= ds * (fs1 / sfrq);
}
return rv;
}
template<class REAL>
Upsampler<REAL>::~Upsampler()
{
avs_free(f1order);
avs_free(f1inc);
avs_free(stage1[0]);
avs_free(stage1);
avs_free(stage2);
avs_free(fft_ip);
avs_free(fft_w);
for (i = 0; i<nch; i++) avs_free(buf1[i]);
avs_free(buf1);
for (i = 0; i<nch; i++) avs_free(buf2[i]);
avs_free(buf2);
avs_free(inbuf);
avs_free(outbuf);
//free(rawoutbuf);
}
template<class REAL>
class Downsampler : public Resampler_i_base<REAL>
{
//using Resampler_i_base<REAL>::peak; overridden here
// Strict c++: access protected fields from a templated class (or use this->)
using Resampler_i_base<REAL>::FFTFIRLEN;
using Resampler_i_base<REAL>::sfrq;
using Resampler_i_base<REAL>::dfrq;
using Resampler_i_base<REAL>::nch;
using Resampler_i_base<REAL>::DF;
using Resampler_i_base<REAL>::AA;
using Resampler_i_base<REAL>::make_outbuf;
using Resampler_i_base<REAL>::make_inbuf;
private:
int frqgcd,osf,fs1,fs2;
REAL *stage1,**stage2;
int n2,n2x,n2y,n1,n1b;
int filter1len;
int *f2order,*f2inc;
int *fft_ip;// = NULL;
REAL *fft_w;// = NULL;
//unsigned char *rawinbuf,*rawoutbuf;
REAL *inbuf,*outbuf;
REAL **buf1,**buf2;
int i,j;
int spcount;// = 0;
double peak;//=0;
int n1b2;// = n1b/2;
int rp; // keep the location of the next samples to read in inbuf at fs1.
int rps; // the reminder obtained by dividing rp by (fs1/sfrq=osf).
int rp2; // keep the location of the next samples to read in buf2 at fs2.
int ds; // the number of samples to dispose next in sfrq.
int nsmplwrt2; // actually number of samples to send stage2 filter .
int s2p; // the reminder obtained by dividing the samples output from stage1 filter by n1y*osf.
int init,ending;
int osc;
REAL *bp; // the location of the next samples to read calculated with rp2
int rps_backup,s2p_backup;
int k,ch,p;
int inbuflen;//=0;
unsigned int sumread,sumwrite;
int delay;// = 0;
int delay2;
REAL *op;
public:
Downsampler(Resampler_base::CONFIG & c);
~Downsampler();
/*
{
avs_free(stage1);
avs_free(fft_ip);
avs_free(fft_w);
avs_free(f2order);
avs_free(f2inc);
avs_free(stage2[0]);
avs_free(stage2);
for(i=0;i<nch;i++) avs_free(buf1[i]);
avs_free(buf1);
for(i=0;i<nch;i++) avs_free(buf2[i]);
avs_free(buf2);
avs_free(inbuf);
avs_free(outbuf);
//free(rawoutbuf);
}; // dtor
*/
unsigned int Resample(REAL_inout * rawinbuf, unsigned int in_size, int ending);
};
template<class REAL>
Downsampler<REAL>::Downsampler(Resampler_base::CONFIG & c) : Resampler_i_base<REAL>(c)
{
spcount = 0;
peak = 0;
fft_ip = 0;
fft_w = 0;
filter1len = FFTFIRLEN; /* stage 1 filter length */
/* Make stage 1 filter */
{
double aa = AA; /* stop band attenuation(dB) */
double lpf, delta, d, df, alp, iza;
int ipsize, wsize;
frqgcd = gcd(sfrq, dfrq);
if (dfrq / frqgcd == 1) osf = 1;
else if (dfrq / frqgcd % 2 == 0) osf = 2;
else if (dfrq / frqgcd % 3 == 0) osf = 3;
else {
// fprintf(stderr,"Resampling from %dHz to %dHz is not supported.\n",sfrq,dfrq);
// fprintf(stderr,"%d/gcd(%d,%d)=%d must be divided by 2 or 3.\n",dfrq,sfrq,dfrq,dfrq/frqgcd);
// exit(-1);
return;
}
fs1 = sfrq * osf;
delta = pow(10.0, -aa / 20);
if (aa <= 21) d = 0.9222; else d = (aa - 7.95) / 14.36;
n1 = filter1len;
for (i = 1;; i = i * 2)
{
n1 = filter1len * i;
if (n1 % 2 == 0) n1--;
df = (fs1*d) / (n1 - 1);
lpf = (dfrq - df) / 2;
if (df < DF) break;
}
alp = alpha(aa);
iza = dbesi0(alp);
for (n1b = 1; n1b<n1; n1b *= 2);
n1b *= 2;
stage1 = (REAL*)avs_malloc(sizeof(REAL)*n1b, 64);
for (i = 0; i<n1b; i++) stage1[i] = 0;
for (i = -(n1 / 2); i <= n1 / 2; i++) {
stage1[i + n1 / 2] = win(i, n1, alp, iza)*hn_lpf(i, lpf, fs1)*fs1 / sfrq / n1b * 2;
}
ipsize = 2 + sqrt((double)n1b);
fft_ip = (int*)avs_malloc(sizeof(int)*ipsize, 64);
fft_ip[0] = 0;
wsize = n1b / 2;
fft_w = (REAL*)avs_malloc(sizeof(REAL)*wsize, 64);
fft<REAL>::rdft(n1b, 1, stage1, fft_ip, fft_w);
}
/* Make stage 2 filter */
if (osf == 1) {
fs2 = sfrq / frqgcd * dfrq;
n2 = 1;
n2y = n2x = 1;
f2order = (int*)avs_malloc(sizeof(int)*n2y, 64);
f2order[0] = 0;
f2inc = (int*)avs_malloc(sizeof(int)*n2y, 64);
f2inc[0] = sfrq / dfrq;
stage2 = (REAL**)avs_malloc(sizeof(REAL *)*n2y, 64);
stage2[0] = (REAL*)avs_malloc(sizeof(REAL)*n2x*n2y, 64);
stage2[0][0] = 1;
}
else {
double aa = AA; /* stop band attenuation(dB) */
double lpf, delta, d, df, alp, iza;
double guard = 2;
fs2 = sfrq / frqgcd * dfrq;
df = (fs1 / 2 - sfrq / 2) * 2 / guard;
lpf = sfrq / 2 + (fs1 / 2 - sfrq / 2) / guard;
delta = pow(10.0, -aa / 20);
if (aa <= 21) d = 0.9222; else d = (aa - 7.95) / 14.36;
n2 = fs2 / df * d + 1;
if (n2 % 2 == 0) n2++;
alp = alpha(aa);
iza = dbesi0(alp);
n2y = fs2 / fs1; // The interval where the sample which isn't 0 in fs2 exists.
n2x = n2 / n2y + 1;
f2order = (int*)avs_malloc(sizeof(int)*n2y, 64);
for (i = 0; i<n2y; i++) {
f2order[i] = fs2 / fs1 - (i*(fs2 / dfrq)) % (fs2 / fs1);
if (f2order[i] == fs2 / fs1) f2order[i] = 0;
}
f2inc = (int*)avs_malloc(sizeof(int)*n2y, 64);
for (i = 0; i<n2y; i++) {
f2inc[i] = (fs2 / dfrq - f2order[i]) / (fs2 / fs1) + 1;
if (f2order[i + 1 == n2y ? 0 : i + 1] == 0) f2inc[i]--;
}
stage2 = (REAL**)avs_malloc(sizeof(REAL *)*n2y, 64);
stage2[0] = (REAL*)avs_malloc(sizeof(REAL)*n2x*n2y, 64);
for (i = 1; i<n2y; i++) {
stage2[i] = &(stage2[0][n2x*i]);
for (j = 0; j<n2x; j++) stage2[i][j] = 0;
}
for (i = -(n2 / 2); i <= n2 / 2; i++)
{
stage2[(i + n2 / 2) % n2y][(i + n2 / 2) / n2y] = win(i, n2, alp, iza)*hn_lpf(i, lpf, fs2)*fs2 / fs1;
}
}
/* Apply filters */
n1b2 = n1b / 2;
inbuflen = 0;
// delay = 0;
// |....B....|....C....| buf1 n1b2+n1b2
//|.A.|....D....| buf2 n2x+n1b2
//
// At first, take samples from inbuf and multiplied by osf, then write those into B.
// Clear C.
// Apply stage1-filter to B and C.
// Add B to D.
// Apply stage2-filter to A and D
// Move last part of D to A.
// Copy C to D.
buf1 = (REAL**)_aligned_malloc(sizeof(REAL *)*nch, 64);
for (i = 0; i<nch; i++)
buf1[i] = (REAL*)avs_malloc(n1b * sizeof(REAL), 64);
buf2 = (REAL**)avs_malloc(sizeof(REAL *)*nch, 64);
for (i = 0; i<nch; i++) {
buf2[i] = (REAL*)avs_malloc(sizeof(REAL)*(n2x + 1 + n1b2), 64);
for (j = 0; j<n2x + n1b2; j++) buf2[i][j] = 0;
}
//rawoutbuf = (unsigned char*)malloc(dbps*nch*((double)n1b2*sfrq/dfrq+1));
inbuf = (REAL*)avs_malloc(nch*(n1b2 / osf + osf + 1) * sizeof(REAL), 64);
outbuf = (REAL*)avs_malloc(sizeof(REAL)*nch*((double)n1b2*sfrq / dfrq + 1), 64);
op = outbuf;
s2p = 0;
rp = 0;
rps = 0;
ds = 0;
osc = 0;
rp2 = 0;
init = 1;
ending = 0;
delay = (double)n1 / 2 / ((double)fs1 / dfrq) + (double)n2 / 2 / ((double)fs2 / dfrq);
delay2 = delay * nch;
sumread = sumwrite = 0;
}; // ctor
template<class REAL>
Downsampler<REAL>::~Downsampler()
{
avs_free(stage1);
avs_free(fft_ip);
avs_free(fft_w);
avs_free(f2order);
avs_free(f2inc);
avs_free(stage2[0]);
avs_free(stage2);
for (i = 0; i<nch; i++) avs_free(buf1[i]);
avs_free(buf1);
for (i = 0; i<nch; i++) avs_free(buf2[i]);
avs_free(buf2);
avs_free(inbuf);
avs_free(outbuf);
//free(rawoutbuf);
}; // dtor
template<class REAL>
unsigned int Downsampler<REAL>::Resample(REAL_inout * rawinbuf, unsigned int in_size, int ending) {
unsigned int rv;
int nsmplread;
int toberead;
toberead = (n1b2 - rps - 1) / osf + 1;
if (!ending)
{
rv = nch * toberead;
if (in_size<rv) return 0;
nsmplread = toberead;
}
else
{
nsmplread = in_size / nch;
rv = nsmplread * nch;
}
make_inbuf(nsmplread, inbuflen, rawinbuf, inbuf, toberead);
sumread += nsmplread;
rps_backup = rps;
s2p_backup = s2p;
for (ch = 0; ch<nch; ch++)
{
rps = rps_backup;
for (k = 0; k<rps; k++) buf1[ch][k] = 0;
for (i = rps, j = 0; i<n1b2; i += osf, j++)
{
assert(j < ((n1b2 - rps - 1) / osf + 1));
buf1[ch][i] = inbuf[j*nch + ch];
for (k = i + 1; k<i + osf; k++) buf1[ch][k] = 0;
}
assert(j == ((n1b2 - rps - 1) / osf + 1));
for (k = n1b2; k<n1b; k++) buf1[ch][k] = 0;
rps = i - n1b2;
rp += j;
fft<REAL>::rdft(n1b, 1, buf1[ch], fft_ip, fft_w);
buf1[ch][0] = stage1[0] * buf1[ch][0];
buf1[ch][1] = stage1[1] * buf1[ch][1];
for (i = 1; i<n1b2; i++)
{
REAL re, im;
re = stage1[i * 2] * buf1[ch][i * 2] - stage1[i * 2 + 1] * buf1[ch][i * 2 + 1];
im = stage1[i * 2 + 1] * buf1[ch][i * 2] + stage1[i * 2] * buf1[ch][i * 2 + 1];
buf1[ch][i * 2] = re;
buf1[ch][i * 2 + 1] = im;
}
fft<REAL>::rdft(n1b, -1, buf1[ch], fft_ip, fft_w);
for (i = 0; i<n1b2; i++) {
buf2[ch][n2x + 1 + i] += buf1[ch][i];
}
{
int t1 = rp2 / (fs2 / fs1);
if (rp2 % (fs2 / fs1) != 0) t1++;
bp = &(buf2[ch][t1]);
}
s2p = s2p_backup;
for (p = 0; bp - buf2[ch]<n1b2 + 1; p++)
{
REAL tmp = 0;
REAL *bp2;
int s2o;
bp2 = bp;
s2o = f2order[s2p];
bp += f2inc[s2p];
s2p++;
if (s2p == n2y) s2p = 0;
assert((bp2 - &(buf2[ch][0]))*(fs2 / fs1) - (rp2 + p * (fs2 / dfrq)) == s2o);
for (i = 0; i<n2x; i++)
tmp += stage2[s2o][i] * *bp2++;
op[p*nch + ch] = tmp;
}
nsmplwrt2 = p;
}
rp2 += nsmplwrt2 * (fs2 / dfrq);
make_outbuf(nsmplwrt2, outbuf, delay2);
if (!init) {
if (ending) {
if ((double)sumread*dfrq / this->sfrq + 2 > sumwrite + nsmplwrt2) {
sumwrite += nsmplwrt2;
}
else {
return rv;
}
}
else {
sumwrite += nsmplwrt2;
}
}
else {
if (nsmplwrt2 < delay) {
delay -= nsmplwrt2;
}
else {
if (ending) {
if ((double)sumread*this->dfrq / this->sfrq + 2 > sumwrite + nsmplwrt2 - delay) {
sumwrite += nsmplwrt2 - delay;
}
else {
return rv;
}
}
else {
sumwrite += nsmplwrt2 - delay;
init = 0;
}
}
}
{
int ds = (rp2 - 1) / (fs2 / fs1);
if (ds > n1b2) ds = n1b2;
for (ch = 0; ch<nch; ch++)
mem_ops<REAL>::move(buf2[ch], buf2[ch] + ds, n2x + 1 + n1b2 - ds);
rp2 -= ds * (fs2 / fs1);
}
for (ch = 0; ch<nch; ch++)
mem_ops<REAL>::copy(buf2[ch] + n2x + 1, buf1[ch] + n1b2, n1b2);
return rv;
}
Resampler_base::Resampler_base(const Resampler_base::CONFIG & c)
{
if (c.fast)
{
AA = 96;
DF = 8000;
FFTFIRLEN = 1024;
}
else
{
AA=120;
DF=100;
FFTFIRLEN=16384;
}
/*
#else
AA=170;
DF=100;
FFTFIRLEN=65536;
#endif
*/
nch=c.nch;
sfrq=c.sfrq;
dfrq=c.dfrq;
double noiseamp = 0.18;
//double att=0;
gain=1;//pow(10.0,-att/20);
}
Resampler_base * Resampler_base::Create(Resampler_base::CONFIG & c)
{
if (!CanResample(c.sfrq,c.dfrq)) return 0;
/* if (c.math)
{
if (c.sfrq < c.dfrq) return new Upsampler<double>(c);
else if (c.sfrq > c.dfrq) return new Downsampler<double>(c);
else return 0;
}
else*/
{
if (c.sfrq < c.dfrq) return new Upsampler<float>(c);
else if (c.sfrq > c.dfrq) return new Downsampler<float>(c);
else return 0;
}
}
Resampler_base *SSRC_create(int sfrq, int dfrq, int nch, int dither, int pdf, int fast)
{
Resampler_base::CONFIG c(sfrq, dfrq, nch, dither, pdf, fast);
return Resampler_base::Create(c);
}
| 22.278559 | 117 | 0.541711 | wurui1994 |
e85abaf9084edff95cf3b43144191390184028c3 | 142 | cpp | C++ | src/Debug.cpp | JurisPolevskis/PolygonFinder | dd09a89c246f959071ebb1148c2cbe38cdc60edb | [
"Unlicense"
] | null | null | null | src/Debug.cpp | JurisPolevskis/PolygonFinder | dd09a89c246f959071ebb1148c2cbe38cdc60edb | [
"Unlicense"
] | null | null | null | src/Debug.cpp | JurisPolevskis/PolygonFinder | dd09a89c246f959071ebb1148c2cbe38cdc60edb | [
"Unlicense"
] | null | null | null | #include "Debug.h"
#include <iostream>
void Debug::print(const std::string& str)
{
#ifdef DEBUG
std::cout << str << std::endl;
#endif
} | 14.2 | 42 | 0.640845 | JurisPolevskis |
e85d05c1eddad62c9ec79e5d962f64270864c35e | 820 | cpp | C++ | jobtaskitem.cpp | dayuanyuan1989/RemoteBinder | 6c07896828187bbb890115fa1326f9db4fbd7b68 | [
"MIT"
] | null | null | null | jobtaskitem.cpp | dayuanyuan1989/RemoteBinder | 6c07896828187bbb890115fa1326f9db4fbd7b68 | [
"MIT"
] | null | null | null | jobtaskitem.cpp | dayuanyuan1989/RemoteBinder | 6c07896828187bbb890115fa1326f9db4fbd7b68 | [
"MIT"
] | null | null | null | #include "jobtaskitem.h"
#include "ui_jobtaskitem.h"
JobTaskItem::JobTaskItem(QWidget *parent) :
QWidget(parent),
ui(new Ui::JobTaskItem)
{
ui->setupUi(this);
// SetBodyVisible(false);
}
JobTaskItem::~JobTaskItem()
{
delete ui;
}
void JobTaskItem::SetTitle(const QString& str)
{
ui->title->setText(str);
}
void JobTaskItem::SetSizeValue(const QString& str)
{
ui->size->setText(str);
}
void JobTaskItem::SetQualityValue(const QString& str)
{
ui->quality->setText(str);
}
void JobTaskItem::SetBodyVisible(bool visible)
{
if(visible) {
resize(width(), JOB_ITEM_TOTAL_HEIGHT);
} else {
resize(width(), JOB_ITEM_HEAD_HEIGHT);
}
}
bool JobTaskItem::BodyVisible()
{
return (height() != JOB_ITEM_HEAD_HEIGHT);
}
| 17.826087 | 54 | 0.634146 | dayuanyuan1989 |
e86220fd31d629176ceb8d429c28bdc75b743123 | 386 | cpp | C++ | HackerRank/University-Codesprint-5/Exceeding-the-Speed-Limit.cpp | TISparta/competitive-programming-solutions | 31987d4e67bb874bf15653565c6418b5605a20a8 | [
"MIT"
] | 1 | 2018-01-30T13:21:30.000Z | 2018-01-30T13:21:30.000Z | HackerRank/University-Codesprint-5/Exceeding-the-Speed-Limit.cpp | TISparta/competitive-programming-solutions | 31987d4e67bb874bf15653565c6418b5605a20a8 | [
"MIT"
] | null | null | null | HackerRank/University-Codesprint-5/Exceeding-the-Speed-Limit.cpp | TISparta/competitive-programming-solutions | 31987d4e67bb874bf15653565c6418b5605a20a8 | [
"MIT"
] | 1 | 2018-08-29T13:26:50.000Z | 2018-08-29T13:26:50.000Z | /**
* > Author : TISparta
* > Date : 09-09-18
* > Tags : Implementation
* > Difficulty : 1 / 10
*/
#include <bits/stdc++.h>
using namespace std;
int main () {
int s;
cin >> s;
if (s <= 90) printf("%d %s\n", 0, "No punishment");
else if (s <= 110) printf("%d %s\n", (s - 90) * 300, "Warning");
else printf("%d %s\n", (s - 90) * 500, "License removed");
return (0);
}
| 19.3 | 66 | 0.523316 | TISparta |
e8628b6b7b6a594051ce4cfd1f1c842b4ca0866c | 12,960 | cpp | C++ | copyworker.cpp | haraki/farman | 9aab8cfdd3f9d98f3be8dfddd6bad8451ea27297 | [
"MIT"
] | 5 | 2018-08-19T05:45:45.000Z | 2020-10-09T09:37:57.000Z | copyworker.cpp | haraki/farman | 9aab8cfdd3f9d98f3be8dfddd6bad8451ea27297 | [
"MIT"
] | 95 | 2018-04-26T12:13:24.000Z | 2020-05-03T08:23:56.000Z | copyworker.cpp | haraki/farman | 9aab8cfdd3f9d98f3be8dfddd6bad8451ea27297 | [
"MIT"
] | 1 | 2018-08-19T05:46:02.000Z | 2018-08-19T05:46:02.000Z | #include <QDebug>
#include <QFileInfo>
#include <QDir>
#include <QFile>
#include <QTemporaryFile>
#include <QDateTime>
#include <QMutex>
#include <QThread>
#include "copyworker.h"
#include "workerresult.h"
#include "default_settings.h"
namespace Farman
{
CopyWorker::CopyWorker(const QStringList& srcPaths, const QString& dstPath, bool moveMode, qint64 unitSize, QObject *parent)
: Worker(parent)
, m_srcPaths(srcPaths)
, m_dstPath(dstPath)
, m_moveMode(moveMode)
, m_methodType(DEFAULT_OVERWRITE_METHOD_TYPE)
, m_methodTypeKeep(false)
, m_renameFileName("")
, m_copyUnitSize(unitSize)
{
}
CopyWorker::~CopyWorker()
{
}
void CopyWorker::run()
{
qDebug() << "start CopyWorker::run()";
m_timer.start();
QString prepareStr = (m_moveMode) ? tr("Preparing move...") : tr("Preparing copy...");
QString prepareAbortStr = (m_moveMode) ? tr("Preparing move...aborted.") : tr("Preparing copy...aborted.");
QString prepareFailedStr = (m_moveMode) ? tr("Preparing move...failed.") : tr("Preparing copy...failed.");
emitProcess(prepareStr);
QMap<QString, QString> copyList;
QList<QString> removeDirList;
// コピーするファイル・ディレクトリのリストを作成
for(auto srcPath : m_srcPaths)
{
if(isAborted())
{
//emitOutputConsole(tr("Aborted.\n")); // makeList() 内部でコンソール出力しているので、ここではコンソール出力しない
emitProcess(prepareAbortStr);
emitFinished(static_cast<int>(WorkerResult::Abort));
return;
}
int ret = makeList(srcPath, m_dstPath, copyList, removeDirList);
if(isError(ret))
{
qDebug() << "makeList() : ret =" << QString("%1").arg(ret, 0, 16);
emitProcess(prepareFailedStr);
emitFinished(ret);
return;
}
}
emitStart(0, copyList.size());
QString preStr = (m_moveMode) ? tr("%1 file(s) move...") : tr("%1 file(s) copy...");
QString postStr = (m_moveMode) ? tr("%1 file(s) move...done.") : tr("%1 file(s) copy...done.");
QString abortStr = (m_moveMode) ? tr("%1 file(s) move...aborted.") : tr("%1 file(s) copy...aborted.");
QString failedStr = (m_moveMode) ? tr("%1 file(s) move...failed.") : tr("%1 file(s) copy...failed.");
int progress = 0;
for(QMap<QString, QString>::const_iterator itr = copyList.cbegin();itr != copyList.cend();itr++)
{
thread()->msleep(1); // sleep を入れないと Abort できない場合がある
emitProcess(QString(preStr).arg(progress + 1));
int ret = copyExec(itr.key(), itr.value());
if(isAborted())
{
//emitOutputConsole(tr("Aborted.\n")); // copyExec() 内部でコンソール出力しているので、ここではコンソール出力しない
emitProcess(QString(abortStr).arg(progress + 1));
emitFinished(static_cast<int>(WorkerResult::Abort));
return;
}
if(isError(ret))
{
qDebug() << "copyExec() : ret =" << QString("%1").arg(ret, 0, 16);
emitProcess(QString(failedStr).arg(progress + 1));
emitFinished(ret);
return;
}
emitProcess(QString(postStr).arg(progress + 1));
progress++;
emitProgress(progress);
}
if(m_moveMode)
{
// ディレクトリ削除
for(auto dirPath : removeDirList)
{
qDebug() << "remove dir :" << dirPath;
if(!QDir().rmdir(dirPath))
{
// 移動元のディレクトリ削除失敗
qDebug() << "remove dir error :" << dirPath;
emitProcess(QString(tr("remove %1 folder failed.")).arg(dirPath));
emitFinished(static_cast<int>(WorkerResult::ErrorRemoveDir));
return;
}
}
}
emitOutputConsole(QString("Total time : %L1 ms.\n").arg(m_timer.elapsed()));
qDebug() << "finish CopyWorker::run()";
emitFinished(static_cast<int>(WorkerResult::Success));
}
int CopyWorker::makeList(const QString& srcPath, const QString& dstDirPath, QMap<QString, QString>& copyList, QList<QString>& removeDirList)
{
if(isAborted())
{
emitOutputConsole(tr("Aborted.\n"));
return static_cast<int>(WorkerResult::Abort);
}
QFileInfo srcFileInfo(srcPath);
QDir dstDir(dstDirPath);
QString dstPath = dstDir.absoluteFilePath(srcFileInfo.fileName());
QFileInfo dstFileInfo(dstPath);
copyList.insert(srcFileInfo.absoluteFilePath(), dstFileInfo.absoluteFilePath());
qDebug() << srcFileInfo.absoluteFilePath() << ">>" << dstFileInfo.absoluteFilePath();
if(srcFileInfo.isDir())
{
// 再帰処理でコピー元ディレクトリ内のエントリをリストに追加する
QDir srcDir(srcPath);
QFileInfoList srcChildFileInfoList = srcDir.entryInfoList(QDir::AllEntries |
QDir::AccessMask |
QDir::AllDirs |
QDir::NoDotAndDotDot,
QDir::DirsFirst);
for(auto srcChildFileInfo : srcChildFileInfoList)
{
int ret = makeList(srcChildFileInfo.absoluteFilePath(), dstFileInfo.absoluteFilePath(), copyList, removeDirList);
if(ret == static_cast<int>(WorkerResult::Abort) || isError(ret))
{
return ret;
}
}
if(m_moveMode)
{
// 最後にディレクトリをまとめて削除するためのリストを作成
removeDirList.push_back(srcFileInfo.absoluteFilePath());
}
}
return static_cast<int>(WorkerResult::Success);
}
int CopyWorker::copyExec(const QString& srcPath, const QString& dstPath)
{
if(isAborted())
{
emitOutputConsole(tr("Aborted.\n"));
return static_cast<int>(WorkerResult::Abort);
}
QFileInfo srcFileInfo(srcPath);
QFileInfo dstFileInfo(dstPath);
emitOutputConsole(QString("%1 >> %2 ... ").arg(srcFileInfo.absoluteFilePath()).arg(dstFileInfo.absoluteFilePath()));
qDebug() << srcFileInfo.absoluteFilePath() << ">>" << dstFileInfo.absoluteFilePath();
if(srcFileInfo.isDir())
{
// ディレクトリの場合はコピー先にディレクトリを作成する
if(dstFileInfo.exists())
{
emitOutputConsole(tr("is exists.\n"));
}
else
{
QDir dstDir(dstPath);
if(!dstDir.mkdir(dstPath))
{
// ディレクトリ作成失敗
emitOutputConsole(tr("Failed make directory.\n"));
return static_cast<int>(WorkerResult::ErrorMakeDir);
}
emitOutputConsole(tr("Made directory.\n"));
qDebug() << "succeed mkdir(" << dstPath << ")";
}
}
else
{
// ファイル
while(dstFileInfo.exists())
{
// コピー先にファイルが存在している
m_renameFileName = "";
if(!m_methodTypeKeep || m_methodType == OverwriteMethodType::Rename)
{
showConfirmOverwrite(srcFileInfo.absoluteFilePath(), dstFileInfo.absoluteFilePath(), m_methodType);
if(isAborted())
{
// 中断
emitOutputConsole(tr("Aborted.\n"));
return static_cast<int>(WorkerResult::Abort);
}
}
if(m_methodType == OverwriteMethodType::Overwrite)
{
if(!QFile::remove(dstFileInfo.absoluteFilePath()))
{
emitOutputConsole((m_moveMode) ? tr("Failed move.\n") : tr("Failed copy.\n"));
return static_cast<int>(WorkerResult::ErrorRemoveFile);
}
break;
}
else if(m_methodType == OverwriteMethodType::OverwriteIfNewer)
{
if(srcFileInfo.lastModified() <= dstFileInfo.lastModified())
{
emitOutputConsole(tr("Skipped.\n"));
return static_cast<int>(WorkerResult::Skip);
}
if(!QFile::remove(dstFileInfo.absoluteFilePath()))
{
emitOutputConsole((m_moveMode) ? tr("Failed move.\n") : tr("Failed copy.\n"));
return static_cast<int>(WorkerResult::ErrorRemoveFile);
}
break;
}
else if(m_methodType == OverwriteMethodType::Skip)
{
emitOutputConsole(tr("Skipped.\n"));
return static_cast<int>(WorkerResult::Skip);
}
else if(m_methodType == OverwriteMethodType::Rename)
{
dstFileInfo.setFile(dstFileInfo.absolutePath(), m_renameFileName);
}
else
{
// ここにくることはありえないはず
emitOutputConsole(tr("Fatal error.\n"));
return static_cast<int>(WorkerResult::ErrorFatal);
}
}
int result = copy(srcFileInfo.absoluteFilePath(), dstFileInfo.absoluteFilePath());
if(result == static_cast<int>(WorkerResult::Abort))
{
emitOutputConsole(tr("Aborted.\n"));
return static_cast<int>(WorkerResult::Abort);
}
else if(isError(result))
{
// コピー失敗
emitOutputConsole((m_moveMode) ? tr("Failed move.\n") : tr("Failed copy.\n"));
return static_cast<int>(WorkerResult::ErrorCopyFile);
}
if(m_moveMode)
{
qDebug() << "remove file : " << srcFileInfo.absoluteFilePath();
if(!QFile::remove(srcFileInfo.absoluteFilePath()))
{
// 移動元のファイル削除失敗
emitOutputConsole(tr("Failed move.\n"));
return static_cast<int>(WorkerResult::ErrorRemoveFile);
}
}
emitOutputConsole((m_moveMode) ? tr("Moved\n") : tr("Copied\n"));
}
return static_cast<int>(WorkerResult::Success);
}
void CopyWorker::showConfirmOverwrite(const QString& srcFilePath, const QString& dstFilePath, OverwriteMethodType methodType)
{
emitConfirmOverwrite(srcFilePath, dstFilePath, methodType);
m_timer.invalidate();
QMutex mutex;
{
QMutexLocker locker(&mutex);
m_confirmWait.wait(&mutex);
}
m_timer.restart();
}
void CopyWorker::emitConfirmOverwrite(const QString& srcFilePath, const QString& dstFilePath, OverwriteMethodType methodType)
{
emit confirmOverwrite(srcFilePath, dstFilePath, static_cast<int>(methodType));
}
void CopyWorker::finishConfirmOverwrite(OverwriteMethodType methodType, bool methodTypeKeep, const QString& renameFileName)
{
m_methodType = methodType;
m_methodTypeKeep = methodTypeKeep;
m_renameFileName = renameFileName;
m_confirmWait.wakeAll();
}
void CopyWorker::cancelConfirmOverwrite()
{
abort();
m_confirmWait.wakeAll();
}
void CopyWorker::emitStartSub(qint64 min, qint64 max)
{
emit startSub(min, max);
}
void CopyWorker::emitProgressSub(qint64 value)
{
emit progressSub(value);
}
int CopyWorker::copy(const QString& srcPath, const QString& dstPath)
{
qDebug() << "CopyWorker::copy() : " << srcPath << " >> " << dstPath;
QFile srcFile(srcPath);
if(!srcFile.open(QIODevice::ReadOnly))
{
return static_cast<int>(WorkerResult::ErrorCopyFile);
}
QTemporaryFile dstFile(QString(QLatin1String("%1/temp.XXXXXX")).arg(QFileInfo(dstPath).path()));
if(!dstFile.open())
{
srcFile.close();
return static_cast<int>(WorkerResult::ErrorCopyFile);
}
QByteArray buffer;
WorkerResult result = WorkerResult::Success;
qint64 remineSize = srcFile.size();
qint64 totalSize = 0;
emitStartSub(0, remineSize);
while(!srcFile.atEnd())
{
thread()->msleep(1); // sleep を入れないと Abort できない場合がある
if(isAborted())
{
result = WorkerResult::Abort;
break;
}
qint64 readSize = (remineSize > m_copyUnitSize) ? m_copyUnitSize : remineSize;
buffer = srcFile.read(readSize);
if(buffer.size() < readSize)
{
result = WorkerResult::ErrorCopyFile;
break;
}
qint64 wroteSize = dstFile.write(buffer);
if(wroteSize < readSize)
{
result = WorkerResult::ErrorCopyFile;
break;
}
remineSize -= readSize;
totalSize += readSize;
emitProgressSub(totalSize);
}
if(result == WorkerResult::Success)
{
dstFile.rename(dstPath);
dstFile.setAutoRemove(false);
if(!dstFile.setPermissions(srcFile.permissions()))
{
qDebug() << "set permissons error!! : " << dstPath;
result = WorkerResult::ErrorCopyFile;
}
}
srcFile.close();
dstFile.close();
return static_cast<int>(result);
}
} // namespace Farman
| 29.930716 | 140 | 0.568519 | haraki |
e8643795d6a7607cb957f73e500daddd2ac3a37a | 2,283 | hpp | C++ | src/mfx/hw/RPiDmaBlocks.hpp | D-J-Roberts/pedalevite | 157611b5ccf2bb97f0007d7d17b4c07bd6a21fba | [
"WTFPL"
] | 69 | 2017-01-17T13:17:31.000Z | 2022-03-01T14:56:32.000Z | src/mfx/hw/RPiDmaBlocks.hpp | D-J-Roberts/pedalevite | 157611b5ccf2bb97f0007d7d17b4c07bd6a21fba | [
"WTFPL"
] | 1 | 2020-11-03T14:52:45.000Z | 2020-12-01T20:31:15.000Z | src/mfx/hw/RPiDmaBlocks.hpp | D-J-Roberts/pedalevite | 157611b5ccf2bb97f0007d7d17b4c07bd6a21fba | [
"WTFPL"
] | 8 | 2017-02-08T13:30:42.000Z | 2021-12-09T08:43:09.000Z | /*****************************************************************************
RPiDmaBlocks.hpp
Author: Laurent de Soras, 2021
--- Legal stuff ---
This program is free software. It comes without any warranty, to
the extent permitted by applicable law. You can redistribute it
and/or modify it under the terms of the Do What The Fuck You Want
To Public License, Version 2, as published by Sam Hocevar. See
http://www.wtfpl.net/ for more details.
*Tab=3***********************************************************************/
#if ! defined (mfx_hw_RPiDmaBlocks_CODEHEADER_INCLUDED)
#define mfx_hw_RPiDmaBlocks_CODEHEADER_INCLUDED
/*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
#include <cassert>
namespace mfx
{
namespace hw
{
/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
int RPiDmaBlocks::get_nbr_blocks () const
{
return _nbr_cbs;
}
bcm2837dma::CtrlBlock & RPiDmaBlocks::use_cb (int idx)
{
assert (idx >= 0);
assert (idx < _nbr_cbs);
return _cb_ptr [idx];
}
const bcm2837dma::CtrlBlock & RPiDmaBlocks::use_cb (int idx) const
{
assert (idx >= 0);
assert (idx < _nbr_cbs);
return _cb_ptr [idx];
}
int RPiDmaBlocks::get_buf_len () const
{
return _buf_len;
}
// Buffer is 32-byte aligned (_align_min)
uint8_t * RPiDmaBlocks::use_buf ()
{
return _buf_ptr;
}
const uint8_t* RPiDmaBlocks::use_buf () const
{
return _buf_ptr;
}
template <typename T>
T * RPiDmaBlocks::use_buf ()
{
return reinterpret_cast <T *> (_buf_ptr);
}
template <typename T>
const T * RPiDmaBlocks::use_buf () const
{
return reinterpret_cast <const T *> (_buf_ptr);
}
uint32_t RPiDmaBlocks::virt_to_phys (const void *virt_ptr)
{
const ptrdiff_t offset =
reinterpret_cast <const uint8_t *> (virt_ptr) - _mbox.get_virt_ptr ();
assert (offset >= 0);
assert (offset < _tot_len);
return _mbox.get_phys_adr () + uint32_t (offset);
}
/*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
/*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
} // namespace hw
} // namespace mfx
#endif // mfx_hw_RPiDmaBlocks_CODEHEADER_INCLUDED
/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
| 16.911111 | 78 | 0.551905 | D-J-Roberts |