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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9603f5ed110e157362f45ee4f58cb664d4919beb | 3,149 | cc | C++ | src/automaton/tests/crypto/test_Keccak_256_cryptopp.cc | automaton-network/automaton | 34f6df278dc71d11340084c3487564ab58b04c2e | [
"MIT"
] | 2 | 2018-12-19T18:01:14.000Z | 2019-03-29T12:54:41.000Z | src/automaton/tests/crypto/test_Keccak_256_cryptopp.cc | automaton-network/automaton | 34f6df278dc71d11340084c3487564ab58b04c2e | [
"MIT"
] | 3 | 2018-12-20T17:44:31.000Z | 2020-03-25T16:45:04.000Z | src/automaton/tests/crypto/test_Keccak_256_cryptopp.cc | automaton-network/automaton | 34f6df278dc71d11340084c3487564ab58b04c2e | [
"MIT"
] | 2 | 2020-03-12T13:33:10.000Z | 2020-03-22T00:48:51.000Z | #include <cryptopp/cryptlib.h>
#include <cryptopp/keccak.h>
#include <cryptopp/hex.h>
#include <cryptopp/filters.h>
#include <string>
#include "automaton/core/crypto/cryptopp/Keccak_256_cryptopp.h"
#include "automaton/core/crypto/hash_transformation.h"
#include "automaton/core/io/io.h"
#include "gtest/gtest.h"
using automaton::core::crypto::cryptopp::Keccak_256_cryptopp;
using automaton::core::crypto::hash_transformation;
using automaton::core::io::bin2hex;
TEST(keccak_256_cryptopp, calculate_digest) {
Keccak_256_cryptopp hasher;
size_t digest_size = hasher.digest_size();
uint8_t* digest = new uint8_t[digest_size];
constexpr uint32_t test_cases = 6;
std::string test[test_cases][2] = {
{"a",
"3AC225168DF54212A25C1C01FD35BEBFEA408FDAC2E31DDD6F80A4BBF9A5F1CB"},
{"abc",
"4E03657AEA45A94FC7D47BA826C8D667C0D1E6E33A64A036EC44F58FA12D6C45"},
{"",
"C5D2460186F7233C927E7DB2DCC703C0E500B653CA82273B7BFAD8045D85A470"},
{"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
"45D3B367A6904E6E8D502EE04999A7C27647F91FA845D456525FD352AE3D7371"},
{"abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmno"
"ijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu",
"F519747ED599024F3882238E5AB43960132572B7345FBEB9A90769DAFD21AD67"},
{"testing",
"5F16F4C7F149AC4F9510D9CF8CF384038AD348B3BCDC01915F95DE12DF9D1B02"}
};
for (uint32_t i = 0; i < test_cases; i++) {
hasher.calculate_digest(reinterpret_cast<const uint8_t*>(test[i][0].data()),
test[i][0].length(), digest);
std::string result(reinterpret_cast<char*>(digest), digest_size);
EXPECT_EQ(bin2hex(result), test[i][1]);
}
delete[] digest;
}
TEST(keccak_256_cryptopp, update_and_finish) {
Keccak_256_cryptopp hasher;
size_t digest_size = hasher.digest_size();
uint8_t* digest = new uint8_t[digest_size];
std::string test_input(
"abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmno");
const std::string EXP1 =
"C8A625720D2C6221C09DB8A33A63FB936E628A0C10195768A206E7AD8D1E54DE";
const uint8_t* p_test_input = reinterpret_cast<const uint8_t*>(test_input.data());
size_t len = test_input.length();
for (uint32_t i = 0; i < 10; i++) {
hasher.update(p_test_input, len);
}
hasher.final(digest);
std::string result(reinterpret_cast<char*>(digest), digest_size);
EXPECT_EQ(bin2hex(result), EXP1);
// Try to hash a new string to see if everything restarted as intended
const uint8_t* a = reinterpret_cast<const uint8_t*>("a");
const uint8_t* b = reinterpret_cast<const uint8_t*>("b");
const uint8_t* c = reinterpret_cast<const uint8_t*>("c");
const std::string EXP2 =
"4E03657AEA45A94FC7D47BA826C8D667C0D1E6E33A64A036EC44F58FA12D6C45";
hasher.update(a, 1);
hasher.update(b, 1);
hasher.update(c, 1);
hasher.final(digest);
std::string result2(reinterpret_cast<char*>(digest), digest_size);
EXPECT_EQ(bin2hex(result2), EXP2);
delete[] digest;
}
TEST(keccak_256_cryptopp, digest_size) {
Keccak_256_cryptopp hasher;
EXPECT_EQ(hasher.digest_size(), static_cast<size_t>(CryptoPP::Keccak_256::DIGESTSIZE));
}
| 34.988889 | 89 | 0.755478 | automaton-network |
960634c731a2413e1e4df7fb0f6868ec71e19018 | 1,715 | cxx | C++ | Testing/selxDataManager.cxx | FBerendsen/SuperElastix-1 | 69d97589e34f6f2109621e917792ce18e32442fe | [
"Apache-2.0"
] | null | null | null | Testing/selxDataManager.cxx | FBerendsen/SuperElastix-1 | 69d97589e34f6f2109621e917792ce18e32442fe | [
"Apache-2.0"
] | null | null | null | Testing/selxDataManager.cxx | FBerendsen/SuperElastix-1 | 69d97589e34f6f2109621e917792ce18e32442fe | [
"Apache-2.0"
] | null | null | null | /*=========================================================================
*
* Copyright Leiden University Medical Center, Erasmus University Medical
* Center and contributors
*
* 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.txt
*
* 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 <itkSimpleDataObjectDecorator.h>
#include "selxDataManager.h"
const std::string
DataManager
::GetInputFile( const std::string filename ) const
{
const std::string path = this->GetInputDirectory() + this->GetFolderSeparator() + filename;
return path;
}
const std::string
DataManager
::GetOutputFile( const std::string filename ) const
{
const std::string path = this->GetOutputDirectory() + this->GetFolderSeparator() + filename;
return path;
}
const std::string
DataManager
::GetBaselineFile( const std::string filename ) const
{
const std::string path = this->GetBaselineDirectory() + this->GetFolderSeparator() + filename;
return path;
}
const std::string
DataManager
::GetConfigurationFile( const std::string filename ) const
{
const std::string path = this->GetConfigurationDirectory() + this->GetFolderSeparator() + filename;
return path;
}
| 30.087719 | 101 | 0.674636 | FBerendsen |
96082fb730247b5c8f489914f0b3486bb74308f9 | 1,489 | cpp | C++ | msgexchange/src/main/cpp/msgexchange/tests/json.cpp | Plex-VDR-HDHomerun/androidtv-example-plexdvrinput | 9c374d451301101eeeb73cd9fa696a4c2bf08f5c | [
"Apache-2.0"
] | 82 | 2015-07-14T22:16:45.000Z | 2022-03-16T00:09:52.000Z | msgexchange/src/main/cpp/msgexchange/tests/json.cpp | Plex-VDR-HDHomerun/androidtv-example-plexdvrinput | 9c374d451301101eeeb73cd9fa696a4c2bf08f5c | [
"Apache-2.0"
] | 63 | 2015-07-08T20:10:22.000Z | 2022-03-19T13:32:24.000Z | msgexchange/src/main/cpp/msgexchange/tests/json.cpp | Plex-VDR-HDHomerun/androidtv-example-plexdvrinput | 9c374d451301101eeeb73cd9fa696a4c2bf08f5c | [
"Apache-2.0"
] | 46 | 2015-07-15T00:59:10.000Z | 2021-12-13T14:59:55.000Z | #include "msgjson.h"
#include "msgpacket.h"
#include <iostream>
int main(int agrc, char* argv[]) {
std::string json =
"{\n"
"\"msgid\": 23,\n"
"\"type\": 2,\n"
"\"packet\":\n"
" [\n"
" { \"name\": \"param1\", \"type\": \"string\", \"value\": \"string1\" },\n"
" { \"name\": \"param2\", \"type\": \"uint32\", \"value\": 3433 },\n"
" { \"name\": \"param3\", \"type\": \"uint8\", \"value\": 255 },\n"
" { \"name\": \"param4\", \"type\": \"string\", \"value\": \"string1\" },\n"
" { \"name\": \"encoderid\", \"type\": \"uint32\", \"value\": 111 },\n"
" { \"name\": \"encoderid\", \"type\": \"uint32\", \"value\": 2 }\n"
" ]\n"
"}";
std::string jsonformat =
"{\n"
"\"packet\":\n"
" [\n"
" { \"name\": \"param1\", \"type\": \"string\", \"value\": \"\" },\n"
" { \"name\": \"param2\", \"type\": \"uint32\", \"value\": 0 },\n"
" { \"name\": \"param3\", \"type\": \"uint8\", \"value\": 0 },\n"
" { \"name\": \"param4\", \"type\": \"string\", \"value\": \"\" },\n"
" { \"name\": \"encoderid\", \"type\": \"uint32\", \"value\": 0 },\n"
" { \"name\": \"encoderid\", \"type\": \"uint32\", \"value\": 0 }\n"
" ]\n"
"}";
std::cout << "JSON (original): " << json << std::endl;
MsgPacket* p = MsgPacketFromJSON(json, 11);
p->print();
std::string result = MsgPacketToJSON(p, jsonformat);
std::cout << "JSON: " << result << std::endl;
delete p;
return 0;
}
| 33.088889 | 82 | 0.425789 | Plex-VDR-HDHomerun |
9609947f949f294eb4177f7f3593162b38fd812d | 2,801 | cpp | C++ | WindowBottom.cpp | jjzhang166/SPlayer-Qt-Framework4 | 1eceb28c31c2b51933cfdeb4e91ee30371dd58d4 | [
"MIT"
] | 12 | 2018-08-14T07:37:23.000Z | 2020-12-29T09:57:12.000Z | WindowBottom.cpp | jjzhang166/SPlayer-Qt-Framework4 | 1eceb28c31c2b51933cfdeb4e91ee30371dd58d4 | [
"MIT"
] | null | null | null | WindowBottom.cpp | jjzhang166/SPlayer-Qt-Framework4 | 1eceb28c31c2b51933cfdeb4e91ee30371dd58d4 | [
"MIT"
] | 9 | 2019-03-27T00:44:53.000Z | 2022-03-19T10:48:38.000Z | #include "WindowBottom.h"
//播放、停止等主界面底部视图的效果呈现
WindowBottom::WindowBottom(QWidget *parent):BaseWidget(parent)
{
QImage image;
m_pRunTimeLen = new QLabel(this);
m_pRunTimeLen->setText("00:00:00");
m_pRunTimeLen->setMouseTracking(true);
m_pSign = new QLabel(this);
m_pSign->setText("/");
m_pTotalTimeLen = new QLabel(this);
m_pTotalTimeLen->setText("00:00:00");
//图片按钮
m_pStop = new SButton(this);
image = QImage(":/Image/Resource/stop.png");
m_pStop->setFixedSize(image.width()/4,image.height());
m_pStop->AppendImage(image);
m_pPre = new SButton(this);
image = QImage(":/Image/Resource/pre.png");
m_pPre->setFixedSize(image.width()/4,image.height());
m_pPre->AppendImage(image);
m_PPaly = new SButton(this);
image = QImage(":/Image/Resource/play.png");
m_PPaly->setFixedSize(image.width()/4,image.height());
m_PPaly->AppendImage(image);
m_pNext = new SButton(this);
image = QImage(":/Image/Resource/next.png");
m_pNext->setFixedSize(image.width()/4,image.height());
m_pNext->AppendImage(image);
m_pSound = new SButton(this);
image = QImage(":/Image/Resource/sound.png");
m_pSound->setFixedSize(image.width()/4,image.height());
m_pSound->AppendImage(image);
m_pProgressBar = new SProgressBar(this);
m_pProgressBar->setFixedSize(60,4);
m_pProgressBar->SetCurrentProgress(50);
m_pFull = new SButton(this);
image = QImage(":/Image/Resource/full.png");
m_pFull->setFixedSize(image.width()/4,image.height());
m_pFull->AppendImage(image);
//水平布局
QHBoxLayout *pHBoxLayout = new QHBoxLayout(this);
pHBoxLayout->setContentsMargins(10,0,10,0);
pHBoxLayout->setSpacing(0);
//依次添加Stretch以及Widget
pHBoxLayout->addStretch(1);
pHBoxLayout->addWidget(m_pStop);
pHBoxLayout->addSpacing(10);
pHBoxLayout->addWidget(m_pPre);
pHBoxLayout->addWidget(m_PPaly);
pHBoxLayout->addWidget(m_pNext);
pHBoxLayout->addSpacing(10);
pHBoxLayout->addWidget(m_pSound);
pHBoxLayout->addStretch(1);
}
WindowBottom::~WindowBottom()
{
}
//自动布局与手动布局结合方式
void WindowBottom::resizeEvent(QResizeEvent *event)
{
int textWidth = QFontMetrics(font()).width("00:00:00");
int textHeight = QFontMetrics(font()).height();
m_pRunTimeLen->setGeometry(10,(height()-textHeight)/2,textWidth,textHeight);
m_pSign->setGeometry(m_pRunTimeLen->geometry().right()+5,m_pRunTimeLen->y(),QFontMetrics(font()).width("/"),textHeight);
m_pTotalTimeLen->setGeometry(m_pSign->geometry().right()+5,m_pRunTimeLen->y(),textWidth,textHeight);
m_pProgressBar->move(m_pSound->geometry().right(),(height()-4)/2);
m_pFull->move(geometry().right()-10-m_pFull->width(),(height()-m_pFull->height())/2);
QWidget::resizeEvent(event);
}
| 32.952941 | 124 | 0.689754 | jjzhang166 |
9609b68b248bbcf6790467bdbacdb5302ab865da | 1,396 | cpp | C++ | Chapter-6-Functions/Review Questions and Exercises/Programming Challenges/23.cpp | jesushilarioh/C-Plus-Plus | bbff921460ac4267af48558f040c7d82ccf42d5e | [
"MIT"
] | 3 | 2019-10-28T01:12:46.000Z | 2021-10-16T09:16:31.000Z | Chapter-6-Functions/Review Questions and Exercises/Programming Challenges/23.cpp | jesushilarioh/C-Plus-Plus | bbff921460ac4267af48558f040c7d82ccf42d5e | [
"MIT"
] | null | null | null | Chapter-6-Functions/Review Questions and Exercises/Programming Challenges/23.cpp | jesushilarioh/C-Plus-Plus | bbff921460ac4267af48558f040c7d82ccf42d5e | [
"MIT"
] | 4 | 2020-04-10T17:22:17.000Z | 2021-11-04T14:34:00.000Z | /************************************************************
*
* 23. Prime Number List
*
* Use the isPrime function that you wrote in Programming
* Challenge 22 in a program that stores a list of all
* the prime numbers from 1 through 100 in a file.
*
* Jesus Hilario Hernandez
* December 27, 2018 --> "Merry Christmas!"
*
*************************************************************/
#include <iostream>
#include <fstream>
using namespace std;
// Function Prototypes
bool isPrime(int);
int main()
{
ofstream outputFile;
outputFile.open("primeNumbers.txt");
if (outputFile)
{
for (int i = 0; i <= 100; i++)
{
if(isPrime(i))
outputFile << i << endl;
}
outputFile.close();
}
else
{
cout << "Error opening the file.\n";
}
return 0;
}
/****************************************************
* Definition for isPrime(): ` *
* isPrime takes a integer as an argument and *
* returns true if the argument is a prime number, *
* or false otherwise. *
****************************************************/
bool isPrime(int number)
{
int isPrime = 0;
for (int i = 1; i <= number; i++)
{
if (number % i == 0)
isPrime++;
}
return isPrime == 2 ? 1 : 0;
} | 22.885246 | 63 | 0.437679 | jesushilarioh |
960d1fd91f48fbeb3609a53dcb4c3fdb9b09bf4d | 476 | cc | C++ | sieve2015/src/tst_sieve_bit_table.cc | mhdeleglise/Gh | 21a0b9bd53ae9de17f8b99040cac95cd6e1897e4 | [
"MIT"
] | null | null | null | sieve2015/src/tst_sieve_bit_table.cc | mhdeleglise/Gh | 21a0b9bd53ae9de17f8b99040cac95cd6e1897e4 | [
"MIT"
] | null | null | null | sieve2015/src/tst_sieve_bit_table.cc | mhdeleglise/Gh | 21a0b9bd53ae9de17f8b99040cac95cd6e1897e4 | [
"MIT"
] | null | null | null | #include<mylib.h>
#include"../Include/sieve_slices.h"
int main(int argc, char* argv[]) {
long32 wsize = (argc==2)? atoi(argv[1]) : 100;
presieved_primes::init_prime_table(1000,3);
cout << "Sieve par tranche avec crible d'Eratosthène automatique\n";
sieve_by_slice<bit_table,long64> sl(2,1,wsize,0,6, AUTO_SIEVE);
for (int n=0; n < 3; n++) {
sl.display();
cout << "Shift_forward\n";
sl.shift_window_forward();
}
cout << "ok" << endl;
return 0;
}
| 25.052632 | 70 | 0.644958 | mhdeleglise |
96113c99cfc4100aa3f391017decfe684b6e18bf | 2,397 | cc | C++ | rest/testing/rest_request_binding_test.cc | kstepanmpmg/mldb | f78791cd34d01796705c0f173a14359ec1b2e021 | [
"Apache-2.0"
] | 665 | 2015-12-09T17:00:14.000Z | 2022-03-25T07:46:46.000Z | rest/testing/rest_request_binding_test.cc | tomzhang/mldb | a09cf2d9ca454d1966b9e49ae69f2fe6bf571494 | [
"Apache-2.0"
] | 797 | 2015-12-09T19:48:19.000Z | 2022-03-07T02:19:47.000Z | rest/testing/rest_request_binding_test.cc | matebestek/mldb | f78791cd34d01796705c0f173a14359ec1b2e021 | [
"Apache-2.0"
] | 103 | 2015-12-25T04:39:29.000Z | 2022-02-03T02:55:22.000Z | /** rest_request_binding_test.cc
Jeremy Barnes, 31 March 2015
Copyright (c) 2015 mldb.ai inc. All rights reserved.
This file is part of MLDB. Copyright 2015 mldb.ai inc. All rights reserved.
*/
#define BOOST_TEST_MAIN
#define BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>
#include "mldb/rest/rest_request_router.h"
#include "mldb/rest/rest_request_binding.h"
#include "mldb/rest/in_process_rest_connection.h"
using namespace std;
using namespace MLDB;
BOOST_AUTO_TEST_CASE( test_header_matching )
{
RestRequestRouter router;
struct TestObject {
std::string call1()
{
return "hello";
}
std::string call2(std::string name)
{
return "hello " + name;
}
};
TestObject testObject;
addRouteSyncJsonReturn(router, "/test", { "PUT" }, "Call test object",
"hello",
&TestObject::call1, &testObject);
addRouteSyncJsonReturn(router, "/test2", { "PUT" }, "Call test object",
"hello",
&TestObject::call2, &testObject,
RestParam<std::string>("name", "name of person to say hello to"));
{
auto conn = InProcessRestConnection::create();
router.handleRequest(*conn, RestRequest("PUT", "/test", {}, ""));
conn->waitForResponse();
BOOST_CHECK_EQUAL(conn->response(), "\"hello\"\n");
}
{
auto conn = InProcessRestConnection::create();
router.handleRequest(*conn, RestRequest("PUT", "/test", { { "param", "true" } }, ""));
conn->waitForResponse();
BOOST_CHECK_EQUAL(conn->responseCode(), 400);
}
{
cerr << "test 3" << endl;
auto conn = InProcessRestConnection::create();
router.handleRequest(*conn, RestRequest("PUT", "/test2", { { "name", "bob" } }, ""));
conn->waitForResponse();
BOOST_CHECK_EQUAL(conn->responseCode(), 200);
BOOST_CHECK_EQUAL(conn->response(), "\"hello bob\"\n");
}
{
cerr << "test 4" << endl;
auto conn = InProcessRestConnection::create();
router.handleRequest(*conn, RestRequest("PUT", "/test2", { { "name2", "bob" } }, ""));
conn->waitForResponse();
cerr << conn->response() << endl;
BOOST_CHECK_EQUAL(conn->responseCode(), 400);
}
}
| 29.592593 | 94 | 0.576971 | kstepanmpmg |
9612a3d737b10d4151ab74e2225092d3c96e75ac | 1,421 | cpp | C++ | lib/FuzzingCommon/DummyFuzzingSolver.cpp | delcypher/jfs | d38b3685e878bf552da52b9410b53dd2adcfdfd1 | [
"MIT"
] | 192 | 2018-01-08T03:28:28.000Z | 2019-06-18T02:52:39.000Z | lib/FuzzingCommon/DummyFuzzingSolver.cpp | mc-imperial/jfs | d38b3685e878bf552da52b9410b53dd2adcfdfd1 | [
"MIT"
] | 24 | 2019-08-28T18:15:09.000Z | 2020-12-07T03:56:45.000Z | lib/FuzzingCommon/DummyFuzzingSolver.cpp | delcypher/jfs | d38b3685e878bf552da52b9410b53dd2adcfdfd1 | [
"MIT"
] | 14 | 2018-01-08T06:58:39.000Z | 2019-04-08T08:40:52.000Z | //===----------------------------------------------------------------------===//
//
// JFS
//
// Copyright 2017-2018 Daniel Liew
//
// This file is distributed under the MIT license.
// See LICENSE.txt for details.
//
//===----------------------------------------------------------------------===//
#include "jfs/FuzzingCommon/DummyFuzzingSolver.h"
using namespace jfs::core;
namespace jfs {
namespace fuzzingCommon {
DummyFuzzingSolver::DummyFuzzingSolver(
std::unique_ptr<SolverOptions> options,
std::unique_ptr<WorkingDirectoryManager> wdm, JFSContext& ctx)
: FuzzingSolver(std::move(options), std::move(wdm), ctx) {}
DummyFuzzingSolver::~DummyFuzzingSolver() {}
llvm::StringRef DummyFuzzingSolver::getName() const {
return "DummyFuzzingSolver";
}
void DummyFuzzingSolver::cancel() {
// Dummy solver, so nothing to cancel
}
class DummyFuzzingSolverResponse : public SolverResponse {
public:
DummyFuzzingSolverResponse() : SolverResponse(SolverResponse::UNKNOWN) {}
Model* getModel() override {
// There is no model
return nullptr;
}
};
std::unique_ptr<jfs::core::SolverResponse>
DummyFuzzingSolver::fuzz(jfs::core::Query& q, bool produceModel,
std::shared_ptr<FuzzingAnalysisInfo> info) {
// Don't try to fuzz. Just give up immediately
return std::unique_ptr<SolverResponse>(new DummyFuzzingSolverResponse());
}
}
}
| 29 | 80 | 0.627727 | delcypher |
961569204d83b05767f48e91acd8cd62dd6563b8 | 1,588 | hpp | C++ | include/mbgl/geometry/geometry.hpp | free1978/mapbox-gl-native | 2a50fccd24e762d0de5a53bac358e5ddfea8d213 | [
"BSD-2-Clause"
] | 2 | 2017-02-28T22:41:54.000Z | 2020-02-13T20:54:55.000Z | include/mbgl/geometry/geometry.hpp | free1978/mapbox-gl-native | 2a50fccd24e762d0de5a53bac358e5ddfea8d213 | [
"BSD-2-Clause"
] | null | null | null | include/mbgl/geometry/geometry.hpp | free1978/mapbox-gl-native | 2a50fccd24e762d0de5a53bac358e5ddfea8d213 | [
"BSD-2-Clause"
] | null | null | null | #ifndef MBGL_GEOMETRY_GEOMETRY
#define MBGL_GEOMETRY_GEOMETRY
#include <mbgl/util/pbf.hpp>
#include <mbgl/util/noncopyable.hpp>
#include <cstdlib>
namespace mbgl {
class Geometry : private util::noncopyable {
public:
inline explicit Geometry(pbf& data);
enum command : uint8_t {
end = 0,
move_to = 1,
line_to = 2,
close = 7
};
inline command next(int32_t &rx, int32_t &ry);
private:
pbf& data;
uint8_t cmd;
uint32_t length;
int32_t x, y;
int32_t ox, oy;
};
Geometry::Geometry(pbf& data)
: data(data),
cmd(1),
length(0),
x(0), y(0),
ox(0), oy(0) {}
Geometry::command Geometry::next(int32_t &rx, int32_t &ry) {
if (data.data < data.end) {
if (length == 0) {
uint32_t cmd_length = static_cast<uint32_t>(data.varint());
cmd = cmd_length & 0x7;
length = cmd_length >> 3;
}
--length;
if (cmd == move_to || cmd == line_to) {
rx = (x += data.svarint());
ry = (y += data.svarint());
if (cmd == move_to) {
ox = x;
oy = y;
return move_to;
} else {
return line_to;
}
} else if (cmd == close) {
rx = ox;
ry = oy;
return close;
} else {
fprintf(stderr, "unknown command: %d\n", cmd);
// TODO: gracefully handle geometry parse failures
return end;
}
} else {
return end;
}
}
}
#endif
| 20.358974 | 71 | 0.493703 | free1978 |
9617e0b6a859f09ae2edac9f830c28ff03cd67c9 | 4,998 | cpp | C++ | lib/cover/cover.cpp | spookey/full_power | a1c603da0ec552d15ee79ff1806e32619424a332 | [
"MIT"
] | null | null | null | lib/cover/cover.cpp | spookey/full_power | a1c603da0ec552d15ee79ff1806e32619424a332 | [
"MIT"
] | null | null | null | lib/cover/cover.cpp | spookey/full_power | a1c603da0ec552d15ee79ff1806e32619424a332 | [
"MIT"
] | null | null | null | #include "cover.hpp"
Cover::Cover(Cable& txt, Shell& exe, Flash& ini)
: txt(txt), exe(exe), ini(ini) {}
void Cover::setup(void) {
if (!WiFi.mode(WIFI_STA)) { this->txt.sos("wifi error", true); }
this->apply();
this->exe.add(this, &Cover::cmd_dialup, "wdial", "wifi dialup");
this->exe.add(this, &Cover::cmd_hangup, "whang", "wifi hangup");
this->exe.add(this, &Cover::cmd_lookup, "wlook", "mDNS lookup");
this->exe.add(this, &Cover::cmd_status, "wstat", "wifi status");
}
bool Cover::check(bool quick) {
if (WiFi.isConnected()) { return true; }
else if(quick) { return false; }
for (uint16_t tick = 2048; tick > 0; tick--) {
switch(WiFi.status()) {
case WL_DISCONNECTED: this->txt.text("~"); break;
case WL_IDLE_STATUS: this->txt.text("-"); break;
case WL_NO_SSID_AVAIL:
this->txt.log("cover", "wifi ssid can't be reached!");
return false;
case WL_CONNECT_FAILED:
this->txt.log("cover", "wifi password incorrect!");
return false;
case WL_CONNECTION_LOST:
this->txt.log("cover", "wifi connection lost!");
return false;
case WL_SCAN_COMPLETED:
this->txt.log("cover", "wifi scan completed.");
break;
case WL_CONNECTED:
this->txt.log("cover", "wifi connected!");
return true;
default: break;
}
delay(16);
}
this->txt.text(" ... giving up!", true);
return false;
}
bool Cover::hangup(void) {
if (!WiFi.isConnected()) { return true; }
this->txt.log("cover", "hangup");
this->txt.llg("connected", "hang up..");
WiFi.disconnect(true); delay(1024);
this->hangups++;
return (!WiFi.isConnected());
}
bool Cover::apply(void) {
String hostname = this->ini.get("hostname", this->txt.join(
COVER_H_NAME, "-", String(ESP.getChipId())
), true);
String wifissid = this->ini.get("wifissid", COVER_W_SSID, true);
String wifipass = this->ini.get("wifipass", COVER_W_PASS, true);
this->hangup();
this->txt.log("cover", "apply");
this->txt.llg("hostname", hostname);
this->txt.llg("ssid", wifissid);
this->txt.llg("pass", this->txt.fill(wifipass.length(), '*'));
WiFi.hostname(hostname);
WiFi.setAutoReconnect(true);
WiFi.begin(wifissid.c_str(), wifipass.c_str());
this->dialups++;
if (!this->check(false)) { return false; }
this->status();
if (MDNS.begin(hostname.c_str(), WiFi.localIP())) {
this->txt.llg("mDNS", "started");
MDNS.addService("http", "tcp", SERVE_HARBOR);
this->txt.llg("service", "registered");
}
return true;
}
void Cover::status(void) {
this->txt.log("cover", "status");
this->txt.llg("dialups", String(this->dialups));
this->txt.llg("hangups", String(this->hangups));
if (!WiFi.isConnected()) {
this->txt.llg("status", "disconnected!"); return;
} else {
this->txt.llg("status", "connected!");
}
this->txt.llg("ssid", WiFi.SSID());
this->txt.llg("bssid", WiFi.BSSIDstr());
this->txt.llg("mac", WiFi.macAddress());
this->txt.llg("channel", this->get_channel());
this->txt.llg("signal", this->get_signal());
this->txt.llg(":", this->get_hostname(), " ::");
this->txt.llg("address", WiFi.localIP().toString());
this->txt.llg("subnet", WiFi.subnetMask().toString());
this->txt.llg("gateway", WiFi.gatewayIP().toString());
this->txt.llg("dns", WiFi.dnsIP().toString());
}
void Cover::lookup(void) {
this->txt.log("cover", "lookup");
if (!WiFi.isConnected()) {
this->txt.llg("status", "disconnected!"); return;
}
const int query = MDNS.queryService("http", "tcp");
if (!query) { this->txt.llg("no results", "sorry"); return; }
this->txt.llg("results", String(query));
for (uint16_t idx = 0; idx < query; idx++) {
this->txt.llg(":", "#", String(idx + 1), " ::");
this->txt.llg("hostname", String(MDNS.hostname(idx)));
this->txt.llg("address", MDNS.IP(idx).toString());
this->txt.llg("port", String(MDNS.port(idx)));
}
}
void Cover::loop(void) {
if (this->repeat <= 1) {
if ((millis() - this->replay) > COVER_REPLAY) {
this->repeat = COVER_REPEAT; return;
}
return;
}
if (this->check(true)) { this->repeat = COVER_REPEAT; return; }
this->replay = millis(); this->repeat--;
this->apply();
}
uint8_t Cover::cmd_dialup(String _) {
this->repeat = 0; return (this->apply() ? 0 : 1);
}
uint8_t Cover::cmd_hangup(String _) {
this->repeat = 0; return (this->hangup() ? 0 : 1);
}
String Cover::get_hostname(void) { return WiFi.hostname(); }
String Cover::get_signal(void) {
return this->txt.join(String(WiFi.RSSI()), " dBm");
}
String Cover::get_channel(void) {
return this->txt.join("#", String(WiFi.channel()));
}
| 35.446809 | 70 | 0.572429 | spookey |
9618fb5b56c5f7b01859f9a2fe962bfff9f6c53a | 1,684 | cpp | C++ | apis/rest/services/pkduck_service/code/Joiner/Verifier/LargeTokenGreedyVerifier.cpp | qcri/data_civilizer_system | 3c732e3e8c65ea9ee4a44569b0d031bc2c17f946 | [
"MIT"
] | 6 | 2019-05-09T04:24:06.000Z | 2021-04-17T16:01:02.000Z | apis/rest/services/pkduck_service/code/Joiner/Verifier/LargeTokenGreedyVerifier.cpp | qcri/data_civilizer_system | 3c732e3e8c65ea9ee4a44569b0d031bc2c17f946 | [
"MIT"
] | 1 | 2020-10-08T11:19:03.000Z | 2020-10-08T11:19:03.000Z | apis/rest/services/pkduck_service/code/Joiner/Verifier/LargeTokenGreedyVerifier.cpp | qcri/data_civilizer_system | 3c732e3e8c65ea9ee4a44569b0d031bc2c17f946 | [
"MIT"
] | 3 | 2019-07-09T17:18:44.000Z | 2021-05-26T13:52:16.000Z | //
// Created by Wenbo Tao on 1/16/17.
//
#include "../PolynomialJoiner.h"
using namespace std;
double PolynomialJoiner::large_token_get_similarity(int x, int y)
{
// cout << endl;
// cout << cells[x] << endl << cells[y] << endl;
// for (auto c : edges)
// cout << c.first.first << " " << c.first.second << " & " << c.second.first << " " << c.second.second << endl;
vector<bool> x_used(tokens[x].size());
vector<bool> y_used(tokens[y].size());
int i_size = 0;
int u_size = 0;
for (auto cp_x : matchable_tokens[x])
for (auto cp_y : matchable_tokens[y])
{
vector<string> lhs, rhs;
for (int i = cp_x.first; i <= cp_x.second; i ++)
lhs.push_back(tokens[x][i]);
for (int i = cp_y.first; i <= cp_y.second; i ++)
rhs.push_back(tokens[y][i]);
if (! (lhs == rhs || rule_hash_table.count(make_pair(lhs, rhs))))
continue;
bool ok = true;
for (int k = cp_x.first; k <= cp_x.second; k ++)
if (x_used[k])
{
ok = false;
break;
}
if (! ok) break;
for (int k = cp_y.first; k <= cp_y.second; k ++)
if (y_used[k])
{
ok = false;
break;
}
if (! ok) continue;
for (int k = cp_x.first; k <= cp_x.second; k ++)
x_used[k] = true;
for (int k = cp_y.first; k <= cp_y.second; k ++)
y_used[k] = true;
// int max_size = max(cp_x.second - cp_x.first, cp_y.second - cp_y.first) + 1;
i_size += 1;
}
u_size = i_size;
for (int i = 0; i < (int) tokens[x].size(); i ++)
if (! x_used[i])
u_size ++;
for (int i = 0; i < (int) tokens[y].size(); i ++)
if (! y_used[i])
u_size ++;
// cout << i_size << " " << u_size << endl;
//return jaccard similarity
return (double) i_size / u_size;
}
| 24.764706 | 112 | 0.558789 | qcri |
961a80fab4c34c5d50cfbb2aabb1c5c8c59f5a4f | 8,222 | cpp | C++ | gui/tool-bar.cpp | lukas-ke/faint-graphics-editor | 33eb9e6a3f2216fb2cf6ef9709a14f3d20b78fbf | [
"Apache-2.0"
] | 10 | 2016-12-28T22:06:31.000Z | 2021-05-24T13:42:30.000Z | gui/tool-bar.cpp | lukas-ke/faint-graphics-editor | 33eb9e6a3f2216fb2cf6ef9709a14f3d20b78fbf | [
"Apache-2.0"
] | 4 | 2015-10-09T23:55:10.000Z | 2020-04-04T08:09:22.000Z | gui/tool-bar.cpp | lukas-ke/faint-graphics-editor | 33eb9e6a3f2216fb2cf6ef9709a14f3d20b78fbf | [
"Apache-2.0"
] | null | null | null | // -*- coding: us-ascii-unix -*-
// Copyright 2012 Lukas Kemmer
//
// 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 <vector>
#include "wx/sizer.h"
#include "app/resource-id.hh"
#include "bitmap/bitmap.hh"
#include "bitmap/color.hh"
#include "bitmap/draw.hh"
#include "geo/int-size.hh"
#include "gui/art.hh"
#include "gui/events.hh" // LayerChangeEvent
#include "gui/image-toggle-ctrl.hh"
#include "gui/setting-events.hh"
#include "gui/status-button.hh"
#include "gui/tool-bar.hh"
#include "gui/tool-drop-down-button.hh"
#include "util-wx/bind-event.hh"
#include "util-wx/convert-wx.hh"
#include "util-wx/fwd-wx.hh"
#include "util-wx/layout-wx.hh"
#include "util/color-bitmap-util.hh" // with_border
#include "util/setting-id.hh"
namespace faint{
const wxSize g_toolButtonSize(25,25);
const IntSetting g_layerSetting;
// Create the shaded "selected" tool graphic
static wxBitmap create_selected_bitmap(const wxBitmap& image){
auto bg(with_border(Bitmap(to_faint(image.GetSize()), Color(113,152,207,209)),
Color(113,153,208,115), LineStyle::SOLID));
blend(at_top_left(to_faint(image)), onto(bg));
return to_wx_bmp(bg);
}
class Toolbar::ToolbarImpl{
public:
ToolbarImpl(wxWindow* parent,
StatusInterface& status,
Art& art)
: m_activeButton(nullptr),
m_groupButton(nullptr),
m_panel(create_panel(parent))
{
using namespace layout;
auto hline = [this](int down){
return SizerItem(create_hline(m_panel),
Proportion(0), wxEXPAND|wxDOWN, down);
};
m_layerChoice = create_image_toggle(m_panel, g_layerSetting,
IntSize(30, 32),
status,
Tooltip("Raster or Object layer"),
{ToggleImage(art.Get(Icon::LAYER_RASTER), to_int(Layer::RASTER),
"Select the Raster Layer"),
ToggleImage(art.Get(Icon::LAYER_OBJECT), to_int(Layer::OBJECT),
"Select the Object Layer")},
Axis::HORIZONTAL,
IntSize(3, 3));
set_sizer(m_panel, create_column(OuterSpacing(0), ItemSpacing(0), {
{m_layerChoice, Proportion(0), wxEXPAND|wxDOWN, 5},
hline(5),
{CreateToolButtons(art, status),
Proportion(0), wxALIGN_CENTER_HORIZONTAL}}));
bind_fwd(m_panel, wxEVT_TOGGLEBUTTON,
[&](wxCommandEvent& event){
if (event.GetEventObject() != m_groupButton){
SendToolChoiceEvent(to_tool_id(event.GetId()));
}
event.Skip();
});
bind_fwd(m_panel, EVT_FAINT_IntSettingChange,
[&](const SettingEvent<IntSetting>& e){
assert(e.GetSetting() == g_layerSetting);
events::layer_change(m_panel, to_layerstyle(e.GetValue()));
});
}
wxWindow* AsWindow(){
return m_panel;
}
void SendToolChoiceEvent(ToolId id){
// Remove the selected indication from the current tool button
m_activeButton->SetValue(false);
auto it = m_idToButton.find(id);
if (it != end(m_idToButton)){
wxBitmapToggleButton* button = it->second;
if (!button->IsEnabled()){
// Do not select a disabled tool
return;
}
// Add the selected indication to the new tool
m_activeButton = button;
m_activeButton->SetValue(true);
}
else if (m_groupButton->SetSelectedTool(id)){
m_activeButton = m_groupButton;
}
else{
// Tool without button.
}
events::tool_change(m_panel, id);
}
void SendLayerChoiceEvent(Layer layer){
m_layerChoice->SetValue(to_int(layer));
m_layerChoice->SendChangeEvent();
}
private:
void AddTool(const wxBitmap& bmpInactive,
const Tooltip& tooltip,
const Description& description,
ToolId id,
wxGridSizer* sizer,
StatusInterface& status)
{
wxBitmap bmpActive(create_selected_bitmap(bmpInactive));
auto button = make_wx<ToggleStatusButton>(m_panel,
to_int(id),
m_panel->FromDIP(g_toolButtonSize),
status,
bmpInactive,
bmpActive,
tooltip,
description);
m_idToButton[id] = button;
sizer->Add(button);
if (m_activeButton == nullptr){
m_activeButton = button;
}
}
ToolDropDownButton* AddToolGroup(wxGridSizer* sizer,
const std::vector<ToolInfo>& tools)
{
auto* button = tool_drop_down_button(
m_panel,
to_faint(m_panel->FromDIP(g_toolButtonSize)),
tools);
sizer->Add(button);
events::on_tool_change(button,
[&](ToolId toolId){
SendToolChoiceEvent(toolId);
});
return button;
}
wxSizer* CreateToolButtons(Art& art, StatusInterface& status){
auto sizer = make_wx<wxGridSizer>(0, 2, 0, 0);
auto add_tool =
[&](Icon icon,
const Tooltip& tooltip,
const Description& description,
ToolId id)
{
AddTool(art.Get(icon),
tooltip,
description,
id,
sizer,
status);
};
add_tool(Icon::TOOL_SELECTION,
Tooltip("Selection"),
Description("Adjusts the selection."),
ToolId::SELECTION);
add_tool(Icon::TOOL_PEN,
Tooltip("Pen"),
Description("Draws single pixels."),
ToolId::PEN);
add_tool(Icon::TOOL_BRUSH,
Tooltip("Brush"),
Description("Free hand drawing with selected brush shape and size."),
ToolId::BRUSH);
add_tool(Icon::TOOL_PICKER,
Tooltip("Color picker"),
Description("Selects a color in the image."),
ToolId::PICKER);
add_tool(Icon::TOOL_LINE,
Tooltip("Line"),
Description("Draws lines."),
ToolId::LINE);
add_tool(Icon::TOOL_PATH,
Tooltip("Path"),
Description("Draws paths."),
ToolId::PATH);
add_tool(Icon::TOOL_RECTANGLE,
Tooltip("Rectangle"),
Description("Draws rectangles or squares."),
ToolId::RECTANGLE);
add_tool(Icon::TOOL_ELLIPSE,
Tooltip("Ellipse"),
Description("Draws ellipses or circles."),
ToolId::ELLIPSE);
add_tool(Icon::TOOL_POLYGON,
Tooltip("Polygon"),
Description("Draws polygons."),
ToolId::POLYGON);
add_tool(Icon::TOOL_TEXT,
Tooltip("Text"),
Description("Writes text."),
ToolId::TEXT);
m_groupButton = AddToolGroup(sizer, {
{ art.Get(Icon::TOOL_CALIBRATE),
create_selected_bitmap(art.Get(Icon::TOOL_CALIBRATE)),
Tooltip("Calibrate"),
Description("Defines image measurements."),
ToolId::CALIBRATE},
{ art.Get(Icon::TOOL_TAPE_MEASURE),
create_selected_bitmap(art.Get(Icon::TOOL_TAPE_MEASURE)),
Tooltip("Tape measure"),
Description("Image measurements"),
ToolId::TAPE_MEASURE},
{ art.Get(Icon::TOOL_LEVEL),
create_selected_bitmap(art.Get(Icon::TOOL_LEVEL)),
Tooltip("Level"),
Description("Image alignment"),
ToolId::LEVEL},
{ art.Get(Icon::TOOL_HOT_SPOT),
create_selected_bitmap(art.Get(Icon::TOOL_HOT_SPOT)),
Tooltip("Hot spot"),
Description("Sets the image hot spot."),
ToolId::HOT_SPOT}});
add_tool(Icon::TOOL_FLOODFILL,
Tooltip("Fill"),
Description("Fills contiguous areas."),
ToolId::FLOOD_FILL);
return sizer;
}
private:
wxBitmapToggleButton* m_activeButton;
ToolDropDownButton* m_groupButton;
wxWindow* m_panel;
std::map<ToolId, wxBitmapToggleButton*> m_idToButton;
IntSettingCtrl* m_layerChoice;
};
Toolbar::Toolbar(wxWindow* parent, StatusInterface& status, Art& art){
m_impl = make_dumb<ToolbarImpl>(parent, status, art);
}
wxWindow* Toolbar::AsWindow(){
return m_impl->AsWindow();
}
void Toolbar::SendLayerChoiceEvent(Layer layer){
m_impl->SendLayerChoiceEvent(layer);
}
void Toolbar::SendToolChoiceEvent(ToolId toolId){
m_impl->SendToolChoiceEvent(toolId);
}
} // namespace
| 27.406667 | 80 | 0.658721 | lukas-ke |
961ad0caa3d86b36395e7f5d15f6cec868c12577 | 6,404 | cpp | C++ | Chapter07/sim/test/simulation.cpp | PacktPublishing/Hands-On-Embedded-Programming-with-CPP-17 | a9e11ab66bbe1e022c3c620b58e8599305dfaa64 | [
"MIT"
] | 37 | 2019-03-04T14:01:19.000Z | 2022-03-27T22:53:49.000Z | Chapter07/sim/test/simulation.cpp | PacktPublishing/Hands-On-Embedded-Programming-with-CPP-17 | a9e11ab66bbe1e022c3c620b58e8599305dfaa64 | [
"MIT"
] | 1 | 2019-03-11T13:40:13.000Z | 2020-09-21T05:31:23.000Z | Chapter07/sim/test/simulation.cpp | PacktPublishing/Hands-On-Embedded-Programming-with-CPP-17 | a9e11ab66bbe1e022c3c620b58e8599305dfaa64 | [
"MIT"
] | 16 | 2019-03-08T15:27:01.000Z | 2021-12-27T08:45:32.000Z | /*
simulation.cpp - Main file for the BMaC simulation and validation framework.
Revision 0
Features:
-
Notes:
-
2018/09/18, Maya Posch
*/
#include "config.h"
#include "building.h"
#include "nodes.h"
#include <nymph/nymph.h>
#include <thread>
#include <condition_variable>
#include <mutex>
std::condition_variable gCon;
std::mutex gMutex;
bool gPredicate = false;
void signal_handler(int signal) {
gPredicate = true;
gCon.notify_one();
}
// --- LOG FUNCTION ---
void logFunction(int level, string logStr) {
std::cout << level << " - " << logStr << endl;
}
// --- GET MAC ---
// Request MAC address for a new node instance.
// Returns a string type with the MAC.
NymphMessage* getNewMac(int session, NymphMessage* msg, void* data) {
NymphMessage* returnMsg = msg->getReplyMessage();
// Get new MAC and register it with this session ID.
std::string mac = Nodes::getMAC();
Nodes::registerSession(mac, session);
returnMsg->setResultValue(new NymphString(mac));
return returnMsg;
}
// --- WRITE UART ---
// Writes data to the UART.
NymphMessage* writeUart(int session, NymphMessage* msg, void* data) {
NymphMessage* returnMsg = msg->getReplyMessage();
// Get the MAC address, then call the function on the associated Node instance.
std::string mac = ((NymphString*) msg->parameters()[0])->getValue();
std::string bytes = ((NymphString*) msg->parameters()[1])->getValue();
returnMsg->setResultValue(new NymphBoolean(Nodes::writeUart(mac, bytes)));
return returnMsg;
}
// --- WRITE SPI ---
NymphMessage* writeSPI(int session, NymphMessage* msg, void* data) {
NymphMessage* returnMsg = msg->getReplyMessage();
// Get the MAC address, then call the function on the associated Node instance.
std::string mac = ((NymphString*) msg->parameters()[0])->getValue();
std::string bytes = ((NymphString*) msg->parameters()[1])->getValue();
returnMsg->setResultValue(new NymphBoolean(Nodes::writeSPI(mac, bytes)));
return returnMsg;
}
// --- READ SPI ---
NymphMessage* readSPI(int session, NymphMessage* msg, void* data) {
NymphMessage* returnMsg = msg->getReplyMessage();
// Get the MAC address, then call the function on the associated Node instance.
std::string mac = ((NymphString*) msg->parameters()[0])->getValue();
returnMsg->setResultValue(new NymphString(Nodes::readSPI(mac)));
return returnMsg;
}
// --- WRITE I2C ---
NymphMessage* writeI2C(int session, NymphMessage* msg, void* data) {
NymphMessage* returnMsg = msg->getReplyMessage();
// Get the MAC address, then call the function on the associated Node instance.
std::string mac = ((NymphString*) msg->parameters()[0])->getValue();
int i2cAddress = ((NymphSint32*) msg->parameters()[1])->getValue();
std::string bytes = ((NymphString*) msg->parameters()[2])->getValue();
returnMsg->setResultValue(new NymphBoolean(Nodes::writeI2C(mac, i2cAddress, bytes)));
return returnMsg;
}
// --- READ I2C ---
NymphMessage* readI2C(int session, NymphMessage* msg, void* data) {
NymphMessage* returnMsg = msg->getReplyMessage();
// Get the MAC address, then call the function on the associated Node instance.
std::string mac = ((NymphString*) msg->parameters()[0])->getValue();
int i2cAddress = ((NymphSint32*) msg->parameters()[1])->getValue();
int length = ((NymphSint32*) msg->parameters()[2])->getValue();
returnMsg->setResultValue(new NymphString(Nodes::readI2C(mac, i2cAddress, length)));
return returnMsg;
}
int main() {
// For this simulation, we need to set up a simulated building structure, with rooms containing
// everything from sensors to AC units to plants to coffee machines to people, to get realistic
// input for the nodes and thus the back-ends.
// We assume at this point that the back-end servers have been started already and are present
// on the local network.
// First, read in the building configuration file.
Config config;
config.load("config.cfg");
// Configure and start the NymphRPC server instance.
// We need to provide methods for the following actions:
// * Get the network MAC.
// * SPI access.
// * I2C access.
// * UART access.
vector<NymphTypes> parameters;
NymphMethod getNewMacFunction("getNewMac", parameters, NYMPH_STRING);
getNewMacFunction.setCallback(getNewMac);
NymphRemoteClient::registerMethod("getNewMac", getNewMacFunction);
parameters.push_back(NYMPH_STRING);
NymphMethod serialRxCallback("serialRxCallback", parameters, NYMPH_NULL);
serialRxCallback.enableCallback();
NymphRemoteClient::registerCallback("serialRxCallback", serialRxCallback);
// string readI2C(string MAC, int i2cAddress, int length)
parameters.push_back(NYMPH_SINT32);
parameters.push_back(NYMPH_SINT32);
NymphMethod readI2CFunction("readI2C", parameters, NYMPH_STRING);
readI2CFunction.setCallback(readI2C);
NymphRemoteClient::registerMethod("readI2C", readI2CFunction);
// bool writeUart(string MAC, string bytes)
parameters.clear();
parameters.push_back(NYMPH_STRING);
parameters.push_back(NYMPH_STRING);
NymphMethod writeUartFunction("writeUart", parameters, NYMPH_BOOL);
writeUartFunction.setCallback(writeUart);
NymphRemoteClient::registerMethod("writeUart", writeUartFunction);
// bool writeSPI(string MAC, string bytes)
NymphMethod writeSPIFunction("writeSPI", parameters, NYMPH_BOOL);
writeSPIFunction.setCallback(writeSPI);
NymphRemoteClient::registerMethod("writeSPI", writeSPIFunction);
// bool writeI2C(string MAC, int i2cAddress, string bytes)
parameters.clear();
parameters.push_back(NYMPH_STRING);
parameters.push_back(NYMPH_SINT32);
parameters.push_back(NYMPH_SINT32);
NymphMethod writeI2CFunction("writeI2C", parameters, NYMPH_BOOL);
writeI2CFunction.setCallback(writeI2C);
NymphRemoteClient::registerMethod("writeI2C", writeI2CFunction);
// Install signal handler to terminate the server.
signal(SIGINT, signal_handler);
// Start server on port 4004.
NymphRemoteClient::start(4004);
// Next, we want to construct the building. We do this by creating a Building class instance.
// We pass this the desired building configuration.
Building building(config);
// Loop until the SIGINT signal has been received.
std::unique_lock<std::mutex> lock(gMutex);
while (!gPredicate) {
gCon.wait(lock);
}
// Clean-up
NymphRemoteClient::shutdown();
// Wait before exiting, giving threads time to exit.
Thread::sleep(2000); // 2 seconds.
return 0;
}
| 31.860697 | 97 | 0.733604 | PacktPublishing |
961da7e11f5eb214302d009f5624b574a4979a27 | 414 | hpp | C++ | trader/tools/PreprocessorOptions.hpp | joshuakarbi/trader | 07f3ecf1f0eefd800464e2dfe9ee27b58c15254f | [
"MIT"
] | 11 | 2019-01-10T19:34:14.000Z | 2019-09-24T05:30:03.000Z | trader/tools/PreprocessorOptions.hpp | joshuakarbi/trader | 07f3ecf1f0eefd800464e2dfe9ee27b58c15254f | [
"MIT"
] | 8 | 2019-01-10T21:18:23.000Z | 2019-02-12T20:11:56.000Z | trader/tools/PreprocessorOptions.hpp | joshuakarbi/trader | 07f3ecf1f0eefd800464e2dfe9ee27b58c15254f | [
"MIT"
] | 2 | 2019-01-10T19:37:10.000Z | 2019-07-12T01:49:18.000Z | #include <exception>
// override rapidjson assertions to throw exceptions instead
// this is better
#ifndef RAPIDJSON_ASSERT
#define RAPIDJSON_ASSERT(x) if(!(x)){ \
throw std::runtime_error("ERROR: rapidjson internal assertion failure: " #x); }
#endif
// required for paper trading vs. real url to be used
#define PAPER
// #define REAL
// toggle between regular and debug log files to be used
#define DEBUG
| 24.352941 | 81 | 0.743961 | joshuakarbi |
961f692429d76baf5718cf982737112e10d238e1 | 301 | cpp | C++ | starter_kits/C++/hlt/dropoff.cpp | johnnykwwang/Halite-III | dd16463f1f13d652e7172e82687136f2217bb427 | [
"MIT"
] | 2 | 2018-11-15T14:04:26.000Z | 2018-11-19T01:54:01.000Z | starter_kits/C++/hlt/dropoff.cpp | johnnykwwang/Halite-III | dd16463f1f13d652e7172e82687136f2217bb427 | [
"MIT"
] | 5 | 2021-02-08T20:26:47.000Z | 2022-02-26T04:28:33.000Z | starter_kits/C++/hlt/dropoff.cpp | johnnykwwang/Halite-III | dd16463f1f13d652e7172e82687136f2217bb427 | [
"MIT"
] | 1 | 2018-11-22T14:58:12.000Z | 2018-11-22T14:58:12.000Z | #include "dropoff.hpp"
#include "input.hpp"
std::shared_ptr<hlt::Dropoff> hlt::Dropoff::_generate(hlt::PlayerId player_id) {
hlt::EntityId dropoff_id;
int x;
int y;
hlt::get_sstream() >> dropoff_id >> x >> y;
return std::make_shared<hlt::Dropoff>(player_id, dropoff_id, x, y);
}
| 25.083333 | 80 | 0.664452 | johnnykwwang |
9620151bddeb826f190047268d1a0e3323664403 | 2,121 | cpp | C++ | Projetos/Aula16/main.cpp | chaua/programacao-avancada | 4f580006d6e7e79e1bb6b32a62702eda3daa5874 | [
"MIT"
] | 15 | 2018-04-05T00:15:01.000Z | 2022-03-26T00:08:32.000Z | Projetos/Aula16/main.cpp | chaua/programacao-avancada | 4f580006d6e7e79e1bb6b32a62702eda3daa5874 | [
"MIT"
] | null | null | null | Projetos/Aula16/main.cpp | chaua/programacao-avancada | 4f580006d6e7e79e1bb6b32a62702eda3daa5874 | [
"MIT"
] | 7 | 2018-03-23T00:11:56.000Z | 2020-05-05T02:55:44.000Z | #include <iostream>
#include <fstream>
#include <string>
#include "data.h"
#include "data_dao.h"
using namespace std;
// ARQUIVOS
// - Caminho Absoluto:
// - Realiza a busca do arquivo a partir da raiz do sistema operacional
// - Utiliza o caminho inteiro do arquivo
// - Precisa conhecer a estrutura de diretorios do disco
// - Exemplo:
// C:\projeto\teste\arquivo.txt
// C:/projeto/teste/arquivo.txt
// /home/user/arquivo.txt
//
// - Caminho Relativo
// - Busca o arquivo a partir do diretorio que se executa o programa
// - Exemplo:
// arquivo.txt
// ./arquivo.txt (. representa o diretorio corrente)
// ../arquivo.txt (.. representa o diretorio pai)
// ../../teste.txt
// pasta/arquivo.txt
int main() {
// =========================
// ESCREVER DADOS NO ARQUIVO
// =========================
// 1. Abre o arquivo para escrita
// - param1: nome do arquivo
// - param2: modo de abertura
// ios_base::out - escrita destrutiva (padrao)
// ios_base::ate - escrita concatenada
// ios_base::app - escrita com append
ofstream fout("teste.txt", ios_base::out);
// 2. Escreve dados no arquivo
fout << "Isso eh uma linha de texto!!!" << endl;
fout << "Isso eh um numero: " << 99902 << endl;
// 3. Fecha o arquivo
fout.close(); // EOF
// ====================
// LER DADOS DO ARQUIVO
// ====================
// 1. Abre o arquivo para leitura
// ios_base::in
ifstream fin("teste.txt", ios_base::in);
// 2. Le os dados do arquivo
string buffer;
// leitura de token por token
// fin >> palavra1 >> palavra2 >> numero >> palavra3;
// leitura do arquivo linha a linha
while (getline(fin, buffer)) {
cout << buffer << endl;
}
// 3. Fecha o arquivo
fin.close();
// Teste da classe DAO
Data data(7, 6, 2021);
DataDAO dao;
dao.insere(data);
Data novaData = dao.consulta();
cout << "nova data: " << novaData << endl;
return 0;
} | 25.554217 | 76 | 0.548326 | chaua |
9624eae0b5701a399486623f869dece64200ee7c | 3,545 | cpp | C++ | implementations/memory_io/janice_io_memory.cpp | Noblis/INVSC-janice | 82373b84b5faa0fb483c059c639e08de4b7c37cc | [
"MIT"
] | 8 | 2017-07-03T10:06:00.000Z | 2021-02-12T02:03:11.000Z | implementations/memory_io/janice_io_memory.cpp | Noblis/INVSC-janice | 82373b84b5faa0fb483c059c639e08de4b7c37cc | [
"MIT"
] | 45 | 2017-06-30T15:57:47.000Z | 2018-08-07T19:55:56.000Z | implementations/memory_io/janice_io_memory.cpp | Noblis/INVSC-janice | 82373b84b5faa0fb483c059c639e08de4b7c37cc | [
"MIT"
] | 8 | 2018-02-06T19:46:22.000Z | 2020-04-09T14:17:33.000Z | #include <janice_io_memory.h>
#include <janice_io_memory_utils.hpp>
namespace
{
struct JaniceMediaIteratorStateType
{
JaniceImage image;
bool at_end;
};
JaniceError is_video(JaniceMediaIterator*, bool* video)
{
*video = false;
return JANICE_SUCCESS;
}
JaniceError get_frame_rate(JaniceMediaIterator*, float*)
{
return JANICE_INVALID_MEDIA;
}
JaniceError get_physical_frame_rate(JaniceMediaIterator*, float*)
{
return JANICE_INVALID_MEDIA;
}
JaniceError next(JaniceMediaIterator* it, JaniceImage* image)
{
JaniceMediaIteratorStateType* state = (JaniceMediaIteratorStateType*) it->_internal;
if (state->at_end) {
return JANICE_MEDIA_AT_END;
}
JaniceError ret = mem_utils::copy_janice_image(state->image, *image);
if (ret == JANICE_SUCCESS) { // Don't mark finished unless the copy succeeded
state->at_end = true;
}
return ret;
}
// seek to the specified frame number
JaniceError seek(JaniceMediaIterator* it, uint32_t frame)
{
if (frame != 0) {
return JANICE_INVALID_MEDIA;
}
return it->reset(it);
}
// get the specified frame. This is a stateless operation so it resets the
// frame position after the get.
JaniceError get(JaniceMediaIterator* it, JaniceImage* image, uint32_t frame)
{
if (frame != 0) {
return JANICE_INVALID_MEDIA;
}
JaniceMediaIteratorStateType* state = (JaniceMediaIteratorStateType*) it->_internal;
return mem_utils::copy_janice_image(state->image, *image);
}
// say what frame we are currently on.
JaniceError tell(JaniceMediaIterator*, uint32_t*)
{
return JANICE_INVALID_MEDIA;
}
// Map a logical frame number (as from tell) to a physical frame number, allowing
// for downsampling, clipping, etc. on videos. Here, we just return the physical frame.
JaniceError physical_frame(JaniceMediaIterator*, uint32_t logical, uint32_t *physical)
{
if (physical == NULL) {
return JANICE_BAD_ARGUMENT;
}
*physical = logical;
return JANICE_SUCCESS;
}
JaniceError free_image(JaniceImage* image)
{
if (image && image->owner) {
free(image->data);
image->data = nullptr;
}
return JANICE_SUCCESS;
}
JaniceError free_iterator(JaniceMediaIterator* it)
{
if (it && it->_internal) {
JaniceMediaIteratorStateType* state = (JaniceMediaIteratorStateType*) it->_internal;
free_image(&state->image);
}
return JANICE_SUCCESS;
}
JaniceError reset(JaniceMediaIterator* it)
{
JaniceMediaIteratorStateType* state = (JaniceMediaIteratorStateType*) it->_internal;
state->at_end = false;
return JANICE_SUCCESS;
}
} // anoymous namespace
// ----------------------------------------------------------------------------
// OpenCV I/O only, create an opencv_io media iterator
JaniceError janice_io_memory_create_media_iterator(const JaniceImage* image, JaniceMediaIterator* it)
{
it->is_video = &is_video;
it->get_frame_rate = &get_frame_rate;
it->get_physical_frame_rate = &get_physical_frame_rate;
it->next = &next;
it->seek = &seek;
it->get = &get;
it->tell = &tell;
it->physical_frame = &physical_frame;
it->free_image = &free_image;
it->free = &free_iterator;
it->reset = &reset;
JaniceMediaIteratorStateType* state = new JaniceMediaIteratorStateType();
JaniceError ret = mem_utils::copy_janice_image(*image, state->image);
if (ret != JANICE_SUCCESS) {
return ret;
}
it->_internal = (void*) (state);
return JANICE_SUCCESS;
}
| 24.280822 | 101 | 0.686037 | Noblis |
9625e830e78799ddfc9788441147b41f31784393 | 383 | cpp | C++ | test/scope.cpp | heavywatal/cxxwtl | c5eedd06201cfb99fd2020a107ad85a24146d293 | [
"MIT"
] | null | null | null | test/scope.cpp | heavywatal/cxxwtl | c5eedd06201cfb99fd2020a107ad85a24146d293 | [
"MIT"
] | 3 | 2017-11-07T10:28:28.000Z | 2018-10-30T13:28:21.000Z | test/scope.cpp | heavywatal/cxxwtl | c5eedd06201cfb99fd2020a107ad85a24146d293 | [
"MIT"
] | 1 | 2018-04-16T05:52:04.000Z | 2018-04-16T05:52:04.000Z | #include <wtl/scope.hpp>
#include <iostream>
void rvalue() {
auto atexit = wtl::scope_exit([]{std::cout << "rvalue exit\n";});
std::cout << "rvalue body\n";
}
void lvalue() {
auto func = []{std::cout << "lvalue exit\n";};
auto atexit = wtl::scope_exit(std::move(func));
std::cout << "lvalue body\n";
}
int main() {
lvalue();
rvalue();
return 0;
}
| 18.238095 | 69 | 0.563969 | heavywatal |
96282217dad5b4fddac78d4b0c004db3aaba69e8 | 33,880 | cpp | C++ | src/mongo/db/s/resharding/resharding_oplog_crud_application_test.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | src/mongo/db/s/resharding/resharding_oplog_crud_application_test.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | src/mongo/db/s/resharding/resharding_oplog_crud_application_test.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright (C) 2021-present MongoDB, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Server Side Public License, version 1,
* as published by MongoDB, Inc.
*
* 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
* Server Side Public License for more details.
*
* You should have received a copy of the Server Side Public License
* along with this program. If not, see
* <http://www.mongodb.com/licensing/server-side-public-license>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the Server Side Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#include "mongo/platform/basic.h"
#include <memory>
#include <vector>
#include "mongo/bson/bsonmisc.h"
#include "mongo/db/catalog/collection_options.h"
#include "mongo/db/catalog_raii.h"
#include "mongo/db/logical_session_cache_noop.h"
#include "mongo/db/op_observer_registry.h"
#include "mongo/db/persistent_task_store.h"
#include "mongo/db/query/internal_plans.h"
#include "mongo/db/repl/apply_ops.h"
#include "mongo/db/repl/repl_client_info.h"
#include "mongo/db/repl/replication_coordinator_mock.h"
#include "mongo/db/repl/storage_interface_impl.h"
#include "mongo/db/s/collection_sharding_runtime.h"
#include "mongo/db/s/op_observer_sharding_impl.h"
#include "mongo/db/s/resharding/resharding_data_copy_util.h"
#include "mongo/db/s/resharding/resharding_metrics.h"
#include "mongo/db/s/resharding/resharding_oplog_application.h"
#include "mongo/db/s/resharding/resharding_util.h"
#include "mongo/db/s/sharding_state.h"
#include "mongo/db/service_context_d_test_fixture.h"
#include "mongo/db/session_catalog_mongod.h"
#include "mongo/s/catalog/type_chunk.h"
#include "mongo/s/chunk_manager.h"
#include "mongo/unittest/unittest.h"
#define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kTest
namespace mongo {
namespace {
class ReshardingOplogCrudApplicationTest : public ServiceContextMongoDTest {
public:
void setUp() override {
ServiceContextMongoDTest::setUp();
// Initialize sharding components as a shard server.
serverGlobalParams.clusterRole = ClusterRole::ShardServer;
auto serviceContext = getServiceContext();
ShardingState::get(serviceContext)->setInitialized(_myDonorId.toString(), OID::gen());
{
auto opCtx = makeOperationContext();
auto replCoord = std::make_unique<repl::ReplicationCoordinatorMock>(serviceContext);
ASSERT_OK(replCoord->setFollowerMode(repl::MemberState::RS_PRIMARY));
repl::ReplicationCoordinator::set(serviceContext, std::move(replCoord));
repl::createOplog(opCtx.get());
auto storageImpl = std::make_unique<repl::StorageInterfaceImpl>();
repl::StorageInterface::set(serviceContext, std::move(storageImpl));
MongoDSessionCatalog::onStepUp(opCtx.get());
LogicalSessionCache::set(serviceContext, std::make_unique<LogicalSessionCacheNoop>());
// OpObserverShardingImpl is required for timestamping the writes from
// ReshardingOplogApplicationRules.
auto opObserverRegistry =
dynamic_cast<OpObserverRegistry*>(serviceContext->getOpObserver());
invariant(opObserverRegistry);
opObserverRegistry->addObserver(std::make_unique<OpObserverShardingImpl>());
}
{
auto opCtx = makeOperationContext();
for (const auto& nss : {_outputNss, _myStashNss, _otherStashNss}) {
resharding::data_copy::ensureCollectionExists(
opCtx.get(), nss, CollectionOptions{});
}
{
AutoGetCollection autoColl(opCtx.get(), _outputNss, MODE_X);
CollectionShardingRuntime::get(opCtx.get(), _outputNss)
->setFilteringMetadata(
opCtx.get(),
CollectionMetadata(makeChunkManagerForOutputCollection(), _myDonorId));
}
_metrics = std::make_unique<ReshardingMetrics>(getServiceContext());
_metricsNew =
ReshardingMetricsNew::makeInstance(_sourceUUID,
BSON(_newShardKey << 1),
_outputNss,
ShardingDataTransformMetrics::Role::kRecipient,
serviceContext->getFastClockSource()->now(),
serviceContext);
_oplogApplierMetrics =
std::make_unique<ReshardingOplogApplierMetrics>(_metricsNew.get(), boost::none);
_applier = std::make_unique<ReshardingOplogApplicationRules>(
_outputNss,
std::vector<NamespaceString>{_myStashNss, _otherStashNss},
0U,
_myDonorId,
makeChunkManagerForSourceCollection(),
_metrics.get(),
_oplogApplierMetrics.get());
}
}
ReshardingOplogApplicationRules* applier() {
return _applier.get();
}
StringData sk() {
return _currentShardKey;
}
const NamespaceString& outputNss() {
return _outputNss;
}
const NamespaceString& myStashNss() {
return _myStashNss;
}
const NamespaceString& otherStashNss() {
return _otherStashNss;
}
repl::OplogEntry makeInsertOp(BSONObj document) {
repl::MutableOplogEntry op;
op.setOpType(repl::OpTypeEnum::kInsert);
op.setNss(_sourceNss);
op.setObject(std::move(document));
// These are unused by ReshardingOplogApplicationRules but required by IDL parsing.
op.setOpTime({{}, {}});
op.setWallClockTime({});
return {op.toBSON()};
}
repl::OplogEntry makeUpdateOp(BSONObj filter, BSONObj update) {
repl::MutableOplogEntry op;
op.setOpType(repl::OpTypeEnum::kUpdate);
op.setNss(_sourceNss);
op.setObject(std::move(update));
op.setObject2(std::move(filter));
// These are unused by ReshardingOplogApplicationRules but required by IDL parsing.
op.setOpTime({{}, {}});
op.setWallClockTime({});
return {op.toBSON()};
}
repl::OplogEntry makeDeleteOp(BSONObj document) {
repl::MutableOplogEntry op;
op.setOpType(repl::OpTypeEnum::kDelete);
op.setNss(_sourceNss);
op.setObject(std::move(document));
// These are unused by ReshardingOplogApplicationRules but required by IDL parsing.
op.setOpTime({{}, {}});
op.setWallClockTime({});
return {op.toBSON()};
}
void checkCollectionContents(OperationContext* opCtx,
const NamespaceString& nss,
const std::vector<BSONObj>& documents) {
AutoGetCollection coll(opCtx, nss, MODE_IS);
ASSERT_TRUE(bool(coll)) << "Collection '" << nss << "' does not exist";
auto exec = InternalPlanner::indexScan(opCtx,
&*coll,
coll->getIndexCatalog()->findIdIndex(opCtx),
BSONObj(),
BSONObj(),
BoundInclusion::kIncludeStartKeyOnly,
PlanYieldPolicy::YieldPolicy::NO_YIELD,
InternalPlanner::FORWARD,
InternalPlanner::IXSCAN_FETCH);
size_t i = 0;
BSONObj obj;
while (exec->getNext(&obj, nullptr) == PlanExecutor::ADVANCED) {
ASSERT_LT(i, documents.size())
<< "Found extra document in collection: " << nss << ": " << obj;
ASSERT_BSONOBJ_BINARY_EQ(obj, documents[i]);
++i;
}
if (i < documents.size()) {
FAIL("Didn't find document in collection: ") << nss << ": " << documents[i];
}
}
struct SlimApplyOpsInfo {
BSONObj rawCommand;
std::vector<repl::DurableReplOperation> operations;
};
std::vector<SlimApplyOpsInfo> findApplyOpsNewerThan(OperationContext* opCtx, Timestamp ts) {
std::vector<SlimApplyOpsInfo> result;
PersistentTaskStore<repl::OplogEntryBase> store(NamespaceString::kRsOplogNamespace);
store.forEach(opCtx,
BSON("op"
<< "c"
<< "o.applyOps" << BSON("$exists" << true) << "ts" << BSON("$gt" << ts)),
[&](const auto& oplogEntry) {
auto applyOpsCmd = oplogEntry.getObject().getOwned();
auto applyOpsInfo = repl::ApplyOpsCommandInfo::parse(applyOpsCmd);
std::vector<repl::DurableReplOperation> operations;
operations.reserve(applyOpsInfo.getOperations().size());
for (const auto& innerOp : applyOpsInfo.getOperations()) {
operations.emplace_back(repl::DurableReplOperation::parse(
{"findApplyOpsNewerThan"}, innerOp));
}
result.emplace_back(
SlimApplyOpsInfo{std::move(applyOpsCmd), std::move(operations)});
return true;
});
return result;
}
private:
ChunkManager makeChunkManager(const OID& epoch,
const ShardId& shardId,
const NamespaceString& nss,
const UUID& uuid,
const BSONObj& shardKey,
const std::vector<ChunkType>& chunks) {
auto rt = RoutingTableHistory::makeNew(nss,
uuid,
shardKey,
nullptr /* defaultCollator */,
false /* unique */,
epoch,
Timestamp(1, 1),
boost::none /* timeseriesFields */,
boost::none /* reshardingFields */,
boost::none /* chunkSizeBytes */,
true /* allowMigrations */,
chunks);
return ChunkManager(shardId,
DatabaseVersion(UUID::gen(), Timestamp(1, 1)),
makeStandaloneRoutingTableHistory(std::move(rt)),
boost::none /* clusterTime */);
}
ChunkManager makeChunkManagerForSourceCollection() {
// Create three chunks, two that are owned by this donor shard and one owned by some other
// shard. The chunk for {sk: null} is owned by this donor shard to allow test cases to omit
// the shard key field when it isn't relevant.
const OID epoch = OID::gen();
std::vector<ChunkType> chunks = {
ChunkType{
_sourceUUID,
ChunkRange{BSON(_currentShardKey << MINKEY),
BSON(_currentShardKey << -std::numeric_limits<double>::infinity())},
ChunkVersion(100, 0, epoch, Timestamp(1, 1)),
_myDonorId},
ChunkType{_sourceUUID,
ChunkRange{BSON(_currentShardKey << -std::numeric_limits<double>::infinity()),
BSON(_currentShardKey << 0)},
ChunkVersion(100, 1, epoch, Timestamp(1, 1)),
_otherDonorId},
ChunkType{_sourceUUID,
ChunkRange{BSON(_currentShardKey << 0), BSON(_currentShardKey << MAXKEY)},
ChunkVersion(100, 2, epoch, Timestamp(1, 1)),
_myDonorId}};
return makeChunkManager(
epoch, _myDonorId, _sourceNss, _sourceUUID, BSON(_currentShardKey << 1), chunks);
}
ChunkManager makeChunkManagerForOutputCollection() {
const OID epoch = OID::gen();
const UUID outputUuid = UUID::gen();
std::vector<ChunkType> chunks = {
ChunkType{outputUuid,
ChunkRange{BSON(_newShardKey << MINKEY), BSON(_newShardKey << MAXKEY)},
ChunkVersion(100, 0, epoch, Timestamp(1, 1)),
_myDonorId}};
return makeChunkManager(
epoch, _myDonorId, _outputNss, outputUuid, BSON(_newShardKey << 1), chunks);
}
RoutingTableHistoryValueHandle makeStandaloneRoutingTableHistory(RoutingTableHistory rt) {
const auto version = rt.getVersion();
return RoutingTableHistoryValueHandle(
std::make_shared<RoutingTableHistory>(std::move(rt)),
ComparableChunkVersion::makeComparableChunkVersion(version));
}
const StringData _currentShardKey = "sk";
const StringData _newShardKey = "new_sk";
const NamespaceString _sourceNss{"test_crud", "collection_being_resharded"};
const UUID _sourceUUID = UUID::gen();
const ShardId _myDonorId{"myDonorId"};
const ShardId _otherDonorId{"otherDonorId"};
const NamespaceString _outputNss =
constructTemporaryReshardingNss(_sourceNss.db(), _sourceUUID);
const NamespaceString _myStashNss = getLocalConflictStashNamespace(_sourceUUID, _myDonorId);
const NamespaceString _otherStashNss =
getLocalConflictStashNamespace(_sourceUUID, _otherDonorId);
std::unique_ptr<ReshardingOplogApplicationRules> _applier;
std::unique_ptr<ReshardingMetrics> _metrics;
std::unique_ptr<ReshardingMetricsNew> _metricsNew;
std::unique_ptr<ReshardingOplogApplierMetrics> _oplogApplierMetrics;
};
TEST_F(ReshardingOplogCrudApplicationTest, InsertOpInsertsIntoOuputCollection) {
// This case tests applying rule #2 described in
// ReshardingOplogApplicationRules::_applyInsert_inlock.
{
auto opCtx = makeOperationContext();
ASSERT_OK(applier()->applyOperation(opCtx.get(), makeInsertOp(BSON("_id" << 1))));
ASSERT_OK(applier()->applyOperation(opCtx.get(), makeInsertOp(BSON("_id" << 2))));
}
{
auto opCtx = makeOperationContext();
checkCollectionContents(opCtx.get(), outputNss(), {BSON("_id" << 1), BSON("_id" << 2)});
checkCollectionContents(opCtx.get(), myStashNss(), {});
checkCollectionContents(opCtx.get(), otherStashNss(), {});
}
}
TEST_F(ReshardingOplogCrudApplicationTest, InsertOpBecomesReplacementUpdateOnOutputCollection) {
// This case tests applying rule #3 described in
// ReshardingOplogApplicationRules::_applyInsert_inlock.
//
// Make sure a document with {_id: 0} exists in the output collection before applying an insert
// with the same _id. This donor shard owns these documents under the original shard key (it
// owns the range {sk: 0} -> {sk: maxKey}).
{
auto opCtx = makeOperationContext();
ASSERT_OK(
applier()->applyOperation(opCtx.get(), makeInsertOp(BSON("_id" << 0 << sk() << 1))));
checkCollectionContents(opCtx.get(), outputNss(), {BSON("_id" << 0 << sk() << 1)});
}
{
auto opCtx = makeOperationContext();
ASSERT_OK(
applier()->applyOperation(opCtx.get(), makeInsertOp(BSON("_id" << 0 << sk() << 2))));
}
// We should have replaced the existing document in the output collection.
{
auto opCtx = makeOperationContext();
checkCollectionContents(opCtx.get(), outputNss(), {BSON("_id" << 0 << sk() << 2)});
checkCollectionContents(opCtx.get(), myStashNss(), {});
checkCollectionContents(opCtx.get(), otherStashNss(), {});
}
}
TEST_F(ReshardingOplogCrudApplicationTest, InsertOpWritesToStashCollectionAfterConflict) {
// This case tests applying rules #1 and #4 described in
// ReshardingOplogApplicationRules::_applyInsert_inlock.
//
// Make sure a document with {_id: 0} exists in the output collection before applying inserts
// with the same _id. This donor shard does not own the document {_id: 0, sk: -1} under the
// original shard key, so we should apply rule #4 and insert the document into the stash
// collection.
{
auto opCtx = makeOperationContext();
ASSERT_OK(
applier()->applyOperation(opCtx.get(), makeInsertOp(BSON("_id" << 0 << sk() << -1))));
checkCollectionContents(opCtx.get(), outputNss(), {BSON("_id" << 0 << sk() << -1)});
}
{
auto opCtx = makeOperationContext();
ASSERT_OK(
applier()->applyOperation(opCtx.get(), makeInsertOp(BSON("_id" << 0 << sk() << 2))));
}
// The output collection should still hold the document {_id: 0, sk: -1}, and the document with
// {_id: 0, sk: 2} should have been inserted into the stash collection.
{
auto opCtx = makeOperationContext();
checkCollectionContents(opCtx.get(), outputNss(), {BSON("_id" << 0 << sk() << -1)});
checkCollectionContents(opCtx.get(), myStashNss(), {BSON("_id" << 0 << sk() << 2)});
checkCollectionContents(opCtx.get(), otherStashNss(), {});
}
{
auto opCtx = makeOperationContext();
ASSERT_OK(
applier()->applyOperation(opCtx.get(), makeInsertOp(BSON("_id" << 0 << sk() << 3))));
}
// The output collection should still hold the document {_id: 0, sk: 1}. We should have applied
// rule #1 and turned the last insert op into a replacement update on the stash collection, so
// the document {_id: 0, sk: 3} should now exist in the stash collection.
{
auto opCtx = makeOperationContext();
checkCollectionContents(opCtx.get(), outputNss(), {BSON("_id" << 0 << sk() << -1)});
checkCollectionContents(opCtx.get(), myStashNss(), {BSON("_id" << 0 << sk() << 3)});
checkCollectionContents(opCtx.get(), otherStashNss(), {});
}
}
TEST_F(ReshardingOplogCrudApplicationTest, UpdateOpModifiesStashCollectionAfterInsertConflict) {
// This case tests applying rule #1 described in
// ReshardingOplogApplicationRules::_applyUpdate_inlock.
//
// Insert a document {_id: 0} in the output collection before applying the insert of document
// with {_id: 0}. This will force the document {_id: 0, sk: 2} to be inserted to the stash
// collection for this donor shard.
{
auto opCtx = makeOperationContext();
ASSERT_OK(
applier()->applyOperation(opCtx.get(), makeInsertOp(BSON("_id" << 0 << sk() << -1))));
ASSERT_OK(
applier()->applyOperation(opCtx.get(), makeInsertOp(BSON("_id" << 0 << sk() << 2))));
checkCollectionContents(opCtx.get(), outputNss(), {BSON("_id" << 0 << sk() << -1)});
checkCollectionContents(opCtx.get(), myStashNss(), {BSON("_id" << 0 << sk() << 2)});
}
{
auto opCtx = makeOperationContext();
ASSERT_OK(applier()->applyOperation(
opCtx.get(), makeUpdateOp(BSON("_id" << 0), BSON("$set" << BSON("x" << 1)))));
}
// We should have applied rule #1 and updated the document with {_id: 0} in the stash collection
// for this donor to now have the new field 'x'. And the output collection should remain
// unchanged.
{
auto opCtx = makeOperationContext();
checkCollectionContents(opCtx.get(), outputNss(), {BSON("_id" << 0 << sk() << -1)});
checkCollectionContents(
opCtx.get(), myStashNss(), {BSON("_id" << 0 << sk() << 2 << "x" << 1)});
checkCollectionContents(opCtx.get(), otherStashNss(), {});
}
}
TEST_F(ReshardingOplogCrudApplicationTest, UpdateOpIsNoopWhenDifferentOwningDonorOrNotMatching) {
// This case tests applying rules #2 and #3 described in
// ReshardingOplogApplicationRules::_applyUpdate_inlock.
//
// Make sure a document with {_id: 0} exists in the output collection that does not belong to
// this donor shard before applying the updates.
{
auto opCtx = makeOperationContext();
ASSERT_OK(
applier()->applyOperation(opCtx.get(), makeInsertOp(BSON("_id" << 0 << sk() << -1))));
checkCollectionContents(opCtx.get(), outputNss(), {BSON("_id" << 0 << sk() << -1)});
}
{
auto opCtx = makeOperationContext();
ASSERT_OK(applier()->applyOperation(
opCtx.get(), makeUpdateOp(BSON("_id" << 0), BSON("$set" << BSON("x" << 1)))));
}
// The document {_id: 0, sk: -1} that exists in the output collection does not belong to this
// donor shard, so we should have applied rule #3 and done nothing and the document should still
// be in the output collection.
{
auto opCtx = makeOperationContext();
checkCollectionContents(opCtx.get(), outputNss(), {BSON("_id" << 0 << sk() << -1)});
checkCollectionContents(opCtx.get(), myStashNss(), {});
checkCollectionContents(opCtx.get(), otherStashNss(), {});
}
{
auto opCtx = makeOperationContext();
ASSERT_OK(applier()->applyOperation(
opCtx.get(), makeUpdateOp(BSON("_id" << 2), BSON("$set" << BSON("x" << 1)))));
}
// There does not exist a document with {_id: 2} in the output collection, so we should have
// applied rule #2 and done nothing.
{
auto opCtx = makeOperationContext();
checkCollectionContents(opCtx.get(), outputNss(), {BSON("_id" << 0 << sk() << -1)});
checkCollectionContents(opCtx.get(), myStashNss(), {});
checkCollectionContents(opCtx.get(), otherStashNss(), {});
}
}
TEST_F(ReshardingOplogCrudApplicationTest, UpdateOpModifiesOutputCollection) {
// This case tests applying rule #4 described in
// ReshardingOplogApplicationRules::_applyUpdate_inlock.
{
auto opCtx = makeOperationContext();
ASSERT_OK(
applier()->applyOperation(opCtx.get(), makeInsertOp(BSON("_id" << 1 << sk() << 1))));
ASSERT_OK(
applier()->applyOperation(opCtx.get(), makeInsertOp(BSON("_id" << 2 << sk() << 2))));
checkCollectionContents(opCtx.get(),
outputNss(),
{BSON("_id" << 1 << sk() << 1), BSON("_id" << 2 << sk() << 2)});
}
{
auto opCtx = makeOperationContext();
ASSERT_OK(applier()->applyOperation(
opCtx.get(), makeUpdateOp(BSON("_id" << 1), BSON("$set" << BSON("x" << 1)))));
ASSERT_OK(applier()->applyOperation(
opCtx.get(), makeUpdateOp(BSON("_id" << 2), BSON("$set" << BSON("x" << 2)))));
}
// We should have updated both documents in the output collection to include the new field "x".
{
auto opCtx = makeOperationContext();
checkCollectionContents(
opCtx.get(),
outputNss(),
{BSON("_id" << 1 << sk() << 1 << "x" << 1), BSON("_id" << 2 << sk() << 2 << "x" << 2)});
checkCollectionContents(opCtx.get(), myStashNss(), {});
checkCollectionContents(opCtx.get(), otherStashNss(), {});
}
}
TEST_F(ReshardingOplogCrudApplicationTest, DeleteOpRemovesFromStashCollectionAfterInsertConflict) {
// This case tests applying rule #1 described in
// ReshardingOplogApplicationRules::_applyDelete_inlock.
//
// Insert a document {_id: 0} in the output collection before applying the insert of document
// with {_id: 0}. This will force the document {_id: 0, sk: 1} to be inserted to the stash
// collection for this donor shard.
{
auto opCtx = makeOperationContext();
ASSERT_OK(
applier()->applyOperation(opCtx.get(), makeInsertOp(BSON("_id" << 0 << sk() << -1))));
ASSERT_OK(
applier()->applyOperation(opCtx.get(), makeInsertOp(BSON("_id" << 0 << sk() << 2))));
checkCollectionContents(opCtx.get(), outputNss(), {BSON("_id" << 0 << sk() << -1)});
checkCollectionContents(opCtx.get(), myStashNss(), {BSON("_id" << 0 << sk() << 2)});
}
{
auto opCtx = makeOperationContext();
ASSERT_OK(applier()->applyOperation(opCtx.get(), makeDeleteOp(BSON("_id" << 0))));
}
// We should have applied rule #1 and deleted the document with {_id: 0} from the stash
// collection for this donor. And the output collection should remain unchanged.
{
auto opCtx = makeOperationContext();
checkCollectionContents(opCtx.get(), outputNss(), {BSON("_id" << 0 << sk() << -1)});
checkCollectionContents(opCtx.get(), myStashNss(), {});
checkCollectionContents(opCtx.get(), otherStashNss(), {});
}
}
TEST_F(ReshardingOplogCrudApplicationTest, DeleteOpIsNoopWhenDifferentOwningDonorOrNotMatching) {
// This case tests applying rules #2 and #3 described in
// ReshardingOplogApplicationRules::_applyDelete_inlock.
//
// Make sure a document with {_id: 0} exists in the output collection that does not belong to
// this donor shard before applying the deletes.
{
auto opCtx = makeOperationContext();
ASSERT_OK(
applier()->applyOperation(opCtx.get(), makeInsertOp(BSON("_id" << 0 << sk() << -1))));
checkCollectionContents(opCtx.get(), outputNss(), {BSON("_id" << 0 << sk() << -1)});
}
{
auto opCtx = makeOperationContext();
ASSERT_OK(applier()->applyOperation(opCtx.get(), makeDeleteOp(BSON("_id" << 0))));
}
// The document {_id: 0, sk: -1} that exists in the output collection does not belong to this
// donor shard, so we should have applied rule #3 and done nothing and the document should still
// be in the output collection.
{
auto opCtx = makeOperationContext();
checkCollectionContents(opCtx.get(), outputNss(), {BSON("_id" << 0 << sk() << -1)});
checkCollectionContents(opCtx.get(), myStashNss(), {});
checkCollectionContents(opCtx.get(), otherStashNss(), {});
}
{
auto opCtx = makeOperationContext();
ASSERT_OK(applier()->applyOperation(opCtx.get(), makeDeleteOp(BSON("_id" << 2))));
}
// There does not exist a document with {_id: 2} in the output collection, so we should have
// applied rule #2 and done nothing.
{
auto opCtx = makeOperationContext();
checkCollectionContents(opCtx.get(), outputNss(), {BSON("_id" << 0 << sk() << -1)});
checkCollectionContents(opCtx.get(), myStashNss(), {});
checkCollectionContents(opCtx.get(), otherStashNss(), {});
}
}
TEST_F(ReshardingOplogCrudApplicationTest, DeleteOpRemovesFromOutputCollection) {
// This case tests applying rule #4 described in
// ReshardingOplogApplicationRules::_applyDelete_inlock.
{
auto opCtx = makeOperationContext();
ASSERT_OK(
applier()->applyOperation(opCtx.get(), makeInsertOp(BSON("_id" << 1 << sk() << 1))));
ASSERT_OK(
applier()->applyOperation(opCtx.get(), makeInsertOp(BSON("_id" << 2 << sk() << 2))));
checkCollectionContents(opCtx.get(),
outputNss(),
{BSON("_id" << 1 << sk() << 1), BSON("_id" << 2 << sk() << 2)});
}
const auto beforeDeleteOpTime = repl::ReplClientInfo::forClient(*getClient()).getLastOp();
{
auto opCtx = makeOperationContext();
ASSERT_OK(applier()->applyOperation(opCtx.get(), makeDeleteOp(BSON("_id" << 1))));
ASSERT_OK(applier()->applyOperation(opCtx.get(), makeDeleteOp(BSON("_id" << 2))));
}
// None of the stash collections have documents with _id == [op _id], so we should not have
// found any documents to insert into the output collection with either {_id: 1} or {_id: 2}.
{
auto opCtx = makeOperationContext();
checkCollectionContents(opCtx.get(), outputNss(), {});
checkCollectionContents(opCtx.get(), myStashNss(), {});
checkCollectionContents(opCtx.get(), otherStashNss(), {});
}
// Assert that the delete on the output collection was run in a transaction by looking in the
// oplog for an applyOps entry with a "d" op on the output collection.
{
auto opCtx = makeOperationContext();
auto applyOpsInfo = findApplyOpsNewerThan(opCtx.get(), beforeDeleteOpTime.getTimestamp());
ASSERT_EQ(applyOpsInfo.size(), 2U);
for (size_t i = 0; i < applyOpsInfo.size(); ++i) {
ASSERT_EQ(applyOpsInfo[i].operations.size(), 1U);
ASSERT_EQ(OpType_serializer(applyOpsInfo[i].operations[0].getOpType()),
OpType_serializer(repl::OpTypeEnum::kDelete));
ASSERT_EQ(applyOpsInfo[i].operations[0].getNss(), outputNss());
ASSERT_BSONOBJ_BINARY_EQ(applyOpsInfo[i].operations[0].getObject()["_id"].wrap(),
BSON("_id" << int32_t(i + 1)));
}
}
}
TEST_F(ReshardingOplogCrudApplicationTest, DeleteOpAtomicallyMovesFromOtherStashCollection) {
// This case tests applying rule #4 described in
// ReshardingOplogApplicationRules::_applyDelete_inlock.
//
// Make sure a document with {_id: 0} exists in the stash collection for the other donor shard.
// The stash collection for this donor shard is empty.
{
auto opCtx = makeOperationContext();
ASSERT_OK(
applier()->applyOperation(opCtx.get(), makeInsertOp(BSON("_id" << 0 << sk() << 2))));
{
AutoGetCollection otherStashColl(opCtx.get(), otherStashNss(), MODE_IX);
WriteUnitOfWork wuow(opCtx.get());
ASSERT_OK(
otherStashColl->insertDocument(opCtx.get(),
InsertStatement{BSON("_id" << 0 << sk() << -3)},
nullptr /* opDebug */));
wuow.commit();
}
checkCollectionContents(opCtx.get(), outputNss(), {BSON("_id" << 0 << sk() << 2)});
checkCollectionContents(opCtx.get(), otherStashNss(), {BSON("_id" << 0 << sk() << -3)});
}
const auto beforeDeleteOpTime = repl::ReplClientInfo::forClient(*getClient()).getLastOp();
{
auto opCtx = makeOperationContext();
ASSERT_OK(applier()->applyOperation(opCtx.get(), makeDeleteOp(BSON("_id" << 0))));
}
// We should have applied rule #4 and deleted the document that was in the output collection
// {_id: 0, sk: 2}, deleted the document with the same _id {_id: 0, sk: -3} in the other donor
// shard's stash collection and inserted this document into the output collection.
{
auto opCtx = makeOperationContext();
checkCollectionContents(opCtx.get(), outputNss(), {BSON("_id" << 0 << sk() << -3)});
checkCollectionContents(opCtx.get(), myStashNss(), {});
checkCollectionContents(opCtx.get(), otherStashNss(), {});
}
// Assert that the delete on the output collection was run in a transaction by looking in the
// oplog for an applyOps entry with the following ops:
// (1) op="d" on the output collection,
// (2) op="d" on the other stash namespace, and
// (3) op="i" on the output collection.
{
auto opCtx = makeOperationContext();
auto applyOpsInfo = findApplyOpsNewerThan(opCtx.get(), beforeDeleteOpTime.getTimestamp());
ASSERT_EQ(applyOpsInfo.size(), 1U);
ASSERT_EQ(applyOpsInfo[0].operations.size(), 3U);
ASSERT_EQ(OpType_serializer(applyOpsInfo[0].operations[0].getOpType()),
OpType_serializer(repl::OpTypeEnum::kDelete));
ASSERT_EQ(applyOpsInfo[0].operations[0].getNss(), outputNss());
ASSERT_BSONOBJ_BINARY_EQ(applyOpsInfo[0].operations[0].getObject()["_id"].wrap(),
BSON("_id" << 0));
ASSERT_EQ(OpType_serializer(applyOpsInfo[0].operations[1].getOpType()),
OpType_serializer(repl::OpTypeEnum::kDelete));
ASSERT_EQ(applyOpsInfo[0].operations[1].getNss(), otherStashNss());
ASSERT_BSONOBJ_BINARY_EQ(applyOpsInfo[0].operations[1].getObject()["_id"].wrap(),
BSON("_id" << 0));
ASSERT_EQ(OpType_serializer(applyOpsInfo[0].operations[2].getOpType()),
OpType_serializer(repl::OpTypeEnum::kInsert));
ASSERT_EQ(applyOpsInfo[0].operations[2].getNss(), outputNss());
ASSERT_BSONOBJ_BINARY_EQ(applyOpsInfo[0].operations[2].getObject(),
BSON("_id" << 0 << sk() << -3));
}
}
} // namespace
} // namespace mongo
| 44.34555 | 100 | 0.600266 | benety |
962838e95ebe6d5e3228d1f25cf29ebd9f2dfc13 | 240 | hpp | C++ | src/modules/CustomPrinter.hpp | NobodyXu/swaystatus | 18d131631ac25a92a78630e033e89d751ebe3306 | [
"MIT"
] | 18 | 2021-02-16T09:06:42.000Z | 2021-12-09T19:08:02.000Z | src/modules/CustomPrinter.hpp | NobodyXu/swaystatus | 18d131631ac25a92a78630e033e89d751ebe3306 | [
"MIT"
] | 18 | 2021-02-23T06:46:22.000Z | 2021-07-26T06:10:13.000Z | src/modules/CustomPrinter.hpp | NobodyXu/swaystatus | 18d131631ac25a92a78630e033e89d751ebe3306 | [
"MIT"
] | 1 | 2021-07-27T03:14:48.000Z | 2021-07-27T03:14:48.000Z | #ifndef __swaystatus_CustomPrinter_HPP__
# define __swaystatus_CustomPrinter_HPP__
# include "Base.hpp"
namespace swaystatus::modules {
std::unique_ptr<Base> makeCustomPrinter(void *config);
} /* namespace swaystatus::modules */
#endif
| 21.818182 | 54 | 0.795833 | NobodyXu |
9628f2598883bdefd15c3295e6e4514d01cff0af | 8,569 | hpp | C++ | include/MCTS/MCTS.hpp | gress2/symreg | 345071111bf2f030ff42d7f1325151abf78eca12 | [
"MIT"
] | null | null | null | include/MCTS/MCTS.hpp | gress2/symreg | 345071111bf2f030ff42d7f1325151abf78eca12 | [
"MIT"
] | null | null | null | include/MCTS/MCTS.hpp | gress2/symreg | 345071111bf2f030ff42d7f1325151abf78eca12 | [
"MIT"
] | null | null | null | #pragma once
#include <algorithm>
#include <fstream>
#include <iostream>
#include <map>
#include <memory>
#include <queue>
#include <random>
#include <unordered_map>
#include <vector>
#include "brick.hpp"
#include "dataset.hpp"
#include "loss.hpp"
#include "training_example.hpp"
#include "util.hpp"
#include "MCTS/scorer.hpp"
#include "MCTS/search_node.hpp"
#include "MCTS/simulator/simulator.hpp"
#define LOG_LEVEL 1
namespace symreg
{
namespace MCTS
{
using AST = brick::AST::AST;
/**
* @brief returns a pointer to the child of a search node with the highest
* UCB1 value.
*
* UCB1: (v/n) + 2 * sqrt(log(N) / n)
*
* Design decision: this metric and its hyperparameters
*
* @return a pointer to the child of a search node with highest UCB1 value
* if children exist, a nullptr otherwise.
*/
search_node* choose_move(search_node* node, double terminal_thresh) {
std::vector<search_node*> moves;
std::vector<search_node*> weak_terminals;
double max = -std::numeric_limits<double>::infinity();
for (auto& child : node->get_children()) {
if (child.get_ast_node()->is_terminal()) {
if (child.get_q() < terminal_thresh) {
weak_terminals.push_back(&child);
continue;
}
}
auto n = child.get_n();
if (n > max) {
max = n;
moves.clear();
moves.push_back(&child);
} else if (n == max) {
moves.push_back(&child);
}
}
// this just assures that we always end up with a valid AST
// from move making
if (moves.empty()) {
for (auto term : weak_terminals) {
auto n = term->get_n();
if (n > max) {
max = n;
moves.clear();
moves.push_back(term);
} else if (n == max) {
moves.push_back(term);
}
}
}
auto random = util::get_random_int(0, moves.size() - 1, symreg::mt);
return moves[random];
}
/**
* @brief the actual coordinator for monte carlo tree search
*/
template <class Regressor = symreg::DNN>
class MCTS {
private:
// MEMBERS
const int num_simulations_;
dataset& dataset_;
search_node root_;
search_node* curr_;
std::ofstream log_stream_;
std::shared_ptr<brick::AST::AST> result_ast_;
double terminal_thresh_ = .999;
simulator::simulator<Regressor> simulator_;
training_examples examples_;
// HELPERS
void write_game_state(int) const;
bool game_over();
std::shared_ptr<brick::AST::AST> build_current_ast();
std::vector<std::shared_ptr<brick::AST::AST>> top_asts_;
public:
// composable constructor for testability
MCTS(dataset&, simulator::simulator<Regressor>, int);
// .toml configurable
MCTS(dataset&, Regressor*, util::config);
void iterate();
std::string to_gv() const;
dataset& get_dataset();
void reset();
std::shared_ptr<brick::AST::AST> get_result();
std::vector<std::shared_ptr<brick::AST::AST>> get_top_n_asts();
training_examples get_training_examples() const;
std::size_t get_num_explored() const;
};
/**
* @brief an MCTS constructor which allows you to inject some
* arbitrary simulator. likely this is only useful for writing
* tests.
* @param ds a reference to a dataset
* @param simulator a simulator instance
* @param num_simulations the number of times you want the simulator
* to simulate between moves
*/
template <class Regressor>
MCTS<Regressor>::MCTS(
dataset& ds,
simulator::simulator<Regressor> _simulator,
int num_simulations
)
: num_simulations_(num_simulations),
dataset_(ds),
root_(search_node(std::make_unique<brick::AST::posit_node>())),
curr_(&root_),
log_stream_("mcts.log"),
result_ast_(nullptr),
simulator_(_simulator)
{
simulator_.add_actions(curr_);
}
/**
* @brief .toml configurable MCTS constructor
* @param ds a reference to a dataset
* @param regr a pointer to a regressor capable of evaluating a search nodes
* value and policy
* @param cfg a wrapper around a cpptoml table
*/
template <class Regressor>
MCTS<Regressor>::MCTS(dataset& ds, Regressor* regr, util::config cfg)
: num_simulations_(cfg.get<int>("mcts.num_simulations")),
dataset_(ds),
root_(search_node(std::make_unique<brick::AST::posit_node>())),
curr_(&root_),
log_stream_(cfg.get<std::string>("logging.file")),
result_ast_(nullptr),
simulator_(simulator::simulator<Regressor>(cfg, ds, regr))
{
simulator_.add_actions(curr_);
}
/**
* @brief The driver for all of the MCTS iterations
*
* A simple loop which first runs a simulation step
* which explores/expands the tree followed by a step
* which heuristically decides a move to take in the tree.
* If make_move() returns false, a move was not made in the
* game, and the game is over.
*
* @param n number determining how many time we wish to loop
*/
template <class Regressor>
void MCTS<Regressor>::iterate() {
std::size_t i = 0;
while (true) {
if (game_over()) {
break;
}
simulator_.simulate(curr_, num_simulations_);
if (simulator_.got_reward_within_thresh()) {
result_ast_ = simulator_.get_ast_within_thresh();
break;
}
search_node* prev = curr_;
examples_.push_back(
training_example{build_current_ast()->to_string(), curr_->get_pi(), 0}
);
curr_ = choose_move(curr_, terminal_thresh_);
#if LOG_LEVEL > 0
log_stream_ << "Iteration: " << i << std::endl;
write_game_state(i);
#endif
if (!curr_) {
curr_ = prev;
break;
}
i++;
}
if (result_ast_) {
simulator_.push_priq(result_ast_);
} else {
simulator_.push_priq(build_current_ast());
}
// assign rewards to examples
auto final_ast = get_result();
auto final_reward = simulator_.get_reward(final_ast);
for (auto& ex : examples_) {
ex.reward = final_reward;
}
}
/**
* @brief writes the MCTS tree as a gv to file
* @param iteration an integer which determines the name of the gv file
*/
template <class Regressor>
void MCTS<Regressor>::write_game_state(int iteration) const {
std::ofstream out_file(std::to_string(iteration) + ".gv");
out_file << to_gv() << std::endl;
}
/**
* @brief a check to determine whether or not more simulation is possible
* given the current move
*/
template <class Regressor>
bool MCTS<Regressor>::game_over() {
return curr_->is_dead_end();
}
/**
* @brief A recursive method for generating a graph viz representation for
* the entire MCTS tree
*
* @return the graph viz string representation
*/
template <class Regressor>
std::string MCTS<Regressor>::to_gv() const {
std::stringstream ss;
ss << "digraph {" << std::endl;
ss << root_.to_gv();
ss << "}" << std::endl;
return ss.str();
}
/**
* @brief a simple getter for the MCTS class' symbol table
*
* @return a non-const reference to the MCTS class' symbol table
*/
template <class Regressor>
dataset& MCTS<Regressor>::get_dataset() {
return dataset_;
}
/**
* @brief Returns the AST which this MCTS has currently
* decided is optimal
*
* @return a shared pointer to an AST
*/
template <class Regressor>
std::shared_ptr<brick::AST::AST> MCTS<Regressor>::build_current_ast() {
return simulator::build_ast_upward(curr_);
}
/**
* @brief returns the best AST the search was able to find.
* @return if the simulator encountered an AST whose value
* was within the early termination threshold, that AST is returned.
* otherwise, we simply return the AST that was formed from traditional
* move making within the tree.
*/
template <class Regressor>
std::shared_ptr<brick::AST::AST> MCTS<Regressor>::get_result() {
return get_top_n_asts().back();
}
/**
* @brief Resets the state of the MCTS search, allowing the next
* iterate call to operate from a blank slate
*/
template <class Regressor>
void MCTS<Regressor>::reset() {
root_.get_children().clear();
root_.set_q(0);
root_.set_n(0);
curr_ = &root_;
result_ast_ = nullptr;
simulator_.reset();
top_asts_.clear();
}
template <class Regressor>
std::vector<std::shared_ptr<brick::AST::AST>> MCTS<Regressor>::get_top_n_asts() {
if (top_asts_.empty()) {
top_asts_ = simulator_.dump_pri_q();
}
return top_asts_;
}
/**
* @brief a getter for the training_examples needed to
* train the regressor/neural network about MCTS states.
* @return a copy of the training examples vector
*/
template <class Regressor>
training_examples MCTS<Regressor>::get_training_examples() const {
return examples_;
}
template <class Regressor>
std::size_t MCTS<Regressor>::get_num_explored() const {
return simulator_.get_num_explored();
}
}
}
| 26.204893 | 81 | 0.681993 | gress2 |
9629f9d70026d388f8545461a22d80a34ff43cdb | 4,364 | cpp | C++ | scratch/projects/folds/xMiuriOri2.cpp | tingelst/versor | c831231e5011cfd1f62da8948cff7956d2f6670b | [
"BSD-3-Clause"
] | null | null | null | scratch/projects/folds/xMiuriOri2.cpp | tingelst/versor | c831231e5011cfd1f62da8948cff7956d2f6670b | [
"BSD-3-Clause"
] | null | null | null | scratch/projects/folds/xMiuriOri2.cpp | tingelst/versor | c831231e5011cfd1f62da8948cff7956d2f6670b | [
"BSD-3-Clause"
] | null | null | null | /*
* =====================================================================================
*
* Filename: xMiuriOri2.cpp
*
* Description:
*
* Version: 1.0
* Created: 12/02/2013 15:37:40
* Revision: none
* Compiler: gcc
*
* Author: Pablo Colapinto (), wolftype (gmail)
* Organization: Media Arts and Technology Program, UCSB
*
* =====================================================================================
*/
#include "vsr_cga3D.h"
#include "vsr_GLVimpl.h"
#include "vsr_fold.h"
#include "vsr_set.h"
using namespace vsr;
using namespace vsr::cga3D;
void Draw(const Truss& ta){
Truss::Points b = ta.base();
glColor3f(.3,.3,.3);
glBegin(GL_TRIANGLES);
TriNormal( ta.p.tl, ta.p.tm, b.tm );
TriNormal( ta.p.tm, ta.p.tr, b.tm );
TriNormal( ta.p.tr, b.tr, b.tm );
TriNormal( b.tm, b.tl, ta.p.tl );
glEnd();
glColor3f(1,0,0);
glBegin(GL_LINE_STRIP);
gfx::GL::Tri( ta.p.tl, ta.p.tm, b.tm );
gfx::GL::Tri( ta.p.tm, ta.p.tr, b.tm );
gfx::GL::Tri( ta.p.tr, b.tr, b.tm );
gfx::GL::Tri( b.tm, b.tl, ta.p.tl );
glEnd();
}
void Draw(const Truss& ta, const Truss& tb){
glColor3f(.3,.3,.3);
glBegin(GL_TRIANGLES);
TriNormal( ta.p.tl, ta.p.tm, tb.p.tm );
TriNormal( ta.p.tm, ta.p.tr, tb.p.tm );
TriNormal( ta.p.tr, tb.p.tr, tb.p.tm );
TriNormal( tb.p.tm, tb.p.tl, ta.p.tl );
glEnd();
glColor3f(1,0,0);
glBegin(GL_LINE_STRIP);
gfx::GL::Tri( ta.p.tl, ta.p.tm, tb.p.tm );
gfx::GL::Tri( ta.p.tm, ta.p.tr, tb.p.tm );
gfx::GL::Tri( ta.p.tr, tb.p.tr, tb.p.tm );
gfx::GL::Tri( tb.p.tm, tb.p.tl, ta.p.tl );
glEnd();
}
struct MyApp : App {
Pnt mouse;
Lin ray;
float amt;
double dx,dy,decay,num;
bool bDrawRigid;
MyApp(Window * win ) : App(win){
scene.camera.pos( 0,0,10 );
}
void initGui(){
gui(dx,"dx")(dy,"dy")(decay,"decay")(amt)(num,"num",1,100);
gui(bDrawRigid);
dx = .2; dy = 0; amt = .1;
}
void getMouse(){
auto tv = interface.vd().ray;
Vec z (tv[0], tv[1], tv[2] );
auto tm = interface.mouse.projectMid;
ray = Round::point( tm[0], tm[1], tm[2] ) ^ z ^ Inf(1);
mouse = Round::point( ray, Ori(1) );
}
virtual void onDraw(){
getMouse();
gfx::GL::twoSidedLighting();
scene.light = Vec3f(5,1,.3);
//BASE
Field<Pnt> f (2,3,1);
for (int i = 0; i< f.w(); ++i){
f.at(i,1) = f.gridAt(i,1).trs(-dx,dy,0);
}
Truss truss ( f.at(1,2), f.at(1,1), f.at(1,0),
f.at(0,2), f.at(0,1), f.at(0,0), true );
truss.bUseSplit = true;
//MOVEMENT
/* Line l = f.at(1,0) ^ f.at(1,1) ^ Inf(1); l = l.unit(); */
/* Pnt np = f.gridAt( 2, 0).mot( l.dual() * PI * amt ) ; */
Line l = f.at(0,1) ^ f.at(1,1) ^ Inf(1); l = l.unit();
Pnt np = f.gridAt( 1, 2).mot( l.dual() * PI * amt ) ;
//FIRST UPDATE
Draw(truss);
truss.reverse();
truss.update( np, f.at(1,1), f.at(1,0));//, np);
int width = num;
int height = 5;
bool switcher = true;
for (int i = 0; i < width; ++i){
switcher = !switcher;
Draw(truss);
// truss.reverse();
// truss.update();
Draw( ( truss.rigidA.a() ^ truss.rigidA.b() ).dual(), 0,1,0);
f.at(1,1) = f.at(1,1).trs(-decay,0,0);
Truss tt ( f.at(1,2), f.at(1,1), f.at(1,0),
f.at(0,2), f.at(0,1), f.at(0,0), switcher );
tt.update( truss );
truss = tt;
f.at(0,1) = f.at(0,1).trs(-decay,0,0);
if(bDrawRigid){
Draw( truss.rigidA.a(),1,0,0,.1);
Draw( truss.rigidA.b(),1,0,0,.1);
Draw( truss.rigidA.c(),1,0,0,.1);
}
}
/* static Cir cir = CXY(1); */
/* Touch(interface,cir); Draw(cir); */
/* static Dls dls = Ro::dls(1.0, 2,0,0); */
/* Touch(interface,dls); Draw(dls); */
/* //Draw( Ta::at( cir, dls ) ); */
/* Draw( (cir.dual() ^ dls).dual(), 0,1,0); */
}
};
MyApp * app;
int main(){
GLV glv(0,0);
Window * win = new Window(800,800,"Miuri-ori",&glv);
app = new MyApp( win );
app -> initGui();
glv << *app;
Application::run();
return 0;
}
| 20.780952 | 88 | 0.463336 | tingelst |
962aa251123eb7fb2b26abbdccd127e06b9aa338 | 4,707 | hpp | C++ | src/ngraph/runtime/cpu/pass/cpu_fusion.hpp | tzerrell/ngraph | b02b0812745ca1cb5f73d426ae9e0ad729eb0bbd | [
"Apache-2.0"
] | null | null | null | src/ngraph/runtime/cpu/pass/cpu_fusion.hpp | tzerrell/ngraph | b02b0812745ca1cb5f73d426ae9e0ad729eb0bbd | [
"Apache-2.0"
] | null | null | null | src/ngraph/runtime/cpu/pass/cpu_fusion.hpp | tzerrell/ngraph | b02b0812745ca1cb5f73d426ae9e0ad729eb0bbd | [
"Apache-2.0"
] | null | null | null | //*****************************************************************************
// Copyright 2017-2019 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.
//*****************************************************************************
#pragma once
#include "ngraph/pass/graph_rewrite.hpp"
#include "ngraph/runtime/cpu/cpu_backend_visibility.h"
namespace ngraph
{
namespace runtime
{
namespace cpu
{
namespace pass
{
class CPUFusion;
class CPUQuantFusion;
}
}
}
}
class CPU_BACKEND_API ngraph::runtime::cpu::pass::CPUFusion : public ngraph::pass::GraphRewrite
{
public:
typedef ngraph::pass::FusionType FusionType;
typedef ngraph::pass::FusionTypeMask FusionTypeMask;
CPUFusion(FusionTypeMask fusions = FusionType::ALL_FUSIONS)
: GraphRewrite()
{
if (fusions.is_set(FusionType::DIFFERENTIABLE_FUSIONS))
{
construct_conv_bias(); // DEPRECATED - Use CoreFusion
construct_sigmoid_multiply();
}
if (fusions.is_set(FusionType::REGULAR_FUSIONS))
{
construct_matmul();
construct_matmulbias();
construct_fprop_bn();
construct_conv_bias_bprop();
construct_conv_bias_folded_batch_norm();
construct_conv_bias_affine_folding();
construct_groupconv_batchnorm_global_stats_folding();
construct_groupconv_batchnorm_global_stats_folding_relu();
construct_batch_norm_relu();
construct_batch_norm_relu_global_stats();
construct_conv_relu();
construct_conv_bias_relu();
construct_conv_bias_add(); // DEPRECATED - Use CoreFusion
construct_conv_bias_add_relu();
construct_leaky_relu();
construct_bounded_relu();
// construct_conv_add() should always be after construct_conv_bias()
construct_conv_add();
construct_conv_add_relu();
construct_update_slice();
construct_fuse_lstm_recurrent_state();
if (std::getenv("NGRAPH_DECONV_FUSE") != nullptr)
{
// Note: enable when the deconv perf is better than convbackpropdata
construct_deconvolution_affine_folding();
construct_deconvolution_affine_folding_relu();
}
construct_dropout();
}
}
private:
void construct_matmul();
void construct_matmulbias();
void construct_conv_bias();
void construct_conv_bias_bprop();
void construct_fprop_bn();
void construct_sigmoid_multiply();
void construct_batch_norm_relu();
void construct_batch_norm_relu_global_stats();
void construct_conv_relu();
void construct_conv_bias_relu();
void construct_conv_bias_add();
void construct_conv_bias_add_relu();
void construct_conv_add();
void construct_conv_add_relu();
void construct_leaky_relu();
void construct_bounded_relu();
void construct_conv_bias_folded_batch_norm();
void construct_conv_bias_affine_folding();
void construct_groupconv_batchnorm_global_stats_folding();
void construct_groupconv_batchnorm_global_stats_folding_relu();
void construct_update_slice();
void construct_fuse_lstm_recurrent_state();
void construct_deconvolution_affine_folding();
void construct_deconvolution_affine_folding_relu();
void construct_dropout();
};
class CPU_BACKEND_API ngraph::runtime::cpu::pass::CPUQuantFusion : public ngraph::pass::GraphRewrite
{
public:
CPUQuantFusion()
: GraphRewrite()
{
construct_qconv_relu(true);
construct_qconv_relu(false);
construct_qavg_pool();
construct_qmax_pool();
construct_qconcat();
construct_qconvb_add();
construct_dq_q();
construct_quantized_matmul();
}
private:
void construct_qconv_relu(bool with_bias);
void construct_qavg_pool();
void construct_qmax_pool();
void construct_qconcat();
void construct_dq_q();
void construct_qconvb_add();
void construct_quantized_matmul();
};
| 34.357664 | 100 | 0.657106 | tzerrell |
962d70afa2544d720e5a2e0830405f1eb4df0a0c | 1,433 | hpp | C++ | Diploma/core/GameProcess/forpawn.hpp | float-cat/diploma | e33d7ae173745e413d374c5b664e295491ac7b55 | [
"Apache-2.0"
] | null | null | null | Diploma/core/GameProcess/forpawn.hpp | float-cat/diploma | e33d7ae173745e413d374c5b664e295491ac7b55 | [
"Apache-2.0"
] | null | null | null | Diploma/core/GameProcess/forpawn.hpp | float-cat/diploma | e33d7ae173745e413d374c5b664e295491ac7b55 | [
"Apache-2.0"
] | null | null | null | #ifndef FORPAWN_HPP
#define FORPAWN_HPP
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <string.h> /* for memset() (on some compilers) */
#if defined __WIN32__ || defined _WIN32 || defined WIN32
#include <malloc.h>
#endif
#include "amx/amx.h"
#include "amx/amxgc.h"
#include "amx/amxaux.h"
#include "scriptapi.hpp"
class ForPawn : public ScriptApi {
AMX amx;
static char *strbuffer;
static ForPawn *pScript;
//functional
static cell AMX_NATIVE_CALL n_CreateButton(AMX* amx, const cell* params);
static cell AMX_NATIVE_CALL n_DebugFunc(AMX* amx, const cell* params);
public:
ForPawn(/*void*/ ClientProtoToClient *cp, void (*BackDoor)(int, void*), char *script); // Here main prepare
~ForPawn(void); // Destruct processes and objects
/*Test Functional*/
/*Test Functional*/
//callbacks
int OnGameProcessStart(void);
int OnGameProcessFinish(void);
int OnGameStarted(void);
//int OnGameFinished(void);
//int OnPlayerWin(int playerid);
int OnCtrlButtonClicked(int buttonid);
int OnPlayerConnected(int playerid);
//int OnPlayerDisconnected(int playerid);
int OnPlayerRecvMessage(int playerid, const char *msg);
int OnPlayerSendMessage(const char *msg);
int OnPlayerCommand(const char *msg);
int OnPlayerReadyCheck(void);
int OnOtherReadyCheck(int playerid);
int OnPlayerStep(int playerid);
int OnStepFinish(void);
int OnAssociated(void);
};
#endif //FORPAWN_HPP
| 29.244898 | 108 | 0.747383 | float-cat |
962e94b12283063a27ffba950be9649d720e9f72 | 944 | cc | C++ | src/ui/a11y/lib/semantics/tests/mocks/mock_semantic_tree_service_factory.cc | dahlia-os/fuchsia-pine64-pinephone | 57aace6f0b0bd75306426c98ab9eb3ff4524a61d | [
"BSD-3-Clause"
] | 10 | 2020-12-28T17:04:44.000Z | 2022-03-12T03:20:43.000Z | src/ui/a11y/lib/semantics/tests/mocks/mock_semantic_tree_service_factory.cc | dahlia-os/fuchsia-pine64-pinephone | 57aace6f0b0bd75306426c98ab9eb3ff4524a61d | [
"BSD-3-Clause"
] | 1 | 2022-01-14T23:38:40.000Z | 2022-01-14T23:38:40.000Z | src/ui/a11y/lib/semantics/tests/mocks/mock_semantic_tree_service_factory.cc | dahliaOS/fuchsia-pine64-pinephone | 57aace6f0b0bd75306426c98ab9eb3ff4524a61d | [
"BSD-3-Clause"
] | 4 | 2020-12-28T17:04:45.000Z | 2022-03-12T03:20:44.000Z | // Copyright 2020 The Fuchsia 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 "src/ui/a11y/lib/semantics/tests/mocks/mock_semantic_tree_service_factory.h"
namespace accessibility_test {
std::unique_ptr<a11y::SemanticTreeService> MockSemanticTreeServiceFactory::NewService(
zx_koid_t koid, fuchsia::accessibility::semantics::SemanticListenerPtr semantic_listener,
vfs::PseudoDir* debug_dir,
a11y::SemanticTreeService::CloseChannelCallback close_channel_callback) {
semantic_tree_ = std::make_unique<MockSemanticTree>();
semantic_tree_ptr_ = semantic_tree_.get();
auto service = std::make_unique<a11y::SemanticTreeService>(
std::move(semantic_tree_), koid, std::move(semantic_listener), debug_dir,
std::move(close_channel_callback));
service_ = service.get();
return service;
}
} // namespace accessibility_test
| 41.043478 | 93 | 0.779661 | dahlia-os |
96335137b48dde4b2aea5a746e46240bcb2b8698 | 7,495 | cpp | C++ | simulation/Simulation.cpp | walachey/football-worldcup-simulator | 36e6f80e3498b4a4dc7b8bf18d45af6c95a8fbe7 | [
"MIT"
] | 1 | 2018-08-14T08:15:47.000Z | 2018-08-14T08:15:47.000Z | simulation/Simulation.cpp | walachey/football-worldcup-simulator | 36e6f80e3498b4a4dc7b8bf18d45af6c95a8fbe7 | [
"MIT"
] | 2 | 2020-01-22T07:17:46.000Z | 2020-01-22T07:17:54.000Z | simulation/Simulation.cpp | walachey/football-worldcup-simulator | 36e6f80e3498b4a4dc7b8bf18d45af6c95a8fbe7 | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "Simulation.h"
#include <thread>
#include <chrono>
namespace sim
{
Simulation *Simulation::singleton = nullptr;
void Simulation::reset()
{
assert(Simulation::singleton == nullptr);
Simulation::singleton = this;
numberOfThreads = 1;
tournamentID = 0;
randomSeed = (unsigned int)std::chrono::system_clock::now().time_since_epoch().count();
}
Simulation::Simulation(json_spirit::Value &jsonData)
{
reset();
json_spirit::Object jsonObject = jsonData.get_obj();
// It is crucial that the teams are setup before the rules.
// To achieve that, we just delay rule initialization.
json_spirit::Array ruleData;
for (json_spirit::Pair &pair : jsonObject)
{
std::string &key = pair.name_;
if (key == "thread_count") numberOfThreads = pair.value_.get_int();
else if (key == "run_count") numberOfRuns = pair.value_.get_int();
else if (key == "tournament_id") tournamentID = pair.value_.get_int();
else if (key == "tournament_type") tournamentType = pair.value_.get_str();
else if (key == "teams") setupTeams(pair.value_.get_array());
else if (key == "rules") ruleData = pair.value_.get_array();
else if (key == "match_database") setupKnownMatches(pair.value_.get_array());
else
std::cerr << "sim::Simulation: invalid property \"" << key << "\"" << std::endl;
}
// Finally (after the teams are setup) init the rules.
if (!ruleData.empty())
setupRules(ruleData);
}
Simulation::~Simulation()
{
for (auto &tournament : tournaments)
delete tournament;
}
void Simulation::setupTeams(json_spirit::Array &teamData)
{
int teamIndex = 0;
for (json_spirit::Value &val : teamData)
{
teams.push_back(Team(val.get_obj(), teamIndex++));
}
}
void Simulation::setupRules(json_spirit::Array &ruleData)
{
for (json_spirit::Value &val : ruleData)
{
rules.push_back(Rule(val.get_obj()));
}
}
void Simulation::setupKnownMatches(json_spirit::Array &matches)
{
for (json_spirit::Value &val : matches)
{
json_spirit::Object &data = val.get_obj();
int teams[2] = { -1, -1 };
int goals[2] = { -1, -1 };
bool hadOvertime = false;
std::string cluster = "all";
int bofRound = -1;
for (json_spirit::Pair &pair : data)
{
std::string &key = pair.name_;
if (key == "teams")
{
for (int i = 0; i < 2; ++i)
teams[i] = pair.value_.get_array().at(i).get_int();
}
else if (key == "goals")
{
for (int i = 0; i < 2; ++i)
goals[i] = pair.value_.get_array().at(i).get_int();
}
else if (key == "bof_round")
{
bofRound = pair.value_.get_int();
}
}
assert(bofRound != -1);
assert(teams[0] != -1);
assert(goals[0] != -1);
if (!knownMatchResults.count(bofRound))
knownMatchResults[bofRound] = std::vector<KnownMatchResult>();
knownMatchResults[bofRound].push_back(KnownMatchResult(bofRound, cluster, teams, goals, hadOvertime));
}
}
void Simulation::execute()
{
// some safety & sanity checks
if (teams.empty())
{
throw "No teams are active. Aborting the tournament.";
}
if (rules.empty())
{
throw "No rules are active. Aborting the tournament.";
}
// 16 threads for one tournament sound impractical
int realThreadCount = std::min(numberOfThreads, numberOfRuns);
std::vector<std::thread> threads;
threads.resize(realThreadCount);
tournaments.resize(realThreadCount);
int remainingRuns = numberOfRuns;
int runsPerThread = numberOfRuns / realThreadCount;
for (int i = 0; i < realThreadCount; ++i, remainingRuns -= runsPerThread)
{
int runsForTournament = std::min(remainingRuns, runsPerThread);
// make sure that there are no remaining runs that don't get distributed
// example: 20 runs and 8 threads, runs per thread = 2, only 2*8=16 tournaments would be started
if (i == realThreadCount - 1)
runsForTournament = remainingRuns;
tournaments[i] = Tournament::newOfType(tournamentType, this, runsForTournament);
tournaments[i]->doSanityChecks(); // allow the tournament some checking prior to the launch
threads[i] = std::thread(&Tournament::start, tournaments[i]);
}
// wait for the simulation to finish
for (auto &thread : threads)
{
thread.join();
}
// setup rank data
{ // scope
std::unique_ptr<Tournament> tournament(Tournament::newOfType(tournamentType, this, 0));
for (RankData const & rank : tournament->getRankDataAssignment())
ranks.push_back(rank);
}
// and then join the results
for (Tournament* &tournament : tournaments)
{
// first the team data
for (auto &clusterToMerge : tournament->clusterTeamResults)
{
std::map<int, TeamResult> &cluster = clusterTeamResults[clusterToMerge.first];
for (auto &team : teams)
{
if (!cluster.count(team.id))
cluster.emplace(std::make_pair(team.id, TeamResult(clusterToMerge.second[team.id])));
else
cluster[team.id].merge(clusterToMerge.second[team.id]);
}
}
// and then the match cluster statistics
for (auto &clusterToMerge : tournament->clusterMatchResultStatisticsLists)
{
clusterMatchResultStatisticsLists[clusterToMerge.first].merge(clusterToMerge.second);
}
}
}
json_spirit::Object Simulation::getJSONResults()
{
json_spirit::Object root;
root.push_back(json_spirit::Pair("tournament_id", tournamentID));
root.push_back(json_spirit::Pair("ranks", json_spirit::Array()));
json_spirit::Array &ranks = root.back().value_.get_array();
fillRankResults(ranks);
root.push_back(json_spirit::Pair("matches", json_spirit::Object()));
json_spirit::Object &matches= root.back().value_.get_obj();
for (auto &cluster : clusterTeamResults)
{
matches.push_back(json_spirit::Pair(cluster.first, json_spirit::Object()));
json_spirit::Object &match = matches.back().value_.get_obj();
match.push_back(json_spirit::Pair("teams", json_spirit::Array()));
json_spirit::Array &teams = match.back().value_.get_array();
fillTeamResults(teams, cluster.first);
match.push_back(json_spirit::Pair("results", json_spirit::Array()));
json_spirit::Array &results = match.back().value_.get_array();
fillMatchResults(results, cluster.first);
if (cluster.first != "all")
{
match.push_back(json_spirit::Pair("bof_round", clusterMatchResultStatisticsLists[cluster.first].bofRound));
match.push_back(json_spirit::Pair("game_in_round", clusterMatchResultStatisticsLists[cluster.first].gameInRound));
}
else
{
match.push_back(json_spirit::Pair("bof_round", 0));
match.push_back(json_spirit::Pair("game_in_round", 0));
}
}
return root;
}
void Simulation::fillRankResults(json_spirit::Array &ranks)
{
for (RankData &rankData : this->ranks)
ranks.push_back(rankData.toJSONObject());
}
void Simulation::fillMatchResults(json_spirit::Array &results, std::string cluster)
{
results = clusterMatchResultStatisticsLists[cluster].toJSONArray();
}
void Simulation::fillTeamResults(json_spirit::Array &teamList, std::string cluster)
{
for (auto &team : teams)
{
json_spirit::Object teamData;
teamData.push_back(json_spirit::Pair("id", team.id));
if (cluster == "all")
{
teamData.push_back(json_spirit::Pair("ranks", clusterTeamResults[cluster][team.id].rankDataToJSONArray(ranks)));
teamData.push_back(json_spirit::Pair("avg_place", clusterTeamResults[cluster][team.id].getAvgPlace()));
}
teamData.push_back(json_spirit::Pair("match_data", clusterTeamResults[cluster][team.id].toJSONObject()));
teamData.push_back(json_spirit::Pair("avg_goals", clusterTeamResults[cluster][team.id].getAvgGoals()));
teamList.push_back(teamData);
}
}
} // namespace sim | 29.050388 | 117 | 0.70567 | walachey |
96359e08953c89a1257ab5bb4a5ad9ad776019bc | 40,016 | cc | C++ | src/sst/core/config.cc | jleidel/sst-core | b4931c2e971c929be53020986f14a53257686be1 | [
"BSD-3-Clause"
] | null | null | null | src/sst/core/config.cc | jleidel/sst-core | b4931c2e971c929be53020986f14a53257686be1 | [
"BSD-3-Clause"
] | null | null | null | src/sst/core/config.cc | jleidel/sst-core | b4931c2e971c929be53020986f14a53257686be1 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2009-2021 NTESS. Under the terms
// of Contract DE-NA0003525 with NTESS, the U.S.
// Government retains certain rights in this software.
//
// Copyright (c) 2009-2021, NTESS
// All rights reserved.
//
// This file is part of the SST software package. For license
// information, see the LICENSE file in the top level directory of the
// distribution.
#include "sst_config.h"
#include "sst/core/config.h"
#include "sst/core/build_info.h"
#include "sst/core/env/envquery.h"
#include "sst/core/output.h"
#include "sst/core/part/sstpart.h"
#include "sst/core/warnmacros.h"
#ifdef SST_CONFIG_HAVE_MPI
DISABLE_WARN_MISSING_OVERRIDE
#include <mpi.h>
REENABLE_WARNING
#endif
#include <cstdlib>
#include <errno.h>
#include <getopt.h>
#include <iostream>
#include <locale>
#include <string>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#ifndef E_OK
#define E_OK 0
#endif
using namespace std;
namespace SST {
// Reserved name to indicate section header in program options
static const char* SECTION_HEADER = "XSECTION_HEADERX";
//// Helper class for setting options
class ConfigHelper
{
private:
Config& cfg;
public:
typedef bool (ConfigHelper::*flagFunction)(void);
typedef bool (ConfigHelper::*argFunction)(const std::string& arg);
// Used to determine what return code to use
bool clean_exit = false;
ConfigHelper(Config& cfg) : cfg(cfg) {}
// Print usage
bool printHelp()
{
clean_exit = true;
return usage();
}
// Prints the SST version
bool printVersion()
{
printf("SST-Core Version (" PACKAGE_VERSION);
if ( strcmp(SSTCORE_GIT_HEADSHA, PACKAGE_VERSION) ) {
printf(", git branch : " SSTCORE_GIT_BRANCH);
printf(", SHA: " SSTCORE_GIT_HEADSHA);
}
printf(")\n");
clean_exit = true;
return false; /* Should not continue */
}
// Verbosity
bool incrVerbose()
{
cfg.verbose_++;
return true;
}
bool setVerbosity(const std::string& arg)
{
try {
unsigned long val = stoul(arg);
cfg.verbose_ = val;
return true;
}
catch ( std::invalid_argument& e ) {
fprintf(stderr, "Failed to parse '%s' as number for option --verbose\n", arg.c_str());
return false;
}
}
// num_threads
bool setNumThreads(const std::string& arg)
{
try {
unsigned long val = stoul(arg);
cfg.world_size_.thread = val;
return true;
}
catch ( std::invalid_argument& e ) {
fprintf(stderr, "Failed to parse '%s' as number for option --num-threads\n", arg.c_str());
return false;
}
}
// SDL file
bool setConfigFile(const std::string& arg)
{
cfg.configFile_ = arg;
return true;
}
// model_options
bool setModelOptions(const std::string& arg)
{
if ( cfg.model_options_.empty() )
cfg.model_options_ = arg;
else
cfg.model_options_ += std::string(" \"") + arg + std::string("\"");
return true;
}
// print timing
bool enablePrintTiming()
{
cfg.print_timing_ = true;
return true;
}
bool setPrintTiming(const std::string& arg)
{
bool success = false;
cfg.print_timing_ = parseBoolean(arg, success, "enable-print-timing");
return success;
}
// stop-at
bool setStopAt(const std::string& arg)
{
cfg.stop_at_ = arg;
return true;
}
// stopAtCycle (deprecated)
bool setStopAtCycle(const std::string& arg)
{
// Uncomment this once all test files have been updated
// fprintf(stderr, "Program option 'stopAtCycle' has been deprecated. Please use 'stop-at' instead");
return setStopAt(arg);
}
// exit after
bool setExitAfter(const std::string& arg)
{
/* TODO: Error checking */
errno = 0;
static const char* templates[] = { "%H:%M:%S", "%M:%S", "%S", "%Hh", "%Mm", "%Ss" };
const size_t n_templ = sizeof(templates) / sizeof(templates[0]);
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wmissing-field-initializers"
struct tm res = {}; /* This warns on GCC 4.8 due to a bug in GCC */
#pragma GCC diagnostic pop
char* p;
for ( size_t i = 0; i < n_templ; i++ ) {
memset(&res, '\0', sizeof(res));
p = strptime(arg.c_str(), templates[i], &res);
fprintf(
stderr, "**** [%s] p = %p ; *p = '%c', %u:%u:%u\n", templates[i], p, (p) ? *p : '\0', res.tm_hour,
res.tm_min, res.tm_sec);
if ( p != nullptr && *p == '\0' ) {
cfg.exit_after_ = res.tm_sec;
cfg.exit_after_ += res.tm_min * 60;
cfg.exit_after_ += res.tm_hour * 60 * 60;
return true;
}
}
fprintf(
stderr,
"Failed to parse stop time [%s]\n"
"Valid formats are:\n",
arg.c_str());
for ( size_t i = 0; i < n_templ; i++ ) {
fprintf(stderr, "\t%s\n", templates[i]);
}
return false;
}
// stop after (deprecated)
bool setStopAfter(const std::string& arg)
{
// Uncomment this once all test files have been updated
// fprintf(stderr, "Program option 'stopAfter' has been deprecated. Please use 'exit-after' instead");
return setExitAfter(arg);
}
// timebase
bool setTimebase(const std::string& arg)
{
// TODO: Error checking. Need to wait until UnitAlgebra
// switches to exceptions on errors instead of calling abort
cfg.timeBase_ = arg;
return true;
}
// partitioner
bool setPartitioner(const std::string& arg)
{
cfg.partitioner_ = arg;
if ( cfg.partitioner_.find('.') == cfg.partitioner_.npos ) { cfg.partitioner_ = "sst." + cfg.partitioner_; }
return true;
}
// heart beat
bool setHeartbeat(const std::string& arg)
{
/* TODO: Error checking */
cfg.heartbeatPeriod_ = arg;
return true;
}
// output directory
bool setOutputDir(const std::string& arg)
{
cfg.output_directory_ = arg;
return true;
}
// core output prefix
bool setOutputPrefix(const std::string& arg)
{
cfg.output_core_prefix_ = arg;
return true;
}
// Configuration output
// output config python
bool setWriteConfig(const std::string& arg)
{
cfg.output_config_graph_ = arg;
return true;
}
// output config json
bool setWriteJSON(const std::string& arg)
{
cfg.output_json_ = arg;
return true;
}
// parallel output
#ifdef SST_CONFIG_HAVE_MPI
bool enableParallelOutput()
{
// If this is only a one rank job, then we can ignore
if ( cfg.world_size_.rank == 1 ) return true;
cfg.parallel_output_ = true;
// For parallel output, we always need to output the partition
// info as well
cfg.output_partition_ = true;
return true;
}
bool enableParallelOutputArg(const std::string& arg)
{
// If this is only a one rank job, then we can ignore, except
// that we will turn on output_partition
if ( cfg.world_size_.rank == 1 ) return true;
bool success = false;
cfg.parallel_output_ = parseBoolean(arg, success, "parallel-output");
// For parallel output, we always need to output the partition
// info as well. Also, if it was already set to true, don't
// overwrite even if parallel_output was set to false.
cfg.output_partition_ = cfg.output_partition_ | cfg.parallel_output_;
return success;
}
#endif
// output config xml
bool setWriteXML(const std::string& arg)
{
cfg.output_xml_ = arg;
return true;
}
// Graph output
// graph output dot
bool setWriteDot(const std::string& arg)
{
cfg.output_dot_ = arg;
return true;
}
// dot verbosity
bool setDotVerbosity(const std::string& arg)
{
try {
unsigned long val = stoul(arg);
cfg.dot_verbosity_ = val;
return true;
}
catch ( std::invalid_argument& e ) {
fprintf(stderr, "Failed to parse '%s' as number for option --dot-verbosity\n", arg.c_str());
return false;
}
}
// output partition
bool setWritePartitionFile(const std::string& arg)
{
cfg.component_partition_file_ = arg;
return true;
}
bool setWritePartition()
{
cfg.output_partition_ = true;
return true;
}
// parallel load
#ifdef SST_CONFIG_HAVE_MPI
bool enableParallelLoad()
{
// If this is only a one rank job, then we can ignore
if ( cfg.world_size_.rank == 1 ) return true;
cfg.parallel_load_ = true;
return true;
}
#endif
// Advanced options
// timevortex
bool setTimeVortex(const std::string& arg)
{
cfg.timeVortex_ = arg;
return true;
}
// interthread links
bool setInterThreadLinks()
{
cfg.interthread_links_ = true;
return true;
}
bool setInterThreadLinksArg(const std::string& arg)
{
bool success = false;
cfg.interthread_links_ = parseBoolean(arg, success, "interthread-links");
return success;
}
// debug file
bool setDebugFile(const std::string& arg)
{
cfg.debugFile_ = arg;
return true;
}
// lib path
bool setLibPath(const std::string& arg)
{
/* TODO: Error checking */
cfg.libpath_ = arg;
return true;
}
// add to lib path
bool addLibPath(const std::string& arg)
{
/* TODO: Error checking */
cfg.libpath_ += std::string(":") + arg;
return true;
}
// run mode
bool setRunMode(const std::string& arg)
{
if ( !arg.compare("init") )
cfg.runMode_ = Simulation::INIT;
else if ( !arg.compare("run") )
cfg.runMode_ = Simulation::RUN;
else if ( !arg.compare("both") )
cfg.runMode_ = Simulation::BOTH;
else {
fprintf(stderr, "Unknown option for --run-mode: %s\n", arg.c_str());
cfg.runMode_ = Simulation::UNKNOWN;
}
return cfg.runMode_ != Simulation::UNKNOWN;
}
// dump undeleted events
#ifdef USE_MEMPOOL
bool setWriteUndeleted(const std::string& arg)
{
cfg.event_dump_file_ = arg;
return true;
}
#endif
// Advanced options - environment
// print environment
bool enablePrintEnv()
{
cfg.print_env_ = true;
return true;
}
// Disable signal handlers
bool disableSigHandlers()
{
cfg.enable_sig_handling_ = false;
return true;
}
// Disable environment loader
bool disableEnvConfig()
{
cfg.no_env_config_ = true;
return true;
}
/**
Special function for catching the magic string indicating a
section header in the options array. It will report that the
value is unknown.
*/
bool sectionHeaderCatch()
{
// This will only ever get called, if, for some reason, someone
// tries to use the reserved section header name as an argument to
// sst. In that case, make it look the same as any other unknown
// argument.
fprintf(stderr, "sst: unrecognized option --%s\n", SECTION_HEADER);
usage();
return false;
}
/**
Special function for catching the magic string indicating a
section header in the options array. It will report that the
value is unknown.
*/
bool sectionHeaderCatchArg(const std::string& UNUSED(arg))
{
// This will only ever get called, if, for some reason, someone
// tries to use the reserved section header name as an argument to
// sst. In that case, make it look the same as any other unknown
// argument.
fprintf(stderr, "sst: unrecognized option --%s\n", SECTION_HEADER);
usage();
return false;
}
// Prints the usage information
bool usage();
// Function to uniformly parse boolean values for command line
// arguments
bool parseBoolean(const std::string& arg, bool& success, const std::string& option);
};
//// Config Class functions
void
Config::print()
{
std::cout << "verbose = " << verbose_ << std::endl;
std::cout << "num_threads = " << world_size_.thread << std::endl;
std::cout << "num_ranks = " << world_size_.rank << std::endl;
std::cout << "configFile = " << configFile_ << std::endl;
std::cout << "model_options = " << model_options_ << std::endl;
std::cout << "print_timing = " << print_timing_ << std::endl;
std::cout << "stop_at = " << stop_at_ << std::endl;
std::cout << "exit_after = " << exit_after_ << std::endl;
std::cout << "timeBase = " << timeBase_ << std::endl;
std::cout << "partitioner = " << partitioner_ << std::endl;
std::cout << "heartbeatPeriod = " << heartbeatPeriod_ << std::endl;
std::cout << "output_directory = " << output_directory_ << std::endl;
std::cout << "output_core_prefix = " << output_core_prefix_ << std::endl;
std::cout << "output_config_graph = " << output_config_graph_ << std::endl;
std::cout << "output_json = " << output_json_ << std::endl;
std::cout << "parallel_output = " << parallel_output_ << std::endl;
std::cout << "output_xml = " << output_xml_ << std::endl;
std::cout << "output_dot = " << output_dot_ << std::endl;
std::cout << "dot_verbosity = " << dot_verbosity_ << std::endl;
std::cout << "component_partition_file = " << component_partition_file_ << std::endl;
std::cout << "output_partition = " << output_partition_ << std::endl;
std::cout << "parallel_load = " << parallel_load_ << std::endl;
std::cout << "timeVortex = " << timeVortex_ << std::endl;
std::cout << "interthread_links = " << interthread_links_ << std::endl;
std::cout << "debugFile = " << debugFile_ << std::endl;
std::cout << "libpath = " << libpath_ << std::endl;
std::cout << "addLlibPath = " << addLibPath_ << std::endl;
std::cout << "runMode = " << runMode_ << std::endl;
#ifdef USE_MEMPOOL
std::cout << "event_dump_file = " << event_dump_file_ << std::endl;
#endif
std::cout << "print_env" << print_env_ << std::endl;
std::cout << "enable_sig_handling = " << enable_sig_handling_ << std::endl;
std::cout << "no_env_config = " << no_env_config_ << std::endl;
}
Config::Config(RankInfo rank_info) : Config()
{
// Basic Options
verbose_ = 0;
world_size_.rank = rank_info.rank;
world_size_.thread = 1;
configFile_ = "NONE";
model_options_ = "";
print_timing_ = false;
stop_at_ = "0 ns";
exit_after_ = 0;
timeBase_ = "1 ps";
partitioner_ = "sst.linear";
heartbeatPeriod_ = "";
char* wd_buf = (char*)malloc(sizeof(char) * PATH_MAX);
getcwd(wd_buf, PATH_MAX);
output_directory_ = "";
if ( nullptr != wd_buf ) {
output_directory_.append(wd_buf);
free(wd_buf);
}
output_core_prefix_ = "@x SST Core: ";
// Configuration Output
output_config_graph_ = "";
output_json_ = "";
parallel_output_ = false;
output_xml_ = "";
// Graph output
output_dot_ = "";
dot_verbosity_ = 0;
component_partition_file_ = "";
output_partition_ = false;
// Advance Options
parallel_load_ = false;
timeVortex_ = "sst.timevortex.priority_queue";
interthread_links_ = false;
debugFile_ = "/dev/null";
libpath_ = SST_INSTALL_PREFIX "/lib/sst";
addLibPath_ = "";
runMode_ = Simulation::BOTH;
#ifdef __SST_DEBUG_EVENT_TRACKING__
event_dump_file_ = "";
#endif
// Advanced Options- environment
print_env_ = false;
enable_sig_handling_ = true;
no_env_config_ = false;
}
// Check for existence of config file
bool
Config::checkConfigFile()
{
struct stat sb;
char* fqpath = realpath(configFile_.c_str(), nullptr);
if ( nullptr == fqpath ) {
fprintf(stderr, "Failed to canonicalize path [%s]: %s\n", configFile_.c_str(), strerror(errno));
return false;
}
configFile_ = fqpath;
free(fqpath);
if ( 0 != stat(configFile_.c_str(), &sb) ) {
fprintf(stderr, "File [%s] cannot be found: %s\n", configFile_.c_str(), strerror(errno));
return false;
}
if ( !S_ISREG(sb.st_mode) ) {
fprintf(stderr, "File [%s] is not a regular file.\n", configFile_.c_str());
return false;
}
if ( 0 != access(configFile_.c_str(), R_OK) ) {
fprintf(stderr, "File [%s] is not readable.\n", configFile_.c_str());
return false;
}
return true;
}
std::string
Config::getLibPath(void) const
{
char* envpath = getenv("SST_LIB_PATH");
// Get configuration options from the user config
std::vector<std::string> overrideConfigPaths;
SST::Core::Environment::EnvironmentConfiguration* envConfig =
SST::Core::Environment::getSSTEnvironmentConfiguration(overrideConfigPaths);
std::string fullLibPath = libpath_;
std::set<std::string> configGroups = envConfig->getGroupNames();
// iterate over groups of settings
for ( auto groupItr = configGroups.begin(); groupItr != configGroups.end(); groupItr++ ) {
SST::Core::Environment::EnvironmentConfigGroup* currentGroup = envConfig->getGroupByName(*groupItr);
std::set<std::string> groupKeys = currentGroup->getKeys();
// find which keys have a LIBDIR at the END of the key
// we recognize these may house elements
for ( auto keyItr = groupKeys.begin(); keyItr != groupKeys.end(); keyItr++ ) {
const std::string& key = *keyItr;
const std::string& value = currentGroup->getValue(key);
if ( key.size() > 6 ) {
if ( "LIBDIR" == key.substr(key.size() - 6) ) {
fullLibPath.append(":");
fullLibPath.append(value);
}
}
}
}
// Clean up and delete the configuration we just loaded up
delete envConfig;
if ( nullptr != envpath ) {
fullLibPath.clear();
fullLibPath.append(envpath);
}
if ( !addLibPath_.empty() ) {
fullLibPath.append(":");
fullLibPath.append(addLibPath_);
}
if ( verbose_ ) {
std::cout << "SST-Core: Configuration Library Path will read from: " << fullLibPath << std::endl;
}
return fullLibPath;
}
// Struct to hold the program option information
struct sstLongOpts_s
{
struct option opt;
const char* argName;
const char* desc;
ConfigHelper::flagFunction flagFunc;
ConfigHelper::argFunction argFunc;
bool sdl_avail;
// Unlike the other variables that hold the information about the
// option, this is used to keep track of options that are set on
// the command line. We need this so we can ignore those when
// setting options from the sdl file.
mutable bool set_cmdline;
};
// Macros to make defining options easier
// Nomenaclature is:
// FLAG - value is either true or false. FLAG defaults to no arguments allowed
// ARG - value is a string. ARG defaults to required argument
// OPTVAL - Takes an optional paramater
// longName - multicharacter name referenced using --
// shortName - single character name referenced using -
// text - help text
// func - function called if there is no value specified
// valFunct - function called if there is a value specified
// sdl_avail - determines whether option is avaialble to set in input files
#define DEF_FLAG_OPTVAL(longName, shortName, text, func, valFunc, sdl_avail) \
{ \
{ longName, optional_argument, 0, shortName }, "[BOOL]", text, func, valFunc, sdl_avail, false \
}
#define DEF_FLAG(longName, shortName, text, func) \
{ \
{ longName, no_argument, 0, shortName }, nullptr, text, func, nullptr, false, false \
}
#define DEF_ARG(longName, shortName, argName, text, valFunc, sdl_avail) \
{ \
{ longName, required_argument, 0, shortName }, argName, text, nullptr, valFunc, sdl_avail, false \
}
//#define DEF_ARGOPT(longName, argName, text, func) DEF_ARGOPT_SHORT(longName, 0, argName, text, func)
#define DEF_ARG_OPTVAL(longName, shortName, argName, text, func, valFunc, sdl_avail) \
{ \
{ longName, optional_argument, 0, shortName }, "[" argName "]", text, func, valFunc, sdl_avail, false \
}
#define DEF_SECTION_HEADING(text) \
{ \
{ SECTION_HEADER, optional_argument, 0, 0 }, nullptr, text, &ConfigHelper::sectionHeaderCatch, \
&ConfigHelper::sectionHeaderCatchArg, false, false \
}
static const struct sstLongOpts_s sstOptions[] = {
/* Informational options */
DEF_SECTION_HEADING("Informational Options"),
DEF_FLAG("help", 'h', "Print help message", &ConfigHelper::printHelp),
DEF_FLAG("version", 'V', "Print SST Release Version", &ConfigHelper::printVersion),
/* Basic Options */
DEF_SECTION_HEADING("Basic Options (most commonly used)"),
DEF_ARG_OPTVAL(
"verbose", 'v', "level", "Verbosity level to determine what information about core runtime is printed",
&ConfigHelper::incrVerbose, &ConfigHelper::setVerbosity, true),
DEF_ARG(
"num_threads", 'n', "NUM", "Number of parallel threads to use per rank", &ConfigHelper::setNumThreads, true),
DEF_ARG(
"sdl-file", 0, "FILE",
"Specify SST Configuration file. Note: this is most often done by just specifying the file without an option.",
&ConfigHelper::setConfigFile, false),
DEF_ARG(
"model-options", 0, "STR",
"Provide options to the python configuration script. Additionally, any arguments provided after a final '-- ' "
"will be "
"appended to the model options (or used as the model options if --model-options was not specified).",
&ConfigHelper::setModelOptions, false),
DEF_FLAG_OPTVAL(
"print-timing-info", 0, "Print SST timing information", &ConfigHelper::enablePrintTiming,
&ConfigHelper::setPrintTiming, true),
DEF_ARG("stop-at", 0, "TIME", "Set time at which simulation will end execution", &ConfigHelper::setStopAt, true),
DEF_ARG(
"stopAtCycle", 0, "TIME",
"[DEPRECATED] Set time at which simulation will end execution (deprecated, please use --stop-at instead)",
&ConfigHelper::setStopAtCycle, true),
DEF_ARG(
"exit-after", 0, "TIME",
"Set the maximum wall time after which simulation will end execution. Time is specified in hours, minutes and "
"seconds, with the following formats supported: H:M:S, M:S, S, Hh, Mm, Ss (captital letters are the "
"appropriate numbers for that value, lower case letters represent the units and are required in for those "
"formats).",
&ConfigHelper::setExitAfter, true),
DEF_ARG(
"stopAfter", 0, "TIME",
"[DEPRECATED] Set the maximum wall time after which simulation will exit (deprecatd, please use --exit-after "
"instead",
&ConfigHelper::setStopAfter, true),
DEF_ARG(
"timebase", 0, "TIMEBASE", "Set the base time step of the simulation (default: 1ps)",
&ConfigHelper::setTimebase, true),
DEF_ARG(
"partitioner", 0, "PARTITIONER", "Select the partitioner to be used. <lib.partitionerName>",
&ConfigHelper::setPartitioner, true),
DEF_ARG(
"heartbeat-period", 0, "PERIOD",
"Set time for heartbeats to be published (these are approximate timings, published by the core, to update on "
"progress)",
&ConfigHelper::setHeartbeat, true),
DEF_ARG(
"output-directory", 0, "DIR", "Directory into which all SST output files should reside",
&ConfigHelper::setOutputDir, true),
DEF_ARG(
"output-prefix-core", 0, "STR", "set the SST::Output prefix for the core", &ConfigHelper::setOutputPrefix,
true),
/* Configuration Output */
DEF_SECTION_HEADING(
"Configuration Output Options (generates a file that can be used as input for reproducing a run)"),
DEF_ARG(
"output-config", 0, "FILE", "File to write SST configuration (in Python format)", &ConfigHelper::setWriteConfig,
true),
DEF_ARG(
"output-json", 0, "FILE", "File to write SST configuration graph (in JSON format)", &ConfigHelper::setWriteJSON,
true),
#ifdef SST_CONFIG_HAVE_MPI
DEF_FLAG_OPTVAL(
"parallel-output", 0,
"Enable parallel output of configuration information. This option is ignored for single rank jobs. Must also "
"specify an output type (--output-config "
"and/or --output-json). Note: this will also cause partition info to be output if set to true.",
&ConfigHelper::enableParallelOutput, &ConfigHelper::enableParallelOutputArg, true),
#endif
DEF_ARG(
"output-xml", 0, "FILE", "[DEPRECATED] File to write SST configuration graph (in XML format)",
&ConfigHelper::setWriteXML, true),
/* Configuration Output */
DEF_SECTION_HEADING("Graph Output Options (for outputting graph information for visualization or inspection)"),
DEF_ARG(
"output-dot", 0, "FILE", "File to write SST configuration graph (in GraphViz format)",
&ConfigHelper::setWriteDot, true),
DEF_ARG(
"dot-verbosity", 0, "INT", "Amount of detail to include in the dot graph output",
&ConfigHelper::setDotVerbosity, true),
DEF_ARG_OPTVAL(
"output-partition", 0, "FILE",
"File to write SST component partitioning information. When used without an argument and in conjuction with "
"--output-json or --output-config options, will cause paritition information to be added to graph output.",
&ConfigHelper::setWritePartition, &ConfigHelper::setWritePartitionFile, true),
/* Advanced Features */
DEF_SECTION_HEADING("Advanced Options"),
#ifdef SST_CONFIG_HAVE_MPI
DEF_FLAG(
"parallel-load", 0, "Enable parallel loading of configuration. This option is ignored for single rank jobs.",
&ConfigHelper::enableParallelLoad),
#endif
DEF_ARG(
"timeVortex", 0, "MODULE", "Select TimeVortex implementation <lib.timevortex>", &ConfigHelper::setTimeVortex,
true),
DEF_FLAG_OPTVAL(
"interthread-links", 0, "[EXPERIMENTAL] Set whether or not interthread links should be used <false>",
&ConfigHelper::setInterThreadLinks, &ConfigHelper::setInterThreadLinksArg, true),
DEF_ARG("debug-file", 0, "FILE", "File where debug output will go", &ConfigHelper::setDebugFile, true),
DEF_ARG("lib-path", 0, "LIBPATH", "Component library path (overwrites default)", &ConfigHelper::setLibPath, true),
DEF_ARG(
"add-lib-path", 0, "LIBPATH", "Component library path (appends to main path)", &ConfigHelper::addLibPath, true),
DEF_ARG("run-mode", 0, "MODE", "Set run mode [ init | run | both (default)]", &ConfigHelper::setRunMode, true),
#ifdef USE_MEMPOOL
DEF_ARG(
"output-undeleted-events", 0, "FILE",
"file to write information about all undeleted events at the end of simulation (STDOUT and STDERR can be used "
"to output to console)",
&ConfigHelper::setWriteUndeleted, true),
#endif
/* Advanced Features - Environment Setup/Reporting */
DEF_SECTION_HEADING("Advanced Options - Environment Setup/Reporting"),
DEF_FLAG("print-env", 0, "Print environment variables SST will see", &ConfigHelper::enablePrintEnv),
DEF_FLAG("disable-signal-handlers", 0, "Disable signal handlers", &ConfigHelper::disableSigHandlers),
DEF_FLAG("no-env-config", 0, "Disable SST environment configuration", &ConfigHelper::disableEnvConfig),
{ { nullptr, 0, nullptr, 0 }, nullptr, nullptr, nullptr, nullptr, false, false }
};
static const size_t nLongOpts = (sizeof(sstOptions) / sizeof(sstLongOpts_s)) - 1;
bool
ConfigHelper::parseBoolean(const std::string& arg, bool& success, const std::string& option)
{
success = true;
std::string arg_lower(arg);
std::locale loc;
for ( auto& ch : arg_lower )
ch = std::tolower(ch, loc);
if ( arg_lower == "true" || arg_lower == "yes" || arg_lower == "1" )
return true;
else if ( arg_lower == "false" || arg_lower == "no" || arg_lower == "0" )
return false;
else {
fprintf(
stderr,
"ERROR: Failed to parse \"%s\" as a bool for option \"%s\", "
"please use true/false, yes/no or 1/0\n",
arg.c_str(), option.c_str());
exit(-1);
return false;
}
}
bool
ConfigHelper::usage()
{
#ifdef SST_CONFIG_HAVE_MPI
int this_rank = 0;
MPI_Comm_rank(MPI_COMM_WORLD, &this_rank);
if ( this_rank != 0 ) return false;
#endif
/* Determine screen / description widths */
uint32_t MAX_WIDTH = 80;
struct winsize size;
if ( ioctl(STDERR_FILENO, TIOCGWINSZ, &size) == 0 ) { MAX_WIDTH = size.ws_col; }
if ( getenv("COLUMNS") ) {
errno = E_OK;
uint32_t x = strtoul(getenv("COLUMNS"), nullptr, 0);
if ( errno == E_OK ) MAX_WIDTH = x;
}
const char sdl_indicator[] = "(S)";
const uint32_t sdl_start = 33;
const uint32_t desc_start = sdl_start + sizeof(sdl_indicator);
const uint32_t desc_width = MAX_WIDTH - desc_start;
/* Print usage */
fprintf(
stderr,
"Usage: sst [options] config-file\n"
" Arguments to options contained in [] are optional.\n"
" BOOL values can be expressed as true/false, yes/no or 1/0 and default to true if the option is specified\n"
" Options available to be set in the sdl file (input configuration file) are denoted by (S)\n");
for ( size_t i = 0; i < nLongOpts; i++ ) {
if ( !strcmp(sstOptions[i].opt.name, SECTION_HEADER) ) {
// Just a section heading
fprintf(stderr, "\n%s\n", sstOptions[i].desc);
continue;
}
uint32_t npos = 0;
if ( sstOptions[i].opt.val ) { npos += fprintf(stderr, " -%c, ", (char)sstOptions[i].opt.val); }
else {
npos += fprintf(stderr, " ");
}
npos += fprintf(stderr, "--%s", sstOptions[i].opt.name);
if ( sstOptions[i].opt.has_arg != no_argument ) { npos += fprintf(stderr, "=%s", sstOptions[i].argName); }
// If we have already gone beyond the description start,
// description starts on new line
if ( npos >= sdl_start ) {
fprintf(stderr, "\n");
npos = 0;
}
// If this can be set in the sdl file, start description with
// "(S)"
while ( npos < sdl_start ) {
npos += fprintf(stderr, " ");
}
if ( sstOptions[i].sdl_avail ) { npos += fprintf(stderr, sdl_indicator); }
const char* text = sstOptions[i].desc;
while ( text != nullptr && *text != '\0' ) {
/* Advance to offset */
while ( npos < desc_start )
npos += fprintf(stderr, " ");
if ( strlen(text) <= desc_width ) {
fprintf(stderr, "%s", text);
break;
}
else {
// Need to find the last space before we need to break
int index = desc_width - 1;
while ( index > 0 ) {
if ( text[index] == ' ' ) break;
index--;
}
int nwritten = fprintf(stderr, "%.*s\n", index, text);
text += (nwritten);
// Skip any extra spaces
while ( *text == ' ' )
text++;
npos = 0;
}
}
fprintf(stderr, "\n");
}
fprintf(stderr, "\n");
return false; /* Should not continue */
}
int
Config::parseCmdLine(int argc, char* argv[])
{
ConfigHelper helper(*this);
static const char* sst_short_options = "hv::Vn:";
struct option sst_long_options[nLongOpts + 1];
for ( size_t i = 0; i < nLongOpts; i++ ) {
sst_long_options[i] = sstOptions[i].opt;
}
sst_long_options[nLongOpts] = { nullptr, 0, nullptr, 0 };
run_name = argv[0];
// Need to see if there are model-options specified after '--'.
// If there is, we will deal with it later and just tell getopt
// about everything before it. getopt does not handle -- and
// positional arguments in a sane way.
int end_arg_index = 0;
for ( int i = 0; i < argc; ++i ) {
if ( !strcmp(argv[i], "--") ) {
end_arg_index = i;
break;
}
}
int my_argc = end_arg_index == 0 ? argc : end_arg_index;
bool ok = true;
helper.clean_exit = false;
while ( ok ) {
int option_index = 0;
const int intC = getopt_long(my_argc, argv, sst_short_options, sst_long_options, &option_index);
if ( intC == -1 ) /* We're done */
break;
const char c = static_cast<char>(intC);
// Getopt is a bit strange it how it returns information.
// There are three cases:
// 1 - Uknown value: c = '?' & option_index = 0
// 2 - long options: c = first letter of option & option_index = index of option in sst_long_options
// 3 - short options: c = short option letter & option_index = 0
// This is a dumb combination of things. They really should
// have return c = 0 in the long option case. As it is,
// there's no way to differentiate a short value from the long
// value in index 0. Thankfully, we have a "Section Header"
// in index 0 so we don't have to worry about that.
// If the character returned from getopt_long is '?', then it
// is an unknown command
if ( c == '?' ) {
// Unknown option
ok = helper.usage();
}
else if ( option_index != 0 ) {
// Long options
if ( optarg == nullptr ) {
ok = (helper.*sstOptions[option_index].flagFunc)();
if ( ok ) sstOptions[option_index].set_cmdline = true;
}
else {
ok = (helper.*sstOptions[option_index].argFunc)(optarg);
if ( ok ) sstOptions[option_index].set_cmdline = true;
}
}
else {
switch ( c ) {
case 0:
// This shouldn't happen, so we'll error if it does
fprintf(stderr, "INTERNAL ERROR: error parsing command line options\n");
exit(1);
break;
case 'v':
if ( optarg == nullptr ) { ok = helper.incrVerbose(); }
else {
ok = helper.setVerbosity(optarg);
}
if ( ok ) sstOptions[option_index].set_cmdline = true;
break;
case 'n':
{
ok = helper.setNumThreads(optarg);
if ( ok ) sstOptions[option_index].set_cmdline = true;
break;
}
case 'V':
ok = helper.printVersion();
helper.clean_exit = true;
break;
case 'h':
helper.clean_exit = true;
default:
ok = helper.usage();
}
}
}
if ( !ok ) {
if ( helper.clean_exit ) return 1;
return -1;
}
/* Handle positional arguments */
if ( optind < argc ) {
// First positional argument is the sdl-file
ok = helper.setConfigFile(argv[optind++]);
// If there are additional position arguments, this is an
// error
if ( optind == (my_argc - 1) ) {
fprintf(
stderr, "Error: sdl-file name is the only positional argument allowed. See help for --model-options "
"for more info on passing parameters to the input script.\n");
ok = false;
}
}
// Check to make sure we had an sdl-file specified
if ( configFile_ == "NONE" ) {
fprintf(stderr, "ERROR: no sdl-file specified\n");
fprintf(stderr, "Usage: %s sdl-file [options]\n", run_name.c_str());
return -1;
}
// Support further additional arguments specified after -- to be
// args to the model.
if ( end_arg_index != 0 ) {
for ( int i = end_arg_index + 1; i < argc; ++i ) {
helper.setModelOptions(argv[i]);
}
}
if ( !ok ) return -1;
/* Sanity check, and other duties */
Output::setFileName(debugFile_ != "/dev/null" ? debugFile_ : "sst_output");
// Ensure output directory ends with a directory separator
if ( output_directory_.size() > 0 ) {
if ( '/' != output_directory_[output_directory_.size() - 1] ) { output_directory_.append("/"); }
}
// Now make sure all the files we are generating go into a directory
if ( output_config_graph_.size() > 0 && isFileNameOnly(output_config_graph_) ) {
output_config_graph_.insert(0, output_directory_);
}
if ( output_dot_.size() > 0 && isFileNameOnly(output_dot_) ) { output_dot_.insert(0, output_directory_); }
if ( output_xml_.size() > 0 && isFileNameOnly(output_xml_) ) { output_xml_.insert(0, output_directory_); }
if ( output_json_.size() > 0 && isFileNameOnly(output_json_) ) { output_json_.insert(0, output_directory_); }
if ( debugFile_.size() > 0 && isFileNameOnly(debugFile_) ) { debugFile_.insert(0, output_directory_); }
return 0;
}
bool
Config::setOptionFromModel(const string& entryName, const string& value)
{
ConfigHelper helper(*this);
for ( size_t i = 0; i < nLongOpts; i++ ) {
if ( !entryName.compare(sstOptions[i].opt.name) ) {
if ( sstOptions[i].sdl_avail ) {
// If this was set on the command line, skip it
if ( sstOptions[i].set_cmdline ) return false;
return (helper.*sstOptions[i].argFunc)(value);
}
else {
fprintf(stderr, "ERROR: Option \"%s\" is not available to be set in the SDL file\n", entryName.c_str());
exit(-1);
return false;
}
}
}
fprintf(stderr, "ERROR: Unknown configuration entry \"%s\"\n", entryName.c_str());
exit(-1);
return false;
}
} // namespace SST
| 33.797297 | 120 | 0.580643 | jleidel |
963ce0e2c4978bd9501a55fe22131ebff42e7a01 | 3,539 | cpp | C++ | Jamma/src/Main.cpp | malisimo/Jamma | 69831e79a64e652e82aa41f8141e082c3899896b | [
"MIT"
] | null | null | null | Jamma/src/Main.cpp | malisimo/Jamma | 69831e79a64e652e82aa41f8141e082c3899896b | [
"MIT"
] | null | null | null | Jamma/src/Main.cpp | malisimo/Jamma | 69831e79a64e652e82aa41f8141e082c3899896b | [
"MIT"
] | null | null | null | ///////////////////////////////////////////////////////////
//
// Copyright(c) 2018-2019 Matt Jones
// Subject to the MIT license, see LICENSE file.
//
///////////////////////////////////////////////////////////
#include "Main.h"
#include "Window.h"
#include "PathUtils.h"
#include "../io/TextReadWriter.h"
#include "../io/InitFile.h"
#include <vector>
#include <fstream>
#include <sstream>
using namespace engine;
using namespace base;
using namespace resources;
using namespace graphics;
using namespace utils;
using namespace io;
#define MAX_JSON_CHARS 1000000u
void SetupConsole()
{
AllocConsole();
FILE* newStdout = nullptr;
FILE* newStderr = nullptr;
FILE* newStdin = nullptr;
freopen_s(&newStdout, "CONOUT$", "w", stdout);
freopen_s(&newStderr, "CONOUT$", "w", stderr);
freopen_s(&newStdin, "CONIN$", "r", stdin);
}
std::optional<io::InitFile> LoadIni()
{
std::wstring initPath = GetPath(PATH_ROAMING) + L"/Jamma/defaults.json";
io::TextReadWriter txtFile;
auto res = txtFile.Read(initPath, MAX_JSON_CHARS);
std::string iniTxt = InitFile::DefaultJson;
if (!res.has_value())
txtFile.Write(initPath, iniTxt, (unsigned int)iniTxt.size(), 0);
else
{
auto [ini, numChars, unused] = res.value();
iniTxt = ini;
}
std::stringstream ss(iniTxt);
return InitFile::FromStream(std::move(ss));
}
std::optional<io::JamFile> LoadJam(io::InitFile& ini)
{
io::TextReadWriter txtFile;
std::string jamJson = JamFile::DefaultJson;
auto res = txtFile.Read(ini.Jam, MAX_JSON_CHARS);
if (!res.has_value())
{
ini.Jam = GetPath(PATH_ROAMING) + L"/Jamma/default.jam";
txtFile.Write(ini.Jam,
jamJson,
(unsigned int)jamJson.size(),
0);
}
else
{
auto [str, numChars, unused] = res.value();
jamJson = str;
}
std::stringstream ss(jamJson);
return JamFile::FromStream(std::move(ss));
}
std::optional<io::RigFile> LoadRig(io::InitFile& ini)
{
io::TextReadWriter txtFile;
std::string rigJson = RigFile::DefaultJson;
auto res = txtFile.Read(ini.Rig, MAX_JSON_CHARS);
if (!res.has_value())
{
ini.Rig = GetPath(PATH_ROAMING) + L"/Jamma/default.rig";
txtFile.Write(ini.Rig,
rigJson,
(unsigned int)rigJson.size(),
0);
}
else
{
auto [str, numChars, unused] = res.value();
rigJson = str;
}
std::stringstream ss(rigJson);
return RigFile::FromStream(std::move(ss));
}
int APIENTRY wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow)
{
SetupConsole();
auto defaults = LoadIni();
SceneParams sceneParams(DrawableParams{ "" }, SizeableParams{ 1400, 1000 });
JamFile jam;
RigFile rig;
if (defaults.has_value())
{
auto jamOpt = LoadJam(defaults.value());
if (jamOpt.has_value())
jam = jamOpt.value();
auto rigOpt = LoadRig(defaults.value());
if (rigOpt.has_value())
rig = rigOpt.value();
}
auto scene = Scene::FromFile(sceneParams, jam, rig, utils::GetParentDirectory(defaults.value().Jam));
if (!scene.has_value())
{
std::cout << "Failed to create Scene... quitting" << std::endl;
return -1;
}
ResourceLib resourceLib;
Window window(*(scene.value()), resourceLib);
if (window.Create(hInstance, nCmdShow) != 0)
PostQuitMessage(1);
scene.value()->InitAudio();
MSG msg;
bool active = true;
while (active)
{
while (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE))
{
if (msg.message == WM_QUIT)
{
scene.value()->CloseAudio();
active = false;
}
TranslateMessage(&msg);
DispatchMessage(&msg);
}
window.Render();
window.Swap();
}
window.Release();
return (int)msg.wParam;
}
| 21.579268 | 102 | 0.659226 | malisimo |
963d0d1765710ef2ae61413d844f2c50676cccab | 31,913 | cpp | C++ | CUSES/sources/CUSESImpl.cpp | metatoaster/cellml-api | d7baf9038e42859fa96117db6c9644f9f09ecf8b | [
"W3C"
] | 1 | 2016-10-19T14:48:20.000Z | 2016-10-19T14:48:20.000Z | CUSES/sources/CUSESImpl.cpp | metatoaster/cellml-api | d7baf9038e42859fa96117db6c9644f9f09ecf8b | [
"W3C"
] | 1 | 2016-12-05T09:20:14.000Z | 2016-12-05T18:08:05.000Z | CUSES/sources/CUSESImpl.cpp | metatoaster/cellml-api | d7baf9038e42859fa96117db6c9644f9f09ecf8b | [
"W3C"
] | 14 | 2015-07-27T13:45:54.000Z | 2022-02-02T05:19:53.000Z | #define IN_CUSES_MODULE
#define MODULE_CONTAINS_CUSES
#include "CUSESImpl.hpp"
#include "CUSESBootstrap.hpp"
#include "IfaceAnnoTools.hxx"
#include "AnnoToolsBootstrap.hpp"
#include <algorithm>
#include <cmath>
#undef max
CDAUserBaseUnit::CDAUserBaseUnit(iface::cellml_api::Units* aBaseUnits)
throw()
: mBaseUnits(aBaseUnits)
{
}
CDAUserBaseUnit::~CDAUserBaseUnit()
throw()
{
}
std::wstring
CDAUserBaseUnit::name()
throw(std::exception&)
{
return mBaseUnits->name();
}
already_AddRefd<iface::cellml_api::Units>
CDAUserBaseUnit::cellmlUnits()
throw(std::exception&)
{
mBaseUnits->add_ref();
return mBaseUnits.getPointer();
}
// Next, the built in base units. These get defined by macro...
#define BASE_UNIT(x) \
class CDABuiltinBaseUnit##x \
: public iface::cellml_services::BaseUnit \
{ \
public:\
void add_ref() throw() {} \
void release_ref() throw() {} \
CDA_IMPL_ID \
CDA_IMPL_QI1(cellml_services::BaseUnit) \
CDABuiltinBaseUnit##x() throw() {} \
~CDABuiltinBaseUnit##x() throw() {} \
\
std::wstring name() throw() { return L###x; } \
}; \
CDABuiltinBaseUnit##x gBuiltinBase##x;
BASE_UNIT(ampere);
BASE_UNIT(candela);
BASE_UNIT(kelvin);
BASE_UNIT(kilogram);
BASE_UNIT(metre);
BASE_UNIT(mole);
BASE_UNIT(second);
CDABaseUnitInstance::CDABaseUnitInstance
(
iface::cellml_services::BaseUnit* aBaseUnit,
double aPrefix,
double aOffset,
double aExponent
)
throw()
: mBaseUnit(aBaseUnit), mPrefix(aPrefix), mOffset(aOffset),
mExponent(aExponent)
{
}
CDABaseUnitInstance::~CDABaseUnitInstance()
throw()
{
}
already_AddRefd<iface::cellml_services::BaseUnit>
CDABaseUnitInstance::unit()
throw(std::exception&)
{
mBaseUnit->add_ref();
return mBaseUnit.getPointer();
}
double
CDABaseUnitInstance::prefix()
throw(std::exception&)
{
return mPrefix;
}
double
CDABaseUnitInstance::offset()
throw(std::exception&)
{
return mOffset;
}
double
CDABaseUnitInstance::exponent()
throw(std::exception&)
{
return mExponent;
}
CDACanonicalUnitRepresentation::CDACanonicalUnitRepresentation(bool aStrict)
throw()
: mStrict(aStrict), mCarry(1.0)
{
}
CDACanonicalUnitRepresentation::~CDACanonicalUnitRepresentation()
throw()
{
std::vector<iface::cellml_services::BaseUnitInstance*>::iterator i;
for (i = baseUnits.begin(); i != baseUnits.end(); i++)
(*i)->release_ref();
}
uint32_t
CDACanonicalUnitRepresentation::length()
throw(std::exception&)
{
return baseUnits.size();
}
already_AddRefd<iface::cellml_services::BaseUnitInstance>
CDACanonicalUnitRepresentation::fetchBaseUnit(uint32_t aIndex)
throw(std::exception&)
{
if (aIndex >= baseUnits.size())
throw iface::cellml_api::CellMLException(L"Attempt to fetch base unit at invalid index");
iface::cellml_services::BaseUnitInstance* bui = baseUnits[aIndex];
bui->add_ref();
return bui;
}
bool
CDACanonicalUnitRepresentation::compatibleWith
(
iface::cellml_services::CanonicalUnitRepresentation* aCompareWith
)
throw(std::exception&)
{
uint32_t l = length();
if (l != aCompareWith->length())
return false;
double mup1 = (unsafe_dynamic_cast<CDACanonicalUnitRepresentation*>(aCompareWith))->carry(),
mup2 = carry();
#ifdef DEBUG_UNITS
printf("carry1 = %g, carry2 = %g\n", mup1, mup2);
#endif
uint32_t i;
for (i = 0; i < l; i++)
{
RETURN_INTO_OBJREF(bui1, iface::cellml_services::BaseUnitInstance,
aCompareWith->fetchBaseUnit(i));
iface::cellml_services::BaseUnitInstance* bui2 = baseUnits[i];
RETURN_INTO_OBJREF(u1, iface::cellml_services::BaseUnit, bui1->unit());
RETURN_INTO_OBJREF(u2, iface::cellml_services::BaseUnit, bui2->unit());
if (CDA_objcmp(u1, u2) != 0)
return false;
if (bui1->exponent() != bui2->exponent())
return false;
if (mStrict && (bui1->offset() != bui2->offset()))
return false;
mup1 *= bui1->prefix();
mup2 *= bui2->prefix();
}
if (mStrict)
{
if (mup1 > mup2)
{
double tmp = mup1;
mup1 = mup2;
mup2 = tmp;
}
double mupErr = mup2 / mup1 - 1.0;
#ifdef DEBUG_UNITS
printf("mup1=%g, mup2=%g, mupErr = %g\n", mup1, mup2, mup2 / mup1 - 1.0);
#endif
if (mupErr > 1E-15)
{
#ifdef DEBUG_UNITS
printf("normErr too big: %g; mup1 = %g, mup2 = %g\n", mupErr, mup1, mup2);
#endif
return false;
}
}
return true;
}
double
CDACanonicalUnitRepresentation::convertUnits
(
iface::cellml_services::CanonicalUnitRepresentation* aCompareWith,
double* aOffset
)
throw(std::exception&)
{
double m1, m2, o1, o2;
m1 = siConversion(&o1);
m2 = aCompareWith->siConversion(&o2);
double fac = m1/m2;
*aOffset = o1 - fac * o2;
return fac;
}
double
CDACanonicalUnitRepresentation::siConversion
(
double* aOffset
)
throw(std::exception&)
{
uint32_t l = length();
if (l == 1 && baseUnits[0]->exponent() == 1.0)
{
double o, m;
o = baseUnits[0]->offset();
m = baseUnits[0]->prefix();
*aOffset = -o / m;
return 1.0 / m;
}
*aOffset = 0.0;
double ret = 1.0;
uint32_t i;
for (i = 0; i < l; i++)
{
iface::cellml_services::BaseUnitInstance* bui = baseUnits[i];
ret *= bui->prefix();
}
return 1.0 / ret;
}
struct CanonicalUnitComparator
{
public:
bool
operator ()(iface::cellml_services::BaseUnitInstance* x,
iface::cellml_services::BaseUnitInstance* y)
{
RETURN_INTO_OBJREF(xu, iface::cellml_services::BaseUnit,
x->unit());
RETURN_INTO_OBJREF(yu, iface::cellml_services::BaseUnit,
y->unit());
int ret = CDA_objcmp(xu, yu);
if (ret != 0)
return (ret < 0);
// We have two identical units, but in strict mode this is a perfectly
// valid final state. Sort by prefix...
return (x->prefix() < y->prefix());
}
};
void
CDACanonicalUnitRepresentation::canonicalise()
throw(std::exception&)
{
CanonicalUnitComparator cuc;
std::sort(baseUnits.begin(), baseUnits.end(), cuc);
bool anyChanges = false;
std::vector<iface::cellml_services::BaseUnitInstance*> newBaseUnits;
uint32_t l = length();
uint32_t i;
iface::cellml_services::BaseUnitInstance *uThis;
ObjRef<iface::cellml_services::BaseUnitInstance> uLast;
#ifdef DEBUG_UNITS
if (mCarry != 1.0)
printf("Canonicalise starting with carry: %g\n", mCarry);
#endif
for (i = 0; i < l; i++)
{
uThis = baseUnits[i];
RETURN_INTO_OBJREF(buThis, iface::cellml_services::BaseUnit,
uThis->unit());
if (uLast != NULL)
{
RETURN_INTO_OBJREF(buLast, iface::cellml_services::BaseUnit,
uLast->unit());
if (CDA_objcmp(buLast, buThis) == 0)
{
anyChanges = true;
double newPref = uThis->prefix() * uLast->prefix();
double newExp = uThis->exponent() + uLast->exponent();
if (!newBaseUnits.empty())
{
newBaseUnits.back()->release_ref();
newBaseUnits.pop_back();
}
if (newExp != 0)
{
uLast = new CDABaseUnitInstance(buThis, newPref, 0.0, newExp);
newBaseUnits.push_back(uLast);
}
else
mCarry *= newPref;
continue;
}
}
uThis->add_ref();
newBaseUnits.push_back(uThis);
uLast = uThis;
}
if (mCarry != 1.0 && !newBaseUnits.empty())
{
iface::cellml_services::BaseUnitInstance* fix = newBaseUnits[0];
RETURN_INTO_OBJREF(buFix, iface::cellml_services::BaseUnit,
fix->unit());
#ifdef DEBUG_UNITS
printf("Retrospectively applying carry %g\n", mCarry);
printf("New prefix for first item: %g\n", fix->prefix() * mCarry);
#endif
newBaseUnits[0] = new CDABaseUnitInstance(buFix, fix->prefix() * mCarry,
fix->offset(), fix->exponent());
anyChanges = true;
mCarry = 1.0;
fix->release_ref();
}
#ifdef DEBUG_UNITS
if (mCarry != 1.0)
printf("Carry saved for next invocation.\n");
#endif
if (anyChanges)
{
std::vector<iface::cellml_services::BaseUnitInstance*>::iterator i;
for (i = baseUnits.begin(); i != baseUnits.end(); i++)
(*i)->release_ref();
baseUnits = newBaseUnits;
}
else
{
std::vector<iface::cellml_services::BaseUnitInstance*>::iterator i;
for (i = newBaseUnits.begin(); i != newBaseUnits.end(); i++)
(*i)->release_ref();
}
}
void
CDACanonicalUnitRepresentation::addBaseUnit
(
iface::cellml_services::BaseUnitInstance* baseUnit
) throw()
{
baseUnit->add_ref();
baseUnits.push_back(baseUnit);
}
already_AddRefd<iface::cellml_services::CanonicalUnitRepresentation>
CDACanonicalUnitRepresentation::mergeWith
(
double aThisExponent,
iface::cellml_services::CanonicalUnitRepresentation* aOther,
double aOtherExponent
)
throw(std::exception&)
{
#ifdef DEBUG_UNITS
printf("mergeWith %g %g\n", aThisExponent, aOtherExponent);
#endif
RETURN_INTO_OBJREF(uNew, CDACanonicalUnitRepresentation,
new CDACanonicalUnitRepresentation(mStrict));
if (aOtherExponent != 0 && aOther == NULL)
throw iface::cellml_api::CellMLException(L"Attempt to merge NULL unit using non-zero exponent");
if (aThisExponent != 0)
{
uint32_t l = length();
for (uint32_t i = 0; i < l; i++)
{
RETURN_INTO_OBJREF(bu, iface::cellml_services::BaseUnitInstance,
fetchBaseUnit(i));
#ifdef DEBUG_UNITS
{
RETURN_INTO_OBJREF(u, iface::cellml_services::BaseUnit, bu->unit());
RETURN_INTO_WSTRING(n, u->name());
printf(" Current: %g %S ^ %g\n", bu->prefix(), n.c_str(), bu->exponent());
}
#endif
if (aThisExponent == 1)
uNew->addBaseUnit(bu);
else
{
RETURN_INTO_OBJREF(u, iface::cellml_services::BaseUnit, bu->unit());
RETURN_INTO_OBJREF(bui, iface::cellml_services::BaseUnitInstance,
new CDABaseUnitInstance
(u, pow(bu->prefix(), aThisExponent), bu->offset(),
bu->exponent() * aThisExponent));
uNew->addBaseUnit(bui);
}
}
#ifdef DEBUG_UNITS
if (carry() != 1.0)
printf("Building uNew, current carry %g\n", carry());
#endif
uNew->carry(pow(carry(), aThisExponent));
}
if (aOtherExponent != 0)
{
uint32_t l = aOther->length();
for (uint32_t i = 0; i < l; i++)
{
RETURN_INTO_OBJREF(bu, iface::cellml_services::BaseUnitInstance,
aOther->fetchBaseUnit(i));
#ifdef DEBUG_UNITS
{
RETURN_INTO_OBJREF(u, iface::cellml_services::BaseUnit, bu->unit());
RETURN_INTO_WSTRING(n, u->name());
printf(" Other: %g %S ^ %g\n", bu->prefix(), n.c_str(), bu->exponent());
}
#endif
if (aOtherExponent == 1 && bu->offset() == 0)
uNew->addBaseUnit(bu);
else
{
RETURN_INTO_OBJREF(u, iface::cellml_services::BaseUnit, bu->unit());
RETURN_INTO_OBJREF(bui, iface::cellml_services::BaseUnitInstance,
new CDABaseUnitInstance
(u, pow(bu->prefix(), aOtherExponent), 0,
bu->exponent() * aOtherExponent));
uNew->addBaseUnit(bui);
}
}
#ifdef DEBUG_UNITS
if (unsafe_dynamic_cast<CDACanonicalUnitRepresentation*>
(aOther)->carry() != 1.0)
printf("Building uNew, current carry %g\n", carry());
#endif
uNew->carry(uNew->carry() * pow(unsafe_dynamic_cast<CDACanonicalUnitRepresentation*>
(aOther)->carry(), aOtherExponent));
}
uNew->canonicalise();
iface::cellml_services::CanonicalUnitRepresentation* cur = uNew;
cur->add_ref();
return cur;
}
template<typename C>
class IObjectListDestroyer
{
public:
IObjectListDestroyer(C& aList)
: mList(aList)
{
}
~IObjectListDestroyer()
{
typename C::iterator i;
for (i = mList.begin(); i != mList.end(); i++)
(*i)->release_ref();
}
private:
C& mList;
};
CDACUSES::CDACUSES(iface::cellml_api::Model* aModel, bool aStrict)
throw()
: mStrict(aStrict)
{
PopulateBuiltinUnits();
RETURN_INTO_OBJREF(ats, iface::cellml_services::AnnotationToolService,
CreateAnnotationToolService());
RETURN_INTO_OBJREF(cusesAS, iface::cellml_services::AnnotationSet,
ats->createAnnotationSet());
ScopeMap<iface::cellml_api::Units> unitsMap;
try
{
aModel->fullyInstantiateImports();
}
catch (...)
{
errorDescription += L"Could not load all imports;";
return;
}
RETURN_INTO_OBJREF(us, iface::cellml_api::UnitsSet,
aModel->allUnits());
RETURN_INTO_OBJREF(ui, iface::cellml_api::UnitsIterator,
us->iterateUnits());
std::list<iface::cellml_api::Units*> unitsList;
IObjectListDestroyer<std::list<iface::cellml_api::Units*> >
unitsListDestroyer(unitsList);
while (true)
{
RETURN_INTO_OBJREF(u, iface::cellml_api::Units, ui->nextUnits());
if (u == NULL)
break;
u->add_ref();
unitsList.push_back(u);
}
RETURN_INTO_OBJREF(ccs, iface::cellml_api::CellMLComponentSet,
aModel->allComponents());
RETURN_INTO_OBJREF(ci, iface::cellml_api::CellMLComponentIterator,
ccs->iterateComponents());
while (true)
{
RETURN_INTO_OBJREF(c, iface::cellml_api::CellMLComponent,
ci->nextComponent());
if (c == NULL)
break;
us = already_AddRefd<iface::cellml_api::UnitsSet>(c->units());
ui = already_AddRefd<iface::cellml_api::UnitsIterator>(us->iterateUnits());
while (true)
{
RETURN_INTO_OBJREF(u, iface::cellml_api::Units, ui->nextUnits());
if (u == NULL)
break;
u->add_ref();
unitsList.push_back(u);
}
}
std::list<iface::cellml_api::Units*>::iterator i;
for (i = unitsList.begin(); i != unitsList.end(); i++)
{
iface::cellml_api::Units* u = *i;
u->add_ref();
unitsMap->insert(std::pair<std::wstring, iface::cellml_api::Units*>
(getUnitScope(u), u));
RETURN_INTO_WSTRING(currentName, u->name());
ObjRef<iface::cellml_api::CellMLElement> el(u);
while (true)
{
RETURN_INTO_OBJREF(par, iface::cellml_api::CellMLElement,
el->parentElement());
if (par == NULL)
break;
el = par;
DECLARE_QUERY_INTERFACE_OBJREF(imp, el, cellml_api::CellMLImport);
if (imp == NULL)
continue;
RETURN_INTO_OBJREF(ius, iface::cellml_api::ImportUnitsSet,
imp->units());
RETURN_INTO_OBJREF(iui, iface::cellml_api::ImportUnitsIterator,
ius->iterateImportUnits());
bool hit = false;
while (true)
{
RETURN_INTO_OBJREF(iu, iface::cellml_api::ImportUnits,
iui->nextImportUnits());
if (iu == NULL)
break;
RETURN_INTO_WSTRING(unitsRef, iu->unitsRef());
if (unitsRef == currentName)
{
currentName = iu->name();
RETURN_INTO_OBJREF(mod, iface::cellml_api::CellMLElement,
imp->parentElement());
std::wstring scopedName(getUnitScope(mod));
if (scopedName != L"")
scopedName += L'/';
scopedName += currentName;
u->add_ref();
unitsMap->insert(std::pair<std::wstring, iface::cellml_api::Units*>
(scopedName, u));
hit = true;
break;
}
}
if (!hit)
break;
}
}
RETURN_INTO_OBJREF(sentinel, UnitDependencies, new UnitDependencies());
std::multimap<std::wstring, iface::cellml_api::Units*>::const_iterator umi;
for (umi = unitsMap->begin(); umi != unitsMap->end(); umi++)
{
RETURN_INTO_OBJREF(depsX, iface::XPCOM::IObject,
cusesAS->getObjectAnnotation((*umi).second, L"dependencies"));
// Only need to annotate each unit once...
if (depsX != NULL)
{
dynamic_cast<UnitDependencies*>(depsX.getPointer())->scopes.
push_back((*umi).first);
continue;
}
sentinel->addDependency((*umi).second);
RETURN_INTO_OBJREF(deps, UnitDependencies, new UnitDependencies());
cusesAS->setObjectAnnotation((*umi).second, L"dependencies", deps);
deps->name = (*umi).second->name();
deps->scopes.push_back((*umi).first);
RETURN_INTO_OBJREF(us, iface::cellml_api::UnitSet,
(*umi).second->unitCollection());
RETURN_INTO_OBJREF(ui, iface::cellml_api::UnitIterator, us->iterateUnits());
while (true)
{
RETURN_INTO_OBJREF(un, iface::cellml_api::Unit, ui->nextUnit());
if (un == NULL)
break;
RETURN_INTO_WSTRING(uname, un->units());
if (uname == L"")
{
warningDescription += L"Found a unit with no units attribute in units ";
warningDescription += deps->name;
warningDescription += L"; ";
continue;
}
iface::cellml_api::Units* ufound =
scopedFind(unitsMap, (*umi).second, uname);
if (ufound == NULL && BuiltinUnit(uname))
continue;
if (ufound == NULL)
{
errorDescription += L"Units ";
RETURN_INTO_WSTRING(refu, (*umi).second->name());
errorDescription += refu;
errorDescription += L" references units ";
errorDescription += uname;
errorDescription += L" but the latter units could not be found";
errorDescription += L"; ";
continue;
}
deps->addDependency(ufound);
}
}
if (errorDescription != L"")
{
return;
}
// DFS visit all units...
dfsResolveUnits(cusesAS, sentinel);
}
CDACUSES::~CDACUSES()
throw()
{
}
template<class C>
C*
CDACUSES::scopedFind
(
ScopeMap<C>& aMap,
iface::cellml_api::CellMLElement* aContext,
const std::wstring& aName
)
{
std::wstring contextScope = getUnitScope(aContext);
while (true)
{
std::wstring full = contextScope;
if (contextScope != L"")
full += L'/';
full += aName;
typename std::multimap<std::wstring, C*>::iterator i(aMap->find(full));
if (i != aMap->end())
return (*i).second;
size_t idx = contextScope.rfind(L'/');
if (idx == std::wstring::npos)
{
if (contextScope == L"")
break;
contextScope = L"";
}
else
contextScope = contextScope.substr(0, idx);
}
return NULL;
}
std::wstring
CDACUSES::getUnitScope(iface::cellml_api::CellMLElement* aContext)
{
std::wstring scope;
ObjRef<iface::cellml_api::CellMLElement> cur(aContext);
DECLARE_QUERY_INTERFACE_OBJREF(u, aContext, cellml_api::Units);
if (u != NULL)
scope = u->name();
do
{
DECLARE_QUERY_INTERFACE_OBJREF(comp, cur, cellml_api::CellMLComponent);
if (comp)
{
RETURN_INTO_WSTRING(sc, comp->name());
std::wstring newScope = L"comp_";
newScope += sc;
if (scope != L"")
newScope += L'/';
scope = newScope + scope;
}
else
{
DECLARE_QUERY_INTERFACE_OBJREF(imp, cur, cellml_api::CellMLImport);
if (imp != NULL)
{
// We name the import by the first import component, or if there is no
// such component, by the first import unit.
RETURN_INTO_OBJREF(ics, iface::cellml_api::ImportComponentSet,
imp->components());
RETURN_INTO_OBJREF(ici, iface::cellml_api::ImportComponentIterator,
ics->iterateImportComponents());
RETURN_INTO_OBJREF(ic, iface::cellml_api::ImportComponent,
ici->nextImportComponent());
if (ic == NULL)
{
RETURN_INTO_OBJREF(ius, iface::cellml_api::ImportUnitsSet,
imp->units());
RETURN_INTO_OBJREF(iui, iface::cellml_api::ImportUnitsIterator,
ius->iterateImportUnits());
RETURN_INTO_OBJREF(iu, iface::cellml_api::ImportUnits,
iui->nextImportUnits());
if (iu != NULL)
{
RETURN_INTO_WSTRING(sc, iu->name());
std::wstring newScope = L"imp_byunits_";
newScope += sc;
if (scope != L"")
newScope += L'/';
scope = newScope + scope;
}
}
else
{
RETURN_INTO_WSTRING(sc, ic->name());
std::wstring newScope = L"imp_bycomp_";
newScope += sc;
if (scope != L"")
newScope += L'/';
scope = newScope + scope;
}
}
}
RETURN_INTO_OBJREF(par, iface::cellml_api::CellMLElement,
cur->parentElement());
cur = par;
}
while (cur != NULL);
return scope;
}
bool
CDACUSES::BuiltinUnit(std::wstring& aName)
{
// ampere farad katal lux pascal tesla
// becquerel gram kelvin meter radian volt
// candela gray kilogram metre second watt
// celsius henry liter mole siemens weber
// coulomb hertz litre newton sievert
// dimensionless joule lumen ohm steradian
if (aName[0] < L'l')
{
if (aName[0] < L'g')
{
if (aName[0] == 'c')
{
if (aName[1] == 'a')
return aName == L"candela";
else if (aName[1] == 'e')
return aName == L"celsius";
else
return aName == L"coulomb";
}
else if (aName[0] <= 'b')
{
if (aName[0] == 'a')
return aName == L"ampere";
else
return aName == L"becquerel";
}
else if (aName[0] == 'd')
{
return aName == L"dimensionless";
}
else
return aName == L"farad";
}
else if (aName[0] < L'k')
{
if (aName[0] == L'g')
return (aName.size() == 4 &&
aName[1] == L'r' && aName[2] == L'a' &&
(aName[3] == L'm' || aName[3] == L'y'));
else if (aName[0] == L'j')
return aName == L"joule";
else if (aName[1] == L'e')
{
if (aName[2] == 'n')
return aName == L"henry";
else
return aName == L"hertz";
}
else
return false;
}
else if (aName[1] < L'i')
{
if (aName[1] == L'a')
return aName == L"katal";
else
return aName == L"kelvin";
}
else
return aName == L"kilogram";
}
else if (aName[0] < L'p')
{
if (aName[0] == L'l')
{
if (aName[1] == L'i')
{
if (aName[2] != L't' ||
aName.size() != 5)
return false;
return (aName[3] == L'e' && aName[4] == L'r') ||
(aName[3] == L'r' && aName[4] == L'e');
}
else if (aName[1] == L'u')
{
if (aName[2] == 'm')
return aName == L"lumen";
else
return aName == L"lux";
}
else
return false;
}
else if (aName[0] == L'm')
{
if (aName[1] == L'e')
{
if (aName[2] != L't' || aName.size() != 5)
return false;
return (aName[3] == L'r' && aName[4] == L'e') ||
(aName[3] == L'e' && aName[4] == L'r');
}
else
return aName == L"mole";
}
else if (aName[0] == L'n')
return aName == L"newton";
else
return aName == L"ohm";
}
else if (aName[0] < L't')
{
if (aName[0] == L's')
{
if (aName[1] == L'i')
{
if (aName[2] != L'e')
return false;
if (aName[3] == L'm')
return aName == L"siemens";
else
return aName == L"sievert";
}
else if (aName[1] == L'e')
return aName == L"second";
else
return aName == L"steradian";
}
else if (aName[0] == L'p')
return aName == L"pascal";
else
return aName == L"radian";
}
else if (aName[0] < L'w')
{
if (aName[0] == L't')
return aName == L"tesla";
else
return aName == L"volt";
}
else if (aName[1] == L'a')
return aName == L"watt";
else
return aName == L"weber";
}
bool
CDACUSES::dfsResolveUnits(iface::cellml_services::AnnotationSet* cusesAS,
UnitDependencies* search)
{
if (search->done)
return true;
if (search->seen)
{
errorDescription += L"Units are defined circularly. One unit in the "
L"cycle is ";
errorDescription += search->name;
errorDescription += L"; ";
return false;
}
std::list<iface::cellml_api::Units*>::iterator i;
search->seen = true;
for (i = search->dependencies.begin(); i != search->dependencies.end(); i++)
{
// Instantiate first, then add the unit...
iface::cellml_api::Units* u = *i;
RETURN_INTO_OBJREF(depsX, iface::XPCOM::IObject,
cusesAS->getObjectAnnotation(*i, L"dependencies"));
UnitDependencies* deps = dynamic_cast<UnitDependencies*>(depsX.getPointer());
if (!dfsResolveUnits(cusesAS, deps))
return false;
ComputeUnits(deps, u);
}
search->done = true;
return true;
}
void
CDACUSES::PopulateBuiltinUnits()
{
#define BUILTIN_UNIT(name, x) \
{ \
RETURN_INTO_OBJREF(cu, CDACanonicalUnitRepresentation, \
new CDACanonicalUnitRepresentation(mStrict)); \
x \
cu->canonicalise(); \
mUnitsMap->insert(std::pair<std::wstring, CDACanonicalUnitRepresentation*> \
(L###name, cu)); \
cu->add_ref(); \
}
#define DERIVES(name, factor, exponent, offset) \
{ \
RETURN_INTO_OBJREF(bui, CDABaseUnitInstance, \
new CDABaseUnitInstance(&gBuiltinBase##name, factor, offset, exponent)); \
cu->addBaseUnit(bui); \
}
BUILTIN_UNIT(ampere, DERIVES(ampere, 1, 1, 0));
BUILTIN_UNIT(becquerel, DERIVES(second, 1, -1, 0));
BUILTIN_UNIT(candela, DERIVES(candela, 1, 1, 0));
BUILTIN_UNIT(celsius, DERIVES(kelvin, 1, 1, -273.15));
BUILTIN_UNIT(coulomb, DERIVES(ampere, 1, 1, 0) DERIVES(second, 1, 1, 0));
BUILTIN_UNIT(dimensionless, ;);
BUILTIN_UNIT(farad , DERIVES(metre, 1, -2, 0) DERIVES(kilogram, 1, -1, 0) DERIVES(second, 1, 4, 0) DERIVES(ampere, 1, 2, 0));
BUILTIN_UNIT(gram, DERIVES(kilogram, 1000, 1, 0));
BUILTIN_UNIT(gray, DERIVES(metre, 1, 2, 0) DERIVES(second, 1, -2, 0));
BUILTIN_UNIT(henry, DERIVES(metre, 1, 2, 0) DERIVES(kilogram, 1, 1, 0) DERIVES(second, 1, -2, 0) DERIVES(ampere, 1, -2, 0));
BUILTIN_UNIT(hertz, DERIVES(second, 1, -1, 0));
BUILTIN_UNIT(joule, DERIVES(metre, 1, 2, 0) DERIVES(kilogram, 1, 1, 0) DERIVES(second, 1, -2, 0));
BUILTIN_UNIT(katal, DERIVES(second, 1, -1, 0) DERIVES(mole, 1, 1, 0));
BUILTIN_UNIT(kelvin, DERIVES(kelvin, 1, 1, 0));
BUILTIN_UNIT(kilogram, DERIVES(kilogram, 1, 1, 0));
BUILTIN_UNIT(liter, DERIVES(metre, 1000, 3, 0));
BUILTIN_UNIT(litre, DERIVES(metre, 1000, 3, 0));
BUILTIN_UNIT(lumen, DERIVES(candela, 1, 1, 0));
BUILTIN_UNIT(lux, DERIVES(candela, 1, 1, 0) DERIVES(metre, 1, -2, 0));
BUILTIN_UNIT(meter, DERIVES(metre, 1, 1, 0));
BUILTIN_UNIT(metre, DERIVES(metre, 1, 1, 0));
BUILTIN_UNIT(mole, DERIVES(mole, 1, 1, 0));
BUILTIN_UNIT(newton, DERIVES(metre, 1, 1, 0) DERIVES(kilogram, 1, 1, 0) DERIVES(second, 1, -2, 0));
BUILTIN_UNIT(ohm, DERIVES(metre, 1, 2, 0) DERIVES(kilogram, 1, 1, 0) DERIVES(second, 1, -3, 0) DERIVES(ampere, 1, -2, 0));
BUILTIN_UNIT(pascal, DERIVES(metre, 1, -1, 0) DERIVES(kilogram, 1, 1, 0) DERIVES(second, 1, -2, 0));
BUILTIN_UNIT(radian, ;);
BUILTIN_UNIT(second, DERIVES(second, 1, 1, 0));
BUILTIN_UNIT(siemens, DERIVES(metre, 1, -2, 0) DERIVES(kilogram, 1, -1, 0) DERIVES(second, 1, 3, 0) DERIVES(ampere, 1, 2, 0));
BUILTIN_UNIT(sievert, DERIVES(metre, 1, 2, 0) DERIVES(second, 1, -2, 0));
BUILTIN_UNIT(steradian, ;);
BUILTIN_UNIT(tesla, DERIVES(kilogram, 1, 1, 0) DERIVES(second, 1, -2, 0) DERIVES(ampere, 1, -1, 0));
BUILTIN_UNIT(volt, DERIVES(metre, 1, 2, 0) DERIVES(kilogram, 1, 1, 0) DERIVES(second, 1, -3, 0) DERIVES(ampere, 1, -1, 0));
BUILTIN_UNIT(watt, DERIVES(metre, 1, 2, 0) DERIVES(kilogram, 1, 1, 0) DERIVES(second, 1, -3, 0));
BUILTIN_UNIT(weber, DERIVES(metre, 1, 2, 0) DERIVES(kilogram, 1, 1, 0) DERIVES(second, 1, -2, 0) DERIVES(ampere, 1, -1, 0));
#undef DERIVES
#undef BUILTIN_UNIT
}
void
CDACUSES::ComputeUnits
(
UnitDependencies* context,
iface::cellml_api::Units* units
)
{
RETURN_INTO_OBJREF(newrep, CDACanonicalUnitRepresentation,
new CDACanonicalUnitRepresentation(mStrict));
if (units->isBaseUnits())
{
RETURN_INTO_OBJREF(ubu, iface::cellml_services::UserBaseUnit,
new CDAUserBaseUnit(units));
RETURN_INTO_OBJREF(nbu, iface::cellml_services::BaseUnitInstance,
new CDABaseUnitInstance(ubu, 1.0, 0.0,
1.0));
newrep->addBaseUnit(nbu);
}
else
{
// All units defined in units should now exist (it is an internal error if
// not), so use this to define the current unit.
RETURN_INTO_OBJREF(us, iface::cellml_api::UnitSet,
units->unitCollection());
RETURN_INTO_OBJREF(ui, iface::cellml_api::UnitIterator,
us->iterateUnits());
while (true)
{
RETURN_INTO_OBJREF(u, iface::cellml_api::Unit,
ui->nextUnit());
if (u == NULL)
break;
// Find the unit...
RETURN_INTO_WSTRING(uname, u->units());
if (uname == L"")
continue;
RETURN_INTO_OBJREF(urep, iface::cellml_services::CanonicalUnitRepresentation,
getUnitsByName(units, uname.c_str()));
// If urep is null, then something is wrong internally, because we have
// already checked the names are valid and resolved all dependency names.
uint32_t l = urep->length();
uint32_t i;
for (i = 0; i < l; i++)
{
RETURN_INTO_OBJREF(bu, iface::cellml_services::BaseUnitInstance,
urep->fetchBaseUnit(i));
double newExponent = u->exponent() * bu->exponent();
double newPrefix;
if (i == 0)
newPrefix = u->multiplier() *
pow(pow(10.0, -u->prefix()) * bu->prefix(), u->exponent());
else
newPrefix = pow(bu->prefix(), u->exponent());
double newOffset;
if (i == 0)
newOffset = u->offset() * pow(bu->prefix(), u->exponent()) + bu->offset();
else
newOffset = bu->offset();
RETURN_INTO_OBJREF(ub, iface::cellml_services::BaseUnit,
bu->unit());
RETURN_INTO_OBJREF(nbu, iface::cellml_services::BaseUnitInstance,
new CDABaseUnitInstance(ub, newPrefix, newOffset,
newExponent));
newrep->addBaseUnit(nbu);
}
}
newrep->canonicalise();
}
std::list<std::wstring>::iterator i(context->scopes.begin());
for (; i != context->scopes.end(); i++)
{
mUnitsMap->insert(std::pair<std::wstring, CDACanonicalUnitRepresentation*>
(*i, newrep.getPointer()));
newrep->add_ref();
}
}
already_AddRefd<iface::cellml_services::CanonicalUnitRepresentation>
CDACUSES::getUnitsByName
(
iface::cellml_api::CellMLElement* aContext,
const std::wstring& aName
)
throw(std::exception&)
{
iface::cellml_services::CanonicalUnitRepresentation* cur =
scopedFind(mUnitsMap, aContext, aName);
if (cur != NULL)
cur->add_ref();
return cur;
}
std::wstring
CDACUSES::modelError()
throw(std::exception&)
{
std::wstring tot = errorDescription;
tot += warningDescription;
return tot;
}
already_AddRefd<iface::cellml_services::CanonicalUnitRepresentation>
CDACUSES::createEmptyUnits()
throw(std::exception&)
{
return new CDACanonicalUnitRepresentation(mStrict);
}
iface::cellml_services::CUSESBootstrap*
CreateCUSESBootstrap(void)
{
return new CDACUSESBootstrap();
}
| 26.999154 | 126 | 0.595713 | metatoaster |
963dcd8af32b7cb003615fae9eff7ef1218cdbf1 | 9,674 | cpp | C++ | openmp/libomptarget/src/interop.cpp | LaudateCorpus1/llvm-project | ff2e0f0c1112558b3f30d8afec7c9882c33c79e3 | [
"Apache-2.0"
] | null | null | null | openmp/libomptarget/src/interop.cpp | LaudateCorpus1/llvm-project | ff2e0f0c1112558b3f30d8afec7c9882c33c79e3 | [
"Apache-2.0"
] | null | null | null | openmp/libomptarget/src/interop.cpp | LaudateCorpus1/llvm-project | ff2e0f0c1112558b3f30d8afec7c9882c33c79e3 | [
"Apache-2.0"
] | null | null | null | //===---------------interop.cpp - Implementation of interop directive -----===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "interop.h"
#include "private.h"
namespace {
omp_interop_rc_t getPropertyErrorType(omp_interop_property_t Property) {
switch (Property) {
case omp_ipr_fr_id:
return omp_irc_type_int;
case omp_ipr_fr_name:
return omp_irc_type_str;
case omp_ipr_vendor:
return omp_irc_type_int;
case omp_ipr_vendor_name:
return omp_irc_type_str;
case omp_ipr_device_num:
return omp_irc_type_int;
case omp_ipr_platform:
return omp_irc_type_int;
case omp_ipr_device:
return omp_irc_type_ptr;
case omp_ipr_device_context:
return omp_irc_type_ptr;
case omp_ipr_targetsync:
return omp_irc_type_ptr;
};
return omp_irc_no_value;
}
void getTypeMismatch(omp_interop_property_t Property, int *Err) {
if (Err)
*Err = getPropertyErrorType(Property);
}
const char *getVendorIdToStr(const omp_foreign_runtime_ids_t VendorId) {
switch (VendorId) {
case cuda:
return ("cuda");
case cuda_driver:
return ("cuda_driver");
case opencl:
return ("opencl");
case sycl:
return ("sycl");
case hip:
return ("hip");
case level_zero:
return ("level_zero");
}
return ("unknown");
}
template <typename PropertyTy>
PropertyTy getProperty(omp_interop_val_t &InteropVal,
omp_interop_property_t Property, int *Err);
template <>
intptr_t getProperty<intptr_t>(omp_interop_val_t &interop_val,
omp_interop_property_t property, int *err) {
switch (property) {
case omp_ipr_fr_id:
return interop_val.backend_type_id;
case omp_ipr_vendor:
return interop_val.vendor_id;
case omp_ipr_device_num:
return interop_val.device_id;
default:;
}
getTypeMismatch(property, err);
return 0;
}
template <>
const char *getProperty<const char *>(omp_interop_val_t &interop_val,
omp_interop_property_t property,
int *err) {
switch (property) {
case omp_ipr_fr_id:
return interop_val.interop_type == kmp_interop_type_tasksync
? "tasksync"
: "device+context";
case omp_ipr_vendor_name:
return getVendorIdToStr(interop_val.vendor_id);
default:
getTypeMismatch(property, err);
return nullptr;
}
}
template <>
void *getProperty<void *>(omp_interop_val_t &interop_val,
omp_interop_property_t property, int *err) {
switch (property) {
case omp_ipr_device:
if (interop_val.device_info.Device)
return interop_val.device_info.Device;
*err = omp_irc_no_value;
return const_cast<char *>(interop_val.err_str);
case omp_ipr_device_context:
return interop_val.device_info.Context;
case omp_ipr_targetsync:
return interop_val.async_info->Queue;
default:;
}
getTypeMismatch(property, err);
return nullptr;
}
bool getPropertyCheck(omp_interop_val_t **interop_ptr,
omp_interop_property_t property, int *err) {
if (err)
*err = omp_irc_success;
if (!interop_ptr) {
if (err)
*err = omp_irc_empty;
return false;
}
if (property >= 0 || property < omp_ipr_first) {
if (err)
*err = omp_irc_out_of_range;
return false;
}
if (property == omp_ipr_targetsync &&
(*interop_ptr)->interop_type != kmp_interop_type_tasksync) {
if (err)
*err = omp_irc_other;
return false;
}
if ((property == omp_ipr_device || property == omp_ipr_device_context) &&
(*interop_ptr)->interop_type == kmp_interop_type_tasksync) {
if (err)
*err = omp_irc_other;
return false;
}
return true;
}
} // namespace
#define __OMP_GET_INTEROP_TY(RETURN_TYPE, SUFFIX) \
RETURN_TYPE omp_get_interop_##SUFFIX(const omp_interop_t interop, \
omp_interop_property_t property_id, \
int *err) { \
omp_interop_val_t *interop_val = (omp_interop_val_t *)interop; \
assert((interop_val)->interop_type == kmp_interop_type_tasksync); \
if (!getPropertyCheck(&interop_val, property_id, err)) { \
return (RETURN_TYPE)(0); \
} \
return getProperty<RETURN_TYPE>(*interop_val, property_id, err); \
}
__OMP_GET_INTEROP_TY(intptr_t, int)
__OMP_GET_INTEROP_TY(void *, ptr)
__OMP_GET_INTEROP_TY(const char *, str)
#undef __OMP_GET_INTEROP_TY
#define __OMP_GET_INTEROP_TY3(RETURN_TYPE, SUFFIX) \
RETURN_TYPE omp_get_interop_##SUFFIX(const omp_interop_t interop, \
omp_interop_property_t property_id) { \
int err; \
omp_interop_val_t *interop_val = (omp_interop_val_t *)interop; \
if (!getPropertyCheck(&interop_val, property_id, &err)) { \
return (RETURN_TYPE)(0); \
} \
return nullptr; \
return getProperty<RETURN_TYPE>(*interop_val, property_id, &err); \
}
__OMP_GET_INTEROP_TY3(const char *, name)
__OMP_GET_INTEROP_TY3(const char *, type_desc)
__OMP_GET_INTEROP_TY3(const char *, rc_desc)
#undef __OMP_GET_INTEROP_TY3
typedef int64_t kmp_int64;
#ifdef __cplusplus
extern "C" {
#endif
void __tgt_interop_init(ident_t *loc_ref, kmp_int32 gtid,
omp_interop_val_t *&interop_ptr,
kmp_interop_type_t interop_type, kmp_int32 device_id,
kmp_int64 ndeps, kmp_depend_info_t *dep_list,
kmp_int32 have_nowait) {
kmp_int32 ndeps_noalias = 0;
kmp_depend_info_t *noalias_dep_list = NULL;
assert(interop_type != kmp_interop_type_unknown &&
"Cannot initialize with unknown interop_type!");
if (device_id == -1) {
device_id = omp_get_default_device();
}
if (interop_type == kmp_interop_type_tasksync) {
__kmpc_omp_wait_deps(loc_ref, gtid, ndeps, dep_list, ndeps_noalias,
noalias_dep_list);
}
interop_ptr = new omp_interop_val_t(device_id, interop_type);
if (!device_is_ready(device_id)) {
interop_ptr->err_str = "Device not ready!";
return;
}
DeviceTy &Device = *PM->Devices[device_id];
if (!Device.RTL || !Device.RTL->init_device_info ||
Device.RTL->init_device_info(device_id, &(interop_ptr)->device_info,
&(interop_ptr)->err_str)) {
delete interop_ptr;
interop_ptr = omp_interop_none;
}
if (interop_type == kmp_interop_type_tasksync) {
if (!Device.RTL || !Device.RTL->init_async_info ||
Device.RTL->init_async_info(device_id, &(interop_ptr)->async_info)) {
delete interop_ptr;
interop_ptr = omp_interop_none;
}
}
}
void __tgt_interop_use(ident_t *loc_ref, kmp_int32 gtid,
omp_interop_val_t *&interop_ptr, kmp_int32 device_id,
kmp_int32 ndeps, kmp_depend_info_t *dep_list,
kmp_int32 have_nowait) {
kmp_int32 ndeps_noalias = 0;
kmp_depend_info_t *noalias_dep_list = NULL;
assert(interop_ptr && "Cannot use nullptr!");
omp_interop_val_t *interop_val = interop_ptr;
if (device_id == -1) {
device_id = omp_get_default_device();
}
assert(interop_val != omp_interop_none &&
"Cannot use uninitialized interop_ptr!");
assert((device_id == -1 || interop_val->device_id == device_id) &&
"Inconsistent device-id usage!");
if (!device_is_ready(device_id)) {
interop_ptr->err_str = "Device not ready!";
return;
}
if (interop_val->interop_type == kmp_interop_type_tasksync) {
__kmpc_omp_wait_deps(loc_ref, gtid, ndeps, dep_list, ndeps_noalias,
noalias_dep_list);
}
// TODO Flush the queue associated with the interop through the plugin
}
void __tgt_interop_destroy(ident_t *loc_ref, kmp_int32 gtid,
omp_interop_val_t *&interop_ptr, kmp_int32 device_id,
kmp_int32 ndeps, kmp_depend_info_t *dep_list,
kmp_int32 have_nowait) {
kmp_int32 ndeps_noalias = 0;
kmp_depend_info_t *noalias_dep_list = NULL;
assert(interop_ptr && "Cannot use nullptr!");
omp_interop_val_t *interop_val = interop_ptr;
if (device_id == -1) {
device_id = omp_get_default_device();
}
if (interop_val == omp_interop_none)
return;
assert((device_id == -1 || interop_val->device_id == device_id) &&
"Inconsistent device-id usage!");
if (!device_is_ready(device_id)) {
interop_ptr->err_str = "Device not ready!";
return;
}
if (interop_val->interop_type == kmp_interop_type_tasksync) {
__kmpc_omp_wait_deps(loc_ref, gtid, ndeps, dep_list, ndeps_noalias,
noalias_dep_list);
}
// TODO Flush the queue associated with the interop through the plugin
// TODO Signal out dependences
delete interop_ptr;
interop_ptr = omp_interop_none;
}
#ifdef __cplusplus
} // extern "C"
#endif
| 33.707317 | 80 | 0.627352 | LaudateCorpus1 |
963e4d0e22135ee1429632178a985b4b2f90042d | 6,138 | cpp | C++ | lib/common/utils.cpp | grayed/tmdcalc | 3f592831ff084a3fca993d36f2cf7bb68b4892b9 | [
"0BSD"
] | null | null | null | lib/common/utils.cpp | grayed/tmdcalc | 3f592831ff084a3fca993d36f2cf7bb68b4892b9 | [
"0BSD"
] | null | null | null | lib/common/utils.cpp | grayed/tmdcalc | 3f592831ff084a3fca993d36f2cf7bb68b4892b9 | [
"0BSD"
] | null | null | null | /*
* Copyright (c) 2017 Artem Lipatov <artem.lipatov@mail.ru>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
// utils.cpp
// Last modified 07.11.2017 by Artem Lipatov
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <ctime>
#include "SM.h"
#include "utils.h"
using namespace std;
TFactorization Factorization = TMD;
TCollision Collision = pp;
THardScale FactorizationScale = SubprocessEnergy;
THardScale RenormalizationScale = SubprocessEnergy;
TScaleRate ScaleRate = DefaultScale;
TPDF PDF = AZERO;
double Ecm = 7000.0; // [GeV]
double g[4][4] = { 1.0, 0.0, 0.0, 0.0,
0.0,-1.0, 0.0, 0.0,
0.0, 0.0,-1.0, 0.0,
0.0, 0.0, 0.0,-1.0 };
unsigned long int nIterations = 20;
unsigned long int nEventsPerIteration = 600000;
double aQED(void)
{
return 1.0/137.0;
}
double aQED(double q2)
{
if (isaQEDrun == false) return aQED();
else return 3.0/(3.0/(5.0*aQED()) - (41.0/10.0)*log(q2/sqr(mE))/(4.0*PI))/5.0;
}
double aQCD(double q2)
{
if (isaQCDHO == false) return aQCDLO(q2);
else return aQCDHO(q2);
}
double aQCDSS(double q2)
{
double b0 = 11.0 - 2.0*NF/3.0;
double LQCD2 = sqr(LQCD);
return (4.0*PI/b0)*(1.0/log(q2/LQCD2) + LQCD2/(LQCD2 - q2));
}
double aQCDLO(double q2)
{
return 4.0*PI/((11.0 - 2.0*NF/3.0)*log(q2/sqr(LQCD)));
}
double aQCDHO(double q2)
{
double b0 = (33.0 - 2.0*NF)/(12.0*PI);
double b1 = (153.0 - 19.0*NF)/(24.0*sqr(PI));
double b2 = 0.0;
double b3 = 0.0;
double t = log(q2/sqr(LQCD));
return (1.0/(b0*t))*( 1.0 - (b1/sqr(b0))*log(t)/t +
(sqr(b1)*(sqr(log(t)) - log(t) - 1.0) + b0*b2)/(pow(b0,4)*sqr(t)) -
(pow(b1,3)*(pow(log(t),3) - 2.5*sqr(log(t)) - 2.0*log(t) + 0.5) + 3*b0*b1*b2*log(t) - 0.5*sqr(b0)*b3)/(pow(b0,6)*pow(t,3)) );
}
double L(double x, double y, double z)
{
return x*x + y*y + z*z - 2.0*x*y - 2.0*x*z - 2.0*y*z;
}
double G(double x, double y, double z, double u, double v, double w)
{
return x*z*w + x*u*v + y*z*v + y*u*w - x*y*(z + u + v + w - x - y) -
z*u*(x + y + v + w - z - u) - v*w*(x + y + z + u - v - w);
}
double Pgg(double z)
{
return 2.0*NC*(z/(1.0 - z) - 1.0 + 1.0/z + z*(1.0 - z));
}
double Pgq(double z)
{
return (4.0/3.0)*(1.0 + sqr(1.0 - z))/z;
}
double Pqg(double z)
{
return (sqr(z) + sqr(1.0 - z))/2.0;
}
double Pqq(double z)
{
return (4.0/3.0)*(1.0 + sqr(z))/(1.0 - z);
}
double zPgg(double z)
{
return z*Pgg(z);
}
double sqr(double x)
{
return x*x;
}
double max(double x, double y)
{
double z = x;
if (y > x) z = y;
return z;
}
double min(double x, double y)
{
double z = x;
if (y < x) z = y;
return z;
}
double heaviside(double x)
{
if (x >= 0.0) return 1.0;
else return 0.0;
}
double approximatedeulergamma(double x)
{
double p[] = { -1.71618513886549492533811e+0,
2.47656508055759199108314e+1,
-3.79804256470945635097577e+2,
6.29331155312818442661052e+2,
8.66966202790413211295064e+2,
-3.14512729688483675254357e+4,
-3.61444134186911729807069e+4,
6.64561438202405440627855e+4 };
double q[] = { -3.08402300119738975254353e+1,
3.15350626979604161529144e+2,
-1.01515636749021914166146e+3,
-3.10777167157231109440444e+3,
2.25381184209801510330112e+4,
4.75584627752788110767815e+3,
-1.34659959864969306392456e+5,
-1.15132259675553483497211e+5 };
double z = x - 1.0;
double a = 0.0;
double b = 1.0;
for(unsigned short int i = 0; i < 8; i++)
{
a = ( a + p[i])*z;
b = b*z + q[i];
}
return (a/b + 1.0);
}
double eulergamma(double x)
{
if ( (x > 0.0) and (x < 1.0)) return eulergamma(x + 1.0)/x;
if (x > 2.0) return (x - 1.0)*eulergamma(x - 1.0);
if (x <= 0.0) return PI/(sin(PI*x)*eulergamma(1.0 - x));
return approximatedeulergamma(x);
}
void randomize(void)
{
srand(time(NULL));
}
double random(double x, double y)
{
return (y - x)*rand()/RAND_MAX + x;
}
void assist(void)
{
switch (PDF)
{
case GRV94LO: NF = 4;
LQCD = 0.2;
isaQCDHO = false;
break;
case MSTW2008LO: NF = 4;
LQCD = 0.2;
isaQCDHO = false;
break;
case MSTW2008NLO: NF = 5;
LQCD = 0.2262;
isaQCDHO = true;
break;
case CTEQ66: NF = 5;
LQCD = 0.2262;
isaQCDHO = true;
break;
case AZERO: NF = 4;
LQCD = 0.2;
isaQCDHO = false;
FactorizationScale = SubprocessEnergyPlusPairTransverseMomentum;
break;
case JH2013set1: NF = 4;
LQCD = 0.2;
isaQCDHO = true;
FactorizationScale = SubprocessEnergyPlusPairTransverseMomentum;
break;
case JH2013set2: NF = 4;
LQCD = 0.2;
isaQCDHO = true;
FactorizationScale = SubprocessEnergyPlusPairTransverseMomentum;
break;
case KMR: NF = 4;
LQCD = 0.2;
isaQCDHO = false;
break;
}
}
| 24.070588 | 129 | 0.544314 | grayed |
9640e1097c204a196f850ce686d3ad76fd9b5e4d | 1,048 | hpp | C++ | src/CError.hpp | Vince0789/SA-MP-MySQL | 9524fcc9088004948770ddd6e05a6074581d3095 | [
"BSD-3-Clause"
] | 182 | 2015-01-17T09:55:05.000Z | 2022-03-30T13:08:48.000Z | src/CError.hpp | Tuise233/SA-MP-MySQL | a8113cd3a7b5dcee1002622c5901ff78e3e6e3fe | [
"BSD-3-Clause"
] | 226 | 2015-01-01T12:22:11.000Z | 2022-02-18T20:36:37.000Z | src/CError.hpp | Tuise233/SA-MP-MySQL | a8113cd3a7b5dcee1002622c5901ff78e3e6e3fe | [
"BSD-3-Clause"
] | 149 | 2015-01-05T16:42:45.000Z | 2022-03-26T22:04:24.000Z | #pragma once
#include <string>
#include <fmt/format.h>
using std::string;
template<typename T>
class CError
{
using ErrorType = typename T::Error;
public:
CError() :
m_Type(ErrorType::NONE)
{ }
CError(ErrorType type, string &&msg) :
m_Type(type),
m_Message(std::move(msg))
{ }
template<typename... Args>
CError(ErrorType type, string &&format, Args &&...args) :
m_Type(type),
m_Message(fmt::format(format, std::forward<Args>(args)...))
{ }
~CError() = default;
operator bool() const
{
return m_Type != ErrorType::NONE;
}
const string &msg() const
{
return m_Message;
}
const ErrorType type() const
{
return m_Type;
}
const string &module() const
{
return T::ModuleName;
}
void set(ErrorType type, string &&msg)
{
m_Type = type;
m_Message.assign(std::move(msg));
}
template<typename... Args>
void set(ErrorType type, string &&format, Args &&...args)
{
m_Type = type;
m_Message.assign(fmt::format(format, std::forward<Args>(args)...));
}
private:
ErrorType m_Type;
string m_Message;
};
| 16.903226 | 69 | 0.659351 | Vince0789 |
96426cac91895b6fb6f18f1d448a9c9bc780717d | 889 | cpp | C++ | demo/util/gl.cpp | coxm/b2draw | e1dc391243161e8f4a88a05fa590f1804cd84e03 | [
"MIT"
] | null | null | null | demo/util/gl.cpp | coxm/b2draw | e1dc391243161e8f4a88a05fa590f1804cd84e03 | [
"MIT"
] | null | null | null | demo/util/gl.cpp | coxm/b2draw | e1dc391243161e8f4a88a05fa590f1804cd84e03 | [
"MIT"
] | null | null | null | #include <iostream>
#include <GL/glew.h>
#include "./gl.h"
namespace demo {
std::string
getLog(
GLuint const handle,
decltype(glGetShaderiv) writeLength,
decltype(glGetShaderInfoLog) writeLog
)
{
GLint length{0};
writeLength(handle, GL_INFO_LOG_LENGTH, &length);
std::string log(length, '\0');
if (length > 0)
{
writeLog(handle, length, nullptr, &log[0]);
}
return log;
}
GLuint const compileShader(GLuint const type, GLchar const* pSource)
{
GLuint const shaderID{glCreateShader(type)};
glShaderSource(shaderID, 1, &pSource, nullptr);
glCompileShader(shaderID);
GLint compiled{GL_FALSE};
glGetShaderiv(shaderID, GL_COMPILE_STATUS, &compiled);
if (compiled != GL_TRUE)
{
std::cout << "Shader compilation failed:" << getShaderLog(shaderID)
<< std::endl;
throw std::runtime_error{"Shader compilation failed"};
}
return shaderID;
}
} // namespace demo
| 18.142857 | 69 | 0.716535 | coxm |
9644b8367042090055f72412600c5c3445ee6bd0 | 1,188 | cpp | C++ | src/prod/src/ServiceModel/ProvisionedFabricCodeVersionQueryResultItem.cpp | vishnuk007/service-fabric | d0afdea185ae932cc3c9eacf179692e6fddbc630 | [
"MIT"
] | 2,542 | 2018-03-14T21:56:12.000Z | 2019-05-06T01:18:20.000Z | src/prod/src/ServiceModel/ProvisionedFabricCodeVersionQueryResultItem.cpp | vishnuk007/service-fabric | d0afdea185ae932cc3c9eacf179692e6fddbc630 | [
"MIT"
] | 994 | 2019-05-07T02:39:30.000Z | 2022-03-31T13:23:04.000Z | src/prod/src/ServiceModel/ProvisionedFabricCodeVersionQueryResultItem.cpp | vishnuk007/service-fabric | d0afdea185ae932cc3c9eacf179692e6fddbc630 | [
"MIT"
] | 300 | 2018-03-14T21:57:17.000Z | 2019-05-06T20:07:00.000Z | // ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#include "stdafx.h"
using namespace std;
using namespace Common;
using namespace ServiceModel;
ProvisionedFabricCodeVersionQueryResultItem::ProvisionedFabricCodeVersionQueryResultItem()
: codeVersion_()
{
}
ProvisionedFabricCodeVersionQueryResultItem::ProvisionedFabricCodeVersionQueryResultItem(wstring const & codeVersion)
: codeVersion_(codeVersion)
{
}
void ProvisionedFabricCodeVersionQueryResultItem::ToPublicApi(
__in Common::ScopedHeap & heap,
__out FABRIC_PROVISIONED_CODE_VERSION_QUERY_RESULT_ITEM & publicQueryResult) const
{
publicQueryResult.CodeVersion = heap.AddString(codeVersion_);
}
void ProvisionedFabricCodeVersionQueryResultItem::WriteTo(TextWriter& w, FormatOptions const &) const
{
w.Write(ToString());
}
wstring ProvisionedFabricCodeVersionQueryResultItem::ToString() const
{
return wformatString("CodeVersion = '{0}'", codeVersion_);
}
| 31.263158 | 117 | 0.714646 | vishnuk007 |
9647fe7c5acc92e8db0b91caa67a37662d46364d | 2,141 | cc | C++ | flare/testing/redis_mock_test.cc | AriCheng/flare | b2c84588fe4ac52f0875791d22284d7e063fd057 | [
"CC-BY-3.0",
"BSD-2-Clause",
"BSD-3-Clause"
] | 868 | 2021-05-28T04:00:22.000Z | 2022-03-31T08:57:14.000Z | flare/testing/redis_mock_test.cc | AriCheng/flare | b2c84588fe4ac52f0875791d22284d7e063fd057 | [
"CC-BY-3.0",
"BSD-2-Clause",
"BSD-3-Clause"
] | 33 | 2021-05-28T08:44:47.000Z | 2021-09-26T13:09:21.000Z | flare/testing/redis_mock_test.cc | AriCheng/flare | b2c84588fe4ac52f0875791d22284d7e063fd057 | [
"CC-BY-3.0",
"BSD-2-Clause",
"BSD-3-Clause"
] | 122 | 2021-05-28T08:22:23.000Z | 2022-03-29T09:52:09.000Z | // Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the
// License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// 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 "flare/testing/redis_mock.h"
#include "gmock/gmock-matchers.h"
#include "gtest/gtest.h"
#include "flare/net/redis/redis_channel.h"
#include "flare/net/redis/redis_client.h"
#include "flare/testing/main.h"
using namespace std::literals;
using testing::_;
namespace flare::testing::detail {
TEST(RedisMock, All) {
RedisChannel channel;
FLARE_CHECK(channel.Open("mock://whatever-it-wants-to-be."));
RedisClient client(&channel);
FLARE_EXPECT_REDIS_COMMAND(RedisCommandEq(RedisCommand("GET", "x")))
.WillRepeatedly(Return(RedisString("str")));
FLARE_EXPECT_REDIS_COMMAND(RedisCommandOpEq("SET"))
.WillRepeatedly(Return(RedisString("str")));
FLARE_EXPECT_REDIS_COMMAND(RedisCommandUserMatch([](auto&& cmd) {
return GetRedisCommandOp(cmd) == "SCAN";
})).WillRepeatedly(Return(RedisString("str")));
auto result = client.Execute(RedisCommand("GET", "x"), 1s);
ASSERT_TRUE(result.is<RedisString>());
EXPECT_EQ("str", *result.as<RedisString>());
result = client.Execute(RedisCommand("SET", "x", "y"), 1s);
ASSERT_TRUE(result.is<RedisString>());
EXPECT_EQ("str", *result.as<RedisString>());
result = client.Execute(RedisCommand("SCAN", "0"), 1s);
ASSERT_TRUE(result.is<RedisString>());
EXPECT_EQ("str", *result.as<RedisString>());
FLARE_EXPECT_REDIS_COMMAND(_).WillRepeatedly(Return(RedisNull()));
EXPECT_TRUE(
client.Execute(RedisCommand("GET", "not existing"), 1s).is<RedisNull>());
}
} // namespace flare::testing::detail
FLARE_TEST_MAIN
| 33.453125 | 80 | 0.726296 | AriCheng |
964a78c866872ed3ebf3a5f76e755e953c6044af | 784 | cpp | C++ | Recursion/39. Combination Sum/Soluition.cpp | VarunSAthreya/LeetCode-Solutions | aeab92df5bca208c2442ffdb1487fe5e3aadb3de | [
"MIT"
] | 1 | 2021-11-24T16:20:32.000Z | 2021-11-24T16:20:32.000Z | Recursion/39. Combination Sum/Soluition.cpp | VarunSAthreya/LeetCode-Solutions | aeab92df5bca208c2442ffdb1487fe5e3aadb3de | [
"MIT"
] | null | null | null | Recursion/39. Combination Sum/Soluition.cpp | VarunSAthreya/LeetCode-Solutions | aeab92df5bca208c2442ffdb1487fe5e3aadb3de | [
"MIT"
] | 3 | 2021-09-03T15:14:12.000Z | 2022-03-07T04:04:32.000Z | class Solution
{
public:
vector<vector<int>> combinationSum(vector<int> &candidates, int target)
{
vector<vector<int>> res;
if (candidates.size() == 0)
return res;
vector<int> ds;
solve(candidates, target, res, ds, 0);
return res;
}
void solve(vector<int> &candidates, int target, vector<vector<int>> &res, vector<int> &ds, int ind)
{
if (ind == candidates.size() || target <= 0)
{
if (target == 0)
{
res.push_back(ds);
}
return;
}
ds.push_back(candidates[ind]);
solve(candidates, target - candidates[ind], res, ds, ind);
ds.pop_back();
solve(candidates, target, res, ds, ind + 1);
}
};
| 26.133333 | 103 | 0.510204 | VarunSAthreya |
964b7c2a1766b0e59fbd0bd4056b47e5937579db | 8,721 | cpp | C++ | expressions/aggregation/AggregationHandleCount.cpp | spring-operator/quickstep | 3e98776002eb5db7154031fd6ef1a7f000a89d81 | [
"Apache-2.0"
] | 31 | 2016-01-20T05:43:46.000Z | 2022-02-07T09:14:06.000Z | expressions/aggregation/AggregationHandleCount.cpp | spring-operator/quickstep | 3e98776002eb5db7154031fd6ef1a7f000a89d81 | [
"Apache-2.0"
] | 221 | 2016-01-20T18:25:10.000Z | 2016-06-26T02:58:12.000Z | expressions/aggregation/AggregationHandleCount.cpp | spring-operator/quickstep | 3e98776002eb5db7154031fd6ef1a7f000a89d81 | [
"Apache-2.0"
] | 17 | 2016-01-20T04:00:21.000Z | 2019-03-12T02:41:25.000Z | /**
* Copyright 2011-2015 Quickstep Technologies LLC.
* Copyright 2015 Pivotal Software, Inc.
* Copyright 2016, Quickstep Research Group, Computer Sciences Department,
* University of Wisconsin—Madison.
*
* 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 "expressions/aggregation/AggregationHandleCount.hpp"
#include <atomic>
#include <cstddef>
#include <memory>
#include <vector>
#include "catalog/CatalogTypedefs.hpp"
#include "storage/HashTable.hpp"
#include "storage/HashTableFactory.hpp"
#ifdef QUICKSTEP_ENABLE_VECTOR_COPY_ELISION_SELECTION
#include "storage/ValueAccessor.hpp"
#include "storage/ValueAccessorUtil.hpp"
#endif
#include "types/TypeFactory.hpp"
#include "types/TypeID.hpp"
#include "types/TypedValue.hpp"
#include "types/containers/ColumnVector.hpp"
#include "types/containers/ColumnVectorUtil.hpp"
#include "glog/logging.h"
namespace quickstep {
class StorageManager;
class Type;
class ValueAccessor;
template <bool count_star, bool nullable_type>
AggregationStateHashTableBase*
AggregationHandleCount<count_star, nullable_type>::createGroupByHashTable(
const HashTableImplType hash_table_impl,
const std::vector<const Type*> &group_by_types,
const std::size_t estimated_num_groups,
StorageManager *storage_manager) const {
return AggregationStateHashTableFactory<AggregationStateCount>::CreateResizable(
hash_table_impl,
group_by_types,
estimated_num_groups,
storage_manager);
}
template <bool count_star, bool nullable_type>
AggregationState*
AggregationHandleCount<count_star, nullable_type>::accumulateColumnVectors(
const std::vector<std::unique_ptr<ColumnVector>> &column_vectors) const {
DCHECK(!count_star)
<< "Called non-nullary accumulation method on an AggregationHandleCount "
<< "set up for nullary COUNT(*)";
DCHECK_EQ(1u, column_vectors.size())
<< "Got wrong number of ColumnVectors for COUNT: " << column_vectors.size();
std::size_t count = 0;
InvokeOnColumnVector(
*column_vectors.front(),
[&](const auto &column_vector) -> void { // NOLINT(build/c++11)
if (nullable_type) {
// TODO(shoban): Iterating over the ColumnVector is a rather slow way to
// do this. We should look at extending the ColumnVector interface to do
// a quick count of the non-null values (i.e. the length minus the
// population count of the null bitmap). We should do something similar
// for ValueAccessor too.
for (std::size_t pos = 0;
pos < column_vector.size();
++pos) {
count += !column_vector.getTypedValue(pos).isNull();
}
} else {
count = column_vector.size();
}
});
return new AggregationStateCount(count);
}
#ifdef QUICKSTEP_ENABLE_VECTOR_COPY_ELISION_SELECTION
template <bool count_star, bool nullable_type>
AggregationState*
AggregationHandleCount<count_star, nullable_type>::accumulateValueAccessor(
ValueAccessor *accessor,
const std::vector<attribute_id> &accessor_ids) const {
DCHECK(!count_star)
<< "Called non-nullary accumulation method on an AggregationHandleCount "
<< "set up for nullary COUNT(*)";
DCHECK_EQ(1u, accessor_ids.size())
<< "Got wrong number of attributes for COUNT: " << accessor_ids.size();
const attribute_id accessor_id = accessor_ids.front();
std::size_t count = 0;
InvokeOnValueAccessorMaybeTupleIdSequenceAdapter(
accessor,
[&accessor_id, &count](auto *accessor) -> void { // NOLINT(build/c++11)
if (nullable_type) {
while (accessor->next()) {
count += !accessor->getTypedValue(accessor_id).isNull();
}
} else {
count = accessor->getNumTuples();
}
});
return new AggregationStateCount(count);
}
#endif
template <bool count_star, bool nullable_type>
void AggregationHandleCount<count_star, nullable_type>::aggregateValueAccessorIntoHashTable(
ValueAccessor *accessor,
const std::vector<attribute_id> &argument_ids,
const std::vector<attribute_id> &group_by_key_ids,
AggregationStateHashTableBase *hash_table) const {
if (count_star) {
DCHECK_EQ(0u, argument_ids.size())
<< "Got wrong number of arguments for COUNT(*): " << argument_ids.size();
aggregateValueAccessorIntoHashTableNullaryHelper<
AggregationHandleCount<count_star, nullable_type>,
AggregationStateCount,
AggregationStateHashTable<AggregationStateCount>>(
accessor,
group_by_key_ids,
AggregationStateCount(),
hash_table);
} else {
DCHECK_EQ(1u, argument_ids.size())
<< "Got wrong number of arguments for COUNT: " << argument_ids.size();
aggregateValueAccessorIntoHashTableUnaryHelper<
AggregationHandleCount<count_star, nullable_type>,
AggregationStateCount,
AggregationStateHashTable<AggregationStateCount>>(
accessor,
argument_ids.front(),
group_by_key_ids,
AggregationStateCount(),
hash_table);
}
}
template <bool count_star, bool nullable_type>
void AggregationHandleCount<count_star, nullable_type>::mergeStates(
const AggregationState &source,
AggregationState *destination) const {
const AggregationStateCount &count_source = static_cast<const AggregationStateCount&>(source);
AggregationStateCount *count_destination = static_cast<AggregationStateCount*>(destination);
count_destination->count_.fetch_add(count_source.count_.load(std::memory_order_relaxed),
std::memory_order_relaxed);
}
template <bool count_star, bool nullable_type>
ColumnVector* AggregationHandleCount<count_star, nullable_type>::finalizeHashTable(
const AggregationStateHashTableBase &hash_table,
std::vector<std::vector<TypedValue>> *group_by_keys) const {
return finalizeHashTableHelper<AggregationHandleCount<count_star, nullable_type>,
AggregationStateHashTable<AggregationStateCount>>(
TypeFactory::GetType(kLong),
hash_table,
group_by_keys);
}
template <bool count_star, bool nullable_type>
AggregationState* AggregationHandleCount<count_star, nullable_type>
::aggregateOnDistinctifyHashTableForSingle(
const AggregationStateHashTableBase &distinctify_hash_table) const {
DCHECK_EQ(count_star, false);
return aggregateOnDistinctifyHashTableForSingleUnaryHelper<
AggregationHandleCount<count_star, nullable_type>,
AggregationStateCount>(
distinctify_hash_table);
}
template <bool count_star, bool nullable_type>
void AggregationHandleCount<count_star, nullable_type>
::aggregateOnDistinctifyHashTableForGroupBy(
const AggregationStateHashTableBase &distinctify_hash_table,
AggregationStateHashTableBase *aggregation_hash_table) const {
DCHECK_EQ(count_star, false);
aggregateOnDistinctifyHashTableForGroupByUnaryHelper<
AggregationHandleCount<count_star, nullable_type>,
AggregationStateCount,
AggregationStateHashTable<AggregationStateCount>>(
distinctify_hash_table,
AggregationStateCount(),
aggregation_hash_table);
}
template <bool count_star, bool nullable_type>
void AggregationHandleCount<count_star, nullable_type>::mergeGroupByHashTables(
const AggregationStateHashTableBase &source_hash_table,
AggregationStateHashTableBase *destination_hash_table) const {
mergeGroupByHashTablesHelper<
AggregationHandleCount,
AggregationStateCount,
AggregationStateHashTable<AggregationStateCount>>(source_hash_table,
destination_hash_table);
}
// Explicitly instantiate and compile in the different versions of
// AggregationHandleCount we need. Note that we do not compile a version with
// 'count_star == true' and 'nullable_type == true', as that combination is
// semantically impossible.
template class AggregationHandleCount<false, false>;
template class AggregationHandleCount<false, true>;
template class AggregationHandleCount<true, false>;
} // namespace quickstep
| 38.082969 | 96 | 0.728816 | spring-operator |
964cd89b95b7fcf7e07190110fc208074d425ec7 | 376 | cpp | C++ | kikilib/TimerEventService.cpp | YukangLiu/kikilib | a6b5d43e720186ac290eb9953f9c03ce4bb5386b | [
"MIT"
] | 46 | 2019-12-05T16:35:59.000Z | 2022-03-26T14:23:19.000Z | kikilib/TimerEventService.cpp | WoBuShiXiaoKang/kikilib | a6b5d43e720186ac290eb9953f9c03ce4bb5386b | [
"MIT"
] | 1 | 2019-12-11T08:02:04.000Z | 2019-12-19T14:28:05.000Z | kikilib/TimerEventService.cpp | WoBuShiXiaoKang/kikilib | a6b5d43e720186ac290eb9953f9c03ce4bb5386b | [
"MIT"
] | 8 | 2019-12-06T11:08:19.000Z | 2022-03-05T02:30:51.000Z | //@Author Liu Yukang
#include "TimerEventService.h"
using namespace kikilib;
TimerEventService::TimerEventService(Socket& sock, EventManager* evMgr)
: EventService(sock, evMgr)
{ }
TimerEventService::TimerEventService(Socket&& sock, EventManager* evMgr)
: EventService(std::move(sock), evMgr)
{ }
void TimerEventService::handleReadEvent()
{
readAll();
runExpired();
} | 20.888889 | 72 | 0.757979 | YukangLiu |
965810bd0b47a5e8a4cbdff646c20d655fce0973 | 6,344 | cpp | C++ | Wing.cpp | ancientlore/wing | 7a86926729a72f603b1ea43a4dd5c2e45a230c64 | [
"MIT"
] | 1 | 2021-09-19T21:48:40.000Z | 2021-09-19T21:48:40.000Z | Wing.cpp | ancientlore/wing | 7a86926729a72f603b1ea43a4dd5c2e45a230c64 | [
"MIT"
] | null | null | null | Wing.cpp | ancientlore/wing | 7a86926729a72f603b1ea43a4dd5c2e45a230c64 | [
"MIT"
] | null | null | null | // Wing.cpp : main source file for Wing.exe
//
#include "stdafx.h"
#include <atlframe.h>
#include <atlctrls.h>
#include <atldlgs.h>
#include "resource.h"
#include "LayeredWindow.h"
volatile bool gTimeToQuit = false;
typedef struct {
UCHAR Ttl;
UCHAR Tos;
UCHAR Flags;
UCHAR OptionsSize;
PUCHAR OptionsData;
} IP_OPTION_INFORMATION, *PIP_OPTION_INFORMATION;
typedef struct {
ULONG Address;
ULONG Status;
ULONG RoundTripTime;
USHORT DataSize;
USHORT Reserved;
PVOID Data;
IP_OPTION_INFORMATION Options;
} ICMPECHO;
HMODULE hIcmpDll;
HANDLE (WINAPI *lpfnIcmpCreateFile)();
BOOL (WINAPI *lpfnIcmpCloseHandle)(HANDLE);
DWORD (WINAPI *lpfnIcmpSendEcho2)(HANDLE, HANDLE, FARPROC, PVOID, ULONG, LPVOID, WORD, PIP_OPTION_INFORMATION, LPVOID, DWORD, DWORD);
DWORD (WINAPI *lpfnIcmpParseReplies)(LPVOID, DWORD);
#include "aboutdlg.h"
#include "optionsdlg.h"
#include "SkinData.h"
#include "sampleskin.h"
#include "selectskindlg.h"
#include "MainFrm.h"
CAppModule _Module;
class CWingThreadManager
{
public:
// thread init param
struct _RunData
{
LPTSTR lpstrCmdLine;
int nCmdShow;
TCHAR WindowID[255];
};
// thread proc
static DWORD WINAPI RunThread(LPVOID lpData)
{
CMessageLoop theLoop;
_Module.AddMessageLoop(&theLoop);
_RunData* pData = (_RunData*)lpData;
CMainFrame wndFrame;
CString s = pData->WindowID;
s.TrimLeft();
s.TrimRight();
if (!s.IsEmpty())
wndFrame.WindowID = s;
//if(wndFrame.CreateEx() == NULL)
if(wndFrame.CreateEx(NULL, NULL, WS_POPUP, WS_EX_LAYERED | WS_EX_NOACTIVATE) == NULL)
{
ATLTRACE(_T("Frame window creation failed!\n"));
return 0;
}
wndFrame.ShowWindow(pData->nCmdShow);
::SetForegroundWindow(wndFrame); // Win95 needs this
delete pData;
int nRet = theLoop.Run();
_Module.RemoveMessageLoop();
return nRet;
}
DWORD m_dwCount;
HANDLE m_arrThreadHandles[MAXIMUM_WAIT_OBJECTS - 1];
CWingThreadManager() : m_dwCount(0)
{ }
// Operations
DWORD AddThread(LPTSTR lpstrCmdLine, int nCmdShow, LPTSTR winID = NULL)
{
if(m_dwCount == (MAXIMUM_WAIT_OBJECTS - 1))
{
::MessageBox(NULL, _T("ERROR: Cannot create ANY MORE threads!!!"), _T("Wing"), MB_OK);
return 0;
}
_RunData* pData = new _RunData;
pData->lpstrCmdLine = lpstrCmdLine;
pData->nCmdShow = nCmdShow;
if (winID != NULL)
_tcscpy(pData->WindowID, winID);
else
pData->WindowID[0] = _T('\0');
DWORD dwThreadID;
HANDLE hThread = ::CreateThread(NULL, 0, RunThread, pData, 0, &dwThreadID);
if(hThread == NULL)
{
::MessageBox(NULL, _T("ERROR: Cannot create thread!!!"), _T("Wing"), MB_OK);
return 0;
}
m_arrThreadHandles[m_dwCount] = hThread;
m_dwCount++;
return dwThreadID;
}
void RemoveThread(DWORD dwIndex)
{
::CloseHandle(m_arrThreadHandles[dwIndex]);
if(dwIndex != (m_dwCount - 1))
m_arrThreadHandles[dwIndex] = m_arrThreadHandles[m_dwCount - 1];
m_dwCount--;
}
int Run(LPTSTR lpstrCmdLine, int nCmdShow)
{
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData)) {
::MessageBox(NULL, _T("ERROR: Could not initialize Windows Sockets"), _T("Error"), MB_OK);
return 0;
}
hIcmpDll = LoadLibrary(_T("ICMP.DLL"));
if (hIcmpDll == INVALID_HANDLE_VALUE) {
::MessageBox(NULL, _T("ERROR: Unable to load ICMP DLL"), _T("Error"), MB_OK);
WSACleanup();
return 0;
}
lpfnIcmpCreateFile = (HANDLE (WINAPI *)()) GetProcAddress(hIcmpDll, "IcmpCreateFile");
lpfnIcmpCloseHandle = (BOOL (WINAPI *)(HANDLE)) GetProcAddress(hIcmpDll, "IcmpCloseHandle");
lpfnIcmpSendEcho2 = (DWORD (WINAPI *)(HANDLE, HANDLE, FARPROC, PVOID, ULONG, LPVOID, WORD, PIP_OPTION_INFORMATION, LPVOID, DWORD, DWORD)) GetProcAddress(hIcmpDll, "IcmpSendEcho2");
lpfnIcmpParseReplies = (DWORD (WINAPI *)(LPVOID, DWORD)) GetProcAddress(hIcmpDll, "IcmpParseReplies");
if (!lpfnIcmpCreateFile || !lpfnIcmpCloseHandle) {
::MessageBox(NULL, _T("ERROR: Unable to find ICMP functions"), _T("Error"), MB_OK);
FreeLibrary(hIcmpDll);
WSACleanup();
return 0;
}
MSG msg;
// force message queue to be created
::PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);
CRegKey key;
if (key.Create(HKEY_CURRENT_USER, _T("Software\\Lore\\Wing\\Windows")) == ERROR_SUCCESS) {
TCHAR kname[256];
DWORD sz = 255;
DWORD i = 0;
while (key.EnumKey(i, kname, &sz) == ERROR_SUCCESS) {
AddThread(lpstrCmdLine, nCmdShow, kname);
sz = 255;
i++;
}
if (i == 0)
AddThread(lpstrCmdLine, nCmdShow);
}
else
AddThread(lpstrCmdLine, nCmdShow);
int nRet = m_dwCount;
DWORD dwRet;
while(m_dwCount > 0)
{
dwRet = ::MsgWaitForMultipleObjects(m_dwCount, m_arrThreadHandles, FALSE, INFINITE, QS_ALLINPUT);
if(dwRet == 0xFFFFFFFF)
{
::MessageBox(NULL, _T("ERROR: Wait for multiple objects failed!!!"), _T("Wing"), MB_OK);
}
else if(dwRet >= WAIT_OBJECT_0 && dwRet <= (WAIT_OBJECT_0 + m_dwCount - 1))
{
RemoveThread(dwRet - WAIT_OBJECT_0);
}
else if(dwRet == (WAIT_OBJECT_0 + m_dwCount))
{
if(::PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
if(msg.message == WM_USER)
AddThread(lpstrCmdLine, SW_SHOWNORMAL);
}
}
else
{
::MessageBeep((UINT)-1);
}
}
FreeLibrary(hIcmpDll);
WSACleanup();
return nRet;
}
};
int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE /*hPrevInstance*/, LPTSTR lpstrCmdLine, int nCmdShow)
{
HRESULT hRes = ::CoInitialize(NULL);
// If you are running on NT 4.0 or higher you can use the following call instead to
// make the EXE free threaded. This means that calls come in on a random RPC thread.
// HRESULT hRes = ::CoInitializeEx(NULL, COINIT_MULTITHREADED);
ATLASSERT(SUCCEEDED(hRes));
// this resolves ATL window thunking problem when Microsoft Layer for Unicode (MSLU) is used
::DefWindowProc(NULL, 0, 0, 0L);
AtlInitCommonControls(ICC_BAR_CLASSES); // add flags to support other controls
hRes = _Module.Init(NULL, hInstance);
ATLASSERT(SUCCEEDED(hRes));
int nRet = 0;
// BLOCK: Run application
{
CWingThreadManager mgr;
nRet = mgr.Run(lpstrCmdLine, nCmdShow);
}
_Module.Term();
::CoUninitialize();
return nRet;
}
| 26 | 183 | 0.667718 | ancientlore |
96587cb1c68e59df4c3d6b3530134f2a29171f51 | 7,625 | cpp | C++ | platform/wm/rhodes/MapView/WmGraphics.cpp | mensfeld/rhodes | 2962610a314ed563a0b7c83fcae6136913a1b033 | [
"MIT"
] | 173 | 2015-01-02T11:14:08.000Z | 2022-03-05T09:54:54.000Z | platform/wm/rhodes/MapView/WmGraphics.cpp | sdwood/rhodes | 8228aa40708dcbcc1d3967a479d1d84364022255 | [
"MIT"
] | 263 | 2015-01-05T04:35:22.000Z | 2021-09-07T06:00:02.000Z | platform/wm/rhodes/MapView/WmGraphics.cpp | sdwood/rhodes | 8228aa40708dcbcc1d3967a479d1d84364022255 | [
"MIT"
] | 77 | 2015-01-12T20:57:18.000Z | 2022-02-17T15:15:14.000Z | /*------------------------------------------------------------------------
* (The MIT License)
*
* Copyright (c) 2008-2011 Rhomobile, Inc.
*
* 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.
*
* http://rhomobile.com
*------------------------------------------------------------------------*/
#include "stdafx.h"
#include <common/RhodesApp.h>
#include <logging/RhoLogConf.h>
#include "WmGraphics.h"
//#if 0
#ifdef OS_WINCE
#include <initguid.h>
#include <imgguids.h>
#endif //OS_WINCE
extern "C" HWND getMainWnd();
static void msg_out(const char* text)
{
RAWLOG_ERROR("MapView Graphics:");
RAWLOG_ERROR(text);
}
static void err_out(const char* text)
{
RAWLOG_ERROR("MapView Graphics:");
RAWLOG_ERROR(text);
}
/*
#else
extern "C" HWND getMainWnd();
#undef DEFINE_GUID
#define DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \
EXTERN_C const GUID name \
= { l, w1, w2, { b1, b2, b3, b4, b5, b6, b7, b8 } }
DEFINE_GUID(IID_IImagingFactory, 0x327abda7,0x072b,0x11d3,0x9d,0x7b,0x00,0x00,0xf8,0x1e,0xf3,0x2e);
DEFINE_GUID(CLSID_ImagingFactory, 0x327abda8,0x072b,0x11d3,0x9d,0x7b,0x00,0x00,0xf8,0x1e,0xf3,0x2e);
#endif*/
#undef DEFAULT_LOGCATEGORY
#define DEFAULT_LOGCATEGORY "WM MapView Graphics"
#define IP_PORTION_COUNT 32
WmDrawingImageImpl::WmDrawingImageImpl(void const *p, int size, bool useAlpha) {
RHO_MAP_TRACE1("create DrawingImage with buffer length = %d", size);
init(NULL, p, size, NULL, useAlpha);
}
WmDrawingImageImpl::WmDrawingImageImpl(const char* path, bool useAlpha) {
RHO_MAP_TRACE1("create DrawingImage with filename = %s", path);
init(path, NULL, 0, NULL, useAlpha);
}
WmDrawingImageImpl::WmDrawingImageImpl(WMBitmap* bitmap) {
init(NULL, NULL, 0, bitmap, false);
}
static int ourDrawingImageID = 0;
WmDrawingImageImpl::~WmDrawingImageImpl()
{
RHO_MAP_TRACE1("DrawingImage destroy with ID = %d", mID);
if (mBitmap != NULL) {
mBitmap->release();
mBitmap = NULL;
}
}
void WmDrawingImageImpl::init(const char* path, void const *p, int size, WMBitmap* bitmap, bool useAlpha)
{
mID = ++ourDrawingImageID;
RHO_MAP_TRACE1("DrawingImage create with ID = %d", mID);
#if defined(_WIN32_WCE)
IImagingFactory *pImgFactory = NULL;
IImage *pImage = NULL;
mWidth = 0;
mHeight = 0;
mBitmap = NULL;
if (bitmap != NULL) {
mBitmap = bitmap;
mBitmap->addRef();
mWidth = bitmap->width();
mHeight = bitmap->height();
return;
}
HRESULT co_init_result = CoInitializeEx(NULL, 0/*COINIT_APARTMENTTHREADED*/);
if ( (co_init_result == S_OK) || (co_init_result == S_FALSE) ) {
msg_out("CoInitializeEx OK");
if (SUCCEEDED(CoCreateInstance (CLSID_ImagingFactory,
NULL,
CLSCTX_INPROC_SERVER,
IID_IImagingFactory,
(void **)&pImgFactory)))
{
HRESULT res = 0;
if (p != NULL) {
// from buf
res = pImgFactory->CreateImageFromBuffer(
p,
size,
BufferDisposalFlagNone,
&pImage);
}
else {
// from file
msg_out("Create Image Factory OK");
wchar_t wc_filename[2048];
mbstowcs(wc_filename, path, 2048);
res = pImgFactory->CreateImageFromFile(
wc_filename,
&pImage);
}
if (SUCCEEDED(res))
{
IImage* mimage = pImage;
ImageInfo imgInfo;
mimage->GetImageInfo(&imgInfo);
mWidth = imgInfo.Width;
mHeight = imgInfo.Height;
RHO_MAP_TRACE2("Drawing Image was created with WIDTH = %d, HEIGHT = %d", mWidth, mHeight);
mBitmap = new WMBitmap(mimage, useAlpha);
mimage->Release();
}
else {
err_out("Image not created !");
}
pImgFactory->Release();
}
else {
err_out("ImageFactory not created !");
}
CoUninitialize();
}
else {
err_out("CoInitializeEx not initialized !");
}
#endif //#if defined(_WIN32_WCE)
}
IDrawingImage* WmDrawingImageImpl::clone() {
RHO_MAP_TRACE1("clone DrawingImage from ID = %d", mID);
return new WmDrawingImageImpl(mBitmap);
}
void WmDrawingImageImpl::draw(HDC hdc, int x, int y)
{
RHO_MAP_TRACE2("draw DrawingImage with x = %d, y = %d", x, y);
if (mBitmap == NULL) {
return;
}
mBitmap->draw(hdc, x, y);
}
WmDrawingContextImpl::WmDrawingContextImpl(HDC hdc, int width, int height) {
RHO_MAP_TRACE2("DrawingContext create with WIDTH = %d, HEIGHT = %d", width, height);
mHDC = hdc;
mWidth = width;
mHeight = height;
}
int WmDrawingContextImpl::getWidth() {
return mWidth;
}
int WmDrawingContextImpl::getHeight() {
return mHeight;
}
void WmDrawingContextImpl::drawImage(int x, int y, IDrawingImage* image) {
WmDrawingImageImpl* img = (WmDrawingImageImpl*)image;
img->draw(mHDC, x, y);
}
void WmDrawingContextImpl::drawText(int x, int y, int nWidth, int nHeight, String const &text, int color)
{
RHO_MAP_TRACE2("DrawingContext drawText with x = %d, y = %d", x, y);
HFONT hfontTahoma;
LOGFONT logfont;
HFONT hfontSave = NULL;
memset (&logfont, 0, sizeof (logfont));
logfont.lfHeight = 18;
logfont.lfWidth = 0;
logfont.lfEscapement = 0;
logfont.lfOrientation = 0;
logfont.lfWeight = FW_BOLD;
logfont.lfItalic = FALSE;
logfont.lfUnderline = FALSE;
logfont.lfStrikeOut = FALSE;
logfont.lfCharSet = DEFAULT_CHARSET;
logfont.lfOutPrecision = OUT_DEFAULT_PRECIS;
logfont.lfClipPrecision = CLIP_DEFAULT_PRECIS;
logfont.lfQuality = DEFAULT_QUALITY;
logfont.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
_tcsncpy (logfont.lfFaceName, TEXT("Tahoma"), LF_FACESIZE);
logfont.lfFaceName[LF_FACESIZE-1] = TEXT('\0'); // Ensure null termination
hfontTahoma = CreateFontIndirect (&logfont);
if (hfontTahoma) {
hfontSave = (HFONT) SelectObject(mHDC, hfontTahoma);
}
StringW pathW = convertToStringW(text);
SetBkMode(mHDC, TRANSPARENT);
SetTextColor(mHDC, color & 0xFFFFFF);
//TextOut(mHDC, x, y, pathW.c_str(), pathW.length());
RECT r;
r.left = x;
r.top = y;
r.right = x+nWidth;
r.bottom = y + nHeight;
DrawText(mHDC, pathW.c_str(), -1, &r, DT_LEFT | DT_TOP);
if (hfontTahoma) {
SelectObject(mHDC, hfontSave);
DeleteObject (hfontTahoma);
}
}
void WmDrawingContextImpl::fillRect(int x, int y, int width, int height, int color) {
RECT r;
r.left = x;
r.top = y;
r.right = x+width;
r.bottom = y + height;
HBRUSH hBrush;
HBRUSH hOldBrush;
hBrush = CreateSolidBrush(0xFF000000 | color);
hOldBrush = (HBRUSH)SelectObject(mHDC, hBrush);
FillRect(mHDC, &r, hBrush);
SelectObject(mHDC, hOldBrush);
DeleteObject(hBrush);
}
void WmDrawingContextImpl::getTextRect(int x, int y, String &text, RECT* resultRect)
{
//GetTextExtentPoint32
}
void WmDrawingContextImpl::drawLine(int x1, int y1, int x2, int y2, int color)
{
} | 26.202749 | 107 | 0.687344 | mensfeld |
9659a1d55c8d410e0f909cb9c9dbdeac8964cafb | 285 | cc | C++ | 9_Palindrome_Number/Solution.cc | Samukawa-T1/LeetCode-Diary | 551329796e7b6e8f9176d8cf85dc658b9211b7e9 | [
"Apache-2.0"
] | null | null | null | 9_Palindrome_Number/Solution.cc | Samukawa-T1/LeetCode-Diary | 551329796e7b6e8f9176d8cf85dc658b9211b7e9 | [
"Apache-2.0"
] | null | null | null | 9_Palindrome_Number/Solution.cc | Samukawa-T1/LeetCode-Diary | 551329796e7b6e8f9176d8cf85dc658b9211b7e9 | [
"Apache-2.0"
] | null | null | null | class Solution {
public:
bool isPalindrome(int x){
if(x < 0 || (x % 10 == 0 && x != 0)) {
return false;
}
int rev_last = 0;
while(x > rev_last) {
rev_last = rev_last * 10 + x % 10;
x /= 10;
}
return x == rev_last || x == rev_last/10;
}
}; | 19 | 45 | 0.477193 | Samukawa-T1 |
965a8b567a6db0c4dbb4aa4a9f8a2776971ad3d6 | 1,298 | hpp | C++ | tests/performance/point_type.hpp | Roboauto/spatial | fe652631eb5ec23a719bf1788c68cbd67060e12b | [
"BSL-1.0"
] | 7 | 2015-12-07T02:10:23.000Z | 2022-01-01T05:39:05.000Z | tests/performance/point_type.hpp | Roboauto/spatial | fe652631eb5ec23a719bf1788c68cbd67060e12b | [
"BSL-1.0"
] | 1 | 2021-01-28T15:07:42.000Z | 2021-01-28T15:07:42.000Z | tests/performance/point_type.hpp | Roboauto/spatial | fe652631eb5ec23a719bf1788c68cbd67060e12b | [
"BSL-1.0"
] | 2 | 2016-08-31T13:30:18.000Z | 2021-07-07T07:22:03.000Z | // -*- C++ -*-
#ifndef SPATIAL_EXAMPLE_POINT_TYPE_HPP
#define SPATIAL_EXAMPLE_POINT_TYPE_HPP
#include <algorithm> // std::fill
struct point3_type
{
typedef double value_type;
point3_type() { }
explicit point3_type (double value)
{ std::fill(values, values + 3, value); }
template <typename Distribution>
explicit point3_type(const Distribution& distrib)
{ values[0] = distrib(); values[1] = distrib(); values[2] = distrib(); }
double operator [] (std::size_t index) const { return values[index]; }
double& operator [] (std::size_t index) { return values[index]; }
private:
double values[3];
};
struct point9_type
{
typedef double value_type;
point9_type() { }
explicit point9_type (double value)
{ std::fill(values, values + 9, value); }
template <typename Distribution>
explicit point9_type(const Distribution& distrib)
{
values[0] = distrib(); values[1] = distrib(); values[2] = distrib();
values[3] = distrib(); values[4] = distrib(); values[5] = distrib();
values[6] = distrib(); values[7] = distrib(); values[8] = distrib();
}
double operator [] (std::size_t index) const { return values[index]; }
double& operator [] (std::size_t index) { return values[index]; }
private:
double values[9];
};
#endif // SPATIAL_EXAMPLE_POINT_TYPE_HPP
| 30.904762 | 74 | 0.680277 | Roboauto |
965d8d71bdd8505b358e260cade2aa310043de9a | 18,870 | cpp | C++ | src/mailews/src/MailEwsSyncTodoTask.cpp | stonewell/exchange-ews-thunderbird | 7b8cc41621ff29deb4145ad905344fecd60ccb0c | [
"MIT"
] | 17 | 2016-02-24T15:13:04.000Z | 2022-03-31T22:07:20.000Z | src/mailews/src/MailEwsSyncTodoTask.cpp | stonewell/exchange-ews-thunderbird | 7b8cc41621ff29deb4145ad905344fecd60ccb0c | [
"MIT"
] | 3 | 2016-02-24T20:05:09.000Z | 2017-04-18T04:23:56.000Z | src/mailews/src/MailEwsSyncTodoTask.cpp | stonewell/exchange-ews-thunderbird | 7b8cc41621ff29deb4145ad905344fecd60ccb0c | [
"MIT"
] | 8 | 2018-06-01T08:32:35.000Z | 2021-07-01T01:22:20.000Z | #include "nsXPCOMCIDInternal.h"
#include "nsThreadUtils.h"
#include "nsServiceManagerUtils.h"
#include "nsIMsgIncomingServer.h"
#include "nsIMsgFolder.h"
#include "nsArrayUtils.h"
#include "nsIMutableArray.h"
#include "nsComponentManagerUtils.h"
#include "nsIVariant.h"
#include "calBaseCID.h"
#include "calITodo.h"
#include "calIAttendee.h"
#include "calIRecurrenceInfo.h"
#include "calIDateTime.h"
#include "calIRecurrenceDate.h"
#include "calITimezoneProvider.h"
#include "calITimezone.h"
#include "calIRecurrenceInfo.h"
#include "calIRecurrenceRule.h"
#include "plbase64.h"
#include "libews.h"
#include "MailEwsSyncTodoTask.h"
#include "MailEwsErrorInfo.h"
#include "MailEwsItemsCallback.h"
#include "MailEwsCalendarUtils.h"
#include "IMailEwsTaskCallback.h"
#include "IMailEwsService.h"
#include "IMailEwsMsgIncomingServer.h"
#include "IMailEwsItemOp.h"
#include "IMailEwsMsgFolder.h"
#include "MailEwsLog.h"
#include "rfc3339/rfc3339.h"
static const char * get_sync_state(void * user_data);
static void set_sync_state(const char * sync_state, void * user_data);
static void new_item(const ews_item * item, void * user_data);
static void update_item(const ews_item * item, void * user_data);
static void delete_item(const ews_item * item, void * user_data);
static void read_item(const ews_item * item, int read, void * user_data);
static int get_max_return_item_count(void * user_data);
static char ** get_ignored_item_ids(int * p_count, void * user_data);
#define USER_PTR(x) ((SyncTodoTask*)x)
extern
nsresult
SetPropertyString(calIItemBase * event,
const nsAString & name,
const nsCString & sValue);
extern
nsresult
GetPropertyString(calIItemBase * event,
const nsAString & name,
nsCString & sValue);
class MailEwsLoadTodoItemsCallback : public MailEwsItemsCallback {
public:
NS_DECL_ISUPPORTS_INHERITED
MailEwsLoadTodoItemsCallback(IMailEwsCalendarItemCallback * calCallback);
NS_IMETHOD LocalOperation(void *severResponse) override;
NS_IMETHOD RemoteOperation(void **severResponse) override;
NS_IMETHOD FreeRemoteResponse(void *severResponse) override;
protected:
virtual ~MailEwsLoadTodoItemsCallback();
nsCOMPtr<IMailEwsCalendarItemCallback> m_pCalCallback;
};
class SyncTodoDoneTask : public MailEwsRunnable
{
public:
SyncTodoDoneTask(int result,
nsISupportsArray * ewsTaskCallbacks,
SyncTodoTask * runnable)
: MailEwsRunnable(ewsTaskCallbacks)
, m_Runnable(runnable)
, m_SyncTodoTask(runnable)
, m_Result(result)
{
}
NS_IMETHOD Run() {
mailews_logger << "sync task done task running."
<< std::endl;
m_SyncTodoTask->CleanupTaskRun();
NotifyEnd(m_Runnable, m_Result);
mailews_logger << "sync task done task done."
<< std::endl;
return NS_OK;
}
private:
nsCOMPtr<nsIRunnable> m_Runnable;
SyncTodoTask * m_SyncTodoTask;
int m_Result;
};
SyncTodoTask::SyncTodoTask(IMailEwsCalendarItemCallback * calCallback,
nsIMsgIncomingServer * pIncomingServer,
nsISupportsArray * ewsTaskCallbacks)
: MailEwsRunnable(ewsTaskCallbacks)
, m_pCalCallback(calCallback)
, m_pIncomingServer(pIncomingServer)
, m_Result(EWS_FAIL) {
calCallback->GetSyncState(m_SyncState, false);
mailews_logger << "task sync state:"
<< (m_SyncState.get())
<< std::endl;
}
SyncTodoTask::~SyncTodoTask() {
}
NS_IMETHODIMP SyncTodoTask::Run() {
char * err_msg = NULL;
if (EWS_FAIL == NotifyBegin(this)) {
return NS_OK;
}
ews_session * session = NULL;
nsresult rv = NS_OK;
bool running = false;
rv = m_pCalCallback->GetIsRunning(&running, false /*todo*/);
NS_ENSURE_SUCCESS(rv, rv);
if (running) {
return NS_OK;
}
mailews_logger << "sync task task running..."
<< std::endl;
m_pCalCallback->SetIsRunning(true, false /* todo */);
nsCOMPtr<IMailEwsMsgIncomingServer> ewsServer(do_QueryInterface(m_pIncomingServer, &rv));
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<IMailEwsService> ewsService;
ewsServer->GetService(getter_AddRefs(ewsService));
NS_ENSURE_SUCCESS(rv, rv);
nsresult rv1 = ewsService->GetNewSession(&session);
if (NS_SUCCEEDED(rv1)
&& session) {
ews_sync_item_callback callback;
callback.get_sync_state = get_sync_state;
callback.set_sync_state = set_sync_state;
callback.new_item = new_item;
callback.update_item = update_item;
callback.delete_item = delete_item;
callback.read_item = read_item;
callback.get_max_return_item_count = get_max_return_item_count;
callback.get_ignored_item_ids = get_ignored_item_ids;
callback.user_data = this;
m_Result = ews_sync_task(session,
&callback,
&err_msg);
NotifyError(this, m_Result, err_msg);
if (err_msg) free(err_msg);
if (m_Result == EWS_SUCCESS) {
ProcessItems();
}
} else {
NotifyError(this, session ? EWS_FAIL : 401, err_msg);
}
nsCOMPtr<nsIRunnable> resultrunnable =
new SyncTodoDoneTask(m_Result,
m_pEwsTaskCallbacks,
this);
NS_DispatchToMainThread(resultrunnable);
ewsService->ReleaseSession(session);
mailews_logger << "sync task task done."
<< std::endl;
return NS_OK;
}
static const char * get_sync_state(void * user_data) {
return USER_PTR(user_data)->GetSyncState().get();
}
static void set_sync_state(const char * sync_state, void * user_data) {
USER_PTR(user_data)->SetSyncState(nsCString(sync_state));
}
static void new_item(const ews_item * item, void * user_data){
if (item->item_type == EWS_Item_Task)
USER_PTR(user_data)->NewItem(item->item_id);
}
static void update_item(const ews_item * item, void * user_data) {
if (item->item_type == EWS_Item_Task)
USER_PTR(user_data)->UpdateItem(item->item_id);
}
static void delete_item(const ews_item * item, void * user_data) {
USER_PTR(user_data)->DeleteItem(item->item_id);
}
static void read_item(const ews_item * item, int read, void * user_data) {
}
static int get_max_return_item_count(void * user_data) {
return 500;
}
static char ** get_ignored_item_ids(int * p_count, void * user_data) {
*p_count = 0;
(void)user_data;
return NULL;
}
void SyncTodoTask::NewItem(const char * item_id) {
UpdateItem(item_id);
}
void SyncTodoTask::UpdateItem(const char * item_id) {
nsCString itemId(item_id);
if (!m_ItemIds.Contains(itemId))
m_ItemIds.AppendElement(itemId);
}
void SyncTodoTask::DeleteItem(const char * item_id) {
nsCString itemId(item_id);
if (!m_DeletedItemIds.Contains(itemId))
m_DeletedItemIds.AppendElement(itemId);
}
NS_IMETHODIMP
SyncTodoTask::ProcessItems() {
nsresult rv = NS_OK;
if (!HasItems()) {
mailews_logger << "sync task found 0 items."
<< std::endl;
return NS_OK;
}
nsCOMPtr<IMailEwsMsgIncomingServer> ewsServer(do_QueryInterface(m_pIncomingServer, &rv));
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<IMailEwsService> ewsService;
rv = ewsServer->GetService(getter_AddRefs(ewsService));
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIMsgFolder> folder;
rv = m_pIncomingServer->GetRootFolder(getter_AddRefs(folder));
NS_ENSURE_SUCCESS(rv, rv);
for (PRUint32 i = 0; i < m_ItemIds.Length(); i++) {
nsCOMPtr<IMailEwsItemsCallback> callback;
callback = new MailEwsLoadTodoItemsCallback(m_pCalCallback);
nsTArray<nsCString> itemIds;
for(PRUint32 j=0; j < 10 && i < m_ItemIds.Length(); j++, i++) {
itemIds.AppendElement(m_ItemIds[i]);
}
callback->SetItemIds(&itemIds);
callback->SetFolder(folder);
rv = ewsService->ProcessItems(folder,
callback,
nullptr);
NS_ENSURE_SUCCESS(rv, rv);
}
mailews_logger << "sync task process items done."
<< std::endl;
return rv;
}
void
SyncTodoTask::CleanupTaskRun() {
m_pCalCallback->SetSyncState(m_SyncState, false);
m_pCalCallback->OnDelete(&m_DeletedItemIds);
m_pCalCallback->SetIsRunning(false, false /*todo*/);
if (HasItems()) {
if (m_Result == EWS_SUCCESS) {
mailews_logger << "sync task, start next round sync"
<< std::endl;
DoSyncTodo();
}
}
}
bool
SyncTodoTask::HasItems() {
return m_ItemIds.Length() > 0 ||
m_DeletedItemIds.Length() > 0;
}
void SyncTodoTask::DoSyncTodo() {
nsresult rv = NS_OK;
mailews_logger << "start next round sync task items"
<< std::endl;
nsCOMPtr<IMailEwsMsgIncomingServer> ewsServer(do_QueryInterface(m_pIncomingServer, &rv));
NS_ENSURE_SUCCESS_VOID(rv);
nsCOMPtr<IMailEwsService> ewsService;
rv = ewsServer->GetService(getter_AddRefs(ewsService));
NS_ENSURE_SUCCESS_VOID(rv);
ewsService->SyncTodo(m_pCalCallback, nullptr);
}
NS_IMPL_ISUPPORTS_INHERITED0(MailEwsLoadTodoItemsCallback, MailEwsItemsCallback)
MailEwsLoadTodoItemsCallback::MailEwsLoadTodoItemsCallback(IMailEwsCalendarItemCallback * calCallback)
:m_pCalCallback(calCallback)
{
}
MailEwsLoadTodoItemsCallback::~MailEwsLoadTodoItemsCallback() {
}
typedef struct __load_item_response {
ews_item ** item;
int item_count;
} load_item_response;
static
void
From(calITodo * e,
ews_task_item * item);
NS_IMETHODIMP
MailEwsLoadTodoItemsCallback::LocalOperation(void * response) {
load_item_response * r = (load_item_response *)response;
if (!r) return NS_OK;
ews_item ** item = r->item;
nsresult rv;
nsCOMPtr<nsIMutableArray> taskItems =
do_CreateInstance(NS_ARRAY_CONTRACTID, &rv);
NS_ENSURE_SUCCESS(rv, rv);
mailews_logger << "create calITodo on main thread:"
<< r->item_count
<< std::endl;
for(int i=0;i < r->item_count;i++) {
if (item[i]->item_type == EWS_Item_Task) {
nsCOMPtr<calITodo> e =
do_CreateInstance(CAL_TODO_CONTRACTID, &rv);
NS_ENSURE_SUCCESS(rv, rv);
From(e, (ews_task_item*)item[i]);
//Save item id
rv = SetPropertyString(e,
NS_LITERAL_STRING("X-ITEM-ID"),
nsCString(item[i]->item_id));
NS_ENSURE_SUCCESS(rv, rv);
//Save change key
rv = SetPropertyString(e,
NS_LITERAL_STRING("X-CHANGE-KEY"),
nsCString(item[i]->change_key));
NS_ENSURE_SUCCESS(rv, rv);
taskItems->AppendElement(e, false);
}
}
nsCOMPtr<nsIArray> resultArray(do_QueryInterface(taskItems));
uint32_t length;
resultArray->GetLength(&length);
mailews_logger << "create calITodo done on main thread:"
<< length
<< std::endl;
return m_pCalCallback->OnResult(resultArray);
}
NS_IMETHODIMP
MailEwsLoadTodoItemsCallback::RemoteOperation(void ** response) {
nsCOMPtr<nsIMsgIncomingServer> server;
if (m_RemoteMsg) {
free(m_RemoteMsg);
m_RemoteMsg = NULL;
}
nsresult rv = m_Folder->GetServer(getter_AddRefs(server));
if (NS_FAILED(rv)) {
NS_FAILED_WARN(rv);
m_RemoteResult = EWS_FAIL;
m_RemoteMsg = NULL;
return rv;
}
nsCOMPtr<IMailEwsMsgIncomingServer> ewsServer(do_QueryInterface(server));
nsCOMPtr<IMailEwsMsgFolder> ewsFolder(do_QueryInterface(m_Folder));
nsCOMPtr<IMailEwsService> ewsService;
ewsServer->GetService(getter_AddRefs(ewsService));
ews_session * session = NULL;
rv = ewsService->GetNewSession(&session);
if (NS_SUCCEEDED(rv) && session) {
const char ** item_ids =
(const char **)malloc(sizeof(const char *) * m_ItemIds.Length());
for (PRUint32 i = 0; i < m_ItemIds.Length(); i++) {
item_ids[i] = m_ItemIds[i].get();
}
ews_item ** items = NULL;
int item_count = m_ItemIds.Length();
mailews_logger << "load task items for:"
<< item_count
<< std::endl;
m_RemoteResult = ews_get_items(session,
item_ids,
item_count,
EWS_GetItems_Flags_AllProperties
| EWS_GetItems_Flags_TaskItem,
&items,
&m_RemoteMsg);
*response = NULL;
if (m_RemoteResult == EWS_SUCCESS && items) {
load_item_response * r;
*response = r = (load_item_response*)malloc(sizeof(load_item_response));
r->item = items;
r->item_count = item_count;
mailews_logger << "load task items done:"
<< item_count
<< std::endl;
}
free(item_ids);
} else {
m_RemoteResult = session ? EWS_FAIL : 401;
m_RemoteMsg = NULL;
}
ewsService->ReleaseSession(session);
return rv;
}
NS_IMETHODIMP
MailEwsLoadTodoItemsCallback::FreeRemoteResponse(void *response) {
if (response) {
load_item_response * r = (load_item_response *)response;
ews_free_items(r->item, r->item_count);
free(r);
}
return NS_OK;
}
static
int16_t
From(int day_of_week_index,
int days_of_week) {
if (day_of_week_index == EWS_DayOfWeekIndex_Last) {
return -8 - days_of_week - 1;
} else {
return 8 * (day_of_week_index + 1) + days_of_week + 1;
}
}
static
bool
From(calIRecurrenceRule * rule,
ews_recurrence_pattern * p) {
int16_t v = From(p->day_of_week_index,
p->days_of_week);
switch(p->pattern_type) {
case EWS_Recurrence_RelativeYearly : {
rule->SetType(NS_LITERAL_CSTRING("YEARLY"));
rule->SetComponent(NS_LITERAL_CSTRING("BYDAY"),
1,
&v);
v = (int16_t)p->month + 1;
rule->SetComponent(NS_LITERAL_CSTRING("BYMONTH"),
1,
&v);
}
break;
case EWS_Recurrence_AbsoluteYearly : {
rule->SetType(NS_LITERAL_CSTRING("YEARLY"));
v = (int16_t)p->month + 1;
rule->SetComponent(NS_LITERAL_CSTRING("BYMONTH"),
1,
&v);
v = (int16_t)p->day_of_month;
rule->SetComponent(NS_LITERAL_CSTRING("BYMONTHDAY"),
1,
&v);
}
break;
case EWS_Recurrence_RelativeMonthly : {
rule->SetType(NS_LITERAL_CSTRING("MONTHLY"));
rule->SetInterval(p->interval);
rule->SetComponent(NS_LITERAL_CSTRING("BYDAY"),
1,
&v);
}
break;
case EWS_Recurrence_AbsoluteMonthly : {
rule->SetType(NS_LITERAL_CSTRING("MONTHLY"));
rule->SetInterval(p->interval);
v = p->day_of_month;
rule->SetComponent(NS_LITERAL_CSTRING("BYMONTHDAY"),
1,
&v);
}
break;
case EWS_Recurrence_Weekly : {
rule->SetType(NS_LITERAL_CSTRING("WEEKLY"));
rule->SetInterval(p->interval);
v = p->days_of_week;
rule->SetComponent(NS_LITERAL_CSTRING("BYDAY"),
1,
&v);
}
break;
case EWS_Recurrence_Daily :
rule->SetType(NS_LITERAL_CSTRING("DAILY"));
rule->SetInterval(p->interval);
break;
default:
return false;
}
return true;
}
static
bool
From(calIRecurrenceRule * l,
ews_recurrence_range * r) {
switch(r->range_type) {
case EWSRecurrenceRangeType_NoEnd:
break;
case EWSRecurrenceRangeType_EndDate: {
date::Rfc3339 rfc3339;
time_t end = rfc3339.parse(r->end_date);
nsCOMPtr<calIDateTime> dt =
do_CreateInstance(CAL_DATETIME_CONTRACTID);
dt->SetNativeTime(end * UNIX_TIME_TO_PRTIME);
l->SetUntilDate(dt);
}
break;
case EWSRecurrenceRangeType_Numbered:
l->SetCount(r->number_of_occurrences);
break;
default:
return false;
}
return true;
}
static
void
From(calIRecurrenceInfo * info,
ews_recurrence * r) {
nsCOMPtr<calIRecurrenceRule> rule(do_CreateInstance(CAL_RECURRENCERULE_CONTRACTID));
if (!From(rule, &r->pattern)) {
return;
}
if (!From(rule, &r->range)) {
return;
}
nsCOMPtr<calIRecurrenceItem> item(do_QueryInterface(rule));
info->AppendRecurrenceItem(item);
}
static
void
From(calITodo * e,
ews_task_item * item) {
nsresult rv = NS_OK;
e->SetId(nsCString(item->item.item_id));
e->SetTitle(nsCString(item->item.subject));
SetPropertyString(e,
NS_LITERAL_STRING("DESCRIPTION"),
nsCString(item->item.body));
bool isCompleted = item->is_complete ||
item->status == EWS__TaskStatusType__Completed ||
(int32_t)item->percent_complete == 100;
e->SetIsCompleted(isCompleted);
if (item->start_date > 0) {
nsCOMPtr<calIDateTime> dt =
do_CreateInstance(CAL_DATETIME_CONTRACTID, &rv);
rv = dt->SetNativeTime(item->start_date * UNIX_TIME_TO_PRTIME);
e->SetEntryDate(dt);
}
if (item->due_date > 0) {
nsCOMPtr<calIDateTime> dt =
do_CreateInstance(CAL_DATETIME_CONTRACTID, &rv);
rv = dt->SetNativeTime(item->due_date * UNIX_TIME_TO_PRTIME);
e->SetDueDate(dt);
}
if (item->complete_date > 0) {
nsCOMPtr<calIDateTime> dt =
do_CreateInstance(CAL_DATETIME_CONTRACTID, &rv);
rv = dt->SetNativeTime(item->complete_date * UNIX_TIME_TO_PRTIME);
e->SetCompletedDate(dt);
}
if (isCompleted) {
e->SetStatus(NS_LITERAL_CSTRING("COMPLETED"));
} else {
switch(item->status) {
default:
case EWS__TaskStatusType__NotStarted :
e->SetStatus(NS_LITERAL_CSTRING("NONE"));
break;
case EWS__TaskStatusType__InProgress :
e->SetStatus(NS_LITERAL_CSTRING("IN-PROCESS"));
break;
case EWS__TaskStatusType__Completed :
e->SetStatus(NS_LITERAL_CSTRING("COMPLETED"));
break;
case EWS__TaskStatusType__WaitingOnOthers :
e->SetStatus(NS_LITERAL_CSTRING("NEEDS-ACTION"));
break;
case EWS__TaskStatusType__Deferred :
e->SetStatus(NS_LITERAL_CSTRING("CANCELLED"));
break;
}
}
if (isCompleted) {
e->SetPercentComplete((int16_t)100);
} else {
e->SetPercentComplete((int16_t)(item->percent_complete));
}
if (item->recurrence) {
nsCOMPtr<calIRecurrenceInfo> rInfo;
e->GetRecurrenceInfo(getter_AddRefs(rInfo));
if (!rInfo) {
rInfo = do_CreateInstance(CAL_RECURRENCEINFO_CONTRACTID);
rInfo->SetItem(e);
e->SetRecurrenceInfo(rInfo);
}
From(rInfo, item->recurrence);
}
}
| 26.803977 | 102 | 0.646211 | stonewell |
965e7396c18b7b129e0c8d1faf86c7cf438fad03 | 312 | cpp | C++ | src/sources/logging/fileloggerimplementation.cpp | rkolovanov/qt-game-rpg | 6fc105481181d246d01db9a5e5a8e5bad04da75f | [
"MIT"
] | 1 | 2021-06-28T18:43:29.000Z | 2021-06-28T18:43:29.000Z | src/sources/logging/fileloggerimplementation.cpp | rkolovanov/qt-game-rpg | 6fc105481181d246d01db9a5e5a8e5bad04da75f | [
"MIT"
] | null | null | null | src/sources/logging/fileloggerimplementation.cpp | rkolovanov/qt-game-rpg | 6fc105481181d246d01db9a5e5a8e5bad04da75f | [
"MIT"
] | null | null | null | #include "sources/logging/fileloggerimplementation.h"
#include "sources/application/time.h"
namespace logging {
void FileLoggerImplementation::log(std::ostream& stream, const std::ostringstream& message) {
stream << "[" << application::Time().getCurrentDateTime() << "] " << message.str() << "\n";
}
};
| 24 | 95 | 0.695513 | rkolovanov |
965eebc8e617ec09fab004c08669a4b7772f6b16 | 137,455 | cpp | C++ | src/uscxml/transform/ChartToPromela.cpp | sradomski/uscxml | b8ba0e7c31f397a66f9d509ff20a85b33619475a | [
"W3C",
"BSD-2-Clause"
] | null | null | null | src/uscxml/transform/ChartToPromela.cpp | sradomski/uscxml | b8ba0e7c31f397a66f9d509ff20a85b33619475a | [
"W3C",
"BSD-2-Clause"
] | null | null | null | src/uscxml/transform/ChartToPromela.cpp | sradomski/uscxml | b8ba0e7c31f397a66f9d509ff20a85b33619475a | [
"W3C",
"BSD-2-Clause"
] | null | null | null | /**
* @file
* @author 2012-2014 Stefan Radomski (stefan.radomski@cs.tu-darmstadt.de)
* @copyright Simplified BSD
*
* @cond
* This program is free software: you can redistribute it and/or modify
* it under the terms of the FreeBSD license as published by the FreeBSD
* project.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* You should have received a copy of the FreeBSD license along with this
* program. If not, see <http://www.opensource.org/licenses/bsd-license>.
* @endcond
*/
#define NEW_DELAY_RESHUFFLE 1
#include "uscxml/transform/ChartToFSM.h"
#include "uscxml/transform/ChartToPromela.h"
#include "uscxml/transform/FlatStateIdentifier.h"
#include "uscxml/plugins/datamodel/promela/PromelaParser.h"
#include "uscxml/plugins/datamodel/promela/parser/promela.tab.hpp"
#include <DOM/io/Stream.hpp>
#include <iostream>
#include "uscxml/UUID.h"
#include <math.h>
#include <boost/algorithm/string.hpp>
#include <glog/logging.h>
#define MSG_QUEUE_LENGTH 5
#define MAX_MACRO_CHARS 64
#define MIN_COMMENT_PADDING 60
#define MAX(X,Y) ((X) > (Y) ? (X) : (Y))
#define ADAPT_SRC(code) _analyzer->adaptCode(code, _prefix)
#define BIT_WIDTH(number) (number > 1 ? (int)ceil(log((double)number) / log((double)2.0)) : 1)
#define LENGTH_FOR_NUMBER(input, output) \
{ \
int number = input; \
int output = 0; \
do { \
number /= 10; \
output++; \
} while (number != 0); \
}
#define INDENT_MIN(stream, start, cols) \
for (int indentIndex = start; indentIndex < cols; indentIndex++) \
stream << " ";
#define DIFF_MAPS(base, compare, result) \
{ \
histIter_t baseIter = base.begin(); \
while(baseIter != base.end()) { \
if (compare.find(baseIter->first) == compare.end()) { \
result[baseIter->first] = baseIter->second; \
} else { \
histMemberIter_t baseMemberIter = baseIter->second.begin(); \
while(baseMemberIter != baseIter->second.end()) { \
if (compare.at(baseIter->first).find(*baseMemberIter) == compare.at(baseIter->first).end()) { \
result[baseIter->first].insert(*baseMemberIter); \
} \
baseMemberIter++; \
} \
} \
baseIter++; \
} \
}
#define INTERSECT_MAPS(base, compare, result) \
{ \
histIter_t baseIter = base.begin(); \
while(baseIter != base.end()) { \
if (compare.find(baseIter->first) != compare.end()) { \
histMemberIter_t baseMemberIter = baseIter->second.begin(); \
while(baseMemberIter != baseIter->second.end()) { \
if (compare.at(baseIter->first).find(*baseMemberIter) != compare.at(baseIter->first).end()) { \
result[baseIter->first].insert(*baseMemberIter); \
} \
baseMemberIter++; \
} \
} \
baseIter++; \
} \
}
#define PRETTY_PRINT_LIST(stream, var) \
{ \
std::list<std::string>::const_iterator listIter = var.begin(); \
std::string sep;\
while(listIter != var.end()) { \
stream << sep << *listIter; \
sep = ", "; \
listIter++; \
} \
}
#define TRANSITION_TRACE(transList, value) \
if (_traceTransitions) { \
for (std::set<int>::iterator transRefIter = transList->transitionRefs.begin(); \
transRefIter != transList->transitionRefs.end(); \
transRefIter++) { \
stream << padding << _prefix << "transitions[" << *transRefIter << "] = "#value"; " << std::endl; \
} \
} \
#define DUMP_STATS(disregardTime) \
uint64_t now = tthread::chrono::system_clock::now(); \
if (now - _lastTimeStamp > 1000 || disregardTime) { \
std::cerr << "## State : " << _perfStatesTotal << " [" << _perfStatesProcessed << "/sec]" << std::endl; \
std::cerr << "## Transition: " << _perfTransTotal << " [" << _perfHistoryProcessed << "/sec]" << std::endl; \
std::cerr << "## History : " << _perfHistoryTotal << " [" << _perfHistoryProcessed << "/sec]" << std::endl; \
std::cerr << "toPML: "; \
std::cerr << _perfStatesTotal << ", " << _perfStatesProcessed << ", "; \
std::cerr << _perfTransTotal << ", " << _perfTransProcessed << ", "; \
std::cerr << _perfHistoryTotal << ", " << _perfHistoryProcessed; \
std::cerr << std::endl << std::endl; \
_perfTransProcessed = 0; \
_perfHistoryProcessed = 0; \
_perfStatesProcessed = 0; \
if (!disregardTime)\
_lastTimeStamp = now; \
}
namespace uscxml {
using namespace Arabica::DOM;
using namespace Arabica::XPath;
Transformer ChartToPromela::transform(const Interpreter& other) {
return boost::shared_ptr<TransformerImpl>(new ChartToPromela(other));
}
void ChartToPromela::writeTo(std::ostream& stream) {
writeProgram(stream);
}
void PromelaCodeAnalyzer::addCode(const std::string& code, ChartToPromela* interpreter) {
PromelaParser parser(code);
// parser.dump();
// find all strings
std::list<PromelaParserNode*> astNodes;
astNodes.push_back(parser.ast);
while(astNodes.size() > 0) {
PromelaParserNode* node = astNodes.front();
astNodes.pop_front();
// node->dump();
bool hasValue = false;
int assignedValue = 0;
switch (node->type) {
case PML_STRING: {
std::string unquoted = node->value;
if (boost::starts_with(unquoted, "'")) {
unquoted = unquoted.substr(1, unquoted.size() - 2);
}
addLiteral(unquoted);
break;
}
case PML_ASGN:
if (node->operands.back()->type == PML_CONST) {
hasValue = true;
if (isInteger(node->operands.back()->value.c_str(), 10)) {
assignedValue = strTo<int>(node->operands.back()->value);
}
}
if (node->operands.back()->type == PML_STRING) {
// remember strings for later
astNodes.push_back(node->operands.back());
}
if (node->operands.front()->type == PML_CMPND) {
node = node->operands.front();
} else {
break;
}
// if (node->operands.front()->type != PML_NAME)
// break; // this will skip array assignments
case PML_CMPND: {
std::string nameOfType;
std::list<PromelaParserNode*>::iterator opIter = node->operands.begin();
if ((*opIter)->type != PML_NAME) {
node->dump();
return;
assert(false);
}
PromelaTypedef* td = &_typeDefs;
std::string seperator;
while(opIter != node->operands.end()) {
switch ((*opIter)->type) {
case PML_NAME:
td = &td->types[(*opIter)->value];
td->occurrences.insert(interpreter);
nameOfType += seperator + (*opIter)->value;
if (nameOfType.compare("_x") == 0)
_usesPlatformVars = true;
seperator = "_";
td->name = nameOfType + "_t";
break;
case PML_VAR_ARRAY: {
PromelaParserNode* name = (*opIter)->operands.front();
PromelaParserNode* subscript = *(++(*opIter)->operands.begin());
td = &td->types[name->value];
td->occurrences.insert(interpreter);
nameOfType += seperator + name->value;
td->name = nameOfType + "_t";
if (isInteger(subscript->value.c_str(), 10)) {
td->arraySize = strTo<int>(subscript->value);
}
break;
}
default:
if ((*opIter)->type == PML_CONST) {
// break fall through from ASGN
break;
}
// node->dump();
// assert(false);
break;
}
if (nameOfType.compare("_x_states") == 0) {
_usesInPredicate = true;
}
if (nameOfType.compare("_event_type") == 0) {
addLiteral("internal");
addLiteral("external");
addLiteral("platform");
}
if (nameOfType.compare("_event_origintype") == 0) {
addLiteral("http://www.w3.org/TR/scxml/#SCXMLEventProcessor");
}
opIter++;
}
if (hasValue) {
if (td->maxValue < assignedValue)
td->maxValue = assignedValue;
if (td->minValue > assignedValue)
td->minValue = assignedValue;
}
continue; // skip processing nested AST nodes
}
case PML_NAME: {
_typeDefs.types[node->value].occurrences.insert(interpreter);
_typeDefs.types[node->value].minValue = 0;
_typeDefs.types[node->value].maxValue = 0;
// test325
if (node->value.compare("_ioprocessors") == 0) {
addCode("_ioprocessors.scxml.location", interpreter);
}
break;
}
default:
// node->dump();
break;
// assert(false);
}
astNodes.insert(astNodes.end(), node->operands.begin(), node->operands.end());
}
}
void PromelaCodeAnalyzer::addEvent(const std::string& eventName) {
if (_events.find(eventName) != _events.end())
return;
addLiteral(eventName, _lastEventIndex);
assert(_strIndex.find(eventName) != _strIndex.end());
_eventTrie.addWord(eventName);
_events[eventName] = _strIndex[eventName];
_lastEventIndex++;
}
void PromelaCodeAnalyzer::addOrigState(const std::string& stateName) {
if (_origStateIndex.find(stateName) == _origStateIndex.end()) {
_origStateIndex[stateName] = _lastStateIndex++;
createMacroName(stateName);
}
}
void PromelaCodeAnalyzer::addState(const std::string& stateName) {
if (_states.find(stateName) != _states.end())
return;
createMacroName(stateName);
}
void PromelaCodeAnalyzer::addLiteral(const std::string& literal, int forceIndex) {
if (boost::starts_with(literal, "'"))
throw std::runtime_error("Literal " + literal + " passed with quotes");
if (_strLiterals.find(literal) != _strLiterals.end())
return;
_strLiterals.insert(literal);
createMacroName(literal);
enumerateLiteral(literal, forceIndex);
}
int PromelaCodeAnalyzer::enumerateLiteral(const std::string& literal, int forceIndex) {
if (forceIndex >= 0) {
_strIndex[literal] = forceIndex;
return forceIndex;
}
if (_strIndex.find(literal) != _strIndex.end())
return _strIndex[literal];
_strIndex[literal] = _lastStrIndex++;
return _lastStrIndex + 1;
}
std::string PromelaCodeAnalyzer::createMacroName(const std::string& literal) {
if (_strMacroNames.find(literal) != _strMacroNames.end())
return _strMacroNames[literal];
// find a suitable macro name for the strings
std::string macroName = literal; //literal.substr(1, literal.size() - 2);
// cannot start with digit
if (isInteger(macroName.substr(0,1).c_str(), 10))
macroName = "_" + macroName;
macroName = macroName.substr(0, MAX_MACRO_CHARS);
boost::to_upper(macroName);
std::string illegalChars = "#\\/:?\"<>| \n\t()[]{}',.-";
std::string tmp;
std::string::iterator it = macroName.begin();
while (it < macroName.end()) {
bool found = illegalChars.find(*it) != std::string::npos;
if(found) {
tmp += '_';
it++;
while(it < macroName.end() && illegalChars.find(*it) != std::string::npos) {
it++;
}
} else {
tmp += *it++;
}
}
macroName = tmp;
if(macroName.length() < 1)
macroName = "_EMPTY_STRING";
if(macroName.length() < 2 && macroName[0] == '_')
macroName = "_WEIRD_CHARS";
unsigned int index = 2;
while (_macroNameSet.find(macroName) != _macroNameSet.end()) {
std::string suffix = toStr(index);
if (macroName.size() > suffix.size()) {
macroName = macroName.substr(0, macroName.size() - suffix.size()) + suffix;
} else {
macroName = suffix;
}
index++;
}
_macroNameSet.insert(macroName);
_strMacroNames[literal] = macroName;
return macroName;
}
std::string PromelaCodeAnalyzer::getTypeReset(const std::string& var, const PromelaTypedef& type, const std::string padding) {
std::stringstream assignment;
std::map<std::string, PromelaTypedef>::const_iterator typeIter = type.types.begin();
while(typeIter != type.types.end()) {
const PromelaTypedef& innerType = typeIter->second;
if (innerType.arraySize > 0) {
for (int i = 0; i < innerType.arraySize; i++) {
assignment << padding << var << "." << typeIter->first << "[" << i << "] = 0;" << std::endl;
}
} else if (innerType.types.size() > 0) {
assignment << getTypeReset(var + "." + typeIter->first, typeIter->second, padding);
} else {
assignment << padding << var << "." << typeIter->first << " = 0;" << std::endl;
}
typeIter++;
}
return assignment.str();
}
std::string PromelaCodeAnalyzer::getTypeAssignment(const std::string& varTo, const std::string& varFrom, const PromelaTypedef& type, const std::string padding) {
std::stringstream assignment;
std::map<std::string, PromelaTypedef>::const_iterator typeIter = type.types.begin();
while(typeIter != type.types.end()) {
const PromelaTypedef& innerType = typeIter->second;
if (innerType.arraySize > 0) {
for (int i = 0; i < innerType.arraySize; i++) {
assignment << padding << varTo << "." << typeIter->first << "[" << i << "] = " << varFrom << "." << typeIter->first << "[" << i << "];" << std::endl;
}
} else if (innerType.types.size() > 0) {
assignment << getTypeAssignment(varTo + "." + typeIter->first, varFrom + "." + typeIter->first, typeIter->second, padding);
} else {
assignment << padding << varTo << "." << typeIter->first << " = " << varFrom << "." << typeIter->first << ";" << std::endl;
}
typeIter++;
}
return assignment.str();
}
std::string PromelaCodeAnalyzer::macroForLiteral(const std::string& literal) {
if (boost::starts_with(literal, "'"))
throw std::runtime_error("Literal " + literal + " passed with quotes");
if (_strMacroNames.find(literal) == _strMacroNames.end())
throw std::runtime_error("No macro for literal '" + literal + "' known");
return _strMacroNames[literal];
}
int PromelaCodeAnalyzer::indexForLiteral(const std::string& literal) {
if (boost::starts_with(literal, "'"))
throw std::runtime_error("Literal " + literal + " passed with quotes");
if (_strIndex.find(literal) == _strIndex.end())
throw std::runtime_error("No index for literal " + literal + " known");
return _strIndex[literal];
}
std::string PromelaCodeAnalyzer::adaptCode(const std::string& code, const std::string& prefix) {
// for (std::map<std::string, std::string>::const_iterator litIter = _strMacroNames.begin(); litIter != _strMacroNames.end(); litIter++) {
// boost::replace_all(replaced, "'" + litIter->first + "'", litIter->second);
// }
// boost::replace_all(replaced, "_event", prefix + "_event");
// replace all variables from analyzer
std::string processed = code;
std::stringstream processedStr;
std::list<std::pair<size_t, size_t> > posList;
std::list<std::pair<size_t, size_t> >::iterator posIter;
size_t lastPos;
// prepend all identifiers with our prefix
{
PromelaParser parsed(processed);
// parsed.dump();
posList = getTokenPositions(code, PML_NAME, parsed.ast);
posList.sort();
posIter = posList.begin();
lastPos = 0;
while (posIter != posList.end()) {
processedStr << code.substr(lastPos, posIter->first - lastPos) << prefix;
lastPos = posIter->first;
posIter++;
}
processedStr << processed.substr(lastPos, processed.size() - lastPos);
processed = processedStr.str();
processedStr.clear();
processedStr.str("");
}
// replace string literals
{
PromelaParser parsed(processed);
posList = getTokenPositions(code, PML_STRING, parsed.ast);
posList.sort();
posIter = posList.begin();
lastPos = 0;
while (posIter != posList.end()) {
processedStr << processed.substr(lastPos, posIter->first - lastPos);
// std::cout << processed.substr(posIter->first + 1, posIter->second - posIter->first - 2) << std::endl;
assert(_strMacroNames.find(processed.substr(posIter->first + 1, posIter->second - posIter->first - 2)) != _strMacroNames.end());
processedStr << _strMacroNames[processed.substr(posIter->first + 1, posIter->second - posIter->first - 2)];
lastPos = posIter->second;
posIter++;
}
processedStr << processed.substr(lastPos, processed.size() - lastPos);
processed = processedStr.str();
processedStr.clear();
processedStr.str("");
}
return processed;
}
//std::string PromelaCodeAnalyzer::prefixIdentifiers(const std::string& expr, const std::string& prefix) {
// PromelaParser parsed(expr);
// std::list<size_t> posList = getTokenPositions(expr, PML_NAME, parsed.ast);
// posList.sort();
//
// std::stringstream prefixed;
// std::list<size_t>::iterator posIter = posList.begin();
// size_t lastPos = 0;
// while (posIter != posList.end()) {
// prefixed << expr.substr(lastPos, *posIter - lastPos) << prefix;
// lastPos = *posIter;
// posIter++;
// }
//
// prefixed << expr.substr(lastPos, expr.size() - lastPos);
// return prefixed.str();
//}
std::list<std::pair<size_t, size_t> > PromelaCodeAnalyzer::getTokenPositions(const std::string& expr, int type, PromelaParserNode* ast) {
std::list<std::pair<size_t, size_t> > posList;
if (ast->type == type && ast->loc != NULL) {
// ast->dump();
if (type == PML_NAME && ast->parent &&
((ast->parent->type == PML_CMPND && ast->parent->operands.front() != ast) ||
(ast->parent->parent && ast->parent->type == PML_VAR_ARRAY && ast->parent->parent->type == PML_CMPND))) {
// field in a compound
} else {
if (ast->loc->firstLine == 0) {
posList.push_back(std::make_pair(ast->loc->firstCol, ast->loc->lastCol));
} else {
int line = ast->loc->firstLine;
size_t lastPos = 0;
while(line > 0) {
lastPos = expr.find_first_of('\n', lastPos + 1);
line--;
}
posList.push_back(std::make_pair(lastPos + ast->loc->firstCol, lastPos + ast->loc->lastCol));
}
}
}
for (std::list<PromelaParserNode*>::iterator opIter = ast->operands.begin(); opIter != ast->operands.end(); opIter++) {
std::list<std::pair<size_t, size_t> > tmp = getTokenPositions(expr, type, *opIter);
posList.insert(posList.end(), tmp.begin(), tmp.end());
}
return posList;
}
std::set<std::string> PromelaCodeAnalyzer::getEventsWithPrefix(const std::string& prefix) {
std::set<std::string> eventNames;
std::list<TrieNode*> trieNodes = _eventTrie.getWordsWithPrefix(prefix);
std::list<TrieNode*>::iterator trieIter = trieNodes.begin();
while(trieIter != trieNodes.end()) {
eventNames.insert((*trieIter)->value);
trieIter++;
}
return eventNames;
}
ChartToPromela::~ChartToPromela() {
if (_analyzer != NULL)
delete(_analyzer);
for (std::map<Arabica::DOM::Node<std::string>, ChartToPromela*>::iterator nestedIter = _machines.begin(); nestedIter != _machines.end(); nestedIter++) {
nestedIter->second->_analyzer = NULL;
delete (nestedIter->second);
}
}
void ChartToPromela::writeEvents(std::ostream& stream) {
std::map<std::string, int> events = _analyzer->getEvents();
std::map<std::string, int>::iterator eventIter = events.begin();
stream << "/* event name identifiers */" << std::endl;
while(eventIter != events.end()) {
if (eventIter->first.length() > 0) {
stream << "#define " << _analyzer->macroForLiteral(eventIter->first) << " " << _analyzer->indexForLiteral(eventIter->first);
stream << " /* from \"" << eventIter->first << "\" */" << std::endl;
}
eventIter++;
}
}
void ChartToPromela::writeStates(std::ostream& stream) {
stream << "/* state name identifiers */" << std::endl;
std::map<std::string, GlobalState*>::iterator stateIter = _activeConf.begin();
while(stateIter != _activeConf.end()) {
stream << "#define " << "s" << stateIter->second->activeIndex << " " << stateIter->second->activeIndex;
stream << " /* from \"" << stateIter->first << "\" */" << std::endl;
stateIter++;
}
// for (int i = 0; i < _globalConf.size(); i++) {
// stream << "#define " << "s" << i << " " << i;
// stream << " /* from \"" << ATTR_CAST(_globalStates[i], "id") << "\" */" << std::endl;
// }
}
void ChartToPromela::writeStateMap(std::ostream& stream) {
stream << "/* original state names */" << std::endl;
std::map<std::string, int> origStates = _analyzer->getOrigStates();
for (std::map<std::string, int>::iterator origIter = origStates.begin(); origIter != origStates.end(); origIter++) {
stream << "#define " << _analyzer->macroForLiteral(origIter->first) << " " << origIter->second;
stream << " /* from \"" << origIter->first << "\" */" << std::endl;
}
// std::map<std::string, int> states = _analyzer->getStates();
// size_t stateIndex = 0;
// for (std::map<std::string, int>::iterator stateIter = states.begin(); stateIter != states.end(); stateIter++) {
// stream << "_x"
// std::list<std::string> origStates = _analyzer->getOrigState(stateIter->first);
// size_t origIndex = 0;
// for (std::list<std::string>::iterator origIter = origStates.begin(); origIter != origStates.end(); origIter++) {
//
// }
// }
}
void ChartToPromela::writeHistoryArrays(std::ostream& stream) {
std::map<std::string, std::map<std::string, size_t> >::iterator histNameIter = _historyMembers.begin();
while(histNameIter != _historyMembers.end()) {
stream << "/* history assignments for " << histNameIter->first << std::endl;
std::map<std::string, size_t>::iterator histMemberIter = histNameIter->second.begin();
while(histMemberIter != histNameIter->second.end()) {
stream << " " << histMemberIter->second << ": " << histMemberIter->first << std::endl;;
histMemberIter++;
}
stream << "*/" << std::endl;
stream << "bool " << _prefix << "_hist_" << boost::replace_all_copy(boost::to_lower_copy(histNameIter->first), ".", "_") << "[" << histNameIter->second.size() << "];" << std::endl;
histNameIter++;
}
}
void ChartToPromela::writeTypeDefs(std::ostream& stream) {
stream << "/* type definitions */" << std::endl;
PromelaCodeAnalyzer::PromelaTypedef typeDefs = _analyzer->getTypes();
if (typeDefs.types.size() == 0)
return;
std::list<PromelaCodeAnalyzer::PromelaTypedef> individualDefs;
std::list<PromelaCodeAnalyzer::PromelaTypedef> currDefs;
currDefs.push_back(typeDefs);
while(currDefs.size() > 0) {
if (std::find(individualDefs.begin(), individualDefs.end(), currDefs.front()) == individualDefs.end()) {
individualDefs.push_back(currDefs.front());
for (std::map<std::string, PromelaCodeAnalyzer::PromelaTypedef>::iterator typeIter = currDefs.front().types.begin(); typeIter != currDefs.front().types.end(); typeIter++) {
currDefs.push_back(typeIter->second);
}
}
currDefs.pop_front();
}
individualDefs.pop_front();
for (std::list<PromelaCodeAnalyzer::PromelaTypedef>::reverse_iterator rIter = individualDefs.rbegin(); rIter != individualDefs.rend(); rIter++) {
PromelaCodeAnalyzer::PromelaTypedef currDef = *rIter;
if (currDef.types.size() == 0 || currDef.name.size() == 0)
continue;
stream << "typedef " << currDef.name << " {" << std::endl;
if (currDef.name.compare("_event_t") ==0) {
if (_analyzer->usesEventField("delay")) {
// make sure delay is the first member for sorted enqueuing to work
stream << " int delay;" << std::endl;
#if NEW_DELAY_RESHUFFLE
#else
stream << " int seqNr;" << std::endl;
#endif
}
stream << " int name;" << std::endl;
if (_analyzer->usesEventField("invokeid")) {
stream << " int invokeid;" << std::endl;
}
}
for (std::map<std::string, PromelaCodeAnalyzer::PromelaTypedef>::iterator tIter = currDef.types.begin(); tIter != currDef.types.end(); tIter++) {
if (currDef.name.compare("_event_t") == 0 && (tIter->first.compare("name") == 0 ||
tIter->first.compare("seqNr") == 0 ||
tIter->first.compare("invokeid") == 0 ||
tIter->first.compare("delay") == 0)) { // special treatment for _event
continue;
}
if (currDef.name.compare("_x_t") == 0 && tIter->first.compare("states") == 0) {
stream << " bool states[" << _analyzer->getOrigStates().size() << "];" << std::endl;
continue;
}
if (tIter->second.types.size() == 0) {
stream << " " << declForRange(tIter->first, tIter->second.minValue, tIter->second.maxValue, true) << ";" << std::endl; // not further nested
// stream << " int " << tIter->first << ";" << std::endl; // not further nested
} else {
stream << " " << tIter->second.name << " " << tIter->first << ";" << std::endl;
}
}
stream << "};" << std::endl << std::endl;
}
// stream << "/* typedef instances */" << std::endl;
// PromelaCodeAnalyzer::PromelaTypedef allTypes = _analyzer->getTypes();
// std::map<std::string, PromelaCodeAnalyzer::PromelaTypedef>::iterator typeIter = allTypes.types.begin();
// while(typeIter != allTypes.types.end()) {
// if (typeIter->second.types.size() > 0) {
// // an actual typedef
// stream << "hidden " << typeIter->second.name << " " << typeIter->first << ";" << std::endl;
// } else {
// stream << "hidden " << declForRange(typeIter->first, typeIter->second.minValue, typeIter->second.maxValue) << ";" << std::endl;
// }
// typeIter++;
// }
}
std::string ChartToPromela::declForRange(const std::string& identifier, long minValue, long maxValue, bool nativeOnly) {
// return "int " + identifier; // just for testing
// we know nothing about this type
if (minValue == 0 && maxValue == 0)
return "int " + identifier;
if (minValue < 0) {
// only short or int for negatives
if (minValue < -32769 || maxValue > 32767)
return "int " + identifier;
return "short " + identifier;
}
// type is definitely positive
if (nativeOnly) {
if (maxValue > 32767)
return "int " + identifier;
if (maxValue > 255)
return "short " + identifier;
if (maxValue > 1)
return "byte " + identifier;
return "bool " + identifier;
} else {
return "unsigned " + identifier + " : " + toStr(BIT_WIDTH(maxValue));
}
}
void ChartToPromela::writeInlineComment(std::ostream& stream, const Arabica::DOM::Node<std::string>& node) {
if (node.getNodeType() != Node_base::COMMENT_NODE)
return;
std::string comment = node.getNodeValue();
boost::trim(comment);
if (!boost::starts_with(comment, "#promela-inline"))
return;
std::stringstream ssLine(comment);
std::string line;
std::getline(ssLine, line); // consume first line
while(std::getline(ssLine, line)) {
if (line.length() == 0)
continue;
stream << line;
}
}
std::string ChartToPromela::conditionForHistoryTransition(const GlobalTransition* transition) {
FlatStateIdentifier flatSource(transition->source);
FlatStateIdentifier flatTarget(transition->destination);
std::string condition;
return condition;
}
std::string ChartToPromela::conditionalizeForHist(GlobalTransition* transition, int indent) {
std::set<GlobalTransition*> transitions;
transitions.insert(transition);
return conditionalizeForHist(transitions);
}
std::string ChartToPromela::conditionalizeForHist(const std::set<GlobalTransition*>& transitions, int indent) {
std::stringstream condition;
std::string memberSep;
std::set<std::map<std::string, std::list<std::string> > > histSeen;
for (std::set<GlobalTransition*>::const_iterator transIter = transitions.begin(); transIter != transitions.end(); transIter++) {
if ((*transIter)->histTargets.size() == 0) // there are no history transitions in here!
continue;
std::map<std::string, std::list<std::string> > relevantHist;
std::map<std::string, std::list<std::string> > currentHist;
FlatStateIdentifier flatSource((*transIter)->source);
currentHist = flatSource.getHistory();
std::set<std::string>::iterator histTargetIter = (*transIter)->histTargets.begin();
while(histTargetIter != (*transIter)->histTargets.end()) {
if (currentHist.find(*histTargetIter) != currentHist.end()) {
relevantHist[*histTargetIter] = currentHist[*histTargetIter];
}
histTargetIter++;
}
if (relevantHist.size() == 0)
continue;
if (histSeen.find(relevantHist) != histSeen.end())
continue;
histSeen.insert(relevantHist);
std::string itemSep;
std::map<std::string, std::list<std::string> >::iterator relevanthistIter = relevantHist.begin();
if (relevantHist.size() > 0)
condition << memberSep;
while(relevanthistIter != relevantHist.end()) {
std::list<std::string>::iterator histItemIter = relevanthistIter->second.begin();
while(histItemIter != relevanthistIter->second.end()) {
assert(_historyMembers.find(relevanthistIter->first) != _historyMembers.end());
assert(_historyMembers[relevanthistIter->first].find(*histItemIter) != _historyMembers[relevanthistIter->first].end());
condition << itemSep << _prefix << "_hist_" << boost::to_lower_copy(_analyzer->macroForLiteral(relevanthistIter->first)) << "[" << _historyMembers[relevanthistIter->first][*histItemIter] << "]";
itemSep = " && ";
histItemIter++;
}
relevanthistIter++;
}
if (relevantHist.size() > 0)
memberSep = " || ";
}
if (condition.str().size() > 0) {
return "(" + condition.str() + ")";
} else {
assert(false);
}
return "true";
}
//std::list<GlobalTransition::Action> ChartToPromela::getTransientContent(GlobalTransition* transition) {
// std::list<GlobalTransition::Action> content;
// GlobalTransition* currTrans = transition;
// for (;;) {
// if (!HAS_ATTR(currState, "transient") || !DOMUtils::attributeIsTrue(ATTR(currState, "transient")))
// break;
// content.push_back(filterChildElements(_nsInfo.xmlNSPrefix + "invoke", currState));
// content.push_back(filterChildElements(_nsInfo.xmlNSPrefix + "onentry", currState));
// content.push_back(filterChildElements(_nsInfo.xmlNSPrefix + "onexit", currState));
// NodeSet<std::string> transitions = filterChildElements(_nsInfo.xmlNSPrefix + "transition", currState);
// currState = _globalConf[ATTR_CAST(transitions[0], "target")];
// }
//
// return content;
//}
void ChartToPromela::writeTransition(std::ostream& stream, GlobalTransition* transition, int indent) {
std::string padding;
for (int i = 0; i < indent; i++) {
padding += " ";
}
std::list<GlobalTransition*>::const_iterator histIter;
if (envVarIsTrue("USCXML_ANNOTATE_NOCOMMENT")) {
stream << std::endl << _prefix << "t" << transition->index << ": /* ######################## */ " << std::endl;
} else {
stream << std::endl << _prefix << "t" << transition->index << ": /* ######################## " << std::endl;
FlatStateIdentifier flatActiveSource(transition->source);
stream << " from state: ";
PRETTY_PRINT_LIST(stream, flatActiveSource.getActive());
stream << std::endl;
// stream << " with history: " << flatActiveSource.getFlatHistory() << std::endl;
stream << " ----- on event: " << (transition->eventDesc.size() > 0 ? transition->eventDesc : "SPONTANEOUS") << " --" << std::endl;
stream << " to state: ";
std::set<FlatStateIdentifier> destinations;
destinations.insert(FlatStateIdentifier(transition->destination));
histIter = transition->historyTrans.begin();
while(histIter != transition->historyTrans.end()) {
destinations.insert(FlatStateIdentifier((*histIter)->destination));
histIter++;
}
std::string seperator = "";
for (std::set<FlatStateIdentifier>::iterator destIter = destinations.begin(); destIter != destinations.end(); destIter++) {
stream << seperator;
PRETTY_PRINT_LIST(stream, destIter->getActive());
stream << " with " << (destIter->getFlatHistory().size() > 0 ? destIter->getFlatHistory() : "no history");
seperator = "\n ";
}
stream << std::endl;
stream << "############################### */" << std::endl;
}
stream << std::endl;
stream << padding << "skip;" << std::endl;
stream << padding << "d_step {" << std::endl;
if (_writeTransitionPrintfs)
stream << padding << " printf(\"Taking Transition " << _prefix << "t" << transition->index << "\\n\");" << std::endl;
padding += " ";
indent++;
// iterators of history transitions executable content
std::map<GlobalTransition*, std::pair<GlobalTransition::Action::iter_t, GlobalTransition::Action::iter_t> > actionIters;
std::map<GlobalTransition*, std::set<GlobalTransition::Action> > actionsInTransition;
typedef std::map<GlobalTransition*, std::pair<GlobalTransition::Action::iter_t, GlobalTransition::Action::iter_t> > actionIters_t;
histIter = transition->historyTrans.begin();
while(histIter != transition->historyTrans.end()) {
actionIters.insert(std::make_pair((*histIter), std::make_pair((*histIter)->actions.begin(), (*histIter)->actions.end())));
// add history transitions actions to the set
for (std::list<GlobalTransition::Action>::iterator actionIter = (*histIter)->actions.begin(); actionIter != (*histIter)->actions.end(); actionIter++) {
actionsInTransition[*histIter].insert(*actionIter);
}
// std::copy((*histIter)->actions.begin(), (*histIter)->actions.end(), std::inserter(actionsInTransition[*histIter], actionsInTransition[*histIter].begin()));
histIter++;
}
// std::cout << "###" << std::endl;
for (std::list<GlobalTransition::Action>::iterator actionIter = transition->actions.begin(); actionIter != transition->actions.end(); actionIter++) {
actionsInTransition[transition].insert(*actionIter);
}
// std::copy(transition->actions.begin(), transition->actions.end(), std::inserter(actionsInTransition[transition], actionsInTransition[transition].begin()));
// GlobalTransition::Action action;
std::set<GlobalTransition*> allBut;
std::list<ExecContentSeqItem> ecSeq;
for (std::list<GlobalTransition::Action>::const_iterator actionIter = transition->actions.begin(); actionIter != transition->actions.end(); actionIter++) {
// for every executable content in base transition
const GlobalTransition::Action& baseAction = *actionIter;
allBut.clear();
for (actionIters_t::iterator histActionIter = actionIters.begin(); histActionIter != actionIters.end(); histActionIter++) {
// iterate every history transition
GlobalTransition* histTrans = histActionIter->first;
if (histActionIter->second.first == histActionIter->second.second) // TODO: is this correct?
continue;
GlobalTransition::Action& histAction = *(histActionIter->second.first);
// is the current action identical or a generated raise for done.state.ID?
// std::cerr << baseAction << std::endl;
// std::cerr << histAction << std::endl;
if (baseAction != histAction && !baseAction.raiseDone) {
// std::cout << baseAction << std::endl;
// std::cout << histAction << std::endl;
// executable content differs - will given executable content appear later in history?
if (actionsInTransition[histTrans].find(baseAction) != actionsInTransition[histTrans].end()) {
// yes -> write all exec content exclusive to this history transition until base executable content
while(baseAction != *(histActionIter->second.first)) {
histAction = *(histActionIter->second.first);
ecSeq.push_back(ExecContentSeqItem(ExecContentSeqItem::EXEC_CONTENT_ONLY_FOR, histTrans, histAction));
actionsInTransition[histTrans].erase(histAction);
histActionIter->second.first++;
}
} else {
// no -> exclude this history transition
allBut.insert(histTrans);
}
} else {
// that's great, they are equal, just increase iterator
histActionIter->second.first++;
}
}
if (allBut.empty()) {
// everyone has the current actionIter one behind the base action
ecSeq.push_back(ExecContentSeqItem(ExecContentSeqItem::EXEC_CONTENT_EVERY, NULL, baseAction));
} else {
// everyone but some have this content
ecSeq.push_back(ExecContentSeqItem(ExecContentSeqItem::EXEC_CONTENT_ALL_BUT, allBut, baseAction));
}
}
// see what remains in history transitions and add as exclusive
for (actionIters_t::iterator histActionIter = actionIters.begin(); histActionIter != actionIters.end(); histActionIter++) {
GlobalTransition* histTrans = histActionIter->first;
while(histActionIter->second.first != histActionIter->second.second) {
GlobalTransition::Action& histAction = *(histActionIter->second.first);
ecSeq.push_back(ExecContentSeqItem(ExecContentSeqItem::EXEC_CONTENT_ONLY_FOR, histTrans, histAction));
histActionIter->second.first++;
}
}
bool isConditionalized = false;
bool wroteHistoryAssignments = false;
for (std::list<ExecContentSeqItem>::const_iterator ecIter = ecSeq.begin(); ecIter != ecSeq.end(); ecIter++) {
const GlobalTransition::Action& action = ecIter->action;
if (action.exited) {
// first onexit handler writes history assignments
if (!wroteHistoryAssignments) {
writeHistoryAssignments(stream, transition, indent);
wroteHistoryAssignments = true;
}
}
if (!_analyzer->usesInPredicate() && (action.entered || action.exited)) {
continue;
}
if (!isConditionalized && ecIter->type == ExecContentSeqItem::EXEC_CONTENT_ONLY_FOR) {
// assert(!wroteHistoryAssignments); // we need to move assignments after dispatching?
stream << padding << "if" << std::endl;
stream << padding << ":: " << conditionalizeForHist(ecIter->transitions) << " -> {" << std::endl;
padding += " ";
indent++;
isConditionalized = true;
} else if (!isConditionalized && ecIter->type == ExecContentSeqItem::EXEC_CONTENT_ALL_BUT) {
// assert(!wroteHistoryAssignments); // we need to move assignments after dispatching?
stream << padding << "if" << std::endl;
stream << padding << ":: " << conditionalizeForHist(ecIter->transitions) << " -> skip;" << std::endl;
stream << padding << ":: else -> {" << std::endl;
padding += " ";
indent++;
isConditionalized = true;
}
#if 0
switch (ecIter->type) {
case ExecContentSeqItem::EXEC_CONTENT_ALL_BUT:
std::cout << "ALL_BUT" << std::endl;
break;
case ExecContentSeqItem::EXEC_CONTENT_EVERY:
std::cout << "EVERY" << std::endl;
break;
case ExecContentSeqItem::EXEC_CONTENT_ONLY_FOR:
std::cout << "ONLY_FOR" << std::endl;
break;
default:
break;
}
#endif
if (action.exited) {
// we left a state
stream << padding << _prefix << "_x.states[" << _analyzer->macroForLiteral(ATTR(action.exited, "id")) << "] = false; " << std::endl;
// continue;
}
if (action.entered) {
// we entered a state
stream << padding << _prefix << "_x.states[" << _analyzer->macroForLiteral(ATTR(action.entered, "id")) << "] = true; " << std::endl;
// continue;
}
if (action.transition) {
// this is executable content from a transition
stream << "/* executable content for transition */" << std::endl;
writeExecutableContent(stream, action.transition, indent);
// continue;
}
if (action.onExit) {
// std::cout<< action.onExit << std::endl;
// executable content from an onexit element
if (action.onExit.getParentNode()) // this should not be necessary?
stream << "/* executable content for exiting state " << ATTR_CAST(action.onExit.getParentNode(), "id") << " */" << std::endl;
writeExecutableContent(stream, action.onExit, indent);
// continue;
}
if (action.onEntry) {
// executable content from an onentry element
if (action.onEntry.getParentNode()) // this should not be necessary?
stream << "/* executable content for entering state " << ATTR_CAST(action.onEntry.getParentNode(), "id") << " */" << std::endl;
writeExecutableContent(stream, action.onEntry, indent);
// continue;
}
if (action.raiseDone) {
// executable content from an onentry element
if (action.raiseDone.getParentNode()) // this should not be necessary?
stream << "/* raising done event for " << ATTR_CAST(action.raiseDone.getParentNode(), "id") << " */" << std::endl;
writeExecutableContent(stream, action.raiseDone, indent);
// continue;
}
if (action.invoke) {
// an invoke element
if (_machines.find(action.invoke) != _machines.end()) {
stream << padding << _prefix << "start!" << _analyzer->macroForLiteral(_machines[action.invoke]->_invokerid) << ";" << std::endl;
} else {
if (HAS_ATTR_CAST(action.invoke, "id")) {
stream << padding << _prefix << ATTR_CAST(action.invoke, "id") << "Running = true;" << std::endl;
}
}
}
if (action.uninvoke) {
if (_machines.find(action.uninvoke) != _machines.end()) {
stream << padding << "do" << std::endl;
stream << padding << ":: " << _prefix << "start??" << _analyzer->macroForLiteral(_machines[action.uninvoke]->_invokerid) << " -> skip" << std::endl;
stream << padding << ":: else -> break;" << std::endl;
stream << padding << "od" << std::endl;
stream << padding << _machines[action.uninvoke]->_prefix << "canceled = true;" << std::endl;
if (_analyzer->usesEventField("delay")) {
stream << padding << "removePendingEventsForInvoker(" << _analyzer->macroForLiteral(_machines[action.uninvoke]->_invokerid) << ");" << std::endl;
}
} else {
if (HAS_ATTR_CAST(action.uninvoke, "id")) {
stream << padding << _prefix << ATTR_CAST(action.uninvoke, "id") << "Running = false;" << std::endl;
}
}
}
if (isConditionalized) {
// peek into next content and see if same conditions apply -> keep conditionalization
bool sameCondition = false;
std::list<ExecContentSeqItem>::const_iterator nextIter = ecIter;
nextIter++;
if (nextIter != ecSeq.end() && ecIter->type == nextIter->type && ecIter->transitions == nextIter->transitions) {
sameCondition = true;
}
if (!sameCondition) {
padding = padding.substr(2);
indent--;
if (ecIter->type == ExecContentSeqItem::EXEC_CONTENT_ALL_BUT) {
stream << padding << "}" << std::endl;
stream << padding << "fi" << std::endl << std::endl;
} else if(ecIter->type == ExecContentSeqItem::EXEC_CONTENT_ONLY_FOR) {
stream << padding << "}" << std::endl;
stream << padding << ":: else -> skip;" << std::endl;
stream << padding << "fi;" << std::endl << std::endl;
}
isConditionalized = false;
}
}
}
if (!wroteHistoryAssignments) {
writeHistoryAssignments(stream, transition, indent);
wroteHistoryAssignments = true;
}
// write new state assignment and goto dispatching
GlobalState* origNewState = NULL;
// sort history transitions by new active state
std::map<GlobalState*, std::set<GlobalTransition*> > histTargets;
histIter = transition->historyTrans.begin();
while(histIter != transition->historyTrans.end()) {
origNewState = _activeConf[(*histIter)->activeDestination];
assert(origNewState != NULL);
histTargets[origNewState].insert(*histIter);
histIter++;
}
origNewState = _activeConf[transition->activeDestination];
bool hasHistoryTarget = false;
for (std::map<GlobalState*, std::set<GlobalTransition*> >::const_iterator histTargetIter = histTargets.begin(); histTargetIter != histTargets.end(); histTargetIter++) {
GlobalState* histNewState = histTargetIter->first;
if (histNewState == origNewState)
continue;
stream << padding << "if" << std::endl;
if (!envVarIsTrue("USCXML_ANNOTATE_NOCOMMENT")) {
stream << "/* to state ";
FlatStateIdentifier flatActiveDest(histNewState->activeId);
PRETTY_PRINT_LIST(stream, flatActiveDest.getActive());
stream << " via history */" << std::endl;
}
stream << padding << ":: " << conditionalizeForHist(histTargetIter->second) << " -> " << _prefix << "s = s" << histNewState->activeIndex << ";" << std::endl;
// writeTransitionClosure(stream, *histTargetIter->second.begin(), histNewState, indent + 1); // is this correct for everyone in set?
hasHistoryTarget = true;
}
origNewState = _activeConf[transition->activeDestination];
FlatStateIdentifier flatActiveDest(transition->activeDestination);
assert(origNewState != NULL);
if (!envVarIsTrue("USCXML_ANNOTATE_NOCOMMENT")) {
stream << "/* to state ";
PRETTY_PRINT_LIST(stream, flatActiveDest.getActive());
stream << " */" << std::endl;
}
if (hasHistoryTarget) {
stream << padding << ":: else -> ";
padding += " ";
indent++;
}
stream << padding << _prefix << "s = s" << origNewState->activeIndex << ";" << std::endl;
if (hasHistoryTarget) {
padding = padding.substr(2);
indent--;
// stream << padding << "}" << std::endl;
stream << padding << "fi;" << std::endl;
}
TRANSITION_TRACE(transition, false);
padding = padding.substr(2);
stream << padding << "}" << std::endl;
// moved up here for goto from d_step
writeTransitionClosure(stream, transition, origNewState, indent-1);
_perfTransProcessed++;
_perfTransTotal++;
DUMP_STATS(false);
}
void ChartToPromela::writeHistoryAssignments(std::ostream& stream, GlobalTransition* transition, int indent) {
std::string padding;
for (int i = 0; i < indent; i++) {
padding += " ";
}
if (transition->historyTrans.size() == 0)
return;
// GlobalState to *changed* history configuration
std::list<HistoryTransitionClass> histClasses;
std::set<GlobalTransition*> allTrans;
allTrans.insert(transition);
allTrans.insert(transition->historyTrans.begin(), transition->historyTrans.end());
// iterate all transitions
std::set<GlobalTransition*>::iterator transIter = allTrans.begin();
while(transIter != allTrans.end()) {
histClasses.push_back(HistoryTransitionClass(*transIter));
transIter++;
}
// nothing to do here
if (histClasses.size() == 0)
return;
// std::cout << histClasses.size() << " / ";
// now sort into equivalence classes
std::list<HistoryTransitionClass>::iterator outerHistClassIter = histClasses.begin();
std::list<HistoryTransitionClass>::iterator innerHistClassIter = histClasses.begin();
while(outerHistClassIter != histClasses.end()) {
HistoryTransitionClass& outerClass = *outerHistClassIter;
// iterate inner iter for every outer iter and see if we can merge
innerHistClassIter = outerHistClassIter;
innerHistClassIter++;
while(innerHistClassIter != histClasses.end()) {
// can we merge the inner class into the outer one?
HistoryTransitionClass& innerClass = *innerHistClassIter;
if (outerClass.matches(innerClass)) {
outerClass.merge(innerClass);
histClasses.erase(innerHistClassIter++);
} else {
innerHistClassIter++;
}
}
_perfHistoryProcessed++;
_perfHistoryTotal++;
outerHistClassIter++;
}
// std::cout << histClasses.size() << std::endl;
bool preambelWritten = false;
std::list<HistoryTransitionClass>::iterator histClassIter = histClasses.begin();
std::list<HistoryTransitionClass>::iterator defaultHistClassIter = histClasses.end();
size_t nrMembers = 0;
while(histClassIter != histClasses.end() || defaultHistClassIter != histClasses.end()) {
// remember iterator position with default transition
if (histClassIter == histClasses.end() && defaultHistClassIter != histClasses.end()) {
histClassIter = defaultHistClassIter;
} else if (histClassIter->members.find(transition) != histClassIter->members.end()) {
defaultHistClassIter = histClassIter;
histClassIter++;
continue;
}
nrMembers += histClassIter->members.size();
if (!preambelWritten && histClasses.size() > 1) {
stream << padding << "if" << std::endl;
preambelWritten = true;
}
if (histClasses.size() > 1) {
stream << padding << "::" << conditionalizeForHist(histClassIter->members) << " {" << std::endl;
}
{
std::map<std::string, std::set<std::string> >::iterator forgetIter = histClassIter->toForget.begin();
while(forgetIter != histClassIter->toForget.end()) {
std::set<std::string>::iterator forgetMemberIter = forgetIter->second.begin();
while(forgetMemberIter != forgetIter->second.end()) {
stream << padding << _prefix << "_hist_" << boost::to_lower_copy(_analyzer->macroForLiteral(forgetIter->first));
stream << "[" << _historyMembers[forgetIter->first][*forgetMemberIter] << "] = 0;";
stream << " \t/* " << *forgetMemberIter << " */" << std::endl;
forgetMemberIter++;
}
forgetIter++;
}
}
{
std::map<std::string, std::set<std::string> >::iterator rememberIter = histClassIter->toRemember.begin();
while(rememberIter != histClassIter->toRemember.end()) {
std::set<std::string>::iterator rememberMemberIter = rememberIter->second.begin();
while(rememberMemberIter != rememberIter->second.end()) {
stream << padding << _prefix << "_hist_" << boost::to_lower_copy(_analyzer->macroForLiteral(rememberIter->first));
stream << "[" << _historyMembers[rememberIter->first][*rememberMemberIter] << "] = 1;";
stream << " \t/* " << *rememberMemberIter << " */" << std::endl;
rememberMemberIter++;
}
rememberIter++;
}
}
if (histClasses.size() > 1) {
stream << padding << "}" << std::endl;
}
if (histClassIter == defaultHistClassIter) {
break;
}
histClassIter++;
}
assert(nrMembers == allTrans.size());
}
HistoryTransitionClass::HistoryTransitionClass(GlobalTransition* transition) {
members.insert(transition);
init(transition->source, transition->destination);
}
HistoryTransitionClass::HistoryTransitionClass(const std::string& from, const std::string& to) {
init(from, to);
}
void HistoryTransitionClass::init(const std::string& from, const std::string& to) {
if (from == to)
return;
FlatStateIdentifier flatSource(from);
FlatStateIdentifier flatTarget(to);
std::map<std::string, std::set<std::string> > activeBefore = flatSource.getHistorySets();
std::map<std::string, std::set<std::string> > activeAfter = flatTarget.getHistorySets();
std::map<std::string, std::set<std::string> >::const_iterator targetHistIter = activeAfter.begin();
while(targetHistIter != activeAfter.end()) {
// for every history state in target, see if it existed in source
if (activeBefore.find(targetHistIter->first) == activeBefore.end()) {
// this target history did not exist source -> every item is changed
std::set<std::string>::const_iterator histMemberIter = activeAfter.at(targetHistIter->first).begin();
while(histMemberIter != activeAfter.at(targetHistIter->first).end()) {
toRemember[targetHistIter->first].insert(*histMemberIter);
histMemberIter++;
}
} else {
// this target *did* already exist, but was it equally assigned?
std::set<std::string>::const_iterator sourceHistMemberIter = activeBefore.at(targetHistIter->first).begin();
while(sourceHistMemberIter != activeBefore.at(targetHistIter->first).end()) {
// iterate every item in source and try to find it in target
if (targetHistIter->second.find(*sourceHistMemberIter) == targetHistIter->second.end()) {
// no, source is no longer in target
toForget[targetHistIter->first].insert(*sourceHistMemberIter);
} else {
toKeep[targetHistIter->first].insert(*sourceHistMemberIter);
}
sourceHistMemberIter++;
}
std::set<std::string>::const_iterator targetHistMemberIter = activeAfter.at(targetHistIter->first).begin();
while(targetHistMemberIter != activeAfter.at(targetHistIter->first).end()) {
// iterate member of target history and see if it is new
if (activeBefore.at(targetHistIter->first).find(*targetHistMemberIter) == activeBefore.at(targetHistIter->first).end()) {
// not found -> new assignment
toRemember[targetHistIter->first].insert(*targetHistMemberIter);
}
targetHistMemberIter++;
}
}
targetHistIter++;
}
}
bool HistoryTransitionClass::matches(const HistoryTransitionClass& other) {
/* does the given transition match this one?:
1. everything remembered has to be remembered as well or already enabled
2. everything forgot has to be forgotten as well or already disabled
and vice versa
*/
std::map<std::string, std::set<std::string> > tmp;
typedef std::map<std::string, std::set<std::string> >::const_iterator histIter_t;
typedef std::set<std::string>::const_iterator histMemberIter_t;
// we will remember these - will the other try to forget them?
INTERSECT_MAPS(toRemember, other.toForget, tmp);
if (tmp.size() > 0)
return false;
// we will keep these - will the other try to forget them?
INTERSECT_MAPS(toKeep, other.toForget, tmp);
if (tmp.size() > 0)
return false;
// we will forget these - will the other try to keep or even remember?
INTERSECT_MAPS(toForget, other.toKeep, tmp);
if (tmp.size() > 0)
return false;
INTERSECT_MAPS(toForget, other.toRemember, tmp);
if (tmp.size() > 0)
return false;
return true;
}
void HistoryTransitionClass::merge(const HistoryTransitionClass& other) {
members.insert(other.members.begin(), other.members.end());
std::map<std::string, std::set<std::string> >::const_iterator histIter;
histIter = other.toRemember.begin();
while(histIter != other.toRemember.end()) {
toRemember[histIter->first].insert(histIter->second.begin(), histIter->second.end());
histIter++;
}
histIter = other.toForget.begin();
while(histIter != other.toForget.end()) {
toForget[histIter->first].insert(histIter->second.begin(), histIter->second.end());
histIter++;
}
histIter = other.toKeep.begin();
while(histIter != other.toKeep.end()) {
toKeep[histIter->first].insert(histIter->second.begin(), histIter->second.end());
histIter++;
}
}
void ChartToPromela::writeTransitionClosure(std::ostream& stream, GlobalTransition* transition, GlobalState* state, int indent) {
std::string padding;
for (int i = 0; i < indent; i++) {
padding += " ";
}
// if (_traceTransitions) {
// for (std::set<int>::iterator transRefIter = transition->transitionRefs.begin(); transRefIter != transition->transitionRefs.end(); transRefIter++) {
// stream << padding << _prefix << "transitions[" << *transRefIter << "] = false; " << std::endl;
// }
// }
if (state->isFinal) {
stream << padding << "goto " << _prefix << "terminate;" << std::endl;
} else {
if (!transition->isEventless) {
stream << padding << _prefix << "spontaneous = true;" << std::endl;
}
stream << padding << "goto " << _prefix << "microStep;" << std::endl;
}
}
void ChartToPromela::writeExecutableContent(std::ostream& stream, const Arabica::DOM::Node<std::string>& node, int indent) {
if (!node)
return;
std::string padding;
for (int i = 0; i < indent; i++) {
padding += " ";
}
if (node.getNodeType() == Node_base::TEXT_NODE) {
if (boost::trim_copy(node.getNodeValue()).length() > 0)
stream << beautifyIndentation(ADAPT_SRC(node.getNodeValue()), indent) << std::endl;
}
if (node.getNodeType() != Node_base::ELEMENT_NODE)
return; // skip anything not an element
Arabica::DOM::Element<std::string> nodeElem = Arabica::DOM::Element<std::string>(node);
if (false) {
} else if(TAGNAME(nodeElem) == "onentry" || TAGNAME(nodeElem) == "onexit" || TAGNAME(nodeElem) == "transition" || TAGNAME(nodeElem) == "finalize") {
// descent into childs and write their contents
Arabica::DOM::Node<std::string> child = node.getFirstChild();
while(child) {
writeExecutableContent(stream, child, indent);
child = child.getNextSibling();
}
} else if(TAGNAME(nodeElem) == "script") {
NodeSet<std::string> scriptText = filterChildType(Node_base::TEXT_NODE, node, true);
for (int i = 0; i < scriptText.size(); i++) {
stream << ADAPT_SRC(beautifyIndentation(scriptText[i].getNodeValue(), indent)) << std::endl;
}
} else if(TAGNAME(nodeElem) == "log") {
std::string label = (HAS_ATTR(nodeElem, "label") ? ATTR(nodeElem, "label") : "");
std::string expr = (HAS_ATTR(nodeElem, "expr") ? ADAPT_SRC(ATTR(nodeElem, "expr")) : "");
std::string trimmedExpr = boost::trim_copy(expr);
bool isStringLiteral = (boost::starts_with(trimmedExpr, "\"") || boost::starts_with(trimmedExpr, "'"));
std::string formatString;
std::string varString;
std::string seperator;
if (label.size() > 0) {
if (expr.size() > 0) {
formatString += label + ": ";
} else {
formatString += label;
}
}
if (isStringLiteral) {
formatString += expr;
} else if (expr.size() > 0) {
formatString += "%d";
varString += seperator + expr;
}
if (varString.length() > 0) {
stream << padding << "printf(\"" + formatString + "\", " + varString + ");" << std::endl;
} else {
stream << padding << "printf(\"" + formatString + "\");" << std::endl;
}
} else if(TAGNAME(nodeElem) == "foreach") {
stream << padding << "for (" << _prefix << (HAS_ATTR(nodeElem, "index") ? ATTR(nodeElem, "index") : "_index") << " in " << _prefix << ATTR(nodeElem, "array") << ") {" << std::endl;
if (HAS_ATTR(nodeElem, "item")) {
stream << padding << " " << _prefix << ATTR(nodeElem, "item") << " = " << _prefix << ATTR(nodeElem, "array") << "[" << _prefix << (HAS_ATTR(nodeElem, "index") ? ATTR(nodeElem, "index") : "_index") << "];" << std::endl;
}
Arabica::DOM::Node<std::string> child = node.getFirstChild();
while(child) {
writeExecutableContent(stream, child, indent + 1);
child = child.getNextSibling();
}
// if (HAS_ATTR(nodeElem, "index"))
// stream << padding << " " << _prefix << ATTR(nodeElem, "index") << "++;" << std::endl;
stream << padding << "}" << std::endl;
} else if(TAGNAME(nodeElem) == "if") {
NodeSet<std::string> condChain;
condChain.push_back(node);
condChain.push_back(filterChildElements(_nsInfo.xmlNSPrefix + "elseif", node));
condChain.push_back(filterChildElements(_nsInfo.xmlNSPrefix + "else", node));
writeIfBlock(stream, condChain, indent);
} else if(TAGNAME(nodeElem) == "assign") {
NodeSet<std::string> assignTexts = filterChildType(Node_base::TEXT_NODE, nodeElem, true);
assert(assignTexts.size() > 0);
stream << beautifyIndentation(ADAPT_SRC(boost::trim_copy(assignTexts[0].getNodeValue())), indent) << std::endl;
} else if(TAGNAME(nodeElem) == "send" || TAGNAME(nodeElem) == "raise") {
std::string targetQueue;
std::string insertOp = "!";
if (TAGNAME(nodeElem) == "raise") {
targetQueue = _prefix + "iQ";
} else if (!HAS_ATTR(nodeElem, "target")) {
if (_allowEventInterleaving) {
targetQueue = _prefix + "tmpQ";
} else {
targetQueue = _prefix + "eQ";
}
} else if (ATTR(nodeElem, "target").compare("#_internal") == 0) {
targetQueue = _prefix + "iQ";
} else if (ATTR(nodeElem, "target").compare("#_parent") == 0) {
targetQueue = _parent->_prefix + "eQ";
} else if (boost::starts_with(ATTR(nodeElem, "target"), "#_") && _machinesPerId.find(ATTR(nodeElem, "target").substr(2)) != _machinesPerId.end()) {
targetQueue = _machines[_machinesPerId[ATTR(nodeElem, "target").substr(2)]]->_prefix + "eQ";
}
if (targetQueue.length() > 0) {
// this is for our external queue
std::string event;
if (HAS_ATTR(nodeElem, "event")) {
event = _analyzer->macroForLiteral(ATTR(nodeElem, "event"));
} else if (HAS_ATTR(nodeElem, "eventexpr")) {
event = ADAPT_SRC(ATTR(nodeElem, "eventexpr"));
}
if (_analyzer->usesComplexEventStruct()) {
stream << padding << "{" << std::endl;
std::string typeReset = _analyzer->getTypeReset("tmpE", _analyzer->getType("_event"), padding + " ");
std::stringstream typeAssignSS;
typeAssignSS << padding << " tmpE.name = " << event << ";" << std::endl;
if (HAS_ATTR(nodeElem, "idlocation")) {
typeAssignSS << padding << " /* idlocation */" << std::endl;
typeAssignSS << padding << " _lastSendId = _lastSendId + 1;" << std::endl;
typeAssignSS << padding << " " << _prefix << ATTR(nodeElem, "idlocation") << " = _lastSendId;" << std::endl;
typeAssignSS << padding << " tmpE.sendid = _lastSendId;" << std::endl;
typeAssignSS << padding << " if" << std::endl;
typeAssignSS << padding << " :: _lastSendId == 2147483647 -> _lastSendId = 0;" << std::endl;
typeAssignSS << padding << " :: else -> skip;" << std::endl;
typeAssignSS << padding << " fi;" << std::endl;
} else if (HAS_ATTR(nodeElem, "id")) {
typeAssignSS << padding << " tmpE.sendid = " << _analyzer->macroForLiteral(ATTR(nodeElem, "id")) << ";" << std::endl;
}
if (_invokerid.length() > 0) { // do not send invokeid if we send / raise to ourself
typeAssignSS << padding << " tmpE.invokeid = " << _analyzer->macroForLiteral(_invokerid) << ";" << std::endl;
}
if (_analyzer->usesEventField("origintype") && !boost::ends_with(targetQueue, "iQ")) {
typeAssignSS << padding << " tmpE.origintype = " << _analyzer->macroForLiteral("http://www.w3.org/TR/scxml/#SCXMLEventProcessor") << ";" << std::endl;
}
if (_analyzer->usesEventField("delay")) {
#if NEW_DELAY_RESHUFFLE
#else
insertOp += "!";
typeAssignSS << padding << " _lastSeqId = _lastSeqId + 1;" << std::endl;
#endif
if (HAS_ATTR_CAST(nodeElem, "delay")) {
typeAssignSS << padding << " tmpE.delay = " << ATTR_CAST(nodeElem, "delay") << ";" << std::endl;
} else if (HAS_ATTR_CAST(nodeElem, "delayexpr")) {
typeAssignSS << padding << " tmpE.delay = " << ADAPT_SRC(ATTR_CAST(nodeElem, "delayexpr")) << ";" << std::endl;
} else {
typeAssignSS << padding << " tmpE.delay = 0;" << std::endl;
}
#if NEW_DELAY_RESHUFFLE
#else
typeAssignSS << padding << " tmpE.seqNr = _lastSeqId;" << std::endl;
#endif
}
if (_analyzer->usesEventField("type")) {
std::string eventType = (targetQueue.compare("iQ!") == 0 ? _analyzer->macroForLiteral("internal") : _analyzer->macroForLiteral("external"));
typeAssignSS << padding << " tmpE.type = " << eventType << ";" << std::endl;
}
NodeSet<std::string> sendParams = filterChildElements(_nsInfo.xmlNSPrefix + "param", nodeElem);
NodeSet<std::string> sendContents = filterChildElements(_nsInfo.xmlNSPrefix + "content", nodeElem);
std::string sendNameList = ATTR(nodeElem, "namelist");
if (sendParams.size() > 0) {
for (int i = 0; i < sendParams.size(); i++) {
Element<std::string> paramElem = Element<std::string>(sendParams[i]);
typeAssignSS << padding << " tmpE.data." << ATTR(paramElem, "name") << " = " << ADAPT_SRC(ATTR(paramElem, "expr")) << ";" << std::endl;
}
}
if (sendNameList.size() > 0) {
std::list<std::string> nameListIds = tokenizeIdRefs(sendNameList);
std::list<std::string>::iterator nameIter = nameListIds.begin();
while(nameIter != nameListIds.end()) {
typeAssignSS << padding << " tmpE.data." << *nameIter << " = " << ADAPT_SRC(*nameIter) << ";" << std::endl;
nameIter++;
}
}
if (sendParams.size() == 0 && sendNameList.size() == 0 && sendContents.size() > 0) {
Element<std::string> contentElem = Element<std::string>(sendContents[0]);
if (contentElem.hasChildNodes() && contentElem.getFirstChild().getNodeType() == Node_base::TEXT_NODE) {
std::string content = spaceNormalize(contentElem.getFirstChild().getNodeValue());
if (!isNumeric(content.c_str(), 10)) {
typeAssignSS << padding << " tmpE.data = " << _analyzer->macroForLiteral(content) << ";" << std::endl;
} else {
typeAssignSS << padding << " tmpE.data = " << content << ";" << std::endl;
}
} else if (HAS_ATTR(contentElem, "expr")) {
typeAssignSS << padding << " tmpE.data = " << ADAPT_SRC(ATTR(contentElem, "expr")) << ";" << std::endl;
}
}
// remove all fields from typeReset that are indeed set by typeAssign
// for (std::string assigned; std::getline(typeAssignSS, assigned); ) {
// assigned = assigned.substr(0, assigned.find('='));
// assigned = assigned.substr(assigned.find('.'));
// std::istringstream typeResetSS (typeReset);
// for (std::string reset; std::getline(typeResetSS, reset); ) {
// if (!boost::find_first(reset, assigned)) {
// stream << reset << std::endl;
// }
// }
// }
// stream << typeAssignSS.str();
std::istringstream typeResetSS (typeReset);
for (std::string reset; std::getline(typeResetSS, reset); ) {
std::string resetField = reset.substr(0, reset.find('='));
resetField = resetField.substr(resetField.find('.'));
for (std::string assigned; std::getline(typeAssignSS, assigned); ) {
if (boost::find_first(resetField, assigned)) {
break;
}
}
stream << reset << std::endl;
}
stream << typeAssignSS.str();
stream << padding << " " << targetQueue << insertOp <<"tmpE;" << std::endl;
#if NEW_DELAY_RESHUFFLE
if (_analyzer->usesEventField("delay") && !boost::ends_with(targetQueue, "iQ")) {
stream << padding << " insertWithDelay(" << targetQueue << ");" << std::endl;
}
#endif
stream << padding << "}" << std::endl;
} else {
stream << padding << targetQueue << insertOp << event << ";" << std::endl;
}
}
} else if(TAGNAME(nodeElem) == "cancel") {
if (HAS_ATTR(nodeElem, "sendid")) {
stream << padding << "cancelSendId(" << _analyzer->macroForLiteral(ATTR(nodeElem, "sendid")) << ", " << (_invokerid.size() > 0 ? _analyzer->macroForLiteral(_invokerid) : "0") << ");" << std::endl;
} else if (HAS_ATTR(nodeElem, "sendidexpr")) {
stream << padding << "cancelSendId(" << ADAPT_SRC(ATTR(nodeElem, "sendidexpr")) << ", " << (_invokerid.size() > 0 ? _analyzer->macroForLiteral(_invokerid) : "0") << ");" << std::endl;
}
} else {
std::cerr << "'" << TAGNAME(nodeElem) << "'" << std::endl << nodeElem << std::endl;
assert(false);
}
}
PromelaInlines::~PromelaInlines() {
return;
}
std::list<PromelaInline*> PromelaInlines::getRelatedTo(const Arabica::DOM::Node<std::string>& node, PromelaInline::PromelaInlineType type) {
std::list<PromelaInline*> related;
std::map<Arabica::DOM::Node<std::string>, std::list<PromelaInline*> >::iterator inlIter = inlines.begin();
while (inlIter != inlines.end()) {
std::list<PromelaInline*>::iterator pmlIter = inlIter->second.begin();
while (pmlIter != inlIter->second.end()) {
if ((type != PromelaInline::PROMELA_NIL || (*pmlIter)->type == type) && (*pmlIter)->relatesTo(node)) {
related.push_back(*pmlIter);
}
pmlIter++;
}
inlIter++;
}
return related;
return related;
}
std::list<PromelaInline*> PromelaInlines::getAllOfType(uint32_t type) {
std::list<PromelaInline*> related;
std::map<Arabica::DOM::Node<std::string>, std::list<PromelaInline*> >::iterator inlIter = inlines.begin();
while (inlIter != inlines.end()) {
std::list<PromelaInline*>::iterator pmlIter = inlIter->second.begin();
while (pmlIter != inlIter->second.end()) {
if ((*pmlIter)->type & type) {
related.push_back(*pmlIter);
}
pmlIter++;
}
inlIter++;
}
return related;
}
PromelaInline::PromelaInline(const Arabica::DOM::Node<std::string>& node) : prevSibling(NULL), nextSibling(NULL), type(PROMELA_NIL) {
if (node.getNodeType() != Node_base::COMMENT_NODE && node.getNodeType() != Node_base::TEXT_NODE)
return; // nothing to do
std::stringstream ssLine(node.getNodeValue());
std::string line;
while(std::getline(ssLine, line)) {
// skip to first promela line
boost::trim(line);
if (boost::starts_with(line, "promela"))
break;
}
if (!boost::starts_with(line, "promela"))
return;
if (false) {
} else if (boost::starts_with(line, "promela-code")) {
type = PROMELA_CODE;
} else if (boost::starts_with(line, "promela-ltl")) {
type = PROMELA_LTL;
} else if (boost::starts_with(line, "promela-event-all")) {
type = PROMELA_EVENT_ALL_BUT;
} else if (boost::starts_with(line, "promela-event")) {
type = PROMELA_EVENT_ONLY;
} else if (boost::starts_with(line, "promela-progress")) {
type = PROMELA_PROGRESS_LABEL;
} else if (boost::starts_with(line, "promela-accept")) {
type = PROMELA_ACCEPT_LABEL;
} else if (boost::starts_with(line, "promela-end")) {
type = PROMELA_END_LABEL;
}
std::stringstream contentSS;
size_t endType = line.find_first_of(": \n");
std::string seperator;
if (endType != std::string::npos && endType + 1 < line.size()) {
contentSS << line.substr(endType + 1, line.size() - endType + 1);
seperator = "\n";
}
while(std::getline(ssLine, line)) {
boost::trim(line);
if (boost::starts_with(line, "promela")) {
std::cerr << "Split multiple #promela pragmas into multiple comments!" << std::endl;
break;
}
contentSS << seperator << line;
seperator = "\n";
}
content = contentSS.str();
}
PromelaInlines::PromelaInlines(const Arabica::DOM::Node<std::string>& node) {
NodeSet<std::string> levelNodes;
levelNodes.push_back(node);
size_t level = 0;
while(levelNodes.size() > 0) {
PromelaInline* predecessor = NULL;
// iterate all nodes at given level
for (int i = 0; i < levelNodes.size(); i++) {
// get all comments
NodeSet<std::string> comments = InterpreterImpl::filterChildType(Node_base::COMMENT_NODE, levelNodes[i]);
for (int j = 0; j < comments.size(); j++) {
PromelaInline* tmp = new PromelaInline(comments[j]);
if (tmp->type == PromelaInline::PROMELA_NIL) {
delete tmp;
continue;
}
if (predecessor != NULL) {
tmp->prevSibling = predecessor;
predecessor->nextSibling = tmp;
}
tmp->level = level;
tmp->container = Element<std::string>(levelNodes[i]);
predecessor = tmp;
inlines[levelNodes[i]].push_back(tmp);
allInlines.push_back(tmp);
}
}
levelNodes = InterpreterImpl::filterChildType(Node_base::ELEMENT_NODE, levelNodes);
level++;
}
}
void PromelaInline::dump() {
#if 0
switch(type) {
case PROMELA_NIL:
std::cerr << "PROMELA_NIL" << std::endl;
break;
case PROMELA_CODE:
std::cerr << "PROMELA_CODE" << std::endl;
break;
case PROMELA_EVENT_SOURCE_ALL:
std::cerr << "PROMELA_EVENT_SOURCE" << std::endl;
break;
case PROMELA_INVOKER:
std::cerr << "PROMELA_INVOKER" << std::endl;
break;
case PROMELA_PROGRESS_LABEL:
std::cerr << "PROMELA_PROGRESS_LABEL" << std::endl;
break;
case PROMELA_ACCEPT_LABEL:
std::cerr << "PROMELA_ACCEPT_LABEL" << std::endl;
break;
case PROMELA_END_LABEL:
std::cerr << "PROMELA_END_LABEL" << std::endl;
break;
}
#endif
}
void ChartToPromela::writeIfBlock(std::ostream& stream, const Arabica::XPath::NodeSet<std::string>& condChain, int indent) {
if (condChain.size() == 0)
return;
std::string padding;
for (int i = 0; i < indent; i++) {
padding += " ";
}
bool noNext = condChain.size() == 1;
bool nextIsElse = false;
if (condChain.size() > 1) {
if (TAGNAME_CAST(condChain[1]) == "else") {
nextIsElse = true;
}
}
Element<std::string> ifNode = Element<std::string>(condChain[0]);
stream << padding << "if" << std::endl;
// we need to nest the elseifs to resolve promela if semantics
stream << padding << ":: (" << ADAPT_SRC(ATTR(ifNode, "cond")) << ") -> {" << std::endl;
Arabica::DOM::Node<std::string> child;
if (TAGNAME(ifNode) == "if") {
child = ifNode.getFirstChild();
} else {
child = ifNode.getNextSibling();
}
while(child) {
if (child.getNodeType() == Node_base::ELEMENT_NODE) {
Arabica::DOM::Element<std::string> childElem = Arabica::DOM::Element<std::string>(child);
if (TAGNAME(childElem) == "elseif" || TAGNAME_CAST(childElem) == "else")
break;
writeExecutableContent(stream, childElem, indent + 1);
}
child = child.getNextSibling();
}
stream << padding << "}" << std::endl;
stream << padding << ":: else -> ";
if (nextIsElse) {
child = condChain[1].getNextSibling();
stream << "{" << std::endl;
while(child) {
if (child.getNodeType() == Node_base::ELEMENT_NODE) {
writeExecutableContent(stream, child, indent + 1);
}
child = child.getNextSibling();
}
stream << padding << "}" << std::endl;
} else if (noNext) {
stream << "skip;" << std::endl;
} else {
stream << "{" << std::endl;
Arabica::XPath::NodeSet<std::string> cdrCondChain;
for (int i = 1; i < condChain.size(); i++) {
cdrCondChain.push_back(condChain[i]);
}
writeIfBlock(stream, cdrCondChain, indent + 1);
stream << padding << "}" << std::endl;
}
stream << padding << "fi;" << std::endl;
}
std::string ChartToPromela::beautifyIndentation(const std::string& code, int indent) {
std::string padding;
for (int i = 0; i < indent; i++) {
padding += " ";
}
// remove topmost indentation from every line and reindent
std::stringstream beautifiedSS;
std::string initialIndent;
bool gotIndent = false;
bool isFirstLine = true;
std::stringstream ssLine(code);
std::string line;
while(std::getline(ssLine, line)) {
size_t firstChar = line.find_first_not_of(" \t\r\n");
if (firstChar != std::string::npos) {
if (!gotIndent) {
initialIndent = line.substr(0, firstChar);
gotIndent = true;
}
beautifiedSS << (isFirstLine ? "" : "\n") << padding << boost::replace_first_copy(line, initialIndent, "");
isFirstLine = false;
}
}
return beautifiedSS.str();
}
void ChartToPromela::writeStrings(std::ostream& stream) {
stream << "/* string literals */" << std::endl;
std::set<std::string> literals = _analyzer->getLiterals();
std::map<std::string, int> events = _analyzer->getEvents();
std::map<std::string, int> origStates = _analyzer->getOrigStates();
for (std::set<std::string>::const_iterator litIter = literals.begin(); litIter != literals.end(); litIter++) {
if (events.find(*litIter) == events.end() && (origStates.find(*litIter) == origStates.end() || !_analyzer->usesInPredicate()))
stream << "#define " << _analyzer->macroForLiteral(*litIter) << " " << _analyzer->indexForLiteral(*litIter) << " /* " << *litIter << " */" << std::endl;
}
}
void ChartToPromela::writeDeclarations(std::ostream& stream) {
stream << "/* global variables " << (_prefix.size() > 0 ? "for " + _prefix : "") << " */" << std::endl;
// we cannot know our event queue with nested invokers? Adding some for test422
size_t tolerance = 6;
if (_analyzer->usesComplexEventStruct()) {
// event is defined with the typedefs
stream << "_event_t " << _prefix << "_event; /* current event */" << std::endl;
stream << "unsigned " << _prefix << "s : " << BIT_WIDTH(_activeConf.size() + 1) << "; /* current state */" << std::endl;
stream << "chan " << _prefix << "iQ = [" << MAX(_internalQueueLength, 1) << "] of {_event_t} /* internal queue */" << std::endl;
stream << "chan " << _prefix << "eQ = [" << _externalQueueLength + tolerance << "] of {_event_t} /* external queue */" << std::endl;
if (_allowEventInterleaving)
stream << "chan " << _prefix << "tmpQ = [" << MAX(_externalQueueLength + tolerance, 1) << "] of {_event_t} /* temporary queue for external events in transitions */" << std::endl;
} else {
stream << "unsigned " << _prefix << "_event : " << BIT_WIDTH(_analyzer->getEvents().size() + 1) << "; /* current event */" << std::endl;
stream << "unsigned " << _prefix << "s : " << BIT_WIDTH(_activeConf.size() + 1) << "; /* current state */" << std::endl;
stream << "chan " << _prefix << "iQ = [" << MAX(_internalQueueLength, 1) << "] of {int} /* internal queue */" << std::endl;
stream << "chan " << _prefix << "eQ = [" << _externalQueueLength + tolerance << "] of {int} /* external queue */" << std::endl;
if (_allowEventInterleaving)
stream << "chan " << _prefix << "tmpQ = [" << MAX(_externalQueueLength + tolerance, 1) << "] of {int} /* temporary queue for external events in transitions */" << std::endl;
// stream << "hidden unsigned " << _prefix << "tmpQItem : " << BIT_WIDTH(_analyzer->getEvents().size() + 1) << ";" << std::endl;
}
if (_machines.size() > 0) {
stream << "chan " << _prefix << "start = [" << _machines.size() << "] of {int} /* nested machines to start at next macrostep */" << std::endl;
}
if (_hasIndexLessLoops)
stream << "hidden int " << _prefix << "_index; /* helper for indexless foreach loops */" << std::endl;
stream << "hidden int " << _prefix << "procid; /* the process id running this machine */" << std::endl;
stream << "bool " << _prefix << "spontaneous; /* whether to take spontaneous transitions */" << std::endl;
stream << "bool " << _prefix << "done; /* is the state machine stopped? */" << std::endl;
stream << "bool " << _prefix << "canceled; /* is the state machine canceled? */" << std::endl;
if (_traceTransitions)
stream << "bool " << _prefix << "transitions[" << indexedTransitions.size() << "]; /* transitions in the optimal transition set */" << std::endl;
if (_analyzer->getTypes().types.find("_ioprocessors") != _analyzer->getTypes().types.end()) {
stream << "hidden _ioprocessors_t " << _prefix << "_ioprocessors;" << std::endl;
_varInitializers.push_front("_ioprocessors.scxml.location = " + (_invokerid.size() > 0 ? _analyzer->macroForLiteral(_invokerid) : "1") + ";");
}
if (_prefix.size() == 0 || _prefix == "MAIN_") {
if (_analyzer->usesEventField("sendid")) {
// stream << "chan sendIdQ = [" << MAX(_externalQueueLength + 1, 1) << "] of {_event_t} /* temporary queue to cancel events per sendidexpr */" << std::endl;
stream << "hidden int _lastSendId = 0; /* sequential counter for send ids */" << std::endl;
}
if (_analyzer->usesEventField("delay")) {
#if NEW_DELAY_RESHUFFLE
#else
stream << "hidden int _lastSeqId = 0; /* sequential counter for delayed events */" << std::endl;
#endif
}
}
// if (_analyzer->usesPlatformVars()) {
// stream << "_x_t _x;" << std::endl;
// }
if (_analyzer->usesInPredicate()) {
stream << "_x_t " << _prefix << "_x;" << std::endl;
}
std::list<PromelaInline*> pmls = pmlInlines.getAllOfType(PromelaInline::PROMELA_EVENT_ALL_BUT | PromelaInline::PROMELA_EVENT_ONLY);
for (std::list<PromelaInline*>::iterator pmlIter = pmls.begin(); pmlIter != pmls.end(); pmlIter++) {
if ((*pmlIter)->container && LOCALNAME((*pmlIter)->container) == "invoke") {
stream << "bool " << _prefix << ATTR_CAST((*pmlIter)->container, "id") << "Running;" << std::endl;
}
}
stream << std::endl << std::endl;
// get all data elements
NodeSet<std::string> datas = _xpath.evaluate("//" + _nsInfo.xpathPrefix + "data", _scxml).asNodeSet();
// write their text content
stream << "/* data model variables" << (_prefix.size() > 0 ? " for " + _prefix : "") << " */" << std::endl;
std::set<std::string> processedIdentifiers;
// automatic types
PromelaCodeAnalyzer::PromelaTypedef allTypes = _analyzer->getTypes();
for (int i = 0; i < datas.size(); i++) {
Node<std::string> data = datas[i];
if (isInEmbeddedDocument(data))
continue;
std::string identifier = (HAS_ATTR_CAST(data, "id") ? ATTR_CAST(data, "id") : "");
std::string type = boost::trim_copy(HAS_ATTR_CAST(data, "type") ? ATTR_CAST(data, "type") : "");
_dataModelVars.insert(identifier);
if (processedIdentifiers.find(identifier) != processedIdentifiers.end())
continue;
processedIdentifiers.insert(identifier);
if (boost::starts_with(type, "string")) {
type = "int" + type.substr(6, type.length() - 6);
}
if (type.length() == 0 || type == "auto") {
if (allTypes.types.find(identifier) != allTypes.types.end()) {
type = allTypes.types[identifier].name;
} else {
LOG(ERROR) << "Automatic or no type for '" << identifier << "' but no type resolved";
continue;
}
}
std::string arrSize;
size_t bracketPos = type.find("[");
if (bracketPos != std::string::npos) {
arrSize = type.substr(bracketPos, type.length() - bracketPos);
type = type.substr(0, bracketPos);
}
std::string decl = type + " " + _prefix + identifier + arrSize;
stream << decl << ";" << std::endl;
}
// implicit and dynamic types
std::map<std::string, PromelaCodeAnalyzer::PromelaTypedef>::iterator typeIter = allTypes.types.begin();
while(typeIter != allTypes.types.end()) {
if (typeIter->second.occurrences.find(this) == typeIter->second.occurrences.end()) {
typeIter++;
continue;
}
if (processedIdentifiers.find(typeIter->first) != processedIdentifiers.end()) {
typeIter++;
continue;
}
if (typeIter->first == "_event" ||
typeIter->first == "_x" ||
typeIter->first == "_ioprocessors" ||
typeIter->first == "_SESSIONID" ||
typeIter->first == "_NAME") {
typeIter++;
continue;
}
processedIdentifiers.insert(typeIter->first);
if (typeIter->second.types.size() == 0) {
stream << "hidden " << declForRange(_prefix + typeIter->first, typeIter->second.minValue, typeIter->second.maxValue) << ";" << std::endl;
} else {
stream << "hidden " << _prefix << typeIter->second.name << " " << typeIter->first << ";" << std::endl;
}
typeIter++;
}
stream << std::endl;
}
void ChartToPromela::writeEventSources(std::ostream& stream) {
}
void ChartToPromela::writeStartInvoker(std::ostream& stream, const Arabica::DOM::Node<std::string>& node, ChartToPromela* invoker, int indent) {
std::string padding;
for (int i = 0; i < indent; i++) {
padding += " ";
}
// set from namelist
if (HAS_ATTR_CAST(node, "namelist")) {
std::list<std::string> namelist = tokenize(ATTR_CAST(node, "namelist"));
for (std::list<std::string>::iterator nlIter = namelist.begin(); nlIter != namelist.end(); nlIter++) {
if (invoker->_dataModelVars.find(*nlIter) != invoker->_dataModelVars.end()) {
stream << padding << invoker->_prefix << *nlIter << " = " << _prefix << *nlIter << ";" << std::endl;
}
}
}
// set from params
NodeSet<std::string> invokeParams = filterChildElements(_nsInfo.xmlNSPrefix + "param", node);
for (int i = 0; i < invokeParams.size(); i++) {
std::string identifier = ATTR_CAST(invokeParams[i], "name");
std::string expression = ATTR_CAST(invokeParams[i], "expr");
if (invoker->_dataModelVars.find(identifier) != invoker->_dataModelVars.end()) {
stream << padding << invoker->_prefix << identifier << " = " << ADAPT_SRC(expression) << ";" << std::endl;
}
}
stream << padding << "run " << invoker->_prefix << "run() priority 20;" << std::endl;
if (HAS_ATTR_CAST(node, "idlocation")) {
stream << padding << ADAPT_SRC(ATTR_CAST(node, "idlocation")) << " = " << _analyzer->macroForLiteral(invoker->_invokerid) << ";" << std::endl;
}
}
void ChartToPromela::writeFSM(std::ostream& stream) {
NodeSet<std::string> transitions;
stream << "proctype " << (_prefix.size() == 0 ? "machine_" : _prefix) << "run() {" << std::endl;
stream << " d_step {" << std::endl;
stream << " " << _prefix << "done = false;" << std::endl;
stream << " " << _prefix << "canceled = false;" << std::endl;
stream << " " << _prefix << "spontaneous = true;" << std::endl;
stream << " " << _prefix << "procid = _pid;" << std::endl;
stream << " }" << std::endl;
// write initial transition
// transitions = filterChildElements(_nsInfo.xmlNSPrefix + "transition", _startState);
// assert(transitions.size() == 1);
NodeSet<std::string> scripts = filterChildElements(_nsInfo.xmlNSPrefix + "script", _scxml, false);
if (scripts.size() > 0) {
stream << std::endl << "/* global scripts */" << std::endl;
for (int i = 0; i < scripts.size(); i++) {
writeExecutableContent(stream, scripts[i], 1);
}
stream << std::endl;
}
stream << std::endl << "/* transition to initial state */" << std::endl;
assert(_start->sortedOutgoing.size() == 1);
// initial transition has to be first one for control flow at start
writeTransition(stream, _start->sortedOutgoing.front(), 1);
stream << std::endl;
// every other transition
for (std::map<std::string, GlobalState*>::iterator stateIter = _activeConf.begin(); stateIter != _activeConf.end(); stateIter++) {
for (std::list<GlobalTransition*>::iterator transIter = stateIter->second->sortedOutgoing.begin(); transIter != stateIter->second->sortedOutgoing.end(); transIter++) {
// don't write invalid transition
if (!(*transIter)->isValid) {
LOG(ERROR) << "Sorted outgoing transitions contains invalid transitions - did you instruct ChartToFSM to keep those?";
abort();
}
// don't write initial transition
if (_start->sortedOutgoing.front() == *transIter)
continue;
// don't write trivial or history transitions
if ((*transIter)->historyBase == NULL) // TODO!
// if ((*transIter)->hasExecutableContent && (*transIter)->historyBase == NULL)
writeTransition(stream, *transIter, 1);
}
_perfStatesProcessed++;
_perfStatesTotal++;
DUMP_STATS(false);
}
DUMP_STATS(true);
stream << std::endl;
stream << _prefix << "macroStep: skip;" << std::endl;
if (_allowEventInterleaving) {
stream << " /* push send events to external queue - this needs to be interleavable! */" << std::endl;
stream << " do" << std::endl;
if (_analyzer->usesEventField("delay")) {
#if NEW_DELAY_RESHUFFLE
stream << " :: len(" << _prefix << "tmpQ) != 0 -> { " << _prefix << "tmpQ?" << _prefix << "_event; " << _prefix << "eQ!" << _prefix << "_event; insertWithDelay(" << _prefix << "eQ); }" << std::endl;
#else
stream << " :: len(" << _prefix << "tmpQ) != 0 -> { " << _prefix << "tmpQ?" << _prefix << "_event; " << _prefix << "eQ!!" << _prefix << "_event }" << std::endl;
#endif
} else {
stream << " :: len(" << _prefix << "tmpQ) != 0 -> { " << _prefix << "tmpQ?" << _prefix << "_event; " << _prefix << "eQ!" << _prefix << "_event }" << std::endl;
}
stream << " :: else -> break;" << std::endl;
stream << " od;" << std::endl << std::endl;
}
if (_machines.size() > 0) {
stream << " /* start pending invokers */" << std::endl;
stream << " int invokerId;" << std::endl;
stream << " do" << std::endl;
stream << " :: " << _prefix << "start?invokerId -> {" << std::endl;
stream << " if " << std::endl;
for (std::map<Arabica::DOM::Node<std::string>, ChartToPromela*>::iterator machIter = _machines.begin(); machIter != _machines.end(); machIter++) {
stream << " :: invokerId == " << _analyzer->macroForLiteral(machIter->second->_invokerid) << " -> {" << std::endl;
writeStartInvoker(stream, machIter->first, machIter->second, 3);
stream << " }" << std::endl;
}
stream << " :: else -> skip; " << std::endl;
stream << " fi " << std::endl;
stream << " }" << std::endl;
stream << " :: else -> break;" << std::endl;
stream << " od" << std::endl << std::endl;
}
if (_analyzer->usesEventField("delay") && _machinesAll->size() > 1) {
stream << "/* Determine machines with smallest delay and set their process priority */" << std::endl;
stream << " scheduleMachines();" << std::endl << std::endl;
}
std::list<PromelaInline*> eventSources = pmlInlines.getAllOfType(PromelaInline::PROMELA_EVENT_ALL_BUT |
PromelaInline::PROMELA_EVENT_ONLY);
stream << " atomic {" << std::endl;
stream << "/* pop an event */" << std::endl;
stream << " if" << std::endl;
stream << " :: len(" << _prefix << "iQ) != 0 -> " << _prefix << "iQ ? " << _prefix << "_event /* from internal queue */" << std::endl;
if (eventSources.size() > 0) {
stream << " :: len(" << _prefix << "eQ) != 0 -> " << _prefix << "eQ ? " << _prefix << "_event /* from external queue */" << std::endl;
stream << " :: else -> {" << std::endl;
stream << " /* external queue is empty -> automatically enqueue external event */" << std::endl;
stream << " if" << std::endl;
for (std::list<PromelaInline*>::iterator esIter = eventSources.begin(); esIter != eventSources.end(); esIter++) {
PromelaEventSource es(**esIter);
std::string condition = "true";
if (LOCALNAME(es.container) == "invoke") {
if (HAS_ATTR_CAST(es.container, "id")) {
condition = _prefix + ATTR_CAST(es.container, "id") + "Running";
} else {
LOG(ERROR) << "Invoker has no id";
}
} else if (HAS_ATTR(es.container, "id")) {
condition = _prefix + "_x.states[" + _analyzer->macroForLiteral(ATTR(es.container, "id")) + "]";
}
stream << " :: " << condition << " -> {" << std::endl;
if (es.type == PromelaInline::PROMELA_EVENT_ALL_BUT) {
std::string excludeEventDescs;
for (std::list<Data>::iterator evIter = es.events.array.begin(); evIter != es.events.array.end(); evIter++) {
excludeEventDescs += " " + evIter->atom;
}
NodeSet<std::string> transitions = filterChildElements("transition", es.container, true);
std::set<std::string> eventNames;
for (int i = 0; i < transitions.size(); i++) {
if (!HAS_ATTR_CAST(transitions[i], "event"))
continue;
if (HAS_ATTR_CAST(transitions[i], "cond") && ATTR_CAST(transitions[i], "cond").find("_event.") != std::string::npos)
continue;
std::list<std::string> events = InterpreterImpl::tokenizeIdRefs(ATTR_CAST(transitions[i], "event"));
for (std::list<std::string>::iterator evIter = events.begin(); evIter != events.end(); evIter++) {
std::string eventName = *evIter;
if (boost::ends_with(eventName, "*"))
eventName = eventName.substr(0, eventName.size() - 1);
if (boost::ends_with(eventName, "."))
eventName = eventName.substr(0, eventName.size() - 1);
// is this event excluded?
if (!InterpreterImpl::nameMatch(excludeEventDescs, eventName)) {
eventNames.insert(eventName);
}
}
}
if (eventNames.size() > 0) {
stream << " if " << std::endl;
for (std::set<std::string>::iterator evIter = eventNames.begin(); evIter != eventNames.end(); evIter++) {
stream << " :: true -> { " << _prefix << "_event" << (_analyzer->usesComplexEventStruct() ? ".name" : "")<< " = " << _analyzer->macroForLiteral(*evIter) << " }" << std::endl;
}
stream << " fi " << std::endl;
}
} else if (es.type == PromelaInline::PROMELA_EVENT_ONLY) {
if (es.events.array.size() > 0) {
stream << " if " << std::endl;
for (std::list<Data>::iterator evIter = es.events.array.begin(); evIter != es.events.array.end(); evIter++) {
stream << " :: true -> { " << std::endl;
stream << dataToAssignments(" _event", *evIter);
stream << " } " << std::endl;
}
stream << " fi " << std::endl;
} else {
stream << dataToAssignments(" _event", es.events);
}
} else {
assert(false);
}
stream << " }" << std::endl;
}
stream << " fi" << std::endl;
stream << " }" << std::endl;
} else {
stream << " :: else -> " << _prefix << "eQ ? " << _prefix << "_event /* from external queue */" << std::endl;
}
stream << " fi;" << std::endl << std::endl;
stream << "/* terminate if we are stopped */" << std::endl;
stream << " if" << std::endl;
stream << " :: " << _prefix << "done -> goto " << _prefix << "terminate;" << std::endl;
if (_parent != NULL) {
stream << " :: " << _prefix << "canceled -> goto " << _prefix << "cancel;" << std::endl;
}
stream << " :: else -> skip;" << std::endl;
stream << " fi;" << std::endl << std::endl;
{
bool finalizeFound = false;
for (std::map<Arabica::DOM::Node<std::string>, ChartToPromela*>::iterator invIter = _machines.begin(); invIter != _machines.end(); invIter++) {
NodeSet<std::string> finalizes = filterChildElements(_nsInfo.xmlNSPrefix + "finalize", invIter->first, false);
if (finalizes.size() > 0) {
finalizeFound = true;
break;
}
}
if (finalizeFound) {
stream << "/* <finalize> event */" << std::endl;
stream << " if" << std::endl;
for (std::map<Arabica::DOM::Node<std::string>, ChartToPromela*>::iterator invIter = _machines.begin(); invIter != _machines.end(); invIter++) {
NodeSet<std::string> finalizes = filterChildElements(_nsInfo.xmlNSPrefix + "finalize", invIter->first, false);
if (finalizes.size() > 0) {
stream << " :: " << _prefix << "_event.invokeid == " << _analyzer->macroForLiteral(invIter->second->_invokerid) << " -> {" << std::endl;
writeExecutableContent(stream, finalizes[0], 3);
stream << " } " << std::endl;
}
}
stream << " :: else -> skip;" << std::endl;
stream << " fi;" << std::endl << std::endl;
}
}
for (std::map<Arabica::DOM::Node<std::string>, ChartToPromela*>::iterator invIter = _machines.begin(); invIter != _machines.end(); invIter++) {
if (invIter->second == this) {
continue;
}
//std::cout << invIter->first << std::endl;
if (stringIsTrue(ATTR_CAST(invIter->first, "autoforward"))) {
stream << "/* autoforward event to " << invIter->second->_invokerid << " invokers */" << std::endl;
stream << " if" << std::endl;
stream << " :: " << invIter->second->_prefix << "done -> skip;" << std::endl;
stream << " :: " << invIter->second->_prefix << "canceled -> skip;" << std::endl;
#if NEW_DELAY_RESHUFFLE
stream << " :: else -> { " << invIter->second->_prefix << "eQ!" << _prefix << "_event" << "; insertWithDelay(" << invIter->second->_prefix << "eQ" << "); }" << std::endl;
#else
stream << " :: else -> { " << invIter->second->_prefix << "eQ!!" << _prefix << "_event" << " }" << std::endl;
#endif
stream << " fi;" << std::endl << std::endl;
}
}
stream << std::endl;
stream << _prefix << "microStep:" << std::endl;
stream << "/* event dispatching per state */" << std::endl;
stream << " if" << std::endl;
writeEventDispatching(stream);
stream << "/* this is an error as we dispatched all valid states */" << std::endl;
stream << " :: else -> assert(false);" << std::endl;
stream << " fi;" << std::endl;
stream << std::endl;
stream << _prefix << "terminate: skip;" << std::endl;
if (_parent != NULL) {
stream << " {" << std::endl;
stream << _analyzer->getTypeReset("tmpE", _analyzer->getType("_event"), " ");
stream << " tmpE.name = " << _analyzer->macroForLiteral("done.invoke." + _invokerid) << ";" << std::endl;
if (_invokerid.length() > 0) {
stream << " tmpE.invokeid = " << _analyzer->macroForLiteral(_invokerid) << ";" << std::endl;
}
if (_analyzer->usesEventField("delay")) {
#if NEW_DELAY_RESHUFFLE
stream << " " << _parent->_prefix << "eQ!tmpE;" << std::endl;
stream << " insertWithDelay(" << _parent->_prefix << "eQ);" << std::endl;
#else
stream << " _lastSeqId = _lastSeqId + 1;" << std::endl;
stream << " tmpE.seqNr = _lastSeqId;" << std::endl;
stream << " " << _parent->_prefix << "eQ!!tmpE;" << std::endl;
#endif
} else {
stream << " " << _parent->_prefix << "eQ!tmpE;" << std::endl;
}
stream << " }" << std::endl;
stream << _prefix << "cancel: skip;" << std::endl;
if (_analyzer->usesEventField("delay"))
stream << " removePendingEventsForInvoker(" << _analyzer->macroForLiteral(this->_invokerid) << ")" << std::endl;
}
stream << " }" << std::endl;
stream << "}" << std::endl;
}
void ChartToPromela::writeRescheduleProcess(std::ostream& stream, int indent) {
std::string padding;
for (int i = 0; i < indent; i++) {
padding += " ";
}
if (_allowEventInterleaving) {
stream << padding << "inline rescheduleProcess(smallestDelay, procId, internalQ, externalQ, tempQ) {" << std::endl;
} else {
stream << padding << "inline rescheduleProcess(smallestDelay, procId, internalQ, externalQ) {" << std::endl;
}
// stream << _analyzer->getTypeReset("tmpE", _analyzer->getType("_event"), " ");
stream << padding << " set_priority(procId, 1);" << std::endl;
stream << padding << " if" << std::endl;
stream << padding << " :: len(internalQ) > 0 -> set_priority(procId, 10);" << std::endl;
stream << padding << " :: else {" << std::endl;
stream << padding << " if" << std::endl;
stream << padding << " :: len(externalQ) > 0 -> {" << std::endl;
stream << padding << " externalQ?<tmpE>;" << std::endl;
stream << padding << " if" << std::endl;
stream << padding << " :: smallestDelay == tmpE.delay -> set_priority(procId, 10);" << std::endl;
stream << padding << " :: else -> skip;" << std::endl;
stream << padding << " fi;" << std::endl;
stream << padding << " }" << std::endl;
if (_allowEventInterleaving) {
stream << padding << " :: len(tempQ) > 0 -> {" << std::endl;
stream << padding << " tempQ?<tmpE>;" << std::endl;
stream << padding << " if" << std::endl;
stream << padding << " :: smallestDelay == tmpE.delay -> set_priority(procId, 10);" << std::endl;
stream << padding << " :: else -> skip;" << std::endl;
stream << padding << " fi;" << std::endl;
stream << padding << " }" << std::endl;
}
stream << padding << " :: else -> skip;" << std::endl;
stream << padding << " fi;" << std::endl;
stream << padding << " }" << std::endl;
stream << padding << " fi;" << std::endl;
stream << padding << "}" << std::endl;
}
void ChartToPromela::writeDetermineShortestDelay(std::ostream& stream, int indent) {
std::string padding;
for (int i = 0; i < indent; i++) {
padding += " ";
}
stream << padding << "inline determineSmallestDelay(smallestDelay, queue) {" << std::endl;
// stream << padding << _analyzer->getTypeReset("tmpE", _analyzer->getType("_event"), " ");
stream << padding << " if" << std::endl;
stream << padding << " :: len(queue) > 0 -> {" << std::endl;
stream << padding << " queue?<tmpE>;" << std::endl;
stream << padding << " if" << std::endl;
stream << padding << " :: (tmpE.delay < smallestDelay) -> { smallestDelay = tmpE.delay; }" << std::endl;
stream << padding << " :: else -> skip;" << std::endl;
stream << padding << " fi;" << std::endl;
stream << padding << " }" << std::endl;
stream << padding << " :: else -> skip;" << std::endl;
stream << padding << " fi;" << std::endl;
stream << padding << "}" << std::endl;
}
void ChartToPromela::writeInsertWithDelay(std::ostream& stream, int indent) {
std::string padding;
for (int i = 0; i < indent; i++) {
padding += " ";
}
uint32_t maxExternalQueueLength = 1;
std::map<Arabica::DOM::Node<std::string>, ChartToPromela*>::iterator machineIter = _machinesAll->begin();
while(machineIter != _machinesAll->end()) {
maxExternalQueueLength = std::max(maxExternalQueueLength, machineIter->second->_externalQueueLength);
machineIter++;
}
maxExternalQueueLength += 6;
if (maxExternalQueueLength <= 1) {
stream << padding << "/* noop for external queues with length <= 1 */" << std::endl;
stream << padding << "inline insertWithDelay(queue) {}" << std::endl;
}
stream << padding << "hidden _event_t _iwdQ[" << maxExternalQueueLength - 1 << "];" << std::endl;
stream << padding << "hidden int _iwdQLength = 0;" << std::endl;
stream << padding << "hidden int _iwdIdx1 = 0;" << std::endl;
stream << padding << "hidden int _iwdIdx2 = 0;" << std::endl;
stream << padding << "hidden _event_t _iwdTmpE;" << std::endl;
stream << padding << "hidden _event_t _iwdLastE;" << std::endl;
stream << padding << "bool _iwdInserted = false;" << std::endl;
stream << padding << "" << std::endl;
stream << padding << "/* last event in given queue is potentially at wrong position */" << std::endl;
stream << padding << "inline insertWithDelay(queue) {" << std::endl;
stream << padding << " d_step {" << std::endl;
stream << padding << "" << std::endl;
stream << padding << " /* only process for non-trivial queues */" << std::endl;
stream << padding << " if" << std::endl;
stream << padding << " :: len(queue) > 1 -> {" << std::endl;
stream << padding << "" << std::endl;
stream << padding << " /* move all events but last over and remember the last one */" << std::endl;
stream << padding << " _iwdIdx1 = 0;" << std::endl;
stream << padding << " _iwdQLength = len(queue) - 1;" << std::endl;
stream << padding << "" << std::endl;
stream << padding << " do" << std::endl;
stream << padding << " :: _iwdIdx1 < _iwdQLength -> {" << std::endl;
stream << padding << " queue?_iwdTmpE;" << std::endl;
stream << padding << " _iwdQ[_iwdIdx1].name = _iwdTmpE.name;" << std::endl;
stream << _analyzer->getTypeAssignment("_iwdQ[_iwdIdx1]", "_iwdTmpE", _analyzer->getType("_event"), padding + " ");
stream << padding << " _iwdIdx1++;" << std::endl;
stream << padding << " }" << std::endl;
stream << padding << " :: else -> break;" << std::endl;
stream << padding << " od" << std::endl;
stream << padding << "" << std::endl;
stream << padding << " queue?_iwdLastE;" << std::endl;
stream << padding << "" << std::endl;
stream << padding << " /* _iwdQ now contains all but last item in _iwdLastE */" << std::endl;
stream << padding << " assert(len(queue) == 0);" << std::endl;
stream << padding << "" << std::endl;
stream << padding << " /* reinsert into queue and place _iwdLastE correctly */" << std::endl;
stream << padding << " _iwdInserted = false;" << std::endl;
stream << padding << " _iwdIdx2 = 0;" << std::endl;
stream << padding << "" << std::endl;
stream << padding << " do" << std::endl;
stream << padding << " :: _iwdIdx2 < _iwdIdx1 -> {" << std::endl;
stream << padding << " _iwdTmpE.name = _iwdQ[_iwdIdx2].name;" << std::endl;
stream << _analyzer->getTypeAssignment("_iwdTmpE", "_iwdQ[_iwdIdx2]", _analyzer->getType("_event"), padding + " ");
stream << padding << "" << std::endl;
stream << padding << " if" << std::endl;
stream << padding << " :: _iwdTmpE.delay > _iwdLastE.delay -> {" << std::endl;
stream << padding << " queue!_iwdLastE;" << std::endl;
stream << padding << " _iwdInserted = true;" << std::endl;
stream << padding << " }" << std::endl;
stream << padding << " :: else -> skip" << std::endl;
stream << padding << " fi;" << std::endl;
stream << padding << "" << std::endl;
stream << padding << " queue!_iwdTmpE;" << std::endl;
stream << padding << " _iwdIdx2++;" << std::endl;
stream << padding << " }" << std::endl;
stream << padding << " :: else -> break;" << std::endl;
stream << padding << " od" << std::endl;
stream << padding << "" << std::endl;
stream << padding << " if" << std::endl;
stream << padding << " :: !_iwdInserted -> queue!_iwdLastE;" << std::endl;
stream << padding << " :: else -> skip;" << std::endl;
stream << padding << " fi;" << std::endl;
stream << padding << "" << std::endl;
stream << padding << " }" << std::endl;
stream << padding << " :: else -> skip;" << std::endl;
stream << padding << " fi;" << std::endl;
stream << padding << " }" << std::endl;
stream << padding << "}" << std::endl;
}
void ChartToPromela::writeAdvanceTime(std::ostream& stream, int indent) {
std::string padding;
for (int i = 0; i < indent; i++) {
padding += " ";
}
stream << padding << "inline advanceTime(increment, queue) {" << std::endl;
stream << padding << " tmpIndex = 0;" << std::endl;
stream << padding << " do" << std::endl;
stream << padding << " :: tmpIndex < len(queue) -> {" << std::endl;
stream << padding << " queue?tmpE;" << std::endl;
stream << padding << " if" << std::endl;
stream << padding << " :: tmpE.delay >= increment -> tmpE.delay = tmpE.delay - increment;" << std::endl;
stream << padding << " :: else -> skip;" << std::endl;
stream << padding << " fi" << std::endl;
stream << padding << " queue!tmpE;" << std::endl;
stream << padding << " tmpIndex++;" << std::endl;
stream << padding << " }" << std::endl;
stream << padding << " :: else -> break;" << std::endl;
stream << padding << " od" << std::endl;
stream << padding << "}" << std::endl;
}
void ChartToPromela::writeRemovePendingEventsFromInvoker(std::ostream& stream, int indent) {
std::list<std::string> queues;
queues.push_back("eQ");
if (_allowEventInterleaving)
queues.push_back("tmpQ");
stream << "inline removePendingEventsForInvoker(invokeIdentifier) {" << std::endl;
for (std::map<Arabica::DOM::Node<std::string>, ChartToPromela*>::iterator queueIter = _machinesAll->begin(); queueIter != _machinesAll->end(); queueIter++) {
for (std::list<std::string>::iterator qIter = queues.begin(); qIter != queues.end(); qIter++) {
stream << " removePendingEventsForInvokerOnQueue(invokeIdentifier, " << queueIter->second->_prefix << *qIter << ");" << std::endl;
}
}
stream << "}" << std::endl;
stream << std::endl;
stream << "inline removePendingEventsForInvokerOnQueue(invokeIdentifier, queue) {" << std::endl;
stream << " tmpIndex = 0;" << std::endl;
// stream << _analyzer->getTypeReset("tmpE", _analyzer->getType("_event"), " ");
stream << " do" << std::endl;
stream << " :: tmpIndex < len(queue) -> {" << std::endl;
stream << " queue?tmpE;" << std::endl;
stream << " if" << std::endl;
stream << " :: tmpE.delay == 0 || tmpE.invokeid != invokeIdentifier -> queue!tmpE;" << std::endl;
stream << " :: else -> skip;" << std::endl;
stream << " fi" << std::endl;
stream << " tmpIndex++;" << std::endl;
stream << " }" << std::endl;
stream << " :: else -> break;" << std::endl;
stream << " od" << std::endl;
stream << "}" << std::endl;
}
void ChartToPromela::writeCancelEvents(std::ostream& stream, int indent) {
std::list<std::string> queues;
queues.push_back("eQ");
if (_allowEventInterleaving)
queues.push_back("tmpQ");
stream << "inline cancelSendId(sendIdentifier, invokerIdentifier) {" << std::endl;
for (std::map<Arabica::DOM::Node<std::string>, ChartToPromela*>::iterator queueIter = _machinesAll->begin(); queueIter != _machinesAll->end(); queueIter++) {
for (std::list<std::string>::iterator qIter = queues.begin(); qIter != queues.end(); qIter++) {
stream << " cancelSendIdOnQueue(sendIdentifier, " << queueIter->second->_prefix << *qIter << ", invokerIdentifier);" << std::endl;
}
}
stream << "}" << std::endl;
stream << std::endl;
stream << "inline cancelSendIdOnQueue(sendIdentifier, queue, invokerIdentifier) {" << std::endl;
stream << " tmpIndex = 0;" << std::endl;
// stream << _analyzer->getTypeReset("tmpE", _analyzer->getType("_event"), " ");
stream << " do" << std::endl;
stream << " :: tmpIndex < len(queue) -> {" << std::endl;
stream << " queue?tmpE;" << std::endl;
stream << " if" << std::endl;
stream << " :: tmpE.invokeid != invokerIdentifier || tmpE.sendid != sendIdentifier || tmpE.delay == 0 -> queue!tmpE;" << std::endl;
stream << " :: else -> skip;" << std::endl;
stream << " fi" << std::endl;
stream << " tmpIndex++;" << std::endl;
stream << " }" << std::endl;
stream << " :: else -> break;" << std::endl;
stream << " od" << std::endl;
stream << "}" << std::endl;
}
void ChartToPromela::writeScheduleMachines(std::ostream& stream, int indent) {
std::string padding;
for (int i = 0; i < indent; i++) {
padding += " ";
}
stream << padding << "inline scheduleMachines() {" << std::endl;
std::list<std::string> queues;
queues.push_back("eQ");
if (_allowEventInterleaving)
queues.push_back("tmpQ");
stream << " /* schedule state-machines with regard to their event's delay */" << std::endl;
stream << " skip;" << std::endl;
stream << " d_step {" << std::endl;
stream << std::endl << "/* determine smallest delay */" << std::endl;
stream << " int smallestDelay = 2147483647;" << std::endl;
for (std::map<Arabica::DOM::Node<std::string>, ChartToPromela*>::iterator queueIter = _machinesAll->begin(); queueIter != _machinesAll->end(); queueIter++) {
for (std::list<std::string>::iterator qIter = queues.begin(); qIter != queues.end(); qIter++) {
stream << " determineSmallestDelay(smallestDelay, " << queueIter->second->_prefix << *qIter << ");" << std::endl;
}
}
// stream << " printf(\"======= Lowest delay is %d\\n\", smallestDelay);" << std::endl;
stream << std::endl << "/* prioritize processes with lowest delay or internal events */" << std::endl;
for (std::map<Arabica::DOM::Node<std::string>, ChartToPromela*>::iterator queueIter = _machinesAll->begin(); queueIter != _machinesAll->end(); queueIter++) {
stream << " rescheduleProcess(smallestDelay, "
<< queueIter->second->_prefix << "procid, "
<< queueIter->second->_prefix << "iQ, "
<< queueIter->second->_prefix << "eQ";
if (_allowEventInterleaving) {
stream << ", " << queueIter->second->_prefix << "tmpQ);" << std::endl;
} else {
stream << ");" << std::endl;
}
}
stream << std::endl << "/* advance time by subtracting the smallest delay from all event delays */" << std::endl;
stream << " if" << std::endl;
stream << " :: (smallestDelay > 0) -> {" << std::endl;
for (std::map<Arabica::DOM::Node<std::string>, ChartToPromela*>::iterator queueIter = _machinesAll->begin(); queueIter != _machinesAll->end(); queueIter++) {
for (std::list<std::string>::iterator qIter = queues.begin(); qIter != queues.end(); qIter++) {
stream << " advanceTime(smallestDelay, " << queueIter->second->_prefix << *qIter << ");" << std::endl;
}
}
stream << " }" << std::endl;
stream << " :: else -> skip;" << std::endl;
stream << " fi;" << std::endl;
stream << " }" << std::endl;
stream << " set_priority(_pid, 10);" << std::endl << std::endl;
stream << padding << "}" << std::endl;
}
void ChartToPromela::writeEventDispatching(std::ostream& stream) {
for (std::map<std::string, GlobalState*>::iterator stateIter = _activeConf.begin(); stateIter != _activeConf.end(); stateIter++) {
const std::string& stateId = stateIter->first;
const GlobalState* state = stateIter->second;
stream << std::endl << "/* ### current state ";
FlatStateIdentifier flatActiveSource(stateId);
PRETTY_PRINT_LIST(stream, flatActiveSource.getActive());
stream << " ######################## */" << std::endl;
stream << " :: (" << _prefix << "s == s" << state->activeIndex << ") -> {" << std::endl;
writeDispatchingBlock(stream, state->sortedOutgoing, 3);
stream << " }" << std::endl;
}
}
void ChartToPromela::writeDispatchingBlock(std::ostream& stream, std::list<GlobalTransition*> transitions, int indent) {
std::string padding;
for (int i = 0; i < indent; i++) {
padding += " ";
}
if (transitions.size() == 0) {
stream << "/* no transition applicable */" << std::endl;
stream << padding << _prefix << "spontaneous = false;" << std::endl;
stream << padding << "goto " << _prefix << "macroStep;" << std::endl;
return;
}
GlobalTransition* currTrans = transitions.front();
transitions.pop_front();
stream << padding << "if" << std::endl;
if (currTrans->condition.size() > 0) {
stream << padding << ":: ((";
} else {
stream << padding << ":: (";
}
if (currTrans->isEventless) {
stream << _prefix << "spontaneous";
} else {
std::string eventDescs = currTrans->eventDesc;
std::list<std::string> eventNames = tokenizeIdRefs(eventDescs);
std::set<std::string> eventPrefixes;
std::list<std::string>::iterator eventNameIter = eventNames.begin();
while(eventNameIter != eventNames.end()) {
std::string eventDesc = *eventNameIter;
if (boost::ends_with(eventDesc, "*"))
eventDesc = eventDesc.substr(0, eventDesc.size() - 1);
if (boost::ends_with(eventDesc, "."))
eventDesc = eventDesc.substr(0, eventDesc.size() - 1);
if (eventDesc.length() > 0) {
std::set<std::string> tmp = _analyzer->getEventsWithPrefix(*eventNameIter);
eventPrefixes.insert(tmp.begin(), tmp.end());
}
eventNameIter++;
}
if (eventPrefixes.size() > 0) {
stream << "!" << _prefix << "spontaneous";
} else {
stream << "!" << _prefix << "spontaneous";
}
if (eventPrefixes.size() > 0)
stream << " &&";
if (eventPrefixes.size() > 1)
stream << " (";
std::string seperator;
std::set<std::string>::iterator eventIter = eventPrefixes.begin();
while(eventIter != eventPrefixes.end()) {
if (_analyzer->usesComplexEventStruct()) {
stream << seperator << " " << _prefix << "_event.name == " << _analyzer->macroForLiteral(*eventIter);
} else {
stream << seperator << " " << _prefix << "_event == " << _analyzer->macroForLiteral(*eventIter);
}
seperator = " || ";
eventIter++;
}
if (eventPrefixes.size() > 1)
stream << ")";
}
stream << ")";
if (currTrans->condition.size() > 0) {
stream << " && (" + ADAPT_SRC(currTrans->condition) + "))";
}
if (currTrans->hasExecutableContent || currTrans->historyTrans.size() > 0) {
stream << " -> { " << std::endl;
if (!envVarIsTrue("USCXML_ANNOTATE_NOCOMMENT")) {
stream << "/* transition to ";
FlatStateIdentifier flatActiveSource(currTrans->activeDestination);
PRETTY_PRINT_LIST(stream, flatActiveSource.getActive());
stream << " */" << std::endl;
}
if (_traceTransitions) {
for (std::set<int>::iterator transRefIter = currTrans->transitionRefs.begin(); transRefIter != currTrans->transitionRefs.end(); transRefIter++) {
stream << padding << " " << _prefix << "transitions[" << *transRefIter << "] = true; " << std::endl;
}
}
stream << padding << " goto " << _prefix << "t" << currTrans->index << ";" << std::endl;
stream << padding << "}" << std::endl;
} else {
stream << " -> {" << std::endl;
GlobalState* newState = _activeConf[currTrans->activeDestination];
assert(newState != NULL);
if (!envVarIsTrue("USCXML_ANNOTATE_NOCOMMENT")) {
stream << "/* new state ";
FlatStateIdentifier flatActiveDest(currTrans->activeDestination);
PRETTY_PRINT_LIST(stream, flatActiveDest.getActive());
stream << " */" << std::endl;
}
stream << padding << " " << _prefix << "s = s" << newState->activeIndex << ";" << std::endl;
TRANSITION_TRACE(currTrans, false);
writeTransitionClosure(stream, currTrans, newState, indent + 1);
stream << padding << "}" << std::endl;
}
stream << padding << ":: else -> {" << std::endl;
writeDispatchingBlock(stream, transitions, indent + 1);
stream << padding << "}" << std::endl;
stream << padding << "fi;" << std::endl;
}
void ChartToPromela::writeMain(std::ostream& stream) {
stream << std::endl;
stream << "init {" << std::endl;
if (_varInitializers.size() > 0) {
stream << "/* initialize data model variables */" << std::endl;
std::list<std::string>::iterator initIter = _varInitializers.begin();
while(initIter != _varInitializers.end()) {
stream << ADAPT_SRC(beautifyIndentation(*initIter, 1)) << std::endl;
initIter++;
}
stream << std::endl;
}
stream << " run " << (_prefix.size() == 0 ? "machine_" : _prefix) << "run() priority 10;" << std::endl;
stream << "}" << std::endl;
}
void ChartToPromela::initNodes() {
// some things we share with our invokers
if (_analyzer == NULL)
_analyzer = new PromelaCodeAnalyzer();
if (_machinesAll == NULL) {
_machinesAll = new std::map<Arabica::DOM::Node<std::string>, ChartToPromela*>();
(*_machinesAll)[_scxml] = this;
}
if (_machinesAllPerId == NULL)
_machinesAllPerId = new std::map<std::string, Arabica::DOM::Node<std::string> >();
if (_parentTopMost == NULL)
_parentTopMost = this;
_internalQueueLength = getMinInternalQueueLength(MSG_QUEUE_LENGTH);
_externalQueueLength = getMinExternalQueueLength(MSG_QUEUE_LENGTH);
// get all states
NodeSet<std::string> states = getAllStates();
for (int i = 0; i < states.size(); i++) {
if (InterpreterImpl::isInEmbeddedDocument(states[i]))
continue;
Element<std::string> stateElem(states[i]);
_analyzer->addOrigState(ATTR(stateElem, "id"));
if (isCompound(stateElem) || isParallel(stateElem)) {
_analyzer->addEvent("done.state." + ATTR(stateElem, "id"));
}
}
{
// shorten UUID ids at invokers for readability
NodeSet<std::string> invokes = filterChildElements(_nsInfo.xmlNSPrefix + "invoke", _scxml, true);
invokes.push_back(filterChildElements(_nsInfo.xmlNSPrefix + "uninvoke", _scxml, true));
// make sure all invokers have an id!
for (int i = 0; i < invokes.size(); i++) {
if (!HAS_ATTR_CAST(invokes[i], "id")) {
Element<std::string> invokeElem(invokes[i]);
invokeElem.setAttribute("id", "INV_" + UUID::getUUID().substr(0,5));
} else if (HAS_ATTR_CAST(invokes[i], "id") && UUID::isUUID(ATTR_CAST(invokes[i], "id"))) {
// shorten UUIDs
Element<std::string> invokeElem(invokes[i]);
invokeElem.setAttribute("id", "INV_" + ATTR_CAST(invokes[i], "id").substr(0,5));
}
}
}
// are there nestes SCXML invokers?
{
NodeSet<std::string> invokes = filterChildElements(_nsInfo.xmlNSPrefix + "invoke", _scxml, true);
for (int i = 0; i < invokes.size(); i++) {
if (!HAS_ATTR_CAST(invokes[i], "type") ||
ATTR_CAST(invokes[i], "type") == "scxml" ||
ATTR_CAST(invokes[i], "type") == "http://www.w3.org/TR/scxml/#SCXMLEventProcessor" ||
ATTR_CAST(invokes[i], "type") == "http://www.w3.org/TR/scxml/") {
assert(HAS_ATTR_CAST(invokes[i], "id"));
Element<std::string>(invokes[i]).setAttribute("name", ATTR_CAST(invokes[i], "id"));
_prefix = "MAIN_";
Interpreter nested;
if (HAS_ATTR_CAST(invokes[i], "src")) {
URL absUrl(ATTR_CAST(invokes[i], "src"));
absUrl.toAbsolute(_baseURL[_scxml]);
nested = Interpreter::fromURL(absUrl);
} else {
NodeSet<std::string> nestedContent = InterpreterImpl::filterChildElements(_nsInfo.xmlNSPrefix + "content", invokes[i]);
assert(nestedContent.size() == 1);
NodeSet<std::string> nestedRoot = InterpreterImpl::filterChildElements(_nsInfo.xmlNSPrefix + "scxml", nestedContent[0]);
assert(nestedRoot.size() == 1);
DOMImplementation<std::string> domFactory = Arabica::SimpleDOM::DOMImplementation<std::string>::getDOMImplementation();
Document<std::string> nestedDoc = domFactory.createDocument(_scxml.getOwnerDocument().getNamespaceURI(), "", 0);
Node<std::string> importRoot = nestedDoc.importNode(nestedRoot[0], true);
nestedDoc.appendChild(importRoot);
nested = Interpreter::fromDOM(nestedDoc, _nsInfo, _sourceURL);
}
// std::cout << invokes[i] << std::endl;
// we found machines but have no prefix
if (_prefix.length() == 0)
_prefix = "MAIN_";
_machines[invokes[i]] = new ChartToPromela(nested);
_machines[invokes[i]]->_analyzer = _analyzer;
_machines[invokes[i]]->_parent = this;
_machines[invokes[i]]->_parentTopMost = _parentTopMost;
_machines[invokes[i]]->_machinesAll = _machinesAll;
(*_machinesAll)[invokes[i]] = _machines[invokes[i]];
_machines[invokes[i]]->_invokerid = ATTR_CAST(invokes[i], "id");
_machines[invokes[i]]->_prefix = ATTR_CAST(invokes[i], "id") + "_";
_analyzer->addLiteral(_machines[invokes[i]]->_invokerid);
_analyzer->addEvent("done.invoke." + _machines[invokes[i]]->_invokerid);
_machinesPerId[ATTR_CAST(invokes[i], "id")] = invokes[i];
(*_machinesAllPerId)[ATTR_CAST(invokes[i], "id")] = invokes[i];
}
}
}
if (_machines.size() > 0) {
_analyzer->addCode("_event.invokeid", this);
}
// gather all potential members per history
std::map<std::string, Arabica::DOM::Element<std::string> >::iterator histIter = _historyTargets.begin();
while(histIter != _historyTargets.end()) {
NodeSet<std::string> histStatesMembers;
bool isDeep = (HAS_ATTR_CAST(histIter->second, "type") && ATTR_CAST(histIter->second, "type") == "deep");
histStatesMembers.push_back(filterChildElements(_nsInfo.xmlNSPrefix + "state", histIter->second.getParentNode(), isDeep));
histStatesMembers.push_back(filterChildElements(_nsInfo.xmlNSPrefix + "parallel", histIter->second.getParentNode(), isDeep));
histStatesMembers.push_back(filterChildElements(_nsInfo.xmlNSPrefix + "final", histIter->second.getParentNode(), isDeep));
for (int i = 0; i < histStatesMembers.size(); i++) {
_historyMembers[histIter->first].insert(std::make_pair(ATTR_CAST(histStatesMembers[i], "id"), i));
}
histIter++;
}
// initialize event trie with all events that might occur
NodeSet<std::string> internalEventNames;
internalEventNames.push_back(_xpath.evaluate("//" + _nsInfo.xpathPrefix + "transition", _scxml).asNodeSet());
internalEventNames.push_back(_xpath.evaluate("//" + _nsInfo.xpathPrefix + "raise", _scxml).asNodeSet());
internalEventNames.push_back(_xpath.evaluate("//" + _nsInfo.xpathPrefix + "send", _scxml).asNodeSet());
for (int i = 0; i < internalEventNames.size(); i++) {
if (HAS_ATTR_CAST(internalEventNames[i], "event")) {
std::string eventNames = ATTR_CAST(internalEventNames[i], "event");
std::list<std::string> events = tokenizeIdRefs(eventNames);
for (std::list<std::string>::iterator eventIter = events.begin();
eventIter != events.end(); eventIter++) {
std::string eventName = *eventIter;
if (boost::ends_with(eventName, "*"))
eventName = eventName.substr(0, eventName.size() - 1);
if (boost::ends_with(eventName, "."))
eventName = eventName.substr(0, eventName.size() - 1);
if (eventName.size() > 0)
_analyzer->addEvent(eventName);
}
}
}
// _analyzer->addCode("bumpDownArrow = 1; _event.foo = 3; forgetSelectedServer = 1;", this);
// exit(0);
// transform data / assign json into PROMELA statements
{
NodeSet<std::string> asgn;
asgn.push_back(filterChildElements(_nsInfo.xmlNSPrefix + "data", _scxml, true));
asgn.push_back(filterChildElements(_nsInfo.xmlNSPrefix + "assign", _scxml, true));
for (int i = 0; i < asgn.size(); i++) {
if (isInEmbeddedDocument(asgn[i]))
continue;
Element<std::string> asgnElem(asgn[i]);
std::string key;
if (HAS_ATTR(asgnElem, "id")) {
key = ATTR(asgnElem, "id");
} else if (HAS_ATTR(asgnElem, "location")) {
key = ATTR(asgnElem, "location");
}
if (key.length() == 0)
continue;
std::string value;
if (HAS_ATTR(asgnElem, "expr")) {
value = ATTR(asgnElem, "expr");
} else if (HAS_ATTR(asgnElem, "src")) {
URL absUrl(ATTR_CAST(asgnElem, "src"));
absUrl.toAbsolute(_baseURL[_scxml]);
value = absUrl.getInContent();
} else {
NodeSet<std::string> textChilds = filterChildType(Node_base::TEXT_NODE, asgnElem);
if (textChilds.size() > 0) {
for (int j = 0; j < textChilds.size(); j++) {
value += textChilds[j].getNodeValue();
}
}
}
boost::trim(value);
if (value.size() == 0)
continue;
// remove all children, we will replae by suitable promela statements
while(asgnElem.hasChildNodes())
asgnElem.removeChild(asgnElem.getFirstChild());
std::string newValue;
Data json = Data::fromJSON(value);
if (!json.empty()) {
newValue = dataToAssignments(key, json);
} else {
newValue = key + " = " + value + ";";
}
newValue = sanitizeCode(newValue);
_analyzer->addCode(newValue, this);
if (asgnElem.getLocalName() == "data")
_varInitializers.push_back(newValue);
Text<std::string> newText = _document.createTextNode(newValue);
asgnElem.insertBefore(newText, Node<std::string>());
}
}
// do we need sendid / invokeid?
{
NodeSet<std::string> invokes = filterChildElements(_nsInfo.xmlNSPrefix + "invoke", _scxml, true);
NodeSet<std::string> sends = filterChildElements(_nsInfo.xmlNSPrefix + "send", _scxml, true);
NodeSet<std::string> cancels = filterChildElements(_nsInfo.xmlNSPrefix + "cancel", _scxml, true);
if (cancels.size() > 0) {
_analyzer->addCode("_event.invokeid", this);
}
for (int i = 0; i < sends.size(); i++) {
if (HAS_ATTR_CAST(sends[i], "idlocation")) {
_analyzer->addCode("_event.sendid", this);
}
if (HAS_ATTR_CAST(sends[i], "id")) {
_analyzer->addLiteral(ATTR_CAST(sends[i], "id"));
_analyzer->addCode("_event.sendid", this);
}
}
// do we need delays?
for (int i = 0; i < sends.size(); i++) {
if (HAS_ATTR_CAST(sends[i], "delay") || HAS_ATTR_CAST(sends[i], "delayexpr")) {
_analyzer->addCode("_event.delay", this);
#if NEW_DELAY_RESHUFFLE
#else
_analyzer->addCode("_event.seqNr", this);
#endif
}
}
}
{
// string literals for raise / send content
NodeSet<std::string> withContent;
withContent.push_back(filterChildElements(_nsInfo.xmlNSPrefix + "send", _scxml, true));
withContent.push_back(filterChildElements(_nsInfo.xmlNSPrefix + "raise", _scxml, true));
for (int i = 0; i < withContent.size(); i++) {
NodeSet<std::string> content = filterChildElements(_nsInfo.xmlNSPrefix + "content", withContent[i], true);
for (int j = 0; j < content.size(); j++) {
Element<std::string> contentElem(content[j]);
std::string content = spaceNormalize(contentElem.getFirstChild().getNodeValue());
if (!isNumeric(content.c_str(), 10))
_analyzer->addLiteral(content);
}
}
}
{
// gather all inline promela comments
pmlInlines = PromelaInlines(_scxml);
if (pmlInlines.getAllOfType(PromelaInline::PROMELA_EVENT_ONLY).size() > 0)
_analyzer->addCode("_x.states", this);
// register events and string literals
for (std::list<PromelaInline*>::iterator inlIter = pmlInlines.allInlines.begin(); inlIter != pmlInlines.allInlines.end(); inlIter++) {
if ((*inlIter)->type != (PromelaInline::PROMELA_EVENT_ONLY))
continue;
Data json = Data::fromJSON((*inlIter)->content);
if (!json.empty()) {
std::list<std::string> eventNames = PromelaInlines::getEventNames(json);
for (std::list<std::string>::iterator evIter = eventNames.begin(); evIter != eventNames.end(); evIter++) {
_analyzer->addEvent(*evIter);
}
std::list<std::string> stringLiterals = PromelaInlines::getStringLiterals(json);
for (std::list<std::string>::iterator strIter = stringLiterals.begin(); strIter != stringLiterals.end(); strIter++) {
_analyzer->addLiteral(*strIter);
}
if (json.array.size() > 0) {
for (int i = 0; i < json.array.size(); i++) {
std::string expr = dataToAssignments("_event", json.item(i));
_analyzer->addCode(expr, this);
}
} else {
std::string expr = dataToAssignments("_event", json);
_analyzer->addCode(expr, this);
}
}
}
}
// add platform variables as string literals
_analyzer->addLiteral(_prefix + "_sessionid");
_analyzer->addLiteral(_prefix + "_name");
if (HAS_ATTR(_scxml, "name")) {
_analyzer->addLiteral(ATTR(_scxml, "name"), _analyzer->indexForLiteral(_prefix + "_sessionid"));
}
NodeSet<std::string> contents = filterChildElements(_nsInfo.xmlNSPrefix + "content", _scxml, true);
for (int i = 0; i < contents.size(); i++) {
Element<std::string> contentElem = Element<std::string>(contents[i]);
if (contentElem.hasChildNodes() && contentElem.getFirstChild().getNodeType() == Node_base::TEXT_NODE && contentElem.getChildNodes().getLength() == 1) {
std::string content = contentElem.getFirstChild().getNodeValue();
_analyzer->addLiteral(spaceNormalize(content));
}
}
// extract and analyze source code
std::set<std::string> allCode;
std::set<std::string> allStrings;
{
NodeSet<std::string> withCond;
withCond.push_back(filterChildElements(_nsInfo.xmlNSPrefix + "transition", _scxml, true));
withCond.push_back(filterChildElements(_nsInfo.xmlNSPrefix + "if", _scxml, true));
withCond.push_back(filterChildElements(_nsInfo.xmlNSPrefix + "elseif", _scxml, true));
for (int i = 0; i < withCond.size(); i++) {
Element<std::string> elem = Element<std::string>(withCond[i]);
if (HAS_ATTR(elem, "cond")) {
std::string code = ATTR(elem, "cond");
code = sanitizeCode(code);
elem.setAttribute("cond", code);
allCode.insert(code);
}
}
}
{
NodeSet<std::string> withExpr;
withExpr.push_back(filterChildElements(_nsInfo.xmlNSPrefix + "log", _scxml, true));
withExpr.push_back(filterChildElements(_nsInfo.xmlNSPrefix + "data", _scxml, true));
withExpr.push_back(filterChildElements(_nsInfo.xmlNSPrefix + "assign", _scxml, true));
withExpr.push_back(filterChildElements(_nsInfo.xmlNSPrefix + "content", _scxml, true));
withExpr.push_back(filterChildElements(_nsInfo.xmlNSPrefix + "param", _scxml, true));
for (int i = 0; i < withExpr.size(); i++) {
Element<std::string> elem = Element<std::string>(withExpr[i]);
if (HAS_ATTR(elem, "expr")) {
std::string code = ATTR(elem, "expr");
code = sanitizeCode(code);
elem.setAttribute("expr", code);
allCode.insert(code);
}
}
}
{
NodeSet<std::string> withLocation;
withLocation.push_back(filterChildElements(_nsInfo.xmlNSPrefix + "assign", _scxml, true));
for (int i = 0; i < withLocation.size(); i++) {
Element<std::string> elem = Element<std::string>(withLocation[i]);
if (HAS_ATTR(elem, "location")) {
std::string code = ATTR(elem, "location");
code = sanitizeCode(code);
elem.setAttribute("location", code);
allCode.insert(code);
}
}
}
{
NodeSet<std::string> withText;
withText.push_back(filterChildElements(_nsInfo.xmlNSPrefix + "script", _scxml, true));
// withText.push_back(filterChildElements(_nsInfo.xmlNSPrefix + "data", _scxml, true));
for (int i = 0; i < withText.size(); i++) {
NodeSet<std::string> texts = filterChildType(Node_base::TEXT_NODE, withText[i], true);
for (int j = 0; j < texts.size(); j++) {
if (texts[j].getNodeValue().size() > 0) {
Text<std::string> elem = Text<std::string>(texts[j]);
std::string code = elem.getNodeValue();
code = sanitizeCode(code);
elem.setNodeValue(code);
allCode.insert(code);
}
}
}
}
{
NodeSet<std::string> foreachs = filterChildElements(_nsInfo.xmlNSPrefix + "foreach", _scxml, true);
for (int i = 0; i < foreachs.size(); i++) {
if (HAS_ATTR_CAST(foreachs[i], "index")) {
allCode.insert(ATTR_CAST(foreachs[i], "index"));
} else {
_hasIndexLessLoops = true;
}
if (HAS_ATTR_CAST(foreachs[i], "item")) {
allCode.insert(ATTR_CAST(foreachs[i], "item"));
}
}
}
for (std::set<std::string>::const_iterator codeIter = allCode.begin(); codeIter != allCode.end(); codeIter++) {
_analyzer->addCode(*codeIter, this);
}
// add all namelist entries to the _event structure
{
NodeSet<std::string> withNamelist;
withNamelist.push_back(filterChildElements(_nsInfo.xmlNSPrefix + "send", _scxml, true));
withNamelist.push_back(filterChildElements(_nsInfo.xmlNSPrefix + "invoke", _scxml, true));
for (int i = 0; i < withNamelist.size(); i++) {
if (HAS_ATTR_CAST(withNamelist[i], "namelist")) {
std::string namelist = ATTR_CAST(withNamelist[i], "namelist");
std::list<std::string> names = tokenizeIdRefs(namelist);
for (std::list<std::string>::iterator nameIter = names.begin(); nameIter != names.end(); nameIter++) {
_analyzer->addCode("_event.data." + *nameIter + " = 0;", this); // introduce for _event_t typedef
}
}
}
}
}
std::list<std::string> PromelaInlines::getStringLiterals(const Data& data) {
std::list<std::string> literals;
if (data.atom.size() > 0 && data.type == Data::VERBATIM) {
literals.push_back(data.atom);
}
if (data.array.size() > 0) {
for (std::list<Data>::const_iterator arrIter = data.array.begin(); arrIter != data.array.end(); arrIter++) {
std::list<std::string> nested = getStringLiterals(*arrIter);
literals.insert(literals.end(), nested.begin(), nested.end());
}
}
if (data.compound.size() > 0) {
for (std::map<std::string, Data>::const_iterator compIter = data.compound.begin(); compIter != data.compound.end(); compIter++) {
std::list<std::string> nested = getStringLiterals(compIter->second);
literals.insert(literals.end(), nested.begin(), nested.end());
}
}
return literals;
}
std::list<std::string> PromelaInlines::getEventNames(const Data& data) {
std::list<std::string> eventNames;
if (data.compound.size() > 0 && data.hasKey("name")) {
eventNames.push_back(data.at("name"));
}
if (data.array.size() > 0) {
for (std::list<Data>::const_iterator arrIter = data.array.begin(); arrIter != data.array.end(); arrIter++) {
std::list<std::string> nested = getEventNames(*arrIter);
eventNames.insert(eventNames.end(), nested.begin(), nested.end());
}
}
if (data.compound.size() > 0) {
for (std::map<std::string, Data>::const_iterator compIter = data.compound.begin(); compIter != data.compound.end(); compIter++) {
std::list<std::string> nested = getEventNames(compIter->second);
eventNames.insert(eventNames.end(), nested.begin(), nested.end());
}
}
return eventNames;
}
std::string ChartToPromela::dataToAssignments(const std::string& prefix, const Data& data) {
std::stringstream retVal;
if (data.atom.size() > 0) {
if (data.type == Data::VERBATIM) {
retVal << prefix << " = " << _analyzer->macroForLiteral(data.atom) << ";" << std::endl;
} else {
retVal << prefix << " = " << data.atom << ";" << std::endl;
}
} else if (data.compound.size() > 0) {
for (std::map<std::string, Data>::const_iterator cIter = data.compound.begin(); cIter != data.compound.end(); cIter++) {
retVal << dataToAssignments(prefix + "." + cIter->first, cIter->second);
}
} else if (data.array.size() > 0) {
size_t index = 0;
for(std::list<Data>::const_iterator aIter = data.array.begin(); aIter != data.array.end(); aIter++) {
retVal << dataToAssignments(prefix + "[" + toStr(index) + "]", *aIter);
index++;
}
}
return retVal.str();
}
std::string ChartToPromela::sanitizeCode(const std::string& code) {
std::string replaced = code;
boost::replace_all(replaced, "\"", "'");
boost::replace_all(replaced, "_sessionid", "_SESSIONID");
boost::replace_all(replaced, "_name", "_NAME");
return replaced;
}
void ChartToPromela::writeProgram(std::ostream& stream) {
_traceTransitions = envVarIsTrue("USCXML_PROMELA_TRANSITION_TRACE");
_writeTransitionPrintfs = envVarIsTrue("USCXML_PROMELA_TRANSITION_DEBUG");
if (!HAS_ATTR(_scxml, "datamodel") || ATTR(_scxml, "datamodel") != "promela") {
LOG(ERROR) << "Can only convert SCXML documents with \"promela\" datamodel";
return;
}
if (_start == NULL) {
interpret();
}
if (HAS_ATTR(_scxml, "binding") && ATTR(_scxml, "binding") != "early") {
LOG(ERROR) << "Can only convert for early data bindings";
return;
}
// std::cerr << _scxml << std::endl;
stream << "/* " << _sourceURL.asString() << " */" << std::endl;
stream << std::endl;
initNodes();
for (std::map<Arabica::DOM::Node<std::string>, ChartToPromela*>::iterator nestedIter = _machines.begin(); nestedIter != _machines.end(); nestedIter++) {
if (nestedIter->second->_start == NULL) {
nestedIter->second->interpret();
}
nestedIter->second->initNodes();
}
writeEvents(stream);
stream << std::endl;
writeStates(stream);
stream << std::endl;
writeStrings(stream);
stream << std::endl;
if (_analyzer->usesInPredicate()) {
writeStateMap(stream);
stream << std::endl;
}
if (_historyMembers.size() > 0) {
writeHistoryArrays(stream);
stream << std::endl;
}
writeTypeDefs(stream);
stream << std::endl;
writeDeclarations(stream);
stream << std::endl;
for (std::map<Arabica::DOM::Node<std::string>, ChartToPromela*>::iterator nestedIter = _machines.begin(); nestedIter != _machines.end(); nestedIter++) {
nestedIter->second->writeDeclarations(stream);
stream << std::endl;
}
stream << std::endl << "/* global inline functions */" << std::endl;
if (_analyzer->usesComplexEventStruct()) {
stream << "hidden _event_t tmpE;" << std::endl;
} else {
stream << "hidden int tmpE;" << std::endl;
}
stream << "hidden int tmpIndex;" << std::endl;
#if NEW_DELAY_RESHUFFLE
if (_analyzer->usesEventField("delay")) {
writeInsertWithDelay(stream);
stream << std::endl;
}
#endif
if (_analyzer->usesEventField("delay") && _machines.size() > 0) {
writeDetermineShortestDelay(stream);
stream << std::endl;
writeAdvanceTime(stream);
stream << std::endl;
writeRescheduleProcess(stream);
stream << std::endl;
writeScheduleMachines(stream);
stream << std::endl;
}
{
NodeSet<std::string> cancels = filterChildElements(_nsInfo.xmlNSPrefix + "cancel", _scxml, true);
if (cancels.size() > 0) {
writeCancelEvents(stream);
stream << std::endl;
}
}
{
NodeSet<std::string> invokes = filterChildElements(_nsInfo.xmlNSPrefix + "invoke", _scxml, true);
if (invokes.size() > 0 && _analyzer->usesEventField("delay")) {
writeRemovePendingEventsFromInvoker(stream);
stream << std::endl;
}
}
stream << std::endl;
writeEventSources(stream);
stream << std::endl;
writeFSM(stream);
stream << std::endl;
writeMain(stream);
stream << std::endl;
for (std::map<Arabica::DOM::Node<std::string>, ChartToPromela*>::iterator nestedIter = _machines.begin(); nestedIter != _machines.end(); nestedIter++) {
nestedIter->second->writeFSM(stream);
stream << std::endl;
}
// write ltl expression for success
std::stringstream acceptingStates;
std::string seperator;
for (std::map<std::string, GlobalState*>::iterator stateIter = _activeConf.begin(); stateIter != _activeConf.end(); stateIter++) {
FlatStateIdentifier flatId(stateIter->first);
if (std::find(flatId.getActive().begin(), flatId.getActive().end(), "pass") != flatId.getActive().end()) {
acceptingStates << seperator << _prefix << "s == s" << stateIter->second->activeIndex;
seperator = " || ";
}
}
if (acceptingStates.str().size() > 0) {
stream << "ltl { eventually (" << acceptingStates.str() << ") }" << std::endl;
}
}
} | 38.427453 | 222 | 0.630694 | sradomski |
96612d790217efb5f7cdcedda512e8fffc06ad98 | 2,840 | cpp | C++ | math/power_of_two.cpp | Phonbopit/C-Plus-Plus | 37a29008e6b77921a97a89ca8b7fd9e700aeccd0 | [
"MIT"
] | 2 | 2022-02-21T06:59:21.000Z | 2022-02-21T06:59:24.000Z | math/power_of_two.cpp | Phonbopit/C-Plus-Plus | 37a29008e6b77921a97a89ca8b7fd9e700aeccd0 | [
"MIT"
] | null | null | null | math/power_of_two.cpp | Phonbopit/C-Plus-Plus | 37a29008e6b77921a97a89ca8b7fd9e700aeccd0 | [
"MIT"
] | 1 | 2022-03-10T11:13:20.000Z | 2022-03-10T11:13:20.000Z | /**
* @file
* @brief Implementation to check whether a number is a power of 2 or not.
*
* @details
* This algorithm uses bit manipulation to check if a number is a power of 2 or
* not.
*
* ### Algorithm
* Let the input number be n, then the bitwise and between n and n-1 will let us
* know whether the number is power of 2 or not
*
* For Example,
* If N= 32 then N-1 is 31, if we perform bitwise and of these two numbers then
* the result will be zero, which indicates that it is the power of 2
* If N=23 then N-1 is 22, if we perform bitwise and of these two numbers then
* the result will not be zero , which indicates that it is not the power of 2
* \note This implementation is better than naive recursive or iterative
* approach.
*
* @author [Neha Hasija](https://github.com/neha-hasija17)
* @author [Rijul.S](https://github.com/Rijul24)
*/
#include <iostream> /// for IO operations
#include <cassert> /// for assert
/**
* @namespace math
* @brief Mathematical algorithms
*/
namespace math {
/**
* @brief This function finds whether a number is power of 2 or not
* @param n value for which we want to check
* prints the result, as "Yes, the number n is a power of 2" or
* "No, the number is not a power of 2" without quotes
* @returns 1 if `n` IS the power of 2
* @returns 0 if n is NOT a power of 2
*/
int power_of_two(int n) {
/// result stores the
/// bitwise and of n and n-1
int result = n & (n - 1);
if (result == 0) {
return 1;
}
return 0;
}
} // namespace math
/**
* @brief Self-test implementations
* @returns void
*/
static void test() {
std::cout << "First case testing... \n"; // for n = 32 return 1
assert(math::power_of_two(32) == 1);
std::cout << "\nPassed!\n";
std::cout << "Second case testing... \n"; // for n = 5 return 0
assert(math::power_of_two(5) == 0);
std::cout << "\nPassed!\n";
std::cout << "Third case testing... \n"; // for n = 232 return 0
assert(math::power_of_two(232) == 0);
std::cout << "\nPassed!\n";
std::cout << "\nAll test cases have successfully passed!\n";
}
/**
* @brief Take user input in the test cases (optional; currently commented)
* @returns void
*/
void user_input_test() {
int n = 0; // input from user
std::cout << "Enter a number " << std::endl;
std::cin >> n;
/// function call with @param n
int result = math::power_of_two(n);
if (result == 1) {
std::cout << "Yes, the number " << n << " is a power of 2\n";
}
else {
std::cout << "No, the number " << n << " is not a power of 2\n";
}
}
/**
* @brief Main function
* @returns 0 on exit
*/
int main() {
test(); // run self-test implementations
// uncomment the line below to take user inputs
//user_input_test();
return 0;
}
| 26.542056 | 80 | 0.616197 | Phonbopit |
96630164ccb876c0a4cea1fee916558013e2eae4 | 4,445 | hpp | C++ | include/xaos/detail/function.hpp | grisumbras/xaos | 9d8a93911b9284a826ad43ba133a2febf960481c | [
"BSL-1.0"
] | null | null | null | include/xaos/detail/function.hpp | grisumbras/xaos | 9d8a93911b9284a826ad43ba133a2febf960481c | [
"BSL-1.0"
] | null | null | null | include/xaos/detail/function.hpp | grisumbras/xaos | 9d8a93911b9284a826ad43ba133a2febf960481c | [
"BSL-1.0"
] | null | null | null | #ifndef XAOS_DETAIL_FUNCTION_HPP
#define XAOS_DETAIL_FUNCTION_HPP
#include <xaos/detail/backend_pointer.hpp>
#include <xaos/detail/function_alloc.hpp>
#include <xaos/detail/function_overloads.hpp>
#include <boost/core/empty_value.hpp>
#include <boost/mp11/algorithm.hpp>
#include <boost/mp11/list.hpp>
#include <boost/mp11/utility.hpp>
namespace xaos {
namespace detail {
template <class Signature, class Traits>
struct function_backend_interface
: alloc_interface
, boost::mp11::mp_apply<
boost::mp11::mp_inherit,
boost::mp11::mp_append<
maybe_clone_interface<Traits>,
boost::mp11::mp_transform<
call_overload_interface,
enabled_overloads<Signature, Traits>>>> {
using signature = Signature;
using traits = Traits;
};
template <class BackendInterface, class Allocator, class Callable>
struct function_backend final
: boost::mp11::mp_fold_q<
enabled_overloads<
typename BackendInterface::signature,
typename BackendInterface::traits>,
maybe_clone_implementation<
typename BackendInterface::traits,
function_backend<BackendInterface, Allocator, Callable>,
BackendInterface>,
boost::mp11::mp_bind_front<
call_overload,
function_backend<BackendInterface, Allocator, Callable>>>
, boost::empty_value<Callable, 0>
, pointer_storage_helper<
function_backend<BackendInterface, Allocator, Callable>,
Allocator,
1> {
using allocator_type = Allocator;
using callable_type = Callable;
using interface_type = BackendInterface;
using pointer_holder_t
= pointer_storage_helper<function_backend, Allocator, 1>;
function_backend(typename pointer_holder_t::pointer ptr, Callable callable)
: boost::empty_value<Callable, 0>(
boost::empty_init_t(), std::move(callable))
, pointer_holder_t(std::move(ptr)) {}
virtual auto relocate(void* type_erased_alloc) -> void* {
auto alloc
= restore_allocator<allocator_type, function_backend>(type_erased_alloc);
auto const raw_ptr = new_backend(alloc, std::move(callable()));
return static_cast<interface_type*>(raw_ptr);
};
virtual void delete_this(void* type_erased_alloc) {
auto alloc
= restore_allocator<allocator_type, function_backend>(type_erased_alloc);
auto const ptr = this->pointer_to(*this);
using proto_traits = std::allocator_traits<Allocator>;
using alloc_traits =
typename proto_traits::template rebind_traits<function_backend>;
alloc_traits::destroy(alloc, this);
alloc_traits::deallocate(alloc, ptr, 1);
};
auto callable() noexcept -> Callable& {
return boost::empty_value<Callable, 0>::get();
}
auto callable() const noexcept -> Callable const& {
return boost::empty_value<Callable, 0>::get();
}
};
template <class Signature, class Traits, class Allocator>
using backend_storage = boost::mp11::mp_apply_q<
boost::mp11::mp_if<
is_copyability_enabled<Traits>,
boost::mp11::mp_quote<copyable_backend_pointer>,
boost::mp11::mp_quote<backend_pointer>>,
boost::mp11::
mp_list<function_backend_interface<Signature, Traits>, Allocator>>;
template <class Signature, class Traits, class Allocator, class... Overloads>
class basic_function
: parens_overload<
basic_function<Signature, Traits, Allocator, Overloads...>,
are_rvalue_overloads_enabled<Traits>::value,
Overloads>...
{
private:
template <class, bool, class>
friend struct parens_overload;
using storage_t = backend_storage<Signature, Traits, Allocator>;
storage_t storage_;
public:
using allocator_type = typename storage_t::allocator_type;
template <class Callable>
basic_function(Callable callable, Allocator alloc = Allocator())
: storage_(alloc, callable) {}
using parens_overload<
basic_function<Signature, Traits, Allocator, Overloads...>,
are_rvalue_overloads_enabled<Traits>::value,
Overloads>::operator()...;
auto get_allocator() const -> allocator_type {
return storage_.get_allocator();
}
void swap(basic_function& other) { storage_.swap(other.storage_); }
};
template <class Signature, class Traits, class Allocator, class... Overloads>
void swap(
basic_function<Signature, Traits, Allocator, Overloads...>& l,
basic_function<Signature, Traits, Allocator, Overloads...>& r) {
l.swap(r);
}
} // namespace detail
} // namespace xaos
#endif // XAOS_DETAIL_FUNCTION_HPP
| 30.033784 | 79 | 0.728459 | grisumbras |
96666edbd8b62ccc00d0e736df792c1f29a392b4 | 1,695 | hpp | C++ | i23dSFM/stl/indexed_sort.hpp | zyxrrr/GraphSfM | 1af22ec17950ffc8a5c737a6a46f4465c40aa470 | [
"BSD-3-Clause"
] | null | null | null | i23dSFM/stl/indexed_sort.hpp | zyxrrr/GraphSfM | 1af22ec17950ffc8a5c737a6a46f4465c40aa470 | [
"BSD-3-Clause"
] | null | null | null | i23dSFM/stl/indexed_sort.hpp | zyxrrr/GraphSfM | 1af22ec17950ffc8a5c737a6a46f4465c40aa470 | [
"BSD-3-Clause"
] | 1 | 2019-02-18T09:49:32.000Z | 2019-02-18T09:49:32.000Z |
// Copyright (c) 2012, 2013 Pierre MOULON.
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef I23DSFM_STL_INDEXED_SORT_H
#define I23DSFM_STL_INDEXED_SORT_H
namespace stl
{
namespace indexed_sort
{
template<typename T1, typename T2>
struct sort_index_packet_ascend {
T1 val;
T2 index;
};
template<typename T1, typename T2>
struct sort_index_packet_descend {
T1 val;
T2 index;
};
template<typename T1, typename T2>
inline
bool
operator< (const sort_index_packet_ascend<T1,T2>& A,
const sort_index_packet_ascend<T1,T2>& B) {
return A.val < B.val;
}
template<typename T1, typename T2>
inline
bool
operator< (const sort_index_packet_descend<T1,T2>& A,
const sort_index_packet_descend<T1,T2>& B) {
return A.val > B.val;
}
/// Sort by default all indexed value, else sort only the NN smallest element of the indexed array.
template<typename packet_type, typename eT>
void
inline
sort_index_helper(std::vector<packet_type>& packet_vec,
const eT* in_mem, int NN = -1) {
const size_t n_elem = packet_vec.size();
for(size_t i=0; i<n_elem; ++i) {
packet_vec[i].val = in_mem[i];
packet_vec[i].index = i;
}
if (NN == -1)
std::sort( packet_vec.begin(), packet_vec.end() );
else
std::partial_sort(packet_vec.begin(), packet_vec.begin() + NN,
packet_vec.end());
}
} // namespace indexed_sort
} // namespace stl
#endif // I23DSFM_STL_INDEXED_SORT_H
| 25.298507 | 101 | 0.658997 | zyxrrr |
966a393e324b20538af1df465413e035a8bfd3ab | 3,157 | cpp | C++ | YorozuyaGSLib/source/CAsyncLogger.cpp | lemkova/Yorozuya | f445d800078d9aba5de28f122cedfa03f26a38e4 | [
"MIT"
] | 29 | 2017-07-01T23:08:31.000Z | 2022-02-19T10:22:45.000Z | YorozuyaGSLib/source/CAsyncLogger.cpp | kotopes/Yorozuya | 605c97d3a627a8f6545cc09f2a1b0a8afdedd33a | [
"MIT"
] | 90 | 2017-10-18T21:24:51.000Z | 2019-06-06T02:30:33.000Z | YorozuyaGSLib/source/CAsyncLogger.cpp | kotopes/Yorozuya | 605c97d3a627a8f6545cc09f2a1b0a8afdedd33a | [
"MIT"
] | 44 | 2017-12-19T08:02:59.000Z | 2022-02-24T23:15:01.000Z | #include <CAsyncLogger.hpp>
START_ATF_NAMESPACE
CAsyncLogger::CAsyncLogger()
{
using org_ptr = void (WINAPIV*)(struct CAsyncLogger*);
(org_ptr(0x1403bda40L))(this);
};
void CAsyncLogger::ctor_CAsyncLogger()
{
using org_ptr = void (WINAPIV*)(struct CAsyncLogger*);
(org_ptr(0x1403bda40L))(this);
};
void CAsyncLogger::Destroy()
{
using org_ptr = void (WINAPIV*)();
(org_ptr(0x1403be1b0L))();
};
bool CAsyncLogger::FormatLog(int iType, char* fmt)
{
using org_ptr = bool (WINAPIV*)(struct CAsyncLogger*, int, char*);
return (org_ptr(0x1403bf220L))(this, iType, fmt);
};
int CAsyncLogger::GetTotalWaitSize()
{
using org_ptr = int (WINAPIV*)(struct CAsyncLogger*);
return (org_ptr(0x1403bfd60L))(this);
};
int CAsyncLogger::Init()
{
using org_ptr = int (WINAPIV*)(struct CAsyncLogger*);
return (org_ptr(0x1403be220L))(this);
};
struct CAsyncLogger* CAsyncLogger::Instance()
{
using org_ptr = struct CAsyncLogger* (WINAPIV*)();
return (org_ptr(0x1403be0f0L))();
};
void CAsyncLogger::Log(char* szFileName, char* szLog, int iLenStr)
{
using org_ptr = void (WINAPIV*)(struct CAsyncLogger*, char*, char*, int);
(org_ptr(0x1403c00e0L))(this, szFileName, szLog, iLenStr);
};
bool CAsyncLogger::Log(int iType, char* szLog)
{
using org_ptr = bool (WINAPIV*)(struct CAsyncLogger*, int, char*);
return (org_ptr(0x1403bfa00L))(this, iType, szLog);
};
bool CAsyncLogger::LogFromArg(int iType, char* fmt, char* arg_ptr)
{
using org_ptr = bool (WINAPIV*)(struct CAsyncLogger*, int, char*, char*);
return (org_ptr(0x1403bf620L))(this, iType, fmt, arg_ptr);
};
void CAsyncLogger::Loop()
{
using org_ptr = void (WINAPIV*)(struct CAsyncLogger*);
(org_ptr(0x1403be870L))(this);
};
void CAsyncLogger::ProcThread(void* p)
{
using org_ptr = void (WINAPIV*)(void*);
(org_ptr(0x1403bfe00L))(p);
};
void CAsyncLogger::ProcWrite()
{
using org_ptr = void (WINAPIV*)(struct CAsyncLogger*);
(org_ptr(0x1403beab0L))(this);
};
bool CAsyncLogger::Regist(ASYNC_LOG_TYPE eType, char* szDirPath, char* szTypeName, bool bAddDateFileName, unsigned int dwUpdateFileNameDelay)
{
using org_ptr = bool (WINAPIV*)(struct CAsyncLogger*, ASYNC_LOG_TYPE, char*, char*, bool, unsigned int);
return (org_ptr(0x1403bebb0L))(this, eType, szDirPath, szTypeName, bAddDateFileName, dwUpdateFileNameDelay);
};
void CAsyncLogger::SystemLog(char* fmt)
{
using org_ptr = void (WINAPIV*)(struct CAsyncLogger*, char*);
(org_ptr(0x1403bfe60L))(this, fmt);
};
CAsyncLogger::~CAsyncLogger()
{
using org_ptr = void (WINAPIV*)(struct CAsyncLogger*);
(org_ptr(0x1403bdc40L))(this);
};
void CAsyncLogger::dtor_CAsyncLogger()
{
using org_ptr = void (WINAPIV*)(struct CAsyncLogger*);
(org_ptr(0x1403bdc40L))(this);
};
END_ATF_NAMESPACE
| 33.585106 | 145 | 0.623377 | lemkova |
966dbc1cc970c3fed8bcd1675bf4f04820057090 | 13,597 | cpp | C++ | source/glannotations/source/States/SplineState.cpp | dgimb89/glannotations | df687dbae1906cdb08c7b10cb006c025c4ba6406 | [
"MIT"
] | null | null | null | source/glannotations/source/States/SplineState.cpp | dgimb89/glannotations | df687dbae1906cdb08c7b10cb006c025c4ba6406 | [
"MIT"
] | null | null | null | source/glannotations/source/States/SplineState.cpp | dgimb89/glannotations | df687dbae1906cdb08c7b10cb006c025c4ba6406 | [
"MIT"
] | null | null | null | #include <glannotations/States/SplineState.h>
#include <glannotations/Renderer/AbstractRenderer.h>
#include <glannotations/AbstractAnnotation.h>
#include <glannotations/States/StateInterpolation.h>
#include <glm/gtx/rotate_vector.hpp>
#include <glm/gtx/vector_angle.hpp>
#include <iostream>
#include <math.h>
glannotations::SplineState::SplineState(glm::vec3 position
, std::vector<glm::vec3> splineBaseControlPoints, std::vector<float> splineBaseKnotValues
, glm::vec3 upToTopSpline)
{
initialize3D(position);
m_splineBase = std::shared_ptr<BSpline>(new BSpline3D(splineBaseControlPoints, splineBaseKnotValues));
m_splineTop = std::shared_ptr<BSpline>(new BSpline3D(splineBaseControlPoints, splineBaseKnotValues));
calculateSplineTop(upToTopSpline);
}
glannotations::SplineState::SplineState(glm::vec3 position
, std::vector<glm::vec3> splineBaseControlPoints, unsigned int baseDegree
, glm::vec3 upToTopSpline)
{
initialize3D(position);
m_splineBase = std::shared_ptr<BSpline>(new BSpline3D(splineBaseControlPoints, baseDegree));
m_splineTop = std::shared_ptr<BSpline>(new BSpline3D(splineBaseControlPoints, baseDegree));
calculateSplineTop(upToTopSpline);
}
glannotations::SplineState::SplineState(glm::vec3 position
, std::vector<glm::vec3> splineBaseControlPoints, std::vector<float> splineBaseKnotValues
, std::vector<glm::vec3> splineTopControlPoints, std::vector<float> splineTopKnotValues)
{
initialize3D(position);
m_splineBase = std::shared_ptr<BSpline>(new BSpline3D(splineBaseControlPoints, splineBaseKnotValues));
m_splineTop = std::shared_ptr<BSpline>(new BSpline3D(splineTopControlPoints, splineTopKnotValues));
}
glannotations::SplineState::SplineState(glm::vec3 position
, std::vector<glm::vec3> splineBaseControlPoints, unsigned int baseDegree
, std::vector<glm::vec3> splineTopControlPoints, unsigned int topDegree)
{
initialize3D(position);
m_splineBase = std::shared_ptr<BSpline>(new BSpline3D(splineBaseControlPoints, baseDegree));
m_splineTop = std::shared_ptr<BSpline>(new BSpline3D(splineTopControlPoints, topDegree));
}
glannotations::SplineState::SplineState(glm::vec3 position
, glm::vec3 planeAxisRight, glm::vec3 planeAxisUp
, std::vector<glm::vec2> splineBaseControlPoints, std::vector<float> splineBaseKnotValues
, glm::vec2 upToTopSpline)
{
initialize2D(position, planeAxisRight, planeAxisUp);
m_splineBase = std::shared_ptr<BSpline>(new BSpline2D(splineBaseControlPoints, splineBaseKnotValues));
m_splineTop = std::shared_ptr<BSpline>(new BSpline2D(splineBaseControlPoints, splineBaseKnotValues));
calculateSplineTop(upToTopSpline);
calculateTransformationMatrix();
}
glannotations::SplineState::SplineState(glm::vec3 position
, glm::vec3 planeAxisRight, glm::vec3 planeAxisUp
, std::vector<glm::vec2> splineBaseControlPoints, unsigned int baseDegree
, glm::vec2 upToTopSpline)
{
initialize2D(position, planeAxisRight, planeAxisUp);
m_splineBase = std::shared_ptr<BSpline>(new BSpline2D(splineBaseControlPoints, baseDegree));
m_splineTop = std::shared_ptr<BSpline>(new BSpline2D(splineBaseControlPoints, baseDegree));
calculateSplineTop(upToTopSpline);
calculateTransformationMatrix();
}
glannotations::SplineState::SplineState(glm::vec3 position
, glm::vec3 planeAxisRight, glm::vec3 planeAxisUp
, std::vector<glm::vec2> splineBaseControlPoints, std::vector<float> splineBaseKnotValues
, std::vector<glm::vec2> splineTopControlPoints, std::vector<float> splineTopKnotValues)
{
initialize2D(position, planeAxisRight, planeAxisUp);
m_splineBase = std::shared_ptr<BSpline>(new BSpline2D(splineBaseControlPoints, splineBaseKnotValues));
m_splineTop = std::shared_ptr<BSpline>(new BSpline2D(splineTopControlPoints, splineTopKnotValues));
calculateTransformationMatrix();
}
glannotations::SplineState::SplineState(glm::vec3 position
, glm::vec3 planeAxisRight, glm::vec3 planeAxisUp
, std::vector<glm::vec2> splineBaseControlPoints, unsigned int baseDegree
, std::vector<glm::vec2> splineTopControlPoints, unsigned int topDegree)
{
initialize2D(position, planeAxisRight, planeAxisUp);
m_splineBase = std::shared_ptr<BSpline>(new BSpline2D(splineBaseControlPoints, baseDegree));
m_splineTop = std::shared_ptr<BSpline>(new BSpline2D(splineTopControlPoints, topDegree));
calculateTransformationMatrix();
}
void glannotations::SplineState::initialize2D(glm::vec3 position, glm::vec3 planeAxisRight, glm::vec3 planeAxisUp) {
m_valid = true; //may be set false by following functions in constructor
m_acceptsExternalReference = true;
m_ll = position;
m_lr = position + planeAxisRight;
m_ur = m_lr + planeAxisUp;
}
void glannotations::SplineState::initialize3D(glm::vec3 position) {
m_valid = true; //may be set false by following functions in constructor
m_acceptsExternalReference = false;
m_ll = position;
m_lr = position;
m_ur = position;
}
void glannotations::SplineState::setExtends(glm::vec3 ll, glm::vec3 lr, glm::vec3 ur) {
if (ll != m_ll || lr != m_lr || ur != m_ur) {
setDirty(true);
m_ll = ll;
m_lr = lr;
m_ur = ur;
}
}
bool glannotations::SplineState::isValid() const {
return m_valid;
}
bool glannotations::SplineState::acceptsExternalReference() const {
return m_acceptsExternalReference;
}
inline std::vector<glm::vec2> discardZ(const std::vector<glm::vec3> points) {
std::vector<glm::vec2> points2D;
for (size_t i = 0; i < points.size(); i++) {
points2D.push_back(glm::vec2(points[i].x, points[i].y));
}
return points2D;
}
void glannotations::SplineState::changeOrientation(glm::vec2 newUp) {
calculateSplineTop(newUp);
}
void glannotations::SplineState::changeOrientation(glm::vec3 newUp) {
calculateSplineTop(newUp);
}
void glannotations::SplineState::changeOrientation(std::shared_ptr<BSpline3D> splineTop) {
if (m_acceptsExternalReference) {
std::cerr << "#Warning: Aborting changeOrientation due to incompatibility, because got a 3D-TopSpline for 2D-BaseSpline.\n";
return;
}
(m_splineTop->asBSpline3D()).setControlPoints(splineTop->getControlPoints());
m_splineTop->setKnotValues(splineTop->getKnotValues());
m_splineTop->calculateSplineDegree();
}
void glannotations::SplineState::changeOrientation(std::shared_ptr<BSpline2D> splineTop) {
if (!m_acceptsExternalReference) {
std::cerr << "#Warning: Aborting changeOrientation due to incompatibility: got a 2D-TopSpline for 3D-BaseSpline.\n";
return;
}
std::vector<glm::vec3> ctrlPoints = splineTop->getControlPoints();
//discard z
std::vector<glm::vec2> ctrlPoints2D = discardZ(ctrlPoints);
(m_splineTop->asBSpline2D()).setControlPoints(ctrlPoints2D);
m_splineTop->setKnotValues(splineTop->getKnotValues());
m_splineTop->calculateSplineDegree();
}
void glannotations::SplineState::calculateSplineTop(glm::vec3 upVecInWorldSpace) {
//for Spline3D only
if (!m_acceptsExternalReference) {
auto ctrlPoints = m_splineBase->getControlPoints();
for (size_t i = 0; i < ctrlPoints.size(); i++) {
ctrlPoints[i] += upVecInWorldSpace;
}
(m_splineTop->asBSpline3D()).setControlPoints(ctrlPoints);
m_splineTop->setKnotValues(m_splineBase->getKnotValues());
}
else {
//unable to calculate splineTop
//mark SplineState as invalid
std::cerr << "#Error: Marking Spline as invalid, could not calculate spline top, given incompatible 3D-up vector for 2D-Spline.\n";
m_valid = false;
}
setDirty(true);
}
void glannotations::SplineState::calculateSplineTop(glm::vec2 upVecInPlaneSpace) {
//for BSpline2D only
std::vector<glm::vec2> ctrlPoints2D;
if (m_acceptsExternalReference){
auto ctrlPoints = (m_splineBase->asBSpline2D()).getControlPoints();
for (size_t i = 0; i < ctrlPoints.size(); i++) {
ctrlPoints2D.push_back(glm::vec2(
ctrlPoints[i].x + upVecInPlaneSpace.x,
ctrlPoints[i].y + upVecInPlaneSpace.y
)
);
}
(m_splineTop->asBSpline2D()).setControlPoints(ctrlPoints2D);
m_splineTop->setKnotValues(m_splineBase->getKnotValues());
}
else {
//unable to calculate splineTop
//mark SplineState as invalid
std::cerr << "#Error: Marking Spline as invalid, could not calculate spline top, given incompatible 2D-up vector for 3D-Spline.\n";
m_valid = false;
}
setDirty(true);
}
void glannotations::SplineState::draw(const globjects::ref_ptr<glannotations::AbstractAnnotation>& annotation, const AbstractRenderer& renderer) {
drawExternalReference(renderer, *this);
renderer.drawSetupState(annotation, *this);
}
const glm::vec3& glannotations::SplineState::getLL() const {
return m_ll;
}
const glm::vec3& glannotations::SplineState::getLR() const {
return m_lr;
}
const glm::vec3& glannotations::SplineState::getUR() const {
return m_ur;
}
globjects::ref_ptr<glannotations::AbstractState> glannotations::SplineState::interpolateWith(const QuadState& mixState, float mix) {
return glannotations::Interpolation::interpolate(*this, mixState, mix);
}
globjects::ref_ptr<glannotations::AbstractState> glannotations::SplineState::interpolateWith(const SplineState& mixState, float mix) {
return glannotations::Interpolation::interpolate(*this, mixState, mix);
}
globjects::ref_ptr<glannotations::AbstractState> glannotations::SplineState::interpolateWith(const ViewportState& mixState, float mix) {
return glannotations::Interpolation::interpolate(*this, mixState, mix);
}
globjects::ref_ptr<glannotations::AbstractState> glannotations::SplineState::clone() const{
globjects::ref_ptr<glannotations::AbstractState> clonedState;
if (m_acceptsExternalReference) {
auto ctrlPointsBase = discardZ((m_splineBase->asBSpline2D()).getControlPoints());
auto ctrlPointsTop = discardZ((m_splineTop->asBSpline2D()).getControlPoints());
clonedState = globjects::ref_ptr<glannotations::AbstractState>(
new SplineState(m_ll
, m_lr - m_ll
, m_ur - m_lr
, ctrlPointsBase
, m_splineBase->getKnotValues()
, ctrlPointsTop
, m_splineTop->getKnotValues()
)
);
}
else {
clonedState = globjects::ref_ptr<glannotations::AbstractState>(
new SplineState(m_ll
, m_splineBase->getControlPoints(), m_splineBase->getKnotValues()
, m_splineTop->getControlPoints(), m_splineTop->getKnotValues()
)
);
}
ReferenceableState::copyState(dynamic_cast<ReferenceableState&> (*clonedState));
return clonedState;
}
void glannotations::SplineState::setExternalReference(const globjects::ref_ptr<glannotations::AbstractExternalReference>& reference) {
if (m_acceptsExternalReference) {
ReferenceableState::setExternalReference(reference);
m_externalReference->setupExternalReference(*this);
}
else {
std::cerr << "#Warning: Cannot set ExternalReference for BSpline3D. No reference set.\n";
}
}
void glannotations::SplineState::updateExtends(glm::vec2 sourceExtends){
if (m_acceptsExternalReference) {
cropExtends(m_ll, m_lr, m_ur, sourceExtends);
calculateTransformationMatrix();
}
}
glannotations::BoundingBox glannotations::SplineState::getBoundingBox() {
//todo: maybe there is a more efficient way
glannotations::BoundingBox bb;
for (auto ctrlPoint : m_splineBase->getControlPoints())
{
bb.extendBy(ctrlPoint);
}
for (auto ctrlPoint : m_splineTop->getControlPoints())
{
bb.extendBy(ctrlPoint);
}
return bb;
}
glm::vec4 glannotations::SplineState::getBoundingRect() const {
//todo: maybe there is a more efficient way
if (!m_acceptsExternalReference) {
return glm::vec4();
}
glm::vec4 brBase = (m_splineBase->asBSpline2D()).getBoundingRect();
glm::vec4 brTop = (m_splineTop->asBSpline2D()).getBoundingRect();
float minX = glm::min(brBase.x, brTop.x);
float minY = glm::min(brBase.y, brTop.y);
float maxX = glm::max(brBase.z, brTop.z);
float maxY = glm::max(brBase.w, brTop.w);
return glm::vec4(minX, minY, maxX, maxY);
}
glm::mat4 glannotations::SplineState::getTransformationMatrix() const {
return m_transformation;
}
void glannotations::SplineState::calculateTransformationMatrix() {
//no translation, because SplineState will take care of positioning later
//scaling matrix
glm::mat4 scalingM = glm::mat4();
glm::vec3 right = m_lr - m_ll;
glm::vec3 up = m_ur - m_lr;
float width = glm::length(right);
float height = glm::length(up);
glm::vec4 plane = getBoundingRect();
float scaleX = width / (plane.z - plane.x);
float scaleY = height / (plane.w - plane.y);
scalingM = glm::scale(scalingM, glm::vec3(scaleX, scaleY, 1.f));
//rotation matrix to
auto eye = glm::vec3(0, 0, 0);
auto center = glm::normalize(glm::cross(glm::normalize(up), glm::normalize(right)));
glm::mat4 rotation = glm::lookAt(eye, eye + center, up);
rotation = glm::inverse(rotation);
m_transformation = rotation * scalingM;
}
void glannotations::SplineState::setSplineDirty(bool dirty) {
m_splineBase->setDirty(dirty);
m_splineTop->setDirty(dirty);
}
bool glannotations::SplineState::isSplineDirty() const {
return (m_splineBase->isDirty() || m_splineTop->isDirty());
}
glm::vec3 glannotations::SplineState::retrieveStartingPoint() {
if (m_acceptsExternalReference)
return m_splineBase->retrieveCurvepointAt(0.f);
return glm::vec3(0, 0, 0);
}
glm::vec3 glannotations::SplineState::retrieveConnectingVectorAt(float t) {
//useful for positioning
//it might be not that orthogonal...
glm::vec3 position_ll = m_splineBase->retrieveCurvepointAt(t);
glm::vec3 position_ul = m_splineTop->retrieveCurvepointAt(t);
return (position_ul - position_ll);
}
glm::vec3 glannotations::SplineState::retrieveSecantVectorAt(float t, float nextT) {
return m_splineBase->retrieveSecantVectorAt(t, nextT);
}
void glannotations::SplineState::prepare() {
updatePositioning(*this);
AbstractState::prepare();
}
| 32.296912 | 146 | 0.762815 | dgimb89 |
966e73f6d241e6fedffd21ef27bebb3bfc9b294f | 476 | hpp | C++ | Engine/src/ecs/components/Renderable.hpp | dabbertorres/LinuxOpenGL | 0dba561244d720e64bea4c839c95db036d479bdf | [
"MIT"
] | null | null | null | Engine/src/ecs/components/Renderable.hpp | dabbertorres/LinuxOpenGL | 0dba561244d720e64bea4c839c95db036d479bdf | [
"MIT"
] | 1 | 2016-05-05T00:51:58.000Z | 2016-05-05T00:51:58.000Z | Engine/src/ecs/components/Renderable.hpp | dabbertorres/LinuxOpenGL | 0dba561244d720e64bea4c839c95db036d479bdf | [
"MIT"
] | null | null | null | #ifndef DBR_ENG_ECS_RENDERABLE_HPP
#define DBR_ENG_ECS_RENDERABLE_HPP
#include "Graphics/Types.hpp"
#include "ecs/Component.hpp"
namespace dbr
{
namespace eng
{
namespace ecs
{
class Renderable : public Component
{
public:
Renderable(Id id, gfx::HandleI bufferHandle);
~Renderable();
private:
gfx::HandleI bufferHandle;
};
}
}
}
#endif
| 17 | 61 | 0.548319 | dabbertorres |
96718ec412d1399e1c17c97b461e1635829bfd2d | 255 | hpp | C++ | lab07/3.2_vehicle/vehicle/Car.hpp | AlexanderFadeev/oop | 62ea584b2c49dea5457b9e520866bfd7a0d883c7 | [
"MIT"
] | null | null | null | lab07/3.2_vehicle/vehicle/Car.hpp | AlexanderFadeev/oop | 62ea584b2c49dea5457b9e520866bfd7a0d883c7 | [
"MIT"
] | 18 | 2018-02-07T07:10:18.000Z | 2018-05-23T08:11:28.000Z | lab07/3.2_vehicle/vehicle/Car.hpp | AlexanderFadeev/oop | 62ea584b2c49dea5457b9e520866bfd7a0d883c7 | [
"MIT"
] | null | null | null | #pragma once
#include "CarBrand.h"
template <typename CVehicle>
class CCar
: public CVehicle
{
public:
using Brand = CarBrand;
CCar(size_t seatsCount, Brand brand);
Brand GetBrand() const override;
private:
Brand m_brand;
};
#include "Car.ipp"
| 12.142857 | 38 | 0.72549 | AlexanderFadeev |
96757bc5087d3d70310677625ff2655dca99cae4 | 1,093 | cc | C++ | Replicator/tests/DBAccessTestWrapper.cc | mhocouchbase/couchbase-lite-core | 8a527a066b703c8865b4e61cbd9e3d41d81ba5ef | [
"Apache-2.0"
] | null | null | null | Replicator/tests/DBAccessTestWrapper.cc | mhocouchbase/couchbase-lite-core | 8a527a066b703c8865b4e61cbd9e3d41d81ba5ef | [
"Apache-2.0"
] | null | null | null | Replicator/tests/DBAccessTestWrapper.cc | mhocouchbase/couchbase-lite-core | 8a527a066b703c8865b4e61cbd9e3d41d81ba5ef | [
"Apache-2.0"
] | null | null | null | //
// DBAccessTestWrapper.cc
//
// Copyright (C) 2020 Jens Alfke. 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 "DBAccessTestWrapper.hh"
#include "DBAccess.hh"
#include "c4DocEnumerator.hh"
using namespace std;
using namespace litecore::repl;
C4DocEnumerator* DBAccessTestWrapper::unresolvedDocsEnumerator(C4Database *db) {
std::shared_ptr<DBAccess> acc = make_shared<DBAccess>(db, false);
return acc->unresolvedDocsEnumerator(true).release();
}
unsigned DBAccessTestWrapper::numDeltasApplied() {
return DBAccess::gNumDeltasApplied;
}
| 31.228571 | 80 | 0.756633 | mhocouchbase |
9675dfae28287c0efd9e911cd002c91a2cf54f50 | 2,267 | hpp | C++ | src/utils/block.hpp | ktrianta/jacobi-svd-evd | 8162562c631c3d1541e23b1fa38ec7600a5032af | [
"MIT"
] | 3 | 2019-03-09T14:22:26.000Z | 2021-04-24T05:40:44.000Z | src/utils/block.hpp | ktrianta/jacobi-svd-evd | 8162562c631c3d1541e23b1fa38ec7600a5032af | [
"MIT"
] | 35 | 2019-03-17T14:02:55.000Z | 2019-06-12T13:15:19.000Z | src/utils/block.hpp | ktrianta/jacobi-svd-evd | 8162562c631c3d1541e23b1fa38ec7600a5032af | [
"MIT"
] | 4 | 2019-03-09T14:22:30.000Z | 2020-09-28T19:36:42.000Z | #pragma once
#include <cstdlib>
#include "matrix.hpp"
// perform C = AB
void mult_block(struct matrix_t Amat, size_t blockA_row, size_t blockA_col, struct matrix_t Bmat, size_t blockB_row,
size_t blockB_col, struct matrix_t Cmat, size_t blockC_row, size_t blockC_col, size_t block_size);
// perform D = C + AB
void mult_add_block(struct matrix_t Amat, size_t blockA_row, size_t blockA_col, struct matrix_t Bmat, size_t blockB_row,
size_t blockB_col, struct matrix_t Cmat, size_t blockC_row, size_t blockC_col, struct matrix_t Dmat,
size_t blockD_row, size_t blockD_col, size_t block_size);
// perform C = (A^T)B
void mult_transpose_block(struct matrix_t Amat, size_t blockA_row, size_t blockA_col, struct matrix_t Bmat,
size_t blockB_row, size_t blockB_col, struct matrix_t Cmat, size_t blockC_row,
size_t blockC_col, size_t block_size);
// perform D = C + (A^T)B
void mult_add_transpose_block(struct matrix_t Amat, size_t blockA_row, size_t blockA_col, struct matrix_t Bmat,
size_t blockB_row, size_t blockB_col, struct matrix_t Cmat, size_t blockC_row,
size_t blockC_col, struct matrix_t Dmat, size_t blockD_row, size_t blockD_col,
size_t block_size);
// perform C = A(B^T)
void mult_transpose_block_right(struct matrix_t Amat, size_t blockA_row, size_t blockA_col, struct matrix_t Bmat,
size_t blockB_row, size_t blockB_col, struct matrix_t Cmat, size_t blockC_row,
size_t blockC_col, size_t block_size);
// perform D = C + A(B^T)
void mult_add_transpose_block_right(struct matrix_t Amat, size_t blockA_row, size_t blockA_col, struct matrix_t Bmat,
size_t blockB_row, size_t blockB_col, struct matrix_t Cmat, size_t blockC_row,
size_t blockC_col, struct matrix_t Dmat, size_t blockD_row, size_t blockD_col,
size_t block_size);
void copy_block(struct matrix_t S, size_t blockS_row, size_t blockS_col, struct matrix_t D, size_t blockD_row,
size_t blockD_col, size_t block_size);
| 70.84375 | 120 | 0.672695 | ktrianta |
9677f50e8b4a0e1aaf745c93fdbeb30a58c31a15 | 995 | cpp | C++ | test/HasherTest.cpp | hdc-arizona/MediatedCubes | bf5d9cdec18eeea9903717a7299cc93ed644af1d | [
"MIT"
] | null | null | null | test/HasherTest.cpp | hdc-arizona/MediatedCubes | bf5d9cdec18eeea9903717a7299cc93ed644af1d | [
"MIT"
] | null | null | null | test/HasherTest.cpp | hdc-arizona/MediatedCubes | bf5d9cdec18eeea9903717a7299cc93ed644af1d | [
"MIT"
] | null | null | null | #include <boost/test/unit_test.hpp>
#include "Hasher.h"
BOOST_AUTO_TEST_SUITE(HasherTest)
BOOST_AUTO_TEST_CASE(UpdateDoesNotCommuteWithConcat)
{
Hasher h;
Hasher g;
h.update(1);
h.update(2);
g.update(12);
BOOST_CHECK(h.digest() != g.digest());
}
BOOST_AUTO_TEST_CASE(CopyProducesIdentical)
{
Hasher h;
h.update(1);
Hasher g = h;
BOOST_CHECK(h.digest() == g.digest());
h.update(2);
g.update(2);
BOOST_CHECK(h.digest() == g.digest());
}
BOOST_AUTO_TEST_CASE(DigestIsIdempotent)
{
Hasher h;
h.update(1);
BOOST_CHECK(h.digest() == h.digest());
}
BOOST_AUTO_TEST_CASE(CopyProducesDisjoint)
{
Hasher h;
h.update(1);
Hasher g = h;
auto digest1 = h.digest();
g.update(2);
auto digest2 = h.digest();
BOOST_CHECK(digest1 == digest2);
}
BOOST_AUTO_TEST_CASE(CopyProducesDisjointReverse)
{
Hasher h;
h.update(1);
Hasher g = h;
auto digest1 = g.digest();
h.update(2);
auto digest2 = g.digest();
BOOST_CHECK(digest1 == digest2);
}
BOOST_AUTO_TEST_SUITE_END()
| 14.632353 | 53 | 0.694472 | hdc-arizona |
9679b0ab04f8dfedb329c8aa0d72085a7c26fa22 | 5,991 | cpp | C++ | tcb/src/v20180608/model/DescribeCloudBaseRunServerDomainNameResponse.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | null | null | null | tcb/src/v20180608/model/DescribeCloudBaseRunServerDomainNameResponse.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | null | null | null | tcb/src/v20180608/model/DescribeCloudBaseRunServerDomainNameResponse.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/tcb/v20180608/model/DescribeCloudBaseRunServerDomainNameResponse.h>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Tcb::V20180608::Model;
using namespace std;
DescribeCloudBaseRunServerDomainNameResponse::DescribeCloudBaseRunServerDomainNameResponse() :
m_publicDomainHasBeenSet(false),
m_internalDomainHasBeenSet(false),
m_domainNameHasBeenSet(false)
{
}
CoreInternalOutcome DescribeCloudBaseRunServerDomainNameResponse::Deserialize(const string &payload)
{
rapidjson::Document d;
d.Parse(payload.c_str());
if (d.HasParseError() || !d.IsObject())
{
return CoreInternalOutcome(Core::Error("response not json format"));
}
if (!d.HasMember("Response") || !d["Response"].IsObject())
{
return CoreInternalOutcome(Core::Error("response `Response` is null or not object"));
}
rapidjson::Value &rsp = d["Response"];
if (!rsp.HasMember("RequestId") || !rsp["RequestId"].IsString())
{
return CoreInternalOutcome(Core::Error("response `Response.RequestId` is null or not string"));
}
string requestId(rsp["RequestId"].GetString());
SetRequestId(requestId);
if (rsp.HasMember("Error"))
{
if (!rsp["Error"].IsObject() ||
!rsp["Error"].HasMember("Code") || !rsp["Error"]["Code"].IsString() ||
!rsp["Error"].HasMember("Message") || !rsp["Error"]["Message"].IsString())
{
return CoreInternalOutcome(Core::Error("response `Response.Error` format error").SetRequestId(requestId));
}
string errorCode(rsp["Error"]["Code"].GetString());
string errorMsg(rsp["Error"]["Message"].GetString());
return CoreInternalOutcome(Core::Error(errorCode, errorMsg).SetRequestId(requestId));
}
if (rsp.HasMember("PublicDomain") && !rsp["PublicDomain"].IsNull())
{
if (!rsp["PublicDomain"].IsString())
{
return CoreInternalOutcome(Core::Error("response `PublicDomain` IsString=false incorrectly").SetRequestId(requestId));
}
m_publicDomain = string(rsp["PublicDomain"].GetString());
m_publicDomainHasBeenSet = true;
}
if (rsp.HasMember("InternalDomain") && !rsp["InternalDomain"].IsNull())
{
if (!rsp["InternalDomain"].IsString())
{
return CoreInternalOutcome(Core::Error("response `InternalDomain` IsString=false incorrectly").SetRequestId(requestId));
}
m_internalDomain = string(rsp["InternalDomain"].GetString());
m_internalDomainHasBeenSet = true;
}
if (rsp.HasMember("DomainName") && !rsp["DomainName"].IsNull())
{
if (!rsp["DomainName"].IsString())
{
return CoreInternalOutcome(Core::Error("response `DomainName` IsString=false incorrectly").SetRequestId(requestId));
}
m_domainName = string(rsp["DomainName"].GetString());
m_domainNameHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
string DescribeCloudBaseRunServerDomainNameResponse::ToJsonString() const
{
rapidjson::Document value;
value.SetObject();
rapidjson::Document::AllocatorType& allocator = value.GetAllocator();
if (m_publicDomainHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "PublicDomain";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_publicDomain.c_str(), allocator).Move(), allocator);
}
if (m_internalDomainHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "InternalDomain";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_internalDomain.c_str(), allocator).Move(), allocator);
}
if (m_domainNameHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "DomainName";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_domainName.c_str(), allocator).Move(), allocator);
}
rapidjson::Value iKey(rapidjson::kStringType);
string key = "RequestId";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value().SetString(GetRequestId().c_str(), allocator), allocator);
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
value.Accept(writer);
return buffer.GetString();
}
string DescribeCloudBaseRunServerDomainNameResponse::GetPublicDomain() const
{
return m_publicDomain;
}
bool DescribeCloudBaseRunServerDomainNameResponse::PublicDomainHasBeenSet() const
{
return m_publicDomainHasBeenSet;
}
string DescribeCloudBaseRunServerDomainNameResponse::GetInternalDomain() const
{
return m_internalDomain;
}
bool DescribeCloudBaseRunServerDomainNameResponse::InternalDomainHasBeenSet() const
{
return m_internalDomainHasBeenSet;
}
string DescribeCloudBaseRunServerDomainNameResponse::GetDomainName() const
{
return m_domainName;
}
bool DescribeCloudBaseRunServerDomainNameResponse::DomainNameHasBeenSet() const
{
return m_domainNameHasBeenSet;
}
| 34.431034 | 132 | 0.698381 | suluner |
9679c785626b7b81aa1da6d3092fe2867f87aef5 | 2,391 | cpp | C++ | Medium/3-longestsubnorep.cpp | mzhou08/Leetcode | b186f6cb4ecc6efb30d4da96be7f3ca15d7c4e59 | [
"Apache-2.0"
] | null | null | null | Medium/3-longestsubnorep.cpp | mzhou08/Leetcode | b186f6cb4ecc6efb30d4da96be7f3ca15d7c4e59 | [
"Apache-2.0"
] | null | null | null | Medium/3-longestsubnorep.cpp | mzhou08/Leetcode | b186f6cb4ecc6efb30d4da96be7f3ca15d7c4e59 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <string>
#include <vector>
using namespace std;
/*
Submission Statistics:
Runtime: 132 ms, faster than 11.94% of C++ online submissions for Longest Substring Without Repeating Characters.
Memory Usage: 104.4 MB, less than 9.22% of C++ online submissions for Longest Substring Without Repeating Characters.
*/
/*
Notes: You can use vector[char] to access an vector of ints with length 128.
Makes this problem a lot easier.
*/
class Solution {
public:
struct dict {
char val;
int index;
dict() : val('\0'), index(-2) {}
dict(char x, int ind) : val(x), index(ind) {}
};
vector<int> repeat(vector<dict*> d, char c, int start, int end) {
vector<int> res;
res.push_back(-1 /*index of dict*/);
res.push_back(-1 /*index of repeat*/);
for (int i = 0; i < d.size(); i++) {
if (d[i]->val == c && d[i]->index >= start) {
res[0] = i;
res[1] = d[i]->index;
return res;
}
}
return res;
}
int lengthOfLongestSubstring(string s) {
int start = 0;
int end = 0;
int longest = 0;
vector<dict*> d;
while (end < s.length()) {
if (repeat(d, s[end], start, end)[0] != -1) {
vector<int> rep = repeat(d, s[end], start, end);
//cout << rep[0] << " " << rep[1] << '\n';
longest = max(longest, end - start);
start = rep[1] + 1;
//Update the dictionary entry for the char at s[end]
dict* new_entry = new dict(s[end], end);
d[rep[0]] = new_entry;
} else if (end == s.length() - 1) {
longest = max(longest, end - start + 1);
} else {
dict* new_entry = new dict(s[end], end);
d.push_back(new_entry);
}
end++;
}
return longest;
}
};
int main () {
Solution S;
cout << "\"abcabcbb\": exp. 3: " << S.lengthOfLongestSubstring("abcabcbb") << "\n";
cout << "\"tmmzuxt\": exp. 5: " << S.lengthOfLongestSubstring("tmmzuxt") << "\n";
cout << "\"\": exp. 0: " << S.lengthOfLongestSubstring("") << "\n";
cout << "\"aabaab!bb\": exp. 3: " << S.lengthOfLongestSubstring("aabaab!bb") << "\n";
} | 30.653846 | 117 | 0.495609 | mzhou08 |
9679ec86b80d94cf8f31dda3a9705ef7ce836464 | 526 | cpp | C++ | 63.cpp | bodhiye/Offer | c723210d3052bebd6cd9adfc2959c4aa2b8a2e0c | [
"MIT"
] | 1 | 2018-05-08T01:35:49.000Z | 2018-05-08T01:35:49.000Z | 63.cpp | bodhiye/Offer | c723210d3052bebd6cd9adfc2959c4aa2b8a2e0c | [
"MIT"
] | null | null | null | 63.cpp | bodhiye/Offer | c723210d3052bebd6cd9adfc2959c4aa2b8a2e0c | [
"MIT"
] | 1 | 2021-07-24T02:15:42.000Z | 2021-07-24T02:15:42.000Z | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> v;
int n;
void Insert(int num) {
v.push_back(num);
n = v.size();
for (int i = n - 1; i > 0 && v[i] < v[i - 1]; --i)
swap(v[i], v[i - 1]);
}
double GetMedian() {
return (v[(n - 1) >> 1] + v[n >> 1]) / 2.0;
}
int main() {
ios::sync_with_stdio(false);
int m, tmp;
cin >> m;
for (int i = 0; i < m; i++) {
cin >> tmp;
Insert(tmp);
}
cout << GetMedian();
return 0;
}
| 16.4375 | 54 | 0.480989 | bodhiye |
967adb093c66db540c2858b60c1f7d13d6b68e81 | 575 | cpp | C++ | Problems/bamboo.cpp | idcodeoverflow/ACMSolvedProblems | aa5ab61e231d871125dd6401edd692d209059ff7 | [
"MIT"
] | null | null | null | Problems/bamboo.cpp | idcodeoverflow/ACMSolvedProblems | aa5ab61e231d871125dd6401edd692d209059ff7 | [
"MIT"
] | null | null | null | Problems/bamboo.cpp | idcodeoverflow/ACMSolvedProblems | aa5ab61e231d871125dd6401edd692d209059ff7 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <math.h>
#define EP 0.001
#define IN 0.00001
int t = 0, i = 0;
double h = 0.0, d = 0.0, s = 0.0;
double obtener_c()
{
double c = 0.0, a = 0.0, b = 0.0, A = 0.0, B = 0.0;
for(A = 0.00; A < 1.0; A += IN)
{
a = A * h;
b = (1.0 - A) * h;
if(a < b)
c = sqrt(b * b - a * a);
else
c = sqrt(a * a - b * b);
if(fabs(d - c) <= EP)
break;
}
return a;
}
int main()
{
scanf("%d", &t);
for(; i < t; i++)
{
scanf("%lf %lf",&h,&d);
h = obtener_c();
printf("%.1lf\n",h);
s += h;
}
printf("%.1lf\n",(double)(s/t));
return 0;
}
| 15.972222 | 52 | 0.446957 | idcodeoverflow |
967d120b5ae8b09b1288d1eea9d8a330f4b30149 | 687 | cpp | C++ | Zork/globals.cpp | Mefiso/zork | 1eb26348f88edcd1cb168ce8061c5ccd5610d1f3 | [
"MIT"
] | null | null | null | Zork/globals.cpp | Mefiso/zork | 1eb26348f88edcd1cb168ce8061c5ccd5610d1f3 | [
"MIT"
] | null | null | null | Zork/globals.cpp | Mefiso/zork | 1eb26348f88edcd1cb168ce8061c5ccd5610d1f3 | [
"MIT"
] | null | null | null | #include "globals.h"
//using namespace std;
// -------------------------------------------------
bool Same(const string& a, const string& b)
{
return _stricmp(a.c_str(), b.c_str()) == 0;
}
bool Same(const char* a, const string& b)
{
return _stricmp(a, b.c_str()) == 0;
}
bool Same(const string& a, const char* b)
{
return _stricmp(a.c_str(), b) == 0;
}
int Roll(int min, int max)
{
return (max > 0) ? min + (rand() % (max - min)) : 0;
}
void Tokenize(const string& line, vector<string>& arguments)
{
const char* str = line.c_str();
do
{
const char *begin = str;
while(*str != ' ' && *str)
str++;
arguments.push_back(string(begin, str));
} while(0 != *str++);
}
| 17.175 | 60 | 0.554585 | Mefiso |
9681341aeca47a0444b1ae3e72e447cba5b786ab | 1,767 | hh | C++ | src/c++/include/reference/Seed.hh | Illumina/Isaac4 | 0924fba8b467868da92e1c48323b15d7cbca17dd | [
"BSD-3-Clause"
] | 13 | 2018-02-09T22:59:39.000Z | 2021-11-29T06:33:22.000Z | src/c++/include/reference/Seed.hh | Illumina/Isaac4 | 0924fba8b467868da92e1c48323b15d7cbca17dd | [
"BSD-3-Clause"
] | 17 | 2018-01-26T11:36:07.000Z | 2022-02-03T18:48:43.000Z | src/c++/include/reference/Seed.hh | Illumina/Isaac4 | 0924fba8b467868da92e1c48323b15d7cbca17dd | [
"BSD-3-Clause"
] | 4 | 2018-10-19T20:00:00.000Z | 2020-10-29T14:44:06.000Z | /**
** Isaac Genome Alignment Software
** Copyright (c) 2010-2017 Illumina, Inc.
** All rights reserved.
**
** This software is provided under the terms and conditions of the
** GNU GENERAL PUBLIC LICENSE Version 3
**
** You should have received a copy of the GNU GENERAL PUBLIC LICENSE Version 3
** along with this program. If not, see
** <https://github.com/illumina/licenses/>.
**
** \file Seed.hh
**
** \brief Seeds are used to find alignment candidates in the reference genome
**
** \author Roman Petrovski
**/
#ifndef iSAAC_REFERENCE_SEED_HH
#define iSAAC_REFERENCE_SEED_HH
#include <iostream>
#include "oligo/Kmer.hh"
namespace isaac
{
namespace reference
{
template <typename KmerT>
class InterleavedSeed
{
public:
typedef KmerT KmerType;
static const unsigned STEP = 1;
static const unsigned KMER_BASES = KmerType::KMER_BASES;
static const unsigned SEED_LENGTH = KMER_BASES * STEP;
InterleavedSeed() : kmer_(0) {}
InterleavedSeed(KmerT kmer) : kmer_(kmer) {}
KmerType &kmer() {return kmer_;}
private:
KmerType kmer_;
};
template <typename KmerT>
inline std::ostream &operator<<(std::ostream &os, const InterleavedSeed<KmerT> &seed)
{
typedef InterleavedSeed<KmerT> SeedT;
return os << "InterleavedSeed(" << oligo::Bases<oligo::BITS_PER_BASE, typename SeedT::KmerType>(seed.getKmer(), oligo::KmerTraits<typename SeedT::KmerType>::KMER_BASES) <<
"(" << oligo::ReverseBases<oligo::BITS_PER_BASE, typename SeedT::KmerType>(seed.getKmer(), oligo::KmerTraits<typename SeedT::KmerType>::KMER_BASES) << ")" <<
")";
}
template <typename KmerT> struct Seed : public InterleavedSeed<KmerT>
{
};
} // namespace reference
} // namespace isaac
#endif // #ifndef iSAAC_REFERENCE_SEED_HH
| 26.772727 | 175 | 0.710243 | Illumina |
9681401242d880547108b3a6efc748f5bbeafd16 | 408 | hpp | C++ | include/RED4ext/Scripting/Natives/Generated/ent/VertexAnimationMapperSourceType.hpp | jackhumbert/RED4ext.SDK | 2c55eccb83beabbbe02abae7945af8efce638fca | [
"MIT"
] | 42 | 2020-12-25T08:33:00.000Z | 2022-03-22T14:47:07.000Z | include/RED4ext/Scripting/Natives/Generated/ent/VertexAnimationMapperSourceType.hpp | jackhumbert/RED4ext.SDK | 2c55eccb83beabbbe02abae7945af8efce638fca | [
"MIT"
] | 38 | 2020-12-28T22:36:06.000Z | 2022-02-16T11:25:47.000Z | include/RED4ext/Scripting/Natives/Generated/ent/VertexAnimationMapperSourceType.hpp | jackhumbert/RED4ext.SDK | 2c55eccb83beabbbe02abae7945af8efce638fca | [
"MIT"
] | 20 | 2020-12-28T22:17:38.000Z | 2022-03-22T17:19:01.000Z | #pragma once
// This file is generated from the Game's Reflection data
#include <cstdint>
namespace RED4ext
{
namespace ent {
enum class VertexAnimationMapperSourceType : uint32_t
{
FloatTrack = 0,
TranslationX = 1,
TranslationY = 2,
TranslationZ = 3,
RotationQuatX = 4,
RotationQuatY = 5,
RotationQuatZ = 6,
RotationQuatW = 7,
};
} // namespace ent
} // namespace RED4ext
| 18.545455 | 57 | 0.683824 | jackhumbert |
96818053ea161b7b0fc284b9617776c30bc8af05 | 334 | hpp | C++ | include/mio/unordered_set.hpp | inie0722/mio | 205411c2a24fe216c9f981b6a974cdb0118f7560 | [
"BSL-1.0"
] | null | null | null | include/mio/unordered_set.hpp | inie0722/mio | 205411c2a24fe216c9f981b6a974cdb0118f7560 | [
"BSL-1.0"
] | null | null | null | include/mio/unordered_set.hpp | inie0722/mio | 205411c2a24fe216c9f981b6a974cdb0118f7560 | [
"BSL-1.0"
] | null | null | null | #pragma once
#include <parallel_hashmap/phmap.h>
namespace mio
{
template <class T,
class Hash = phmap::priv::hash_default_hash<T>,
class Eq = phmap::priv::hash_default_eq<T>,
class Alloc = phmap::priv::Allocator<T>>
using unordered_set = phmap::node_hash_set<T, Hash, Eq, Alloc>;
} | 27.833333 | 67 | 0.628743 | inie0722 |
96833ec3bc2d8527cfd2174dd8522061a28d225b | 23,120 | cxx | C++ | model_server/ui_browser/src/SetsUI.cxx | kit-transue/software-emancipation-discover | bec6f4ef404d72f361d91de954eae9a3bd669ce3 | [
"BSD-2-Clause"
] | 2 | 2015-11-24T03:31:12.000Z | 2015-11-24T16:01:57.000Z | model_server/ui_browser/src/SetsUI.cxx | radtek/software-emancipation-discover | bec6f4ef404d72f361d91de954eae9a3bd669ce3 | [
"BSD-2-Clause"
] | null | null | null | model_server/ui_browser/src/SetsUI.cxx | radtek/software-emancipation-discover | bec6f4ef404d72f361d91de954eae9a3bd669ce3 | [
"BSD-2-Clause"
] | 1 | 2019-05-19T02:26:08.000Z | 2019-05-19T02:26:08.000Z | /*************************************************************************
* Copyright (c) 2015, Synopsys, Inc. *
* All rights reserved. *
* *
* Redistribution and use in source and binary forms, with or without *
* modification, are permitted provided that the following conditions are *
* met: *
* *
* 1. Redistributions of source code must retain the above copyright *
* notice, this list of conditions and the following disclaimer. *
* *
* 2. Redistributions in binary form must reproduce the above copyright *
* notice, this list of conditions and the following disclaimer in the *
* documentation and/or other materials provided with the distribution. *
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS *
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT *
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR *
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT *
* HOLDER 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. *
*************************************************************************/
#ifndef NEW_UI
//
// "SetsUI.C"
//
// Description:
//
// Dialog box for set-theoretic operations.
// Manipulates Access/sw "sets."
//
#include <msg.h>
#include <SetsUI.h>
#include <genError.h>
#include <gtDlgTemplate.h>
#include <gtForm.h>
#include <gtList.h>
#include <gtTogB.h>
#include <gtMainWindow.h>
#include <gtMenuBar.h>
#include <gtCascadeB.h>
#include <gtOptionMenu.h>
#include <gtTopShell.h>
#include <gtStringEd.h>
#include <gtPushButton.h>
#include <gtSepar.h>
#include <help.h>
#include <Interpreter.h>
#include <cLibraryFunctions.h>
#ifndef ISO_CPP_HEADERS
#include <limits.h>
#else /* ISO_CPP_HEADERS */
#include <limits>
using namespace std;
#endif /* ISO_CPP_HEADERS */
#include <messages.h>
#include <ldrList.h>
#include <groupHdr.h>
#include <externApp.h>
#include <browserShell.h>
#define FATAL_ERROR \
if (1) { \
msg("An unexpected error occured in file: $1 Line $2.\nPlease notify technical support.", catastrophe_sev) << __FILE__ << eoarg << __LINE__ << eom; \
Assert(0); \
} else
gtList *SetsUI::sets_list = NULL;
SetsUI *SetsUI::instance = NULL;
int SetsUI::name_idx = 1;
gtStringEditor *SetsUI::name_txt = NULL;
gtTopLevelShell *SetsUI::toplev = NULL;
const int SetsUI::max_name_idx = INT_MAX - 1;
const char *SetsUI::api_cmd_prefix = "_smgr";
bool SetsUI::debug_flag = false;
const char *SetsUI::default_title = "Group Manager";
//
// The order of these matter; they correspond to the CmdCode enum in SetsUI.h:
//
const char *SetsUI::api_cmd[] = {
"size",
"lindex",
"find",
"modelbrowse",
"minibrowse",
"iview",
"create",
"rename",
"delete",
"save",
"print",
"intersection -mktmp",
"union -mktmp",
"difference -mktmp",
"add sel",
"remove sel",
"move sel"
};
SetsUI::SetsUI(const char *title)
{
Initialize(SetsUI::SetsUI);
checkDebug();
buildInterface(title);
invoked = 0;
}
SetsUI::~SetsUI()
{
Initialize(SetsUI::~SetsUI);
toplev->popdown();
delete toplev;
instance = NULL;
}
void SetsUI::Invoke(const char *title)
{
Initialize(SetsUI::Invoke);
if (instance) {
if(!instance->invoked){
instance->toplev->popup();
instance->invoked = 1;
}
instance->toplev->bring_to_top();
} else {
if (!title)
title = default_title;
instance = new SetsUI(title);
instance->toplev->popup();
instance->toplev->bring_to_top();
instance->invoked = 1;
}
}
void SetsUI::CaptureAndInvoke(const char *title, symbolArr& syms)
{
Initialize(SetsUI::CaptureAndInvoke);
if(instance == NULL) {
if (!title)
title = default_title;
instance = new SetsUI(title);
instance->toplev->popup();
instance->invoked = 1;
} else {
if(!instance->invoked){
instance->toplev->popup();
instance->invoked = 1;
}
instance->toplev->bring_to_top();
}
char *name = instance->name_txt->text();
symbolArr *arr = new symbolArr;
extGroupApp* app = (extGroupApp*) extGroupApp::create_tmp(name, arr);
*arr = syms;
app->set_status(externApp::TEMP);
gtFree(name);
instance->Refresh();
instance->setDefaultName();
}
char *SetsUI::GetGroupName(void)
{
static genString grp_name;
if(instance == NULL) {
instance = new SetsUI(default_title);
}
char *name = instance->name_txt->text();
grp_name = name;
gtFree(name);
return (char *)grp_name;
}
void SetsUI::UpdateGroupName(void)
{
if(instance == NULL) {
instance = new SetsUI(default_title);
}
instance->setDefaultName();
}
void SetsUI::buildInterface(const char *title)
{
Initialize(SetsUI::buildInterface);
// Top level, main window:
//
gtShell *gtsh = NULL;
genArrOf(browserShellPtr) *instance_array = browserShell::get_browsers_list();
if (instance_array && instance_array->size()) {
browserShell *bsh = *((*instance_array)[0]);
if (bsh)
gtsh = bsh->top_level();
}
toplev = gtTopLevelShell::create(gtsh, title);
toplev->title(title);
toplev->override_WM_destroy(SetsUI::destroy_CB);
gtMainWindow *main_window = gtMainWindow::create(toplev, "main_window", 0);
main_window->manage();
// Menu bar:
//
gtMenuBar *menu_bar = main_window->menu_bar();
// Menus:
//
gtCascadeButton *cascade_btn;
// "Manage" menu:
cascade_btn = gtCascadeButton::create(menu_bar, "manage_menu", TXT("Group"),
NULL, NULL);
cascade_btn->pulldown_menu("manage_menu",
gtMenuStandard, "create", TXT("Create"), this, SetsUI::create_CB,
gtMenuStandard, "rename", TXT("Rename"), this, SetsUI::rename_CB,
gtMenuStandard, "delete", TXT("Delete"), this, SetsUI::delete_CB,
gtMenuSeparator, "sep",
gtMenuStandard, "save", TXT("Save"), this, SetsUI::save_CB,
gtMenuStandard, "print", TXT("Print"), this, SetsUI::print_CB,
gtMenuSeparator, "sep",
gtMenuStandard, "refresh", TXT("Refresh"), this, SetsUI::refresh_CB,
gtMenuSeparator, "sep",
gtMenuStandard, "close", TXT("Close"), this, SetsUI::quit_CB,
NULL);
cascade_btn->manage();
// "Elements" menu:
cascade_btn = gtCascadeButton::create(menu_bar, "elements_menu", TXT("Elements"),
NULL, NULL);
cascade_btn->pulldown_menu("elements_menu",
gtMenuStandard, "add", TXT("Add"), this, SetsUI::ElementsAdd_CB,
gtMenuStandard, "remove", TXT("Remove"), this, SetsUI::ElementsRemove_CB,
gtMenuStandard, "move", TXT("Replace"), this, SetsUI::ElementsMove_CB,
NULL);
cascade_btn->manage();
// "Operator" menu:
cascade_btn = gtCascadeButton::create(menu_bar, "operator_menu", TXT("Operator"),
NULL, NULL);
cascade_btn->pulldown_menu("operator_menu",
gtMenuStandard, "intersection", TXT("Intersection"), this, SetsUI::intersection_CB,
gtMenuSeparator, "sep",
gtMenuStandard, "union", TXT("Union"), this, SetsUI::union_CB,
gtMenuSeparator, "sep",
gtMenuStandard, "diff_ab", TXT("A - B"), this, SetsUI::diff_ab_CB,
gtMenuStandard, "diff_ba", TXT("B - A"), this, SetsUI::diff_ba_CB,
NULL);
cascade_btn->manage();
// "View" menu:
cascade_btn = gtCascadeButton::create(menu_bar, "browse_menu", TXT("Browse"),
NULL, NULL);
cascade_btn->pulldown_menu("browse_menu",
gtMenuStandard, "model_browser", TXT("Model Browser"), this, SetsUI::ModelBrowser_CB,
gtMenuStandard, "mini_browser", TXT("Minibrowser"), this, SetsUI::MiniBrowser_CB,
gtMenuStandard, "instances", TXT("Instances"), this, SetsUI::instances_CB,
NULL);
cascade_btn->manage();
// "Help" menu:
cascade_btn = gtCascadeButton::create(menu_bar, "help_menu", TXT("Help"),
NULL, NULL);
menu_bar->set_help(cascade_btn);
cascade_btn->pulldown_menu("help_menu",
gtMenuStandard, "help_set_manager", TXT("Contents"), this,
gtBase::help_button_callback, NULL);
REG_HELP(cascade_btn->button("help_set_manager"), "Browser.Y2K.SetsManager.Help");
cascade_btn->manage();
// Create the form:
//
gtForm *form = gtForm::create(main_window, "form");
form->attach_tblr();
form->manage();
// Label for textbox:
//
gtLabel *name_lbl = gtLabel::create(form, "name_lbl", TXT("Name:"));
name_lbl->attach(gtBottom, 0, 17);
name_lbl->attach(gtLeft, 0, 5);
name_lbl->manage();
// Textbox:
//
name_txt = gtStringEditor::create(form, "name_txt", NULL);
name_txt->attach(gtBottom, 0, 10);
name_txt->attach(gtLeft, name_lbl, 5);
name_txt->attach(gtRight);
name_txt->manage();
// Separator:
//
gtSeparator *h_sep = gtSeparator::create(form, "h_sep", gtHORZ);
h_sep->manage();
h_sep->attach(gtLeft);
h_sep->attach(gtRight);
h_sep->attach(gtBottom, name_txt, 10);
// List of Sets:
//
sets_list = gtList::create(form, "sets_list", TXT("Active Groups"), gtExtended,
NULL, 0);
sets_list->width(250);
sets_list->height(300);
sets_list->attach(gtTop, 0, 15);
sets_list->attach(gtBottom, h_sep, 10);
sets_list->attach(gtLeft, 0, 5);
sets_list->attach(gtRight, 0, 5);
sets_list->action_callback(SetsUI::list_double_click_CB, this);
sets_list->manage();
setDefaultName(); // Put some default string in the name box
Refresh(); // Fill in the list
}
void SetsUI::checkDebug()
{
if (OSapi_getenv("PSET_SETS_DEBUG"))
debug_flag = true;
}
//
// Update the graphical list:
//
void SetsUI::Refresh()
{
Initialize(SetsUI::Refresh);
if (!sets_list)
return;
//
// Add any new items that may have been created:
//
genString cmd;
cmd.printf("%s", api_cmd[SIZE]);
genString result;
int code = sendCmd(cmd, result);
if (code == TCL_ERROR)
return;
int size = OSapi_atoi(result);
int i;
for (i = 0; i < size; i++) {
genString num;
num.printf("%d", i);
cmd.printf("%s %s", api_cmd[LINDEX], (char *)num);
int code = sendCmd(cmd, result);
if (code == TCL_ERROR)
return;
if (!inList(result)) {
genString pix;
pix.printf("%c%s", PIX_SET, (char *)result);
sets_list->add_item_unselected(pix, 0);
}
}
//
// Remove any old items that may have been deleted:
//
size = sets_list->num_items();
for (i = size - 1; i >= 0; i--) {
char *item = sets_list->item_at_pos(i);
cmd.printf("%s %s", api_cmd[SEARCH], ((char *)item) + 1);
genString result;
int code = sendCmd(cmd, result);
if (code == TCL_ERROR)
return;
gtFree(item);
if (result == "0") {
// Account for incompatibility between item_at_pos()
// and delete_pos(). The latter uses traditional Motif
// numbering convention (1, 2, ..., 0); the former uses
// intuitive numbering scheme (0, 1, 2, ...).
//
int pos;
int new_size = sets_list->num_items();
if (i == new_size - 1)
pos = 0;
else
pos = i + 1;
sets_list->delete_pos(pos);
}
}
setDefaultName(); // Put some default string in the name box
}
//
// Is the specified string in our list?
//
bool SetsUI::inList(const char *name)
{
Initialize(SetsUI::inList);
if(!name)
return false;
int sz = sets_list->num_items();
bool collision = false;
for (int j = 0; j < sz; j++) {
char *str = sets_list->item_at_pos(j);
if (!(strcmp(str + 1, name))) {
collision = true;
gtFree(str);
break;
}
gtFree(str);
}
return collision;
}
//
// Put some default value into the name field:
//
bool SetsUI::setDefaultName()
{
Initialize(SetsUI::setDefaultName);
genString name;
bool valid = false;
while ((name_idx < max_name_idx) && (valid == false)) {
name.printf("RESULT_%d", name_idx);
if (!inList(name))
valid = true;
else
++name_idx;
}
if (valid == true)
name_txt->text(name);
else
msg("Exceeded maximum index number.", error_sev) << eom;
return valid;
}
void SetsUI::quitWindow()
{
Initialize(SetsUI::quitWindow);
toplev->popdown();
instance->invoked = 0;
}
//
// Get the list of groups currently selected:
//
void SetsUI::ListSelected(TclList &list)
{
Initialize(SetsUI::ListSelected);
if (instance)
instance->tclList2(list);
}
//
// Use new data structure to capture list of selected items:
//
void SetsUI::tclList2(TclList &list)
{
Initialize(SetsUI::tclList2);
int n_items = sets_list->num_selected();
char **v_items = sets_list->selected();
for (int i = 0; i < n_items; i++)
list += (v_items[i]) + 1;
gtFree(v_items);
}
//
// Convert the selections in our graphical list to a Tcl list:
//
void SetsUI::tclList(genString& list, ListDirCode dir = FORWARD)
{
Initialize(SetsUI::tclList);
int n_items = sets_list->num_selected();
char **v_items = sets_list->selected();
if (dir == FORWARD)
for (int i = 0; i < n_items; i++) {
list += "{";
list += (v_items[i]) + 1;
list += "} ";
}
else if (dir == BACKWARD)
for (int i = n_items - 1; i >= 0; i--) {
list += "{";
list += (v_items[i]) + 1;
list += "} ";
}
else
// Shouldn't get here:
FATAL_ERROR;
gtFree(v_items);
}
int SetsUI::sendCmd(genString& cmd)
{
Initialize(SetsUI::sendCmd);
genString result;
return sendCmd(cmd, result);
}
int cli_eval_string(const char*);
int execManageTool(genString cmd, int outFlag)
{
return SetsUI::execCmd(cmd, outFlag);
}
int SetsUI::execCmd(genString cmd, int outFlag )
{
msg("execTool: Sending command: \"$1\".", normal_sev) << (char *)cmd << eom;
cli_eval_string((char*)cmd);
genString result;
int code = interpreter_instance->GetResult(result);
if (code == TCL_ERROR && outFlag )
notifyTclError();
return code;
}
//
// Send a command to the interpreter; do error checking:
//
int SetsUI::sendCmd(const genString& cmd, genString& result)
{
Initialize(SetsUI::sendCmd);
genString full_cmd;
full_cmd.printf("%s { %s }", (char *)api_cmd_prefix, (char *)cmd);
if (debug_flag)
msg("Status: Sets: Sending command: \"$1\".", normal_sev) << (char *)full_cmd << eom;
cli_eval_string(full_cmd);
int code = interpreter_instance->GetResult(result);
if (code == TCL_ERROR)
notifyTclError();
return code;
}
//
// Display Tcl error message:
//
void SetsUI::notifyTclError()
{
Initialize(SetsUI::notifyTclError);
char *err_info = Tcl_GetVar(interpreter_instance->interp, "errorInfo", TCL_GLOBAL_ONLY);
msg("The following error occured:\n$1", error_sev) << err_info << eom;
}
//
// Check to see that the numbers of items selected
// equals the necessary number of operands. Notify
// user of any errors:
//
bool SetsUI::checkOperands(OperandNumCode num)
{
Initialize(SetsUI::checkOperands);
bool retval = false;
int num_sel = sets_list->num_selected();
switch (num)
{
case UNARY: // One operand:
//
if (num_sel != 1)
msg("This operation requires exactly one selection.", error_sev) << eom;
else
retval = true;
break;
case BINARY: // Two operands:
//
if (num_sel != 2)
msg("This operation requires exactly two selections.", error_sev) << eom;
else
retval = true;
break;
case ONE_OR_MORE: // One or more operands:
//
if (num_sel < 1)
msg("This operation requires one or more selections.", error_sev) << eom;
else
retval = true;
break;
case TWO_OR_MORE: // Two or more operands:
//
if (num_sel < 2)
msg("This operation requires two or more selections.", error_sev) << eom;
else
retval = true;
break;
default: // Shouldn't get here:
//
FATAL_ERROR;
break;
}
return retval;
}
void SetsUI::sendToBrowser(BrowseCode bc = MINI_B)
{
Initialize(SetsUI::sendToBrowser);
if (!checkOperands(ONE_OR_MORE))
return;
genString list;
tclList(list);
genString cmd;
CmdCode api;
switch (bc)
{
case INSTANCE_B: api = IVIEW;
break;
case MINI_B: // Slide down
api = MINIBROWSE;
break;
default: api = MODELBROWSE;
break;
}
cmd.printf("%s %s", api_cmd[api], (char *)list);
sendCmd(cmd);
}
char *SetsUI::targetName()
{
Initialize(SetsUI::targetName());
char *name = name_txt->text();
if (!(*name))
if (!setDefaultName()) {
msg("Error occured while trying to get default group name.", error_sev) << eom;
name = NULL;
}
else
name = name_txt->text();
if (inList(name)) {
msg("Duplicate group name specified.", error_sev) << eom;
name = NULL;
}
return name;
}
//
// Callbacks:
//
int SetsUI::destroy_CB(void *)
{
Initialize(SetsUI::destroy_CB);
quitWindow();
instance = NULL;
sets_list = NULL;
return 1;
}
void SetsUI::ElementsAdd_CB(gtPushButton*, gtEventPtr, void*, gtReason)
{
Initialize(SetsUI::ElementsAdd_CB);
if (!checkOperands(UNARY))
return;
genString list;
tclList(list);
genString cmd;
cmd.printf("%s %s", api_cmd[ADD], (char *)list);
int code = sendCmd(cmd);
if (code != TCL_ERROR)
setDefaultName();
}
void SetsUI::ElementsRemove_CB(gtPushButton*, gtEventPtr, void*, gtReason)
{
Initialize(SetsUI::ElementsRemove_CB);
if (!checkOperands(UNARY))
return;
genString list;
tclList(list);
genString cmd;
cmd.printf("%s %s", api_cmd[REMOVE], (char *)list);
int code = sendCmd(cmd);
if (code != TCL_ERROR)
setDefaultName();
}
void SetsUI::ElementsMove_CB(gtPushButton*, gtEventPtr, void*, gtReason)
{
Initialize(SetsUI::ElementsMove_CB);
if (!checkOperands(UNARY))
return;
genString list;
tclList(list);
genString cmd;
cmd.printf("%s %s", api_cmd[MOVE], (char *)list);
int code = sendCmd(cmd);
if (code != TCL_ERROR)
setDefaultName();
}
void SetsUI::create_CB(gtPushButton*, gtEventPtr, void*, gtReason)
{
Initialize(SetsUI::create_CB);
char *name = targetName();
if (!name)
return;
genString cmd;
cmd.printf("%s %s", api_cmd[CREATE], (char *)name);
int code = sendCmd(cmd);
if (code != TCL_ERROR)
setDefaultName();
}
void SetsUI::rename_CB(gtPushButton*, gtEventPtr, void*, gtReason)
{
Initialize(SetsUI::rename_CB);
if (!checkOperands(UNARY))
return;
char *name = targetName();
if (!name)
return;
genString list;
tclList(list);
genString cmd;
cmd.printf("%s %s %s", api_cmd[RENAME], (char *)name, (char *)list);
int code = sendCmd(cmd);
if (code != TCL_ERROR)
setDefaultName();
}
void SetsUI::delete_CB(gtPushButton*, gtEventPtr, void*, gtReason)
{
Initialize(SetsUI::delete_CB);
if (!checkOperands(ONE_OR_MORE))
return;
genString list;
tclList(list);
genString cmd;
cmd.printf("%s %s", api_cmd[DELETE], (char *)list);
sendCmd(cmd);
}
void get_new_subsys_name(genString &, genString &);
void SetsUI::save_CB(gtPushButton*, gtEventPtr, void*, gtReason)
{
Initialize(SetsUI::save_CB);
if (!checkOperands(ONE_OR_MORE))
return;
genString list;
tclList(list);
genString cmd;
cmd.printf("%s %s", api_cmd[SAVE], (char *)list);
sendCmd(cmd);
}
void SetsUI::print_CB(gtPushButton*, gtEventPtr, void*, gtReason)
{
Initialize(SetsUI::print_CB);
if (!checkOperands(ONE_OR_MORE))
return;
genString list;
tclList(list);
genString cmd;
cmd.printf("%s %s", api_cmd[PRINT], (char *)list);
sendCmd(cmd);
}
void SetsUI::refresh_CB(gtPushButton*, gtEventPtr, void*, gtReason)
{
Initialize(SetsUI::refresh_CB);
Refresh();
}
void SetsUI::quit_CB(gtPushButton*, gtEventPtr, void*, gtReason)
{
Initialize(SetsUI::quit_CB);
quitWindow();
}
void SetsUI::intersection_CB(gtPushButton*, gtEventPtr, void*, gtReason)
{
Initialize(SetsUI::intersection_CB);
if (!checkOperands(TWO_OR_MORE))
return;
char *name = targetName();
if (!name)
return;
genString list;
tclList(list);
genString cmd;
cmd.printf("%s %s %s", api_cmd[INTERSECTION], name, (char *)list);
int code = sendCmd(cmd);
if (code != TCL_ERROR)
setDefaultName();
}
void SetsUI::union_CB(gtPushButton*, gtEventPtr, void*, gtReason)
{
Initialize(SetsUI::union_CB);
if (!checkOperands(TWO_OR_MORE))
return;
char *name = targetName();
if (!name)
return;
genString list;
tclList(list);
genString cmd;
cmd.printf("%s %s %s", api_cmd[UNION], name, (char* )list);
int code = sendCmd(cmd);
if (code != TCL_ERROR)
setDefaultName();
}
void SetsUI::diff_ab_CB(gtPushButton*, gtEventPtr, void*, gtReason)
{
Initialize(SetsUI::diff_ab_CB);
if (!checkOperands(BINARY))
return;
char *name = targetName();
if (!name)
return;
genString list;
tclList(list);
genString cmd;
cmd.printf("%s %s %s", api_cmd[DIFFERENCE], name, (char *)list);
int code = sendCmd(cmd);
if (code != TCL_ERROR)
setDefaultName();
}
void SetsUI::diff_ba_CB(gtPushButton*, gtEventPtr, void*, gtReason)
{
Initialize(SetsUI::diff_ba_CB);
if (!checkOperands(BINARY))
return;
char *name = targetName();
if (!name)
return;
genString list;
tclList(list, BACKWARD);
genString cmd;
cmd.printf("%s %s %s", api_cmd[DIFFERENCE], name, (char *)list);
int code = sendCmd(cmd);
if (code != TCL_ERROR)
setDefaultName();
}
void SetsUI::instances_CB(gtPushButton*, gtEventPtr, void*, gtReason)
{
Initialize(SetsUI::instances_CB);
sendToBrowser(INSTANCE_B);
}
void SetsUI::ModelBrowser_CB(gtPushButton*, gtEventPtr, void*, gtReason)
{
Initialize(SetsUI::instances_CB);
sendToBrowser(MODEL_B);
}
void SetsUI::MiniBrowser_CB(gtPushButton*, gtEventPtr, void*, gtReason)
{
Initialize(SetsUI::instances_CB);
sendToBrowser(MINI_B);
}
void SetsUI::browse_CB(gtPushButton*, gtEventPtr, void*, gtReason)
{
Initialize(SetsUI::browse_CB);
sendToBrowser();
}
void SetsUI::list_double_click_CB(gtList*, gtEventPtr, void *, gtReason)
{
Initialize(SetsUI::list_double_click_CB);
sendToBrowser(MODEL_B);
}
#endif /* ! NEW_UI */
| 22.868447 | 153 | 0.627119 | kit-transue |
9683818f3d590400aa4d5b74a6a713ade34d187d | 1,453 | cpp | C++ | led_tutorial/src/rgb_led.cpp | PigeonSensei/raspberry_pi_ros_tutorial | 07f824bf43f304ebe328f1e557ca7fa5c9cad44c | [
"MIT"
] | null | null | null | led_tutorial/src/rgb_led.cpp | PigeonSensei/raspberry_pi_ros_tutorial | 07f824bf43f304ebe328f1e557ca7fa5c9cad44c | [
"MIT"
] | null | null | null | led_tutorial/src/rgb_led.cpp | PigeonSensei/raspberry_pi_ros_tutorial | 07f824bf43f304ebe328f1e557ca7fa5c9cad44c | [
"MIT"
] | 3 | 2021-11-15T00:34:08.000Z | 2022-02-28T09:55:38.000Z | #include <ros/ros.h>
#include <wiringPi.h>
#include "led_tutorial/SetRGBDigital.h"
bool R = true;
bool G = true;
bool B = true;
bool SetRGBDigitalCallBack(led_tutorial::SetRGBDigital::Request &req,
led_tutorial::SetRGBDigital::Response &res)
{
R = req.R;
G = req.G;
B = req.B;
res.result = "True";
res.message = "Set R : " + std::to_string(R) + ", Set G : " + std::to_string(G) + ", Set B : " + std::to_string(B);
res.Timestamp = ros::Time::now();
ROS_INFO("Set R : %d, Set G : %d, Set B : %d", R,G,B);
return true;
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "rgb_led_node");
ros::NodeHandle n("~");
ros::Rate loop_rate(10);
ros::ServiceServer service_server_set_rgb_digital;
service_server_set_rgb_digital = n.advertiseService("setRGBDigital", SetRGBDigitalCallBack);
int r_pin = 0;
int g_pin = 0;
int b_pin = 0;
n.param<int>("RPin", r_pin, 0);
n.param<int>("GPin", g_pin, 0);
n.param<int>("BPin", b_pin, 0);
ROS_INFO("R Pin : %d", r_pin);
ROS_INFO("G Pin : %d", g_pin);
ROS_INFO("B Pin : %d", b_pin);
wiringPiSetupGpio();
pinMode(r_pin, OUTPUT);
pinMode(g_pin, OUTPUT);
pinMode(b_pin, OUTPUT);
while(ros::ok())
{
digitalWrite(r_pin,R);
digitalWrite(g_pin,G);
digitalWrite(b_pin,B);
loop_rate.sleep();
ros::spinOnce();
}
digitalWrite(r_pin,LOW);
digitalWrite(g_pin,LOW);
digitalWrite(b_pin,LOW);
return 0;
}
| 21.367647 | 117 | 0.623538 | PigeonSensei |
9684557bcc67e9f71e660d7bbc9c531861c1b1e8 | 14,199 | cxx | C++ | Rendering/OpenGL2/vtkOpenGLTexture.cxx | vovythevov/VTK | 565751995d1dd2d1eec821d5e34564ec4c21acc8 | [
"BSD-3-Clause"
] | null | null | null | Rendering/OpenGL2/vtkOpenGLTexture.cxx | vovythevov/VTK | 565751995d1dd2d1eec821d5e34564ec4c21acc8 | [
"BSD-3-Clause"
] | null | null | null | Rendering/OpenGL2/vtkOpenGLTexture.cxx | vovythevov/VTK | 565751995d1dd2d1eec821d5e34564ec4c21acc8 | [
"BSD-3-Clause"
] | null | null | null | /*=========================================================================
Program: Visualization Toolkit
Module: vtkOpenGLTexture.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkOpenGLTexture.h"
#include "vtkglVBOHelper.h"
#include "vtkHomogeneousTransform.h"
#include "vtkImageData.h"
#include "vtkLookupTable.h"
#include "vtkMath.h"
#include "vtkObjectFactory.h"
#include "vtkOpenGLRenderer.h"
#include "vtkPointData.h"
#include "vtkRenderWindow.h"
#include "vtkOpenGLRenderWindow.h"
#include "vtkPixelBufferObject.h"
#include "vtkOpenGL.h"
#include "vtkOpenGLError.h"
#include <math.h>
// ----------------------------------------------------------------------------
vtkStandardNewMacro(vtkOpenGLTexture);
// ----------------------------------------------------------------------------
vtkOpenGLTexture::vtkOpenGLTexture()
{
this->Index = 0;
this->RenderWindow = 0;
this->TextureFormat = GL_RGBA;
this->TextureType = GL_TEXTURE_2D;
}
// ----------------------------------------------------------------------------
vtkOpenGLTexture::~vtkOpenGLTexture()
{
if (this->RenderWindow)
{
this->ReleaseGraphicsResources(this->RenderWindow);
this->RenderWindow = 0;
}
}
// ----------------------------------------------------------------------------
void vtkOpenGLTexture::Initialize(vtkRenderer* vtkNotUsed(ren))
{
}
// ----------------------------------------------------------------------------
// Release the graphics resources used by this texture.
void vtkOpenGLTexture::ReleaseGraphicsResources(vtkWindow *win)
{
if (this->Index && win && win->GetMapped())
{
vtkRenderWindow *renWin = dynamic_cast<vtkRenderWindow *>(win);
renWin->MakeCurrent();
vtkOpenGLClearErrorMacro();
// free any textures
if (glIsTexture(static_cast<GLuint>(this->Index)))
{
GLuint tempIndex;
tempIndex = this->Index;
glDeleteTextures(1, &tempIndex);
}
vtkOpenGLCheckErrorMacro("failed after ReleaseGraphicsResources");
}
this->Index = 0;
this->RenderWindow = NULL;
this->Modified();
}
void vtkOpenGLTexture::CopyTexImage(vtkRenderer *ren, int x, int y, int width, int height)
{
vtkOpenGLRenderWindow* renWin =
static_cast<vtkOpenGLRenderWindow*>(ren->GetRenderWindow());
renWin->ActivateTexture(this);
if (this->TextureFormat == GL_DEPTH)
{
glCopyTexImage2D(this->TextureType, 0, GL_DEPTH_COMPONENT,
x, y, width, height, 0);
}
else
{
glCopyTexImage2D(this->TextureType, 0, GL_RGBA,
x, y, width, height, 0);
}
}
// ----------------------------------------------------------------------------
// Implement base class method.
void vtkOpenGLTexture::Load(vtkRenderer *ren)
{
GLenum format = GL_LUMINANCE;
vtkImageData *input = this->GetInput();
this->Initialize(ren);
// Need to reload the texture.
// There used to be a check on the render window's mtime, but
// this is too broad of a check (e.g. it would cause all textures
// to load when only the desired update rate changed).
// If a better check is required, check something more specific,
// like the graphics context.
vtkOpenGLRenderWindow* renWin =
static_cast<vtkOpenGLRenderWindow*>(ren->GetRenderWindow());
vtkOpenGLClearErrorMacro();
// TODO: need something for blending modes
if (this->GetMTime() > this->LoadTime.GetMTime() ||
input->GetMTime() > this->LoadTime.GetMTime() ||
(this->GetLookupTable() && this->GetLookupTable()->GetMTime () >
this->LoadTime.GetMTime()) ||
renWin != this->RenderWindow.GetPointer() ||
renWin->GetContextCreationTime() > this->LoadTime)
{
int size[3];
unsigned char *dataPtr;
unsigned char *resultData = 0;
int xsize, ysize;
GLuint tempIndex = 0;
// Get the scalars the user choose to color with.
vtkDataArray* scalars = this->GetInputArrayToProcess(0, input);
// make sure scalars are non null
if (!scalars)
{
vtkErrorMacro(<< "No scalar values found for texture input!");
return;
}
// free any old display lists (from the old context)
// make the new context current before we mess with opengl
if (this->RenderWindow)
{
this->ReleaseGraphicsResources(this->RenderWindow);
}
this->RenderWindow = renWin;
this->RenderWindow->MakeCurrent();
// get some info
input->GetDimensions(size);
if (input->GetNumberOfCells() == scalars->GetNumberOfTuples())
{
// we are using cell scalars. Adjust image size for cells.
for (int kk = 0; kk < 3; kk++)
{
if (size[kk]>1)
{
size[kk]--;
}
}
}
int bytesPerPixel = scalars->GetNumberOfComponents();
// make sure using unsigned char data of color scalars type
if (this->TextureFormat != GL_DEPTH &&
(this->MapColorScalarsThroughLookupTable ||
scalars->GetDataType() != VTK_UNSIGNED_CHAR ))
{
dataPtr = this->MapScalarsToColors (scalars);
bytesPerPixel = 4;
}
else
{
dataPtr = static_cast<vtkUnsignedCharArray *>(scalars)->GetPointer(0);
}
// we only support 2d texture maps right now
// so one of the three sizes must be 1, but it
// could be any of them, so lets find it
if (size[0] == 1)
{
xsize = size[1]; ysize = size[2];
}
else
{
xsize = size[0];
if (size[1] == 1)
{
ysize = size[2];
}
else
{
ysize = size[1];
if (size[2] != 1)
{
vtkErrorMacro(<< "3D texture maps currently are not supported!");
return;
}
}
}
// -- decide whether the texture needs to be resampled --
GLint maxDimGL;
glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxDimGL);
vtkOpenGLCheckErrorMacro("failed at glGetIntegerv");
// if larger than permitted by the graphics library then must resample
bool resampleNeeded = xsize > maxDimGL || ysize > maxDimGL;
if(resampleNeeded)
{
vtkDebugMacro( "Texture too big for gl, maximum is " << maxDimGL);
}
if (resampleNeeded)
{
vtkDebugMacro(<< "Resampling texture to power of two for OpenGL");
resultData = this->ResampleToPowerOfTwo(xsize, ysize, dataPtr,
bytesPerPixel);
}
if (!resultData)
{
resultData = dataPtr;
}
// define a display list for this texture
// get a unique display list id
renWin->ActivateTexture(this);
glGenTextures(1, &tempIndex);
vtkOpenGLCheckErrorMacro("failed at glGenTextures");
this->Index = static_cast<long>(tempIndex);
glBindTexture(this->TextureType, this->Index);
vtkOpenGLCheckErrorMacro("failed at glBindTexture");
if (this->Interpolate)
{
glTexParameterf(this->TextureType , GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(this->TextureType , GL_TEXTURE_MAG_FILTER, GL_LINEAR);
}
else
{
glTexParameterf(this->TextureType , GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameterf(this->TextureType , GL_TEXTURE_MAG_FILTER, GL_NEAREST);
}
if (this->Repeat)
{
glTexParameterf(this->TextureType , GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameterf(this->TextureType , GL_TEXTURE_WRAP_T, GL_REPEAT);
}
else
{
if (this->EdgeClamp)
{
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
}
else
{
glTexParameterf(this->TextureType , GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameterf(this->TextureType , GL_TEXTURE_WRAP_T, GL_CLAMP);
}
}
vtkOpenGLCheckErrorMacro("failed at glTexParameterf");
int internalFormat = bytesPerPixel;
int dataType = GL_UNSIGNED_BYTE;
switch (bytesPerPixel)
{
case 1: format = GL_LUMINANCE; break;
case 2: format = GL_LUMINANCE_ALPHA; break;
case 3: format = GL_RGB; break;
case 4: format = GL_RGBA; break;
}
// if we are using OpenGL 1.1, you can force 32 or16 bit textures
if (this->Quality == VTK_TEXTURE_QUALITY_32BIT)
{
switch (bytesPerPixel)
{
case 1: internalFormat = GL_LUMINANCE8; break;
case 2: internalFormat = GL_LUMINANCE8_ALPHA8; break;
case 3: internalFormat = GL_RGB8; break;
case 4: internalFormat = GL_RGBA8; break;
}
}
else if (this->Quality == VTK_TEXTURE_QUALITY_16BIT)
{
switch (bytesPerPixel)
{
case 1: internalFormat = GL_LUMINANCE4; break;
case 2: internalFormat = GL_LUMINANCE4_ALPHA4; break;
case 3: internalFormat = GL_RGB4; break;
case 4: internalFormat = GL_RGBA4; break;
}
}
// handle depth textures
if (this->TextureFormat == GL_DEPTH)
{
format = GL_DEPTH_COMPONENT;
internalFormat = GL_DEPTH_COMPONENT32F;
dataType = GL_FLOAT;
}
// blocking call
glTexImage2D(this->TextureType , 0 , internalFormat,
xsize, ysize, 0, format, dataType,
static_cast<const GLvoid *>(resultData));
vtkOpenGLCheckErrorMacro("failed at glTexImage2D");
// modify the load time to the current time
this->LoadTime.Modified();
// free memory
if (resultData != dataPtr)
{
delete [] resultData;
resultData = 0;
}
}
// activate a free texture unit for this texture
renWin->ActivateTexture(this);
glBindTexture(this->TextureType , this->Index);
if (this->PremultipliedAlpha)
{
// save the blend function.
glPushAttrib(GL_COLOR_BUFFER_BIT);
// make the blend function correct for textures premultiplied by alpha.
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
}
vtkOpenGLCheckErrorMacro("failed after Load");
}
// ----------------------------------------------------------------------------
void vtkOpenGLTexture::PostRender(vtkRenderer *ren)
{
vtkOpenGLRenderWindow* renWin =
static_cast<vtkOpenGLRenderWindow*>(ren->GetRenderWindow());
// deactivate the texture
renWin->DeactivateTexture(this);
if (this->GetInput() && this->PremultipliedAlpha)
{
// restore the blend function
glPopAttrib();
vtkOpenGLCheckErrorMacro("failed after PostRender");
}
}
// ----------------------------------------------------------------------------
static int FindPowerOfTwo(int i)
{
int size = vtkMath::NearestPowerOfTwo(i);
// [these lines added by Tim Hutton (implementing Joris Vanden Wyngaerd's
// suggestions)]
// limit the size of the texture to the maximum allowed by OpenGL
// (slightly more graceful than texture failing but not ideal)
GLint maxDimGL;
glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxDimGL);
if (size < 0 || size > maxDimGL)
{
size = maxDimGL ;
}
// end of Tim's additions
return size;
}
// ----------------------------------------------------------------------------
// Creates resampled unsigned char texture map that is a power of two in both
// x and y.
unsigned char *vtkOpenGLTexture::ResampleToPowerOfTwo(int &xs,
int &ys,
unsigned char *dptr,
int bpp)
{
unsigned char *tptr, *p, *p1, *p2, *p3, *p4;
int jOffset, iIdx, jIdx;
double pcoords[3], rm, sm, w0, w1, w2, w3;
int yInIncr = xs;
int xInIncr = 1;
int xsize = FindPowerOfTwo(xs);
int ysize = FindPowerOfTwo(ys);
if (this->RestrictPowerOf2ImageSmaller)
{
if (xsize > xs)
{
xsize /= 2;
}
if (ysize > ys)
{
ysize /= 2;
}
}
double hx = xsize > 1 ? (xs - 1.0) / (xsize - 1.0) : 0;
double hy = ysize > 1 ? (ys - 1.0) / (ysize - 1.0) : 0;
tptr = p = new unsigned char[xsize*ysize*bpp];
// Resample from the previous image. Compute parametric coordinates and
// interpolate
for (int j = 0; j < ysize; j++)
{
pcoords[1] = j*hy;
jIdx = static_cast<int>(pcoords[1]);
if (jIdx >= (ys-1)) //make sure to interpolate correctly at edge
{
if (ys == 1)
{
jIdx = 0;
yInIncr = 0;
}
else
{
jIdx = ys - 2;
}
pcoords[1] = 1.0;
}
else
{
pcoords[1] = pcoords[1] - jIdx;
}
jOffset = jIdx*xs;
sm = 1.0 - pcoords[1];
for (int i = 0; i < xsize; i++)
{
pcoords[0] = i*hx;
iIdx = static_cast<int>(pcoords[0]);
if (iIdx >= (xs-1))
{
if (xs == 1)
{
iIdx = 0;
xInIncr = 0;
}
else
{
iIdx = xs - 2;
}
pcoords[0] = 1.0;
}
else
{
pcoords[0] = pcoords[0] - iIdx;
}
rm = 1.0 - pcoords[0];
// Get pointers to 4 surrounding pixels
p1 = dptr + bpp*(iIdx + jOffset);
p2 = p1 + bpp*xInIncr;
p3 = p1 + bpp*yInIncr;
p4 = p3 + bpp*xInIncr;
// Compute interpolation weights interpolate components
w0 = rm*sm;
w1 = pcoords[0]*sm;
w2 = rm*pcoords[1];
w3 = pcoords[0]*pcoords[1];
for (int k = 0; k < bpp; k++)
{
*p++ = static_cast<unsigned char>(p1[k]*w0 + p2[k]*w1 + p3[k]*w2
+ p4[k]*w3);
}
}
}
xs = xsize;
ys = ysize;
return tptr;
}
// ----------------------------------------------------------------------------
void vtkOpenGLTexture::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "Index: " << this->Index << endl;
}
| 28.627016 | 90 | 0.573209 | vovythevov |
96876780bfc31d4afa27bc75d31ba62b9af5b9fe | 1,567 | hpp | C++ | include/tweedledee/quil/ast/nodes/decl_parameter.hpp | boschmitt/tweedledee | a7f5041681350601469b38311b9654e2c22643c0 | [
"MIT"
] | 4 | 2018-07-21T08:11:56.000Z | 2019-05-30T20:06:43.000Z | include/tweedledee/quil/ast/nodes/decl_parameter.hpp | boschmitt/tweedledee | a7f5041681350601469b38311b9654e2c22643c0 | [
"MIT"
] | null | null | null | include/tweedledee/quil/ast/nodes/decl_parameter.hpp | boschmitt/tweedledee | a7f5041681350601469b38311b9654e2c22643c0 | [
"MIT"
] | 1 | 2019-05-15T14:11:28.000Z | 2019-05-15T14:11:28.000Z | /*-------------------------------------------------------------------------------------------------
| This file is distributed under the MIT License.
| See accompanying file /LICENSE for details.
*------------------------------------------------------------------------------------------------*/
#pragma once
#include "../ast_node.hpp"
#include "../ast_node_kinds.hpp"
#include <cstdint>
#include <memory>
#include <ostream>
#include <rang/rang.hpp>
#include <string>
namespace tweedledee {
namespace quil {
/*! \brief Parameter declaration (decl) AST node
Formal parameters are names prepended with a ‘%’ symbol, which can be defined
in a gate and circuit declarations.
*/
class decl_parameter final : public ast_node {
public:
static std::unique_ptr<decl_parameter>
build(std::uint32_t location, std::string_view identifier)
{
auto result = std::unique_ptr<decl_parameter>(
new decl_parameter(location, std::move(identifier)));
return result;
}
std::string_view identifier() const
{
return identifier_;
}
private:
decl_parameter(std::uint32_t location, std::string_view identifier)
: ast_node(location)
, identifier_(std::move(identifier))
{}
ast_node_kinds do_get_kind() const override
{
return ast_node_kinds::decl_parameter;
}
void do_print(std::ostream& out) const override
{
using namespace rang;
out << style::bold << fgB::green << "decl_parameter " << style::reset << fgB::cyan
<< identifier_ << fg::reset;
}
private:
std::string identifier_;
};
} // namespace quil
} // namespace tweedledee
| 24.484375 | 99 | 0.627313 | boschmitt |
9687d82b43d145ca22f54e7219ac6f0a49256427 | 1,665 | cpp | C++ | 1098/main.cpp | Heliovic/PAT_Solutions | 7c5dd554654045308f2341713c3e52cc790beb59 | [
"MIT"
] | 2 | 2019-03-18T12:55:38.000Z | 2019-09-07T10:11:26.000Z | 1098/main.cpp | Heliovic/My_PAT_Answer | 7c5dd554654045308f2341713c3e52cc790beb59 | [
"MIT"
] | null | null | null | 1098/main.cpp | Heliovic/My_PAT_Answer | 7c5dd554654045308f2341713c3e52cc790beb59 | [
"MIT"
] | null | null | null | #include <cstdio>
#include <algorithm>
#include <cstring>
#define MAX_N 128
using namespace std;
int orignum[MAX_N];
int tempnum[MAX_N];
int destnum[MAX_N];
int N;
bool check()
{
for (int i = 1 ; i <= N; i++)
if (destnum[i] != tempnum[i])
return false;
return true;
}
bool insertion()
{
for (int i = 2; i <= N; i++)
{
sort(tempnum + 1, tempnum + 1 + i);
if (check())
{
sort(tempnum + 1, tempnum + 1 + i + 1);
return true;
}
}
return false;
}
void down_adjust(int s, int n)
{
int i = s, j = 2 * i;
while (j <= n)
{
if (j + 1 <= n && tempnum[j] < tempnum[j + 1])
j++;
swap(tempnum[i], tempnum[j]);
i = j;
j = 2 * i;
}
}
int main()
{
scanf("%d", &N);
for (int i = 1; i <= N; i++)
scanf("%d", &orignum[i]);
for (int i = 1; i <= N; i++)
scanf("%d", &destnum[i]);
memcpy(tempnum, orignum, MAX_N * sizeof(int));
if (insertion())
{
printf("Insertion Sort\n");
for (int i = 1; i <= N; i++)
{
if (i != 1)
printf(" ");
printf("%d", tempnum[i]);
}
return 0;
}
memcpy(tempnum, destnum, MAX_N * sizeof(int));
for (int j = N; j >= 1; j--)
{
if (tempnum[j] < tempnum[1])
{
swap(tempnum[j], tempnum[1]);
down_adjust(1, j - 1);
break;
}
}
printf("Heap Sort\n");
for (int i = 1; i <= N; i++)
{
if (i != 1)
printf(" ");
printf("%d", tempnum[i]);
}
return 0;
}
| 17.526316 | 54 | 0.417417 | Heliovic |
9688129e4a14381f93a0b48d31e79c9e24055d28 | 9,785 | hpp | C++ | include/Nazara/Audio/OpenAL.hpp | AntoineJT/NazaraEngine | e0b05a7e7a2779e20a593b4083b4a881cc57ce14 | [
"BSD-3-Clause-Clear",
"Apache-2.0",
"MIT"
] | null | null | null | include/Nazara/Audio/OpenAL.hpp | AntoineJT/NazaraEngine | e0b05a7e7a2779e20a593b4083b4a881cc57ce14 | [
"BSD-3-Clause-Clear",
"Apache-2.0",
"MIT"
] | null | null | null | include/Nazara/Audio/OpenAL.hpp | AntoineJT/NazaraEngine | e0b05a7e7a2779e20a593b4083b4a881cc57ce14 | [
"BSD-3-Clause-Clear",
"Apache-2.0",
"MIT"
] | null | null | null | // Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Engine - Audio module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#pragma once
#ifndef NAZARA_OPENAL_HPP
#define NAZARA_OPENAL_HPP
#ifdef NAZARA_AUDIO_OPENAL
#include <Nazara/Prerequisites.hpp>
#include <Nazara/Audio/Config.hpp>
#include <Nazara/Audio/Enums.hpp>
#include <Nazara/Core/String.hpp>
#include <vector>
// Inclusion of OpenAL headers
// OpenAL headers does not allow us to only get the signatures without the pointers to the functions
// And I do no want to modify them, I'm obliged to put them in a different namespace
// to put only interesting things back in the global namespace (specially typedef)
namespace OpenALDetail
{
#include <AL/al.h>
#include <AL/alc.h>
}
// If someone has a better idea ...
using OpenALDetail::ALboolean;
using OpenALDetail::ALbyte;
using OpenALDetail::ALchar;
using OpenALDetail::ALdouble;
using OpenALDetail::ALenum;
using OpenALDetail::ALfloat;
using OpenALDetail::ALint;
using OpenALDetail::ALshort;
using OpenALDetail::ALsizei;
using OpenALDetail::ALubyte;
using OpenALDetail::ALuint;
using OpenALDetail::ALushort;
using OpenALDetail::ALvoid;
using OpenALDetail::ALCboolean;
using OpenALDetail::ALCbyte;
using OpenALDetail::ALCchar;
using OpenALDetail::ALCcontext;
using OpenALDetail::ALCdevice;
using OpenALDetail::ALCdouble;
using OpenALDetail::ALCenum;
using OpenALDetail::ALCfloat;
using OpenALDetail::ALCint;
using OpenALDetail::ALCshort;
using OpenALDetail::ALCsizei;
using OpenALDetail::ALCubyte;
using OpenALDetail::ALCuint;
using OpenALDetail::ALCushort;
using OpenALDetail::ALCvoid;
namespace Nz
{
using OpenALFunc = void(*)();
class NAZARA_AUDIO_API OpenAL
{
public:
static OpenALFunc GetEntry(const String& entryPoint);
static String GetRendererName();
static String GetVendorName();
static unsigned int GetVersion();
static bool Initialize(bool openDevice = true);
static bool IsInitialized();
static std::size_t QueryInputDevices(std::vector<String>& devices);
static std::size_t QueryOutputDevices(std::vector<String>& devices);
static bool SetDevice(const String& deviceName);
static void Uninitialize();
static ALenum AudioFormat[AudioFormat_Max + 1];
private:
static void CloseDevice();
static bool OpenDevice();
static OpenALFunc LoadEntry(const char* name, bool throwException = false);
};
// al
NAZARA_AUDIO_API extern OpenALDetail::LPALBUFFER3F alBuffer3f;
NAZARA_AUDIO_API extern OpenALDetail::LPALBUFFER3I alBuffer3i;
NAZARA_AUDIO_API extern OpenALDetail::LPALBUFFERDATA alBufferData;
NAZARA_AUDIO_API extern OpenALDetail::LPALBUFFERF alBufferf;
NAZARA_AUDIO_API extern OpenALDetail::LPALBUFFERFV alBufferfv;
NAZARA_AUDIO_API extern OpenALDetail::LPALBUFFERI alBufferi;
NAZARA_AUDIO_API extern OpenALDetail::LPALBUFFERIV alBufferiv;
NAZARA_AUDIO_API extern OpenALDetail::LPALDELETEBUFFERS alDeleteBuffers;
NAZARA_AUDIO_API extern OpenALDetail::LPALDELETESOURCES alDeleteSources;
NAZARA_AUDIO_API extern OpenALDetail::LPALDISABLE alDisable;
NAZARA_AUDIO_API extern OpenALDetail::LPALDISTANCEMODEL alDistanceModel;
NAZARA_AUDIO_API extern OpenALDetail::LPALDOPPLERFACTOR alDopplerFactor;
NAZARA_AUDIO_API extern OpenALDetail::LPALDOPPLERVELOCITY alDopplerVelocity;
NAZARA_AUDIO_API extern OpenALDetail::LPALENABLE alEnable;
NAZARA_AUDIO_API extern OpenALDetail::LPALGENBUFFERS alGenBuffers;
NAZARA_AUDIO_API extern OpenALDetail::LPALGENSOURCES alGenSources;
NAZARA_AUDIO_API extern OpenALDetail::LPALGETBOOLEAN alGetBoolean;
NAZARA_AUDIO_API extern OpenALDetail::LPALGETBOOLEANV alGetBooleanv;
NAZARA_AUDIO_API extern OpenALDetail::LPALGETBUFFER3F alGetBuffer3f;
NAZARA_AUDIO_API extern OpenALDetail::LPALGETBUFFER3I alGetBuffer3i;
NAZARA_AUDIO_API extern OpenALDetail::LPALGETBUFFERF alGetBufferf;
NAZARA_AUDIO_API extern OpenALDetail::LPALGETBUFFERFV alGetBufferfv;
NAZARA_AUDIO_API extern OpenALDetail::LPALGETBUFFERI alGetBufferi;
NAZARA_AUDIO_API extern OpenALDetail::LPALGETBUFFERIV alGetBufferiv;
NAZARA_AUDIO_API extern OpenALDetail::LPALGETDOUBLE alGetDouble;
NAZARA_AUDIO_API extern OpenALDetail::LPALGETDOUBLEV alGetDoublev;
NAZARA_AUDIO_API extern OpenALDetail::LPALGETENUMVALUE alGetEnumValue;
NAZARA_AUDIO_API extern OpenALDetail::LPALGETERROR alGetError;
NAZARA_AUDIO_API extern OpenALDetail::LPALGETFLOAT alGetFloat;
NAZARA_AUDIO_API extern OpenALDetail::LPALGETFLOATV alGetFloatv;
NAZARA_AUDIO_API extern OpenALDetail::LPALGETINTEGER alGetInteger;
NAZARA_AUDIO_API extern OpenALDetail::LPALGETINTEGERV alGetIntegerv;
NAZARA_AUDIO_API extern OpenALDetail::LPALGETLISTENER3F alGetListener3f;
NAZARA_AUDIO_API extern OpenALDetail::LPALGETLISTENER3I alGetListener3i;
NAZARA_AUDIO_API extern OpenALDetail::LPALGETLISTENERF alGetListenerf;
NAZARA_AUDIO_API extern OpenALDetail::LPALGETLISTENERFV alGetListenerfv;
NAZARA_AUDIO_API extern OpenALDetail::LPALGETLISTENERI alGetListeneri;
NAZARA_AUDIO_API extern OpenALDetail::LPALGETLISTENERIV alGetListeneriv;
NAZARA_AUDIO_API extern OpenALDetail::LPALGETPROCADDRESS alGetProcAddress;
NAZARA_AUDIO_API extern OpenALDetail::LPALGETSOURCE3F alGetSource3f;
NAZARA_AUDIO_API extern OpenALDetail::LPALGETSOURCE3I alGetSource3i;
NAZARA_AUDIO_API extern OpenALDetail::LPALGETSOURCEF alGetSourcef;
NAZARA_AUDIO_API extern OpenALDetail::LPALGETSOURCEFV alGetSourcefv;
NAZARA_AUDIO_API extern OpenALDetail::LPALGETSOURCEI alGetSourcei;
NAZARA_AUDIO_API extern OpenALDetail::LPALGETSOURCEIV alGetSourceiv;
NAZARA_AUDIO_API extern OpenALDetail::LPALGETSTRING alGetString;
NAZARA_AUDIO_API extern OpenALDetail::LPALISBUFFER alIsBuffer;
NAZARA_AUDIO_API extern OpenALDetail::LPALISENABLED alIsEnabled;
NAZARA_AUDIO_API extern OpenALDetail::LPALISEXTENSIONPRESENT alIsExtensionPresent;
NAZARA_AUDIO_API extern OpenALDetail::LPALISSOURCE alIsSource;
NAZARA_AUDIO_API extern OpenALDetail::LPALLISTENER3F alListener3f;
NAZARA_AUDIO_API extern OpenALDetail::LPALLISTENER3I alListener3i;
NAZARA_AUDIO_API extern OpenALDetail::LPALLISTENERF alListenerf;
NAZARA_AUDIO_API extern OpenALDetail::LPALLISTENERFV alListenerfv;
NAZARA_AUDIO_API extern OpenALDetail::LPALLISTENERI alListeneri;
NAZARA_AUDIO_API extern OpenALDetail::LPALLISTENERIV alListeneriv;
NAZARA_AUDIO_API extern OpenALDetail::LPALSOURCE3F alSource3f;
NAZARA_AUDIO_API extern OpenALDetail::LPALSOURCE3I alSource3i;
NAZARA_AUDIO_API extern OpenALDetail::LPALSOURCEF alSourcef;
NAZARA_AUDIO_API extern OpenALDetail::LPALSOURCEFV alSourcefv;
NAZARA_AUDIO_API extern OpenALDetail::LPALSOURCEI alSourcei;
NAZARA_AUDIO_API extern OpenALDetail::LPALSOURCEIV alSourceiv;
NAZARA_AUDIO_API extern OpenALDetail::LPALSOURCEPAUSE alSourcePause;
NAZARA_AUDIO_API extern OpenALDetail::LPALSOURCEPAUSEV alSourcePausev;
NAZARA_AUDIO_API extern OpenALDetail::LPALSOURCEPLAY alSourcePlay;
NAZARA_AUDIO_API extern OpenALDetail::LPALSOURCEPLAYV alSourcePlayv;
NAZARA_AUDIO_API extern OpenALDetail::LPALSOURCEQUEUEBUFFERS alSourceQueueBuffers;
NAZARA_AUDIO_API extern OpenALDetail::LPALSOURCEREWIND alSourceRewind;
NAZARA_AUDIO_API extern OpenALDetail::LPALSOURCEREWINDV alSourceRewindv;
NAZARA_AUDIO_API extern OpenALDetail::LPALSOURCESTOP alSourceStop;
NAZARA_AUDIO_API extern OpenALDetail::LPALSOURCESTOPV alSourceStopv;
NAZARA_AUDIO_API extern OpenALDetail::LPALSOURCEUNQUEUEBUFFERS alSourceUnqueueBuffers;
NAZARA_AUDIO_API extern OpenALDetail::LPALSPEEDOFSOUND alSpeedOfSound;
// alc
NAZARA_AUDIO_API extern OpenALDetail::LPALCCAPTURECLOSEDEVICE alcCaptureCloseDevice;
NAZARA_AUDIO_API extern OpenALDetail::LPALCCAPTUREOPENDEVICE alcCaptureOpenDevice;
NAZARA_AUDIO_API extern OpenALDetail::LPALCCAPTURESAMPLES alcCaptureSamples;
NAZARA_AUDIO_API extern OpenALDetail::LPALCCAPTURESTART alcCaptureStart;
NAZARA_AUDIO_API extern OpenALDetail::LPALCCAPTURESTOP alcCaptureStop;
NAZARA_AUDIO_API extern OpenALDetail::LPALCCLOSEDEVICE alcCloseDevice;
NAZARA_AUDIO_API extern OpenALDetail::LPALCCREATECONTEXT alcCreateContext;
NAZARA_AUDIO_API extern OpenALDetail::LPALCDESTROYCONTEXT alcDestroyContext;
NAZARA_AUDIO_API extern OpenALDetail::LPALCGETCONTEXTSDEVICE alcGetContextsDevice;
NAZARA_AUDIO_API extern OpenALDetail::LPALCGETCURRENTCONTEXT alcGetCurrentContext;
NAZARA_AUDIO_API extern OpenALDetail::LPALCGETENUMVALUE alcGetEnumValue;
NAZARA_AUDIO_API extern OpenALDetail::LPALCGETERROR alcGetError;
NAZARA_AUDIO_API extern OpenALDetail::LPALCGETINTEGERV alcGetIntegerv;
NAZARA_AUDIO_API extern OpenALDetail::LPALCGETPROCADDRESS alcGetProcAddress;
NAZARA_AUDIO_API extern OpenALDetail::LPALCGETSTRING alcGetString;
NAZARA_AUDIO_API extern OpenALDetail::LPALCISEXTENSIONPRESENT alcIsExtensionPresent;
NAZARA_AUDIO_API extern OpenALDetail::LPALCMAKECONTEXTCURRENT alcMakeContextCurrent;
NAZARA_AUDIO_API extern OpenALDetail::LPALCOPENDEVICE alcOpenDevice;
NAZARA_AUDIO_API extern OpenALDetail::LPALCPROCESSCONTEXT alcProcessContext;
NAZARA_AUDIO_API extern OpenALDetail::LPALCSUSPENDCONTEXT alcSuspendContext;
}
#endif // NAZARA_AUDIO_OPENAL
#endif // NAZARA_OPENAL_HPP
| 50.699482 | 100 | 0.79489 | AntoineJT |
96891869ad7149c5ddad7a946e73f1393c97b885 | 4,613 | cpp | C++ | src/kernels/cpu/reference/convolution.cpp | louareg/nncase | 0125654eb57b7ff753fe9c396c84b264c01f34d3 | [
"Apache-2.0"
] | null | null | null | src/kernels/cpu/reference/convolution.cpp | louareg/nncase | 0125654eb57b7ff753fe9c396c84b264c01f34d3 | [
"Apache-2.0"
] | null | null | null | src/kernels/cpu/reference/convolution.cpp | louareg/nncase | 0125654eb57b7ff753fe9c396c84b264c01f34d3 | [
"Apache-2.0"
] | null | null | null | /* Copyright 2019-2021 Canaan Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <nncase/kernels/cpu/reference/convolution.h>
#include <nncase/kernels/kernel_utils.h>
using namespace nncase;
using namespace nncase::runtime;
using namespace nncase::kernels;
using namespace nncase::kernels::cpu;
using namespace nncase::kernels::cpu::reference;
result<void> reference::conv2d(const float *input, const float *weights, const float *bias, float *output,
const runtime_shape_t &in_shape, const runtime_shape_t &in_strides, const runtime_shape_t &w_shape, const runtime_shape_t &w_strides,
const runtime_shape_t &bias_strides, const runtime_shape_t &out_strides, const padding &padding_h, const padding &padding_w,
int32_t groups, int32_t stride_h, int32_t stride_w, int32_t dilation_h, int32_t dilation_w, value_range<float> fused_activation,
NNCASE_UNUSED kernel_context &context) noexcept
{
const auto filter_h = (int32_t)w_shape[2];
const auto filter_w = (int32_t)w_shape[3];
const auto out_channels = w_shape[0];
const auto out_h = kernels::detail::get_windowed_output_size(in_shape[2], filter_h, stride_h, dilation_h, padding_h);
const auto out_w = kernels::detail::get_windowed_output_size(in_shape[3], filter_w, stride_w, dilation_w, padding_w);
const auto g_ic = in_shape[1] / groups;
const auto g_oc = out_channels / groups;
runtime_shape_t in_index(4);
runtime_shape_t w_index(4);
runtime_shape_t bias_index(1);
runtime_shape_t out_index(4);
for (size_t batch = 0; batch < in_shape[0]; batch++)
{
in_index[0] = out_index[0] = batch;
for (size_t og = 0; og < (size_t)groups; og++)
{
for (size_t oc = 0; oc < g_oc; oc++)
{
out_index[1] = w_index[0] = bias_index[0] = og * g_oc + oc;
for (size_t oy = 0; oy < out_h; oy++)
{
out_index[2] = oy;
for (size_t ox = 0; ox < out_w; ox++)
{
out_index[3] = ox;
const int32_t in_y_origin = (oy * stride_h) - padding_h.before;
const int32_t in_x_origin = (ox * stride_w) - padding_w.before;
const size_t filter_y_start = (size_t)std::max(0, (-in_y_origin + dilation_h - 1) / dilation_h);
const size_t filter_y_end = (size_t)std::min(filter_h, ((int32_t)in_shape[2] - in_y_origin + dilation_h - 1) / dilation_h);
const size_t filter_x_start = (size_t)std::max(0, (-in_x_origin + dilation_w - 1) / dilation_w);
const size_t filter_x_end = (size_t)std::min(filter_w, ((int32_t)in_shape[3] - in_x_origin + dilation_w - 1) / dilation_w);
float value = bias[offset(bias_strides, bias_index)];
for (size_t ic = 0; ic < g_ic; ic++)
{
in_index[1] = og * g_ic + ic;
w_index[1] = ic;
for (size_t ky = filter_y_start; ky < filter_y_end; ky++)
{
w_index[2] = ky;
for (size_t kx = filter_x_start; kx < filter_x_end; kx++)
{
w_index[3] = kx;
in_index[2] = in_y_origin + dilation_h * ky;
in_index[3] = in_x_origin + dilation_w * kx;
const float in_v = input[offset(in_strides, in_index)];
const float w = weights[offset(w_strides, w_index)];
value += in_v * w;
}
}
}
output[offset(out_strides, out_index)] = kernels::detail::apply_activation(value, fused_activation);
}
}
}
}
}
return ok();
}
| 49.074468 | 147 | 0.567743 | louareg |
9693badc7f320eb7039e8e3a88284724ad3000a1 | 23,341 | cc | C++ | src/amuse/community/smalln/src/smallN_unpert.cc | rknop/amuse | 85d5bdcc29cfc87dc69d91c264101fafd6658aec | [
"Apache-2.0"
] | 131 | 2015-06-04T09:06:57.000Z | 2022-02-01T12:11:29.000Z | src/amuse/community/smalln/src/smallN_unpert.cc | rknop/amuse | 85d5bdcc29cfc87dc69d91c264101fafd6658aec | [
"Apache-2.0"
] | 690 | 2015-10-17T12:18:08.000Z | 2022-03-31T16:15:58.000Z | src/amuse/community/smalln/src/smallN_unpert.cc | rieder/amuse | 3ac3b6b8f922643657279ddee5c8ab3fc0440d5e | [
"Apache-2.0"
] | 102 | 2015-01-22T10:00:29.000Z | 2022-02-09T13:29:43.000Z |
// Functions to handle partial or full unperturbed motion in smallN.
// Structure shamelessly cribbed from Starlab::hdyn_unpert.C by the
// author. Retained Starlab data structures to simplify code
// importation.
//
// Author: Steve McMillan.
//
// Externally visible functions:
//
// real get_tidal_potential(hdyn *b, hdyn *bi, hdyn *bj, hdyn *cm)
// bool is_unperturbed_and_approaching(hdyn *b, hdyn *bi, hdyn *bj)
// bool create_binary(hdyn *bi, hdyn *bj, bool verbose = false)
// bool extend_or_end_binary(hdyn*& bi, bool verbose = false)
#include "hdyn.h"
real get_tidal_potential(hdyn *b, hdyn *bi, hdyn *bj, hdyn *cm,
bool absolute) // default = true
{
// Calculate the tidal potential of the system on (bi,bj) with
// top-level center of mass cm. If absolute is true (the
// default), the component positions are assumed to be absolute;
// if false, they are relative to their parent node.
real mi = bi->get_mass(), mj = bj->get_mass(), mcm = cm->get_mass();
vec xi = bi->get_pos(), xj = bj->get_pos(), xcm = cm->get_pos();
if (!absolute) {
xi += xcm;
xj += xcm;
}
real phi_t = 0;
for_all_daughters(hdyn, b, bk)
if (bk != bi && bk != bj && bk != cm) {
vec xk = bk->get_pos();
real dphi_k = - mi/abs(xi-xk) - mj/abs(xj-xk) + mcm/abs(xcm-xk);
phi_t += bk->get_mass()*dphi_k;
}
return phi_t;
}
bool is_unperturbed_and_approaching(hdyn *b, real dt, hdyn *bi, hdyn *bj)
{
// Check whether the binary (bi,bj) satisfies the requirements for
// unpeturbed motion. OK to use pos and vel here because pred_pos
// and pos are the same at the end of a step, when this function
// is called.
if (dt > b->get_dt_crit()) return false;
if (bi->is_parent() || bj->is_parent()) return false;
if (square(bi->get_pos()-bj->get_pos()) > b->get_r2_crit()) return false;
if ((bi->get_pos()-bj->get_pos()) * (bi->get_vel()-bj->get_vel()) > 0)
return false;
// Particles are within r_crit and approaching. Check the
// perturbation due to the next nearest neighbor. Work with
// |potential| rather than simple distance to take mass into
// account.
vec cm = (bi->get_mass()*bi->get_pos() + bj->get_mass()*bj->get_pos())
/ (bi->get_mass() + bj->get_mass());
hdyn *bk_nn = NULL;
real max_pot2 = 0, nn_dist2 = 0;
for_all_leaves(hdyn, b, bk)
if ((bk != bi) && (bk != bj) ) {
real dist2 = square(bk->get_pos() - cm);
real pot2 = pow(bk->get_mass(), 2)/dist2;
if (pot2 > max_pot2) {
max_pot2 = pot2;
nn_dist2 = dist2;
bk_nn = bk;
}
}
// Conceivable we are dealing with an isolated 2-body system.
if (!bk_nn) return true;
// Particle bk_nn has the largest potential relative to the CM.
// Compute its perturbation, and return true if it is small.
real dist2 = square(bi->get_pos()-bj->get_pos());
real mass = bi->get_mass() + bj->get_mass();
real gamma2 = 4*pow(bk_nn->get_mass()/mass, 2)*pow(dist2/nn_dist2, 3);
return (gamma2 < b->get_gamma2_unpert());
}
static inline vec get_cm_acc(hdyn *b, hdyn *bi, hdyn *bj, vec pos)
{
// Return the acceleration at location pos due to all nodes
// excluding bi and bj.
vec acc = 0;
for_all_daughters(hdyn, b, bk)
if (bk != bi && bk != bj) {
vec dr = bk->get_pos() - pos;
acc += bk->get_mass()*dr/pow(dr*dr, 1.5);
}
return acc;
}
static inline real integrand(real t, real e)
{
return cos(2*t)/pow(1+e*cos(t),4);
}
static inline real num_int(kepler *k)
{
// Numerial determination of the orbital integral using the
// trapezoid rule (intended as a test of Steve's algebra -- seems
// to be OK).
real M = k->get_total_mass();
real a = k->get_semi_major_axis();
real e = k->get_eccentricity();
real J = k->get_angular_momentum();
real th0 = fabs(k->get_true_anomaly());
real dth = 0.01*th0, sum = 0.5*(integrand(0,e)+integrand(th0,e));
for (real t = dth; t < th0-0.5*dth; t += dth) sum += integrand(t,e);
if (fabs(1-e) < 1.e-6)
return 2*pow(J,7)*sum*dth/pow(M,4);
else
return 2*pow(a*fabs(1-e*e),4)*sum*dth/J;
}
static inline real orb_int(kepler *k)
{
// Compute the angular integral
//
// \int (x^2 - y^2) dt
//
// that appears in the calculation of the change in the angular
// momentum. Transform it to
//
// \int r^4 cos(2 theta) d(theta)/J
//
// from th0 to -th0, where th0 < 0 is the incoming true anomaly
// and J is the angular momentum.
// Angular integral (for e not equal to 1) is
//
// (A^4/J) \int cos(2 theta) / (1 + e cos theta)^4
//
// from th0 to -th0, where th0 < 0 is the true anomaly, A =
// a(1-e^2) and J is angular momentum.
real M = k->get_total_mass();
real a = k->get_semi_major_axis();
real e = k->get_eccentricity();
real J = k->get_angular_momentum();
real r = k->get_separation();
real th0 = fabs(k->get_true_anomaly());
real s = sin(th0);
real c = cos(th0);
// The following integrals are taken from Mathematica, with
// additional algebra to simplify some expressions.
real integral;
if (fabs(1-e) < 1.e-6) {
// ~Parabolic (not linear) orbit. In this case,
//
// r (1 + cos(theta)) = J^2/M
//
// and the integral becomes
//
// (J^7/M^4) \int cos(2 theta) / (1 + cos(theta)) d(theta)
integral = 4*pow(J, 7)*pow(M, -4)
* (-th0 + sin(th0) + 0.5*tan(th0/2));
} else {
// Elliptical or hyperbolic orbit, with
//
// r (1 + e cos(theta)) = A = a |1-e^2|
//
// and the integral is
//
// (A^4/J) \int cos(2 theta) / (1 + e cos theta)^4
//
// Simplify the Mathematica expressions using the above
// expression for r and
//
// A^4/J = sqrt(a^7/M) (1-e^2)^(7/2)
real fac1 = -2*pow(e,5)+9*pow(e,3)+8*e
+ 3*(3*pow(e,4)+9*e*e-2)*c
+ e*(8*pow(e,4)+9*e*e-2)*c*c;
real fac2 = s * J * pow(r,3) / (3*pow(fabs(1-e*e),3)*M);
real fac3 = 10 * e * e * sqrt(pow(a,7)/M);
real fac4 = sqrt(fabs((1-e)/(1+e)))*tan(th0/2);
if (e < 1)
integral = -fac1*fac2 + fac3*atan(fac4);
else
integral = fac1*fac2 - fac3*atanh(fac4);
}
// cout << "orb_int: " << e << " " << integral << " "
// << num_int(k) << endl << flush;
return integral;
}
bool create_binary(hdyn *bi, hdyn *bj, bool verbose)
{
// Combine two nodes, replacing the first by the center of mass of
// the two, and moving both to lie below the new center of mass
// node. On entry we have just completed a step, so {pos,vel} and
// pred_{pos,vel} should be the same.
if (!bi || !bj) return false;
if (bi->get_kepler()
&& bi->get_kepler()->tidal_potential != 0) return false;
// Construct a kepler structure describing the relative motion.
real time = bi->get_system_time();
real mi = bi->get_mass();
real mj = bj->get_mass();
kepler *k = new kepler;
k->set_time(time);
k->set_total_mass(mi+mj);
k->set_rel_pos(bj->get_pos() - bi->get_pos());
k->set_rel_vel(bj->get_vel() - bi->get_vel());
k->initialize_from_pos_and_vel();
// Set a time step. Choose the time to separation at the same
// radius. Could use pred_advance_to_periastron(), but this may
// be quite inaccurate. Better to use mean motion.
real mean_anomaly = k->get_mean_anomaly();
if (k->get_energy() < 0)
mean_anomaly = sym_angle(mean_anomaly); // place in (-PI, PI]
real peri_time;
if (mean_anomaly >= 0) { // should never happen
delete k;
return false;
} else
peri_time = time - mean_anomaly / k->get_mean_motion();
// Create a new center of mass node.
hdyn *cm = new hdyn;
cm->set_mass(mi+mj);
cm->set_pos((mi*bi->get_pos()+mj*bj->get_pos())/cm->get_mass());
cm->set_vel((mi*bi->get_vel()+mj*bj->get_vel())/cm->get_mass());
// Calculate and save data needed to correct the energy and
// angular momentun after the unperturbed segment. See
// partial_unperturbed.pdf for details.
// The energy correction is just the change in the tidal potential
// (components - CM). Store the initial value of the tidal
// potential in k->tidal_potential.
k->tidal_potential = get_tidal_potential(bi->get_parent(), bi, bj, cm);
// The angular momentum correction (neglecting reorientation of
// the orbit plane) requires an integral over the orbit and
// computation of a spatial derivative of the acceleration.
// Specifically, we need to calculate d(a_y)/dx, where x and y are
// coordinates in the orbit plane, with x along the major axis of
// the orbit and y perpendicular to it. We could compute the
// Jacobi matrix \partial da_i/\partial dx_j analytically and
// transform it to the orbital frame, but since we need only a
// single component it is easier to calculate it numerically.
// Compute the "x" component of the acceration at the CM and at a
// point slightly offset (by a distance equal to the current
// particle separation) in the "y" direction.
vec cmpos = cm->get_pos();
vec acc = get_cm_acc(bi->get_parent(), bi, bj, cmpos);
real dx = k->get_separation();
vec cmpos1 = cmpos + dx*k->get_longitudinal_unit_vector();
vec acc1 = get_cm_acc(bi->get_parent(), bi, bj, cmpos1);
real daydx = (acc1-acc)*k->get_transverse_unit_vector()/dx;
// Compute the angular integral orb_int(theta) to the reflection
// point and calculate the change in the angular momentum. Note
// that we expect dJ/J to be less than dE/E by a factor of
// sqrt(gamma), and we keep only the first-order term parallel to
// J, neglecting (second-order) changes in the orbit orientation.
k->delta_angular_momentum = daydx*orb_int(k);
if (verbose) {
cout << endl << "too close: " << bi->get_index();
cout << " and " << bj->get_index() << endl << flush;
PRL(total_energy(bi->get_parent()));
}
//-----------------------------------------------------------------
// Offset components to the center of mass frame.
bi->inc_pos(-cm->get_pos());
bi->inc_vel(-cm->get_vel());
bj->inc_pos(-cm->get_pos());
bj->inc_vel(-cm->get_vel());
// Restructure the tree to create the binary (bi,bj). The new CM
// node is cm.
create_binary_node(cm, bi, bj);
// Leaf indices are meainingful and retain their meaning
// throughout. CM node indices are generated internally, and are
// discarded when the node is destroyed. Desirable to have the CM
// index reflect the indices of the components, but this is in
// general not feasible if the leaf indices are large (e.g. if
// they come from a larger simulation). Instead of a formula to
// compute the indices, just use a manager as in ph4.
int cm_index = bi->get_cm_index();
cm->set_index(cm_index);
bi->set_cm_index(cm_index+1);
// The relevant kepler is attached to (only) the first component.
bi->set_kepler(k);
bi->set_t_pred(2*peri_time-time); // end of unperturbed segment
// Start with pericenter reflection. Later, allow possibility of
// completely unperturbed motion extending over several orbits, as
// in kira.
cm->set_fully_unperturbed(false);
bi->set_fully_unperturbed(false);
if (verbose) {
cout << "created new binary " << cm->get_index()
<< " at time " << bi->get_system_time() << endl;
k->print_all();
real dt_unpert = bi->get_t_pred() - time;
int p = cout.precision(10);
PRC(dt_unpert); PRL(bi->get_t_pred());
PRC(peri_time); PRL(peri_time-time);
PRL(bi->get_t_pred()-time);
cout.precision(p);
PRL(k->tidal_potential);
PRC(daydx); PRL(k->delta_angular_momentum);
// Special planar case: angle to 3rd star; acc should be in
// the x-y plane.
// real phi3 = atan2(acc[1], acc[0]);
// PRL(phi3);
}
// Make sure pos and pred_pos agree.
for_all_nodes(hdyn, cm, bb) {
bb->set_pred_pos(bb->get_pos());
bb->set_pred_vel(bb->get_vel());
}
return true;
}
static inline real time_to_radius(real dr, // distance to cover
real vr, // relative radial velocity
real ar) // relative radial acceleration
{
// Estimate the time required for two particles, of given relative
// velocity and acceleration, to decrease their separation by dr.
// Use the following time scales:
//
// t1 = dr / |vr| ("crossing" time)
// t2 = sqrt (2 * dr / |ar|) ("free-fall" time)
//
// If the particles are in the same clump, then ar is the two-body
// acceleration and t2 really is the free-fall time. Otherwise,
// ar is the relative acceleration in the global cluster field.
if (dr <= 0) return 0;
real dt = _INFINITY_;
if (vr < 0) dt = -dr / vr;
if (ar < 0) dt = fmin(dt, sqrt (-2 * dr / ar));
return dt;
}
static inline real dt_perturbers(hdyn *bcm, hdyn*& bmin)
{
// Return an estimate of the time needed for any particle to
// exceed the threshhold for unperturbed multiple motion of
// the multiple CM bcm.
if (!bcm->get_allow_full_unperturbed()) // turn off extended motion
return -1;
real t_min = _INFINITY_;
bmin = NULL;
hdyn *od = bcm->get_oldest_daughter();
if (od && od->get_kepler()) {
real scale = od->get_kepler()->get_semi_major_axis();
real mass = od->get_kepler()->get_total_mass();
for_all_daughters(hdyn, bcm->get_parent(), bb)
if (bb != bcm) {
// Estimate the time needed for node bb to perturb bcm
// at level gamma. The critical distance for bb to be
// such a perturber is rpert, defined by
//
// 2 * m_bb * scale mass
// ------------------ = gamma * -------
// rpert^3 scale^2
//
// or
//
// rpert = gamma^{-1/3} * scale
// * (2 * m_bb / mass)^{1/3}.
real rpert = bcm->get_gamma_inv3() * scale
* pow(2*bb->get_mass()/mass, 1./3);
// Time estimate is a combination of the free-fall and
// crossing times.
vec dpos = bb->get_pos() - bcm->get_pos();
vec dvel = bb->get_vel() - bcm->get_vel();
vec dacc = bb->get_acc() - bcm->get_acc();
real dr = abs(dpos);
real vr = dvel * dpos / dr;
real ar = dacc * dpos / dr;
real tr = time_to_radius(dr - rpert, vr, ar);
if (tr < t_min) {
t_min = tr;
bmin = bb;
}
if (tr <= 0) break;
}
} else
t_min = -1;
return t_min;
}
static inline real relative_energy(hdyn *bi, hdyn *bj)
{
// Return the relative energy (per unit reduced mass) of nodes bi
// and bj. Assume they have the same parent.
return 0.5*square(bi->get_vel()-bj->get_vel())
-(bi->get_mass()+bj->get_mass())
/ abs(bi->get_pos()-bj->get_pos());
}
static void adjust_binary(hdyn *cm, real& tidal_potential, real dphi_tidal)
{
#if 0
// EXPERIMENTAL CODE: Try to absorb the accumulated tidal error
// dphi_tidal by rotating the binary without changing its core
// orbital elements.
// *** ---> Looks like changing the orientation of the binary ***
// *** ---> generally doesn't work. ***
hdyn *root = cm->get_root();
hdyn *od = cm->get_oldest_daughter();
hdyn *yd = od->get_younger_sister();
real fac = yd->get_mass()/cm->get_mass();
// Save the component positions, just in case.
vec xo = od->get_pos();
vec xy = yd->get_pos();
vec dx = xy - xo;
real sep = abs(dx);
// Calculate the unit vector in the direction of the acceleration.
// To the extent that the acceleration is predominantly due to the
// nearest neighbor, we expect the tidal potential to scale as
//
// sep^2 [3 cos^2(theta) - 1]
//
// where theta is the angle between the separation vector dx and
// the external acceleration. Specifically, this function is
// linear in cos^2(theta) and monotonic decreasing with theta for
// theta between 0 and pi/2.
// Construct unit vectors orb in the direction of the initial
// orbital separation, acc in the direction of the acceleration, n
// perpendicular to the two, and t such that (acc, t, n) form a
// right-handed triad.
vec orb = dx/sep;
vec acc = cm->get_acc() / abs(cm->get_acc());
vec n = orb ^ acc;
n /= abs(n);
vec t = -acc^n;
real c20 = pow(orb*acc, 2);
// Starting point: cos(theta) = c0 gives a tidal potential of
// tidal_potential. We want to find a new value of theta that
// gives tidal_potential - dphi_tidal. Return the new value of
// the tidal potential (or at least the best we can do).
real phi_target = tidal_potential - dphi_tidal;
real dphi0 = dphi_tidal;
PRC(c20); PRL(tidal_potential);
PRC(tidal_potential); PRL(phi_target);
// Try to bracket the solution. Approximate limits on the
// possible values of the tidal potential are obtained with theta
// = 0 (lower) and theta = pi/2 (upper).
real c21, dphi1;
// if (dphi_tidal < 0) {
// Rotate perpendicular to the acceleration.
od->set_pos(-fac*sep*t);
yd->set_pos((1-fac)*sep*t);
c21 = 0;
dphi1 = get_tidal_potential(root, od, yd, cm, false);
PRC(c21); PRL(dphi1);
// } else {
// Rotate parallel to the acceleration.
od->set_pos(-fac*sep*acc);
yd->set_pos((1-fac)*sep*acc);
c21 = 1;
dphi1 = get_tidal_potential(root, od, yd, cm, false);
// }
PRC(c21); PRL(dphi1);
// Restore the positions.
od->set_pos(xo);
yd->set_pos(xy);
#endif
}
bool extend_or_end_binary(hdyn*& bi, bool verbose)
{
// See if unperturbed motion can be extended, or terminate it.
if (!bi) return false;
hdyn *od = bi->get_oldest_daughter();
if (!od) return false;
hdyn *yd = od->get_younger_sister();
if (!yd) return false;
kepler *k = od->get_kepler();
if (!k) err_exit("smallN: binary with no kepler.");
// Correct energy and angular momentum after partial unperturbed
// motion before considering whether to extend the motion.
// Recompute the tidal potential in all cases.
real old_tidal_potential = k->tidal_potential;
real new_tidal_potential = get_tidal_potential(bi->get_parent(), od, yd, bi,
false);
real dphi_tidal = new_tidal_potential - old_tidal_potential;
if (!od->get_fully_unperturbed()) {
if (verbose) {
cout << endl << "correcting binary " << bi->get_index()
<< " at time " << bi->get_system_time()
<< endl << flush;
PRL(total_energy(bi->get_parent()));
}
// Compute the change in the tidal potential (components -
// CM) due to the rest of the system.
if (verbose) {
PRC(old_tidal_potential); PRL(new_tidal_potential);
PRL(dphi_tidal);
int p = cout.precision(12);
PRL(relative_energy(od, yd));
cout.precision(p);
}
// Apply the changes to the kepler structure, then transmit
// it to the components, to keep the kepler consistent in
// case it is needed later.
// Energy change is -dphi_tidal, or -dphi_tidal/mu in kepler.
real mu = od->get_mass()*yd->get_mass()/bi->get_mass();
#if 0
// Old code simply absorbed dphi_total into the binary
// energy by rescaling the relative velocities of the
// components. This changes the angular momentum by an
// amount proportional to vfac.
vec vrel = k->get_rel_vel();
real vfac = sqrt(1 - 2*dphi_tidal/(mu*square(vrel)));
k->set_rel_vel(vfac*vrel);
k->initialize_from_pos_and_vel();
if (verbose) {
cout << "corrected component velocities: "; PRL(vfac);
}
#else
// New code corrects the energy by -dphi_tidal/mu and the
// angular momentum by k->delta_angular_momentum, reinitalizes
// the orbit, and updates the components.
k->set_energy(k->get_energy() - dphi_tidal/mu);
k->set_angular_momentum(k->get_angular_momentum()
+ k->delta_angular_momentum);
k->initialize_from_integrals_and_separation();
if (verbose) {
vec cmpos = bi->get_pos();
vec acc = get_cm_acc(bi->get_parent(), bi, od, cmpos);
real dx = k->get_separation();
vec cmpos1 = cmpos + dx*k->get_longitudinal_unit_vector();
vec acc1 = get_cm_acc(bi->get_parent(), bi, od, cmpos1);
real daydx = (acc1-acc)*k->get_transverse_unit_vector()/dx;
PRL(daydx);
PRL(k->delta_angular_momentum);
int p = cout.precision(12);
cout << "new energy = " << k->get_energy()
<< " angular momentum = " << k->get_angular_momentum()
<< endl << flush;
cout.precision(p);
}
#endif
// Update the components using standard tools.
advance_components_to_time(bi, bi->get_system_time());
update_components_from_pred(bi);
if (verbose) {
k->print_all();
int p = cout.precision(12);
PRL(relative_energy(od, yd));
cout.precision(p);
PRL(total_energy(bi->get_parent()));
}
} else {
// Experimental code to try to absorb the change in the tidal
// potential. Not necessary if we freeze and resolve fully
// unperturbed binaries.
adjust_binary(bi, new_tidal_potential, dphi_tidal);
}
// Check whether extension is possible. Extension will be for an
// integral number of periods, at fixed binary phase (components
// should be receding).
hdyn *bmin = NULL;
real dtp = 0.5*dt_perturbers(bi, bmin); // 0.5 is conservative
real period = k->get_period();
if (bi->get_allow_full_unperturbed() && dtp >= period) {
float np = floor(dtp/period);
od->set_t_pred(od->get_t_pred()+np*period);
if (verbose) {
cout << endl << "extending binary " << bi->get_index()
<< " by " << np << " periods = " << np*period
<< " at time " << bi->get_system_time()
<< endl << flush;
if (bmin)
cout << "NN is " << bmin->get_index()
<< ": dist = " << abs(bmin->get_pos()-bi->get_pos())
<< " sma = " << k->get_semi_major_axis()
<< endl << flush;
PRL(total_energy(bi->get_parent()));
}
bi->set_fully_unperturbed(true);
od->set_fully_unperturbed(true);
// Save the tidal potential for correction at the end of this
// segment.
k->tidal_potential = new_tidal_potential;
return false;
}
// Terminate the binary.
if (verbose) {
cout << endl << "terminating binary " << bi->get_index()
<< " at time " << bi->get_system_time()
<< endl << flush;
if (bmin)
cout << "NN is " << bmin->get_index()
<< ": dist = " << abs(bmin->get_pos()-bi->get_pos())
<< " sma = " << k->get_semi_major_axis()
<< endl << flush;
}
// Clear kepler pointers.
od->set_kepler(NULL);
yd->set_kepler(NULL);
delete k;
// Include the center of mass position and velocity in the
// component quantities.
od->inc_pos(bi->get_pos());
od->inc_vel(bi->get_vel());
yd->inc_pos(bi->get_pos());
yd->inc_vel(bi->get_vel());
// Update the tree.
add_node(od, bi);
add_node(yd, bi);
detach_node(bi);
// Delete the CM node (careful to detach the daughters to
// avoid recursive deletion!).
bi->set_oldest_daughter(NULL);
delete(bi);
// Clear flags.
od->set_fully_unperturbed(false);
yd->set_fully_unperturbed(false);
// Make sure pos and pred_pos agree. Note that init_pred sets
// t_pred = time as well as pred_pos = pos.
od->init_pred();
yd->init_pred();
// Change bi to yd, so next node is correct in loop below.
bi = yd;
if (verbose) PRL(total_energy(bi->get_parent()));
return true;
}
| 30.273671 | 80 | 0.626537 | rknop |
969452b93ed569757597907bf483de31098dec8d | 518 | cpp | C++ | TESTS/mbedmicro-mbed/static_assert/main.cpp | pradeep-gr/mbed-os5-onsemi | 576d096f2d9933c39b8a220f486e9756d89173f2 | [
"Apache-2.0"
] | 7 | 2017-01-15T16:37:41.000Z | 2021-08-10T02:14:04.000Z | TESTS/mbedmicro-mbed/static_assert/main.cpp | pradeep-gr/mbed-os5-onsemi | 576d096f2d9933c39b8a220f486e9756d89173f2 | [
"Apache-2.0"
] | 1 | 2018-05-18T10:50:02.000Z | 2018-05-18T10:50:02.000Z | TESTS/mbedmicro-mbed/static_assert/main.cpp | pradeep-gr/mbed-os5-onsemi | 576d096f2d9933c39b8a220f486e9756d89173f2 | [
"Apache-2.0"
] | 9 | 2017-04-27T07:54:26.000Z | 2021-08-10T02:14:05.000Z | #include <stdio.h>
#include <stdint.h>
#include "mbed_toolchain.h"
#include "greentea-client/test_env.h"
#include "unity.h"
#include "utest.h"
using namespace utest::v1;
void no_test() {}
utest::v1::status_t test_setup(const size_t number_of_cases) {
GREENTEA_SETUP(5, "default_auto");
return verbose_test_setup_handler(number_of_cases);
}
Case cases[] = {
Case("Compilation test", no_test),
};
Specification specification(test_setup, cases);
int main() {
return !Harness::run(specification);
}
| 19.185185 | 62 | 0.722008 | pradeep-gr |
f7b2d83e65c0ecda36a39fc44adf55e2c50a6c75 | 1,443 | cpp | C++ | ex02-find-extremes/ExtremesMain.cpp | kglogins/bitl-ds-workspace-cpp | 0999247f3da9f63d77faebbdef7ba2c6a554f9dd | [
"MIT"
] | null | null | null | ex02-find-extremes/ExtremesMain.cpp | kglogins/bitl-ds-workspace-cpp | 0999247f3da9f63d77faebbdef7ba2c6a554f9dd | [
"MIT"
] | null | null | null | ex02-find-extremes/ExtremesMain.cpp | kglogins/bitl-ds-workspace-cpp | 0999247f3da9f63d77faebbdef7ba2c6a554f9dd | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <iomanip>
#include "Student.h"
using namespace std;
using namespace ds_course;
Student getMin(Student *ss, int count);
Student getMax(Student *ss, int count);
int main()
{
int studentsCount;
cin >> studentsCount;
Student students[studentsCount];
std::string studentInput;
cin.ignore(10000, '\n');
int age;
double height;
for (int i = 0; i < studentsCount; i++)
{
cin >> age >> height;
Student student;
student.age = age;
student.height = height;
students[i] = student;
}
Student minStudent = getMin(students, studentsCount);
Student maxStudent = getMax(students, studentsCount);
cout << minStudent.age << " " << fixed << setprecision(5) << minStudent.height << endl;
cout << maxStudent.age << " " << fixed << setprecision(5) << maxStudent.height << endl;
}
Student getMin(Student *ss, int count)
{
Student minStudent = ss[0];
for (int i = 0; i < count; i++)
{
if (minStudent.compareTo(ss[i]) == 1)
{
minStudent = ss[i];
}
}
return minStudent;
}
Student getMax(Student *ss, int count)
{
Student maxStudent = ss[0];
for (int i = 0; i < count; i++)
{
if (maxStudent.compareTo(ss[i]) == -1)
{
maxStudent = ss[i];
}
}
return maxStudent;
}
| 19.5 | 91 | 0.580735 | kglogins |
f7b40faeb419b286769eec39622a9b1cac460944 | 6,485 | cpp | C++ | Gpufit/tests/Gauss_Fit_1D.cpp | sriharijayaram5/Gpufit | 468ffbce6e6ff98632951af5e027c88c332bc1e0 | [
"MIT"
] | 228 | 2017-08-10T17:46:44.000Z | 2022-03-29T07:06:06.000Z | Gpufit/tests/Gauss_Fit_1D.cpp | sriharijayaram5/Gpufit | 468ffbce6e6ff98632951af5e027c88c332bc1e0 | [
"MIT"
] | 90 | 2017-08-14T11:41:19.000Z | 2022-03-30T12:22:59.000Z | Gpufit/tests/Gauss_Fit_1D.cpp | sriharijayaram5/Gpufit | 468ffbce6e6ff98632951af5e027c88c332bc1e0 | [
"MIT"
] | 76 | 2017-08-16T15:20:08.000Z | 2022-03-16T06:28:38.000Z | #define BOOST_TEST_MODULE Gpufit
#include "Gpufit/gpufit.h"
#include <boost/test/included/unit_test.hpp>
#include <array>
#include <cmath>
template<std::size_t n_points, std::size_t n_parameters>
void generate_gauss_1d(
std::array< REAL, n_points >& values,
std::array< REAL, n_points >& x_data,
std::array< REAL, n_parameters > const & parameters )
{
REAL const a = parameters[ 0 ];
REAL const x0 = parameters[ 1 ];
REAL const s = parameters[ 2 ];
REAL const b = parameters[ 3 ];
for ( int point_index = 0; point_index < n_points; point_index++ )
{
REAL const x = x_data[point_index];
REAL const argx = ( ( x - x0 )*( x - x0 ) ) / ( 2 * s * s );
REAL const ex = exp( -argx );
values[ point_index ] = a * ex + b;
}
}
void gauss_fit_1d()
{
/*
Performs a single fit using the GAUSS_1D model.
- Doesn't use user_info or weights.
- No noise is added.
- Checks fitted parameters equalling the true parameters.
*/
std::size_t const n_fits{ 1 };
std::size_t const n_points{ 5 };
std::size_t const n_parameters{ 4 };
std::array< REAL, n_parameters > const true_parameters{ { 4, 2, .5f, 1 } };
std::array< REAL, n_points > x_data{ { 0, 1, 2, 3, 4} };
std::array< REAL, n_points > data{};
generate_gauss_1d(data, x_data, true_parameters);
std::array< REAL, n_parameters > initial_parameters{ { 2, 1.5f, 0.3f, 0 } };
REAL tolerance{ 0.001f };
int max_n_iterations{ 10 };
std::array< int, n_parameters > parameters_to_fit{ { 1, 1, 1, 1 } };
std::array< REAL, n_parameters > output_parameters;
int output_states;
REAL output_chi_square;
int output_n_iterations;
int const status
= gpufit
(
n_fits,
n_points,
data.data(),
0,
GAUSS_1D,
initial_parameters.data(),
tolerance,
max_n_iterations,
parameters_to_fit.data(),
LSE,
0,
0,
output_parameters.data(),
&output_states,
&output_chi_square,
&output_n_iterations
);
BOOST_CHECK(status == 0);
BOOST_CHECK(output_states == 0);
BOOST_CHECK(output_chi_square < 1e-6f);
BOOST_CHECK(output_n_iterations <= max_n_iterations);
BOOST_CHECK(std::abs(output_parameters[0] - true_parameters[0]) < 1e-6f);
BOOST_CHECK(std::abs(output_parameters[1] - true_parameters[1]) < 1e-6f);
BOOST_CHECK(std::abs(output_parameters[2] - true_parameters[2]) < 1e-6f);
BOOST_CHECK(std::abs(output_parameters[3] - true_parameters[3]) < 1e-6f);
}
void gauss_fit_1d_custom_x()
{
/*
Performs two fits using the GAUSS_1D model.
- Doesn't use or weights.
- Uses user_info for custom x coordinate values, unique for each fit.
- No noise is added.
- Checks fitted parameters equalling the true parameters.
*/
std::size_t const n_fits{ 2 };
std::size_t const n_points{ 5 };
std::size_t const n_parameters{ 4 };
std::array< REAL, n_parameters > const true_parameters_1{ { 4, 0, .25f, 1 } };
std::array< REAL, n_parameters > const true_parameters_2{ { 6, .5f, .15f, 2 } };
std::array< REAL, n_parameters > initial_parameters_1{ { 2, .25f, .15f, 0 } };
std::array< REAL, n_parameters > initial_parameters_2{ { 8, .75f, .2f, 3 } };
std::array< REAL, n_points > x_data_1 = { { -1, -.5f, 0, .5f, 1 } };
std::array< REAL, n_points > x_data_2 = { { 0, .25f, .5f, .75f, 1 } };
std::array< REAL, n_points > fit_data_1{};
std::array< REAL, n_points > fit_data_2{};
generate_gauss_1d(fit_data_1, x_data_1, true_parameters_1);
generate_gauss_1d(fit_data_2, x_data_2, true_parameters_2);
std::array< REAL, n_points * n_fits> data{};
std::array< REAL, n_points * n_fits> x_data{};
for (int i = 0; i < n_points; i++)
{
data[i] = fit_data_1[i];
data[n_points + i] = fit_data_2[i];
x_data[i] = x_data_1[i];
x_data[n_points + i] = x_data_2[i];
}
std::array< REAL, n_parameters * n_fits> initial_parameters{};
for (int i = 0; i < n_parameters; i++)
{
initial_parameters[i] = initial_parameters_1[i];
initial_parameters[n_parameters + i] = initial_parameters_2[i];
}
REAL tolerance{ 1e-6f };
int max_n_iterations{ 20 };
std::array< int, n_parameters > parameters_to_fit{ { 1, 1, 1, 1 } };
std::array< REAL, n_parameters * n_fits > output_parameters;
std::array< int, n_fits > output_states;
std::array< REAL, n_fits > output_chi_square;
std::array< int, n_fits > output_n_iterations;
int const status
= gpufit
(
n_fits,
n_points,
data.data(),
0,
GAUSS_1D,
initial_parameters.data(),
tolerance,
max_n_iterations,
parameters_to_fit.data(),
LSE,
n_points * n_fits * sizeof(REAL),
reinterpret_cast< char * >(x_data.data()),
output_parameters.data(),
output_states.data(),
output_chi_square.data(),
output_n_iterations.data()
);
// check gpufit status
BOOST_CHECK(status == 0);
// check first fit
BOOST_CHECK(output_states[0] == 0);
BOOST_CHECK(output_chi_square[0] < 1e-6f);
BOOST_CHECK(output_n_iterations[0] <= max_n_iterations);
BOOST_CHECK(std::abs(output_parameters[0] - true_parameters_1[0]) < 1e-6f);
BOOST_CHECK(std::abs(output_parameters[1] - true_parameters_1[1]) < 1e-6f);
BOOST_CHECK(std::abs(output_parameters[2] - true_parameters_1[2]) < 1e-6f);
BOOST_CHECK(std::abs(output_parameters[3] - true_parameters_1[3]) < 1e-6f);
// check second fit
BOOST_CHECK(output_states[1] == 0);
BOOST_CHECK(output_chi_square[1] < 1e-6f);
BOOST_CHECK(output_n_iterations[1] <= max_n_iterations);
BOOST_CHECK(std::abs(output_parameters[4] - true_parameters_2[0]) < 1e-6f);
BOOST_CHECK(std::abs(output_parameters[5] - true_parameters_2[1]) < 1e-6f);
BOOST_CHECK(std::abs(output_parameters[6] - true_parameters_2[2]) < 1e-6f);
BOOST_CHECK(std::abs(output_parameters[7] - true_parameters_2[3]) < 1e-6f);
}
BOOST_AUTO_TEST_CASE( Gauss_Fit_1D )
{
// single 1d gauss fit
gauss_fit_1d();
// two gauss fits with custom x coordinate values
gauss_fit_1d_custom_x();
}
| 31.480583 | 84 | 0.615112 | sriharijayaram5 |
f7b747f64abc6d158a6f781eec3c64a96b511b81 | 1,218 | hpp | C++ | src/3rd party/boost/boost/python/detail/construct.hpp | OLR-xray/OLR-3.0 | b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611 | [
"Apache-2.0"
] | 8 | 2016-01-25T20:18:51.000Z | 2019-03-06T07:00:04.000Z | src/3rd party/boost/boost/python/detail/construct.hpp | OLR-xray/OLR-3.0 | b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611 | [
"Apache-2.0"
] | null | null | null | src/3rd party/boost/boost/python/detail/construct.hpp | OLR-xray/OLR-3.0 | b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611 | [
"Apache-2.0"
] | 3 | 2016-02-14T01:20:43.000Z | 2021-02-03T11:19:11.000Z | // Copyright David Abrahams 2002. Permission to copy, use,
// modify, sell and distribute this software is granted provided this
// copyright notice appears in all copies. This software is provided
// "as is" without express or implied warranty, and with no claim as
// to its suitability for any purpose.
#ifndef CONSTRUCT_REFERENCE_DWA2002716_HPP
# define CONSTRUCT_REFERENCE_DWA2002716_HPP
namespace boost { namespace python { namespace detail {
template <class T, class Arg>
void construct_pointee(void* storage, Arg& x
# if !defined(BOOST_MSVC) || BOOST_MSVC > 1300
, T const volatile*
# else
, T const*
# endif
)
{
new (storage) T(x);
}
template <class T, class Arg>
void construct_referent_impl(void* storage, Arg& x, T&(*)())
{
construct_pointee(storage, x, (T*)0);
}
template <class T, class Arg>
void construct_referent(void* storage, Arg const& x, T(*tag)() = 0)
{
construct_referent_impl(storage, x, tag);
}
template <class T, class Arg>
void construct_referent(void* storage, Arg& x, T(*tag)() = 0)
{
construct_referent_impl(storage, x, tag);
}
}}} // namespace boost::python::detail
#endif // CONSTRUCT_REFERENCE_DWA2002716_HPP
| 27.681818 | 69 | 0.697865 | OLR-xray |
f7b8f01a1a001a3314d1d9bb7234a9b98b3fa2b0 | 1,436 | cpp | C++ | 1101-9999/1654. Minimum Jumps to Reach Home.cpp | erichuang1994/leetcode-solution | d5b3bb3ce2a428a3108f7369715a3700e2ba699d | [
"MIT"
] | null | null | null | 1101-9999/1654. Minimum Jumps to Reach Home.cpp | erichuang1994/leetcode-solution | d5b3bb3ce2a428a3108f7369715a3700e2ba699d | [
"MIT"
] | null | null | null | 1101-9999/1654. Minimum Jumps to Reach Home.cpp | erichuang1994/leetcode-solution | d5b3bb3ce2a428a3108f7369715a3700e2ba699d | [
"MIT"
] | null | null | null | class Solution
{
public:
int minimumJumps(vector<int> &forbidden, int a, int b, int x)
{
// int left = min(0,x-2*a-1);
// int right = x+2*b+1;
int left = -1;
int right = 4001;
unordered_set<int> f;
for (auto &n : forbidden)
{
f.insert(n);
}
unordered_set<string> visited;
queue<pair<int, int>> q;
int cnt = 0;
q.push(make_pair(0, 1));
visited.insert(make_key(0, 1));
while (!q.empty())
{
int len = q.size();
// cout<<len<<endl;
for (int i = 0; i < len; i++)
{
auto t = q.front();
q.pop();
if (t.first == x)
{
// cout<<t.first<<" "<<t.second<<endl;
return cnt;
}
string tmpk = make_key(t.first + a, 1);
if (t.first + a < right && visited.find(tmpk) == visited.end() && f.find(t.first + a) == f.end())
{
visited.insert(tmpk);
q.push(make_pair(t.first + a, 1));
}
if (t.second == 1)
{
tmpk = make_key(t.first - b, 0);
if (t.first - b > left && visited.find(tmpk) == visited.end() && f.find(t.first - b) == f.end())
{
visited.insert(tmpk);
q.push(make_pair(t.first - b, 0));
}
}
}
cnt++;
// if(cnt==10)break;
}
return -1;
}
string make_key(int x, int left)
{
return to_string(x) + "_" + to_string(left);
}
}; | 24.758621 | 106 | 0.460306 | erichuang1994 |
f7b9ee44466ed3833737d5f7c3e5ee900edc6df8 | 399 | cpp | C++ | CodeChef/Easy/E0053.cpp | Mohammed-Shoaib/HackerRank-Problems | ccfb9fc2f0d8dff454439d75ce519cf83bad7c3b | [
"MIT"
] | 54 | 2019-05-13T12:13:09.000Z | 2022-02-27T02:59:00.000Z | CodeChef/Easy/E0053.cpp | Mohammed-Shoaib/HackerRank-Problems | ccfb9fc2f0d8dff454439d75ce519cf83bad7c3b | [
"MIT"
] | 2 | 2020-10-02T07:16:43.000Z | 2020-10-19T04:36:19.000Z | CodeChef/Easy/E0053.cpp | Mohammed-Shoaib/HackerRank-Problems | ccfb9fc2f0d8dff454439d75ce519cf83bad7c3b | [
"MIT"
] | 20 | 2020-05-26T09:48:13.000Z | 2022-03-18T15:18:27.000Z | // Problem Code: J7
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
double theBestBox(int P, int S) {
double a, b, V;
a = (P - sqrt(pow(P, 2) - 24*S))/12.0;
b = (P/4.0 - 2*a);
V = pow(a, 2) * b;
return V;
}
int main(){
int T, P, S;
cout << fixed << setprecision(2);
cin >> T;
while(T--) {
cin >> P >> S;
cout << theBestBox(P, S) << endl;
}
return 0;
} | 15.346154 | 39 | 0.546366 | Mohammed-Shoaib |
f7baccebe3c3db9e5caa1ebe34234daa79056103 | 347 | cpp | C++ | Source/modio/Private/Schemas/ModioInstalledMod.cpp | rproepp/UE4Plugin | fea28dd683bce081a57f3346c74c3fee26e76ace | [
"MIT"
] | 12 | 2021-03-26T07:49:10.000Z | 2022-03-30T10:24:24.000Z | Source/modio/Private/Schemas/ModioInstalledMod.cpp | colorstheforce/modio-ue4 | 374241e232269398465cd659b41488933ba42a39 | [
"MIT"
] | 2 | 2021-07-15T16:15:33.000Z | 2021-11-14T09:18:17.000Z | Source/modio/Private/Schemas/ModioInstalledMod.cpp | colorstheforce/modio-ue4 | 374241e232269398465cd659b41488933ba42a39 | [
"MIT"
] | 2 | 2021-06-11T21:45:56.000Z | 2022-03-18T06:30:00.000Z | // Copyright 2020 modio. All Rights Reserved.
// Released under MIT.
#include "Schemas/ModioInstalledMod.h"
void InitializeInstalledMod(FModioInstalledMod &installed_mod, const ModioInstalledMod &modio_installed_mod)
{
installed_mod.Path = UTF8_TO_TCHAR(modio_installed_mod.path);
InitializeMod(installed_mod.Mod, modio_installed_mod.mod);
} | 34.7 | 108 | 0.821326 | rproepp |
f7bdc65129288c8bda92e00828a0ec72e4bf69bf | 1,682 | hpp | C++ | include/fixed_containers/string_literal.hpp | alexkaratarakis/fixed-containers | f845532e9cc5f79a651e22a679ff4a77b5e4967a | [
"MIT"
] | 32 | 2021-06-29T03:07:49.000Z | 2022-03-30T06:13:09.000Z | include/fixed_containers/string_literal.hpp | alexkaratarakis/fixed-containers | f845532e9cc5f79a651e22a679ff4a77b5e4967a | [
"MIT"
] | 1 | 2021-11-10T20:20:04.000Z | 2021-11-22T22:49:25.000Z | include/fixed_containers/string_literal.hpp | alexkaratarakis/fixed-containers | f845532e9cc5f79a651e22a679ff4a77b5e4967a | [
"MIT"
] | 4 | 2021-10-11T02:47:57.000Z | 2022-01-23T18:38:45.000Z | #pragma once
#include <cassert>
#include <cstddef>
#include <string_view>
namespace fixed_containers
{
/**
* Fully constexpr implementation of a compile-time literal null-terminated string.
* StringLiteral is trivially_copyable and standard_layout. Furthermore, all functions are
* constexpr.
*
* Compare:
* <ul>
* <li> static constexpr const char* s = "blah";
* <li> static constexpr const char s[5] = "blah"; // size 5 = 4 chars + null terminator
* <li> static constexpr StringLiteral s = "blah"; // size 4 (null-terminator is not counted)
* </ul>
*
* StringLiteral is cleaner to use, no confusion about size (null terminator), constant time
* size(), safe to use as a return type, size not hardcoded in the type (which would make it
* hard to change the string) and is implicitly convertible to std::string_view and c_str for
* convenient use in existing APIs.
*/
class StringLiteral
{
public:
template <std::size_t N>
/*implicit*/ consteval StringLiteral(const char (&str)[N]) noexcept
: size_(N - 1)
, cstr_(str)
{
assert(cstr_[N - 1] == '\0');
}
constexpr StringLiteral() noexcept
: size_(0)
, cstr_("")
{
}
[[nodiscard]] constexpr std::size_t size() const { return size_; }
[[nodiscard]] constexpr const char* c_str() const { return cstr_; }
/*implicit*/ constexpr operator const char*() const { return c_str(); }
[[nodiscard]] constexpr std::string_view as_view() const { return {cstr_, size_}; }
/*implicit*/ constexpr operator std::string_view() const { return as_view(); }
private:
std::size_t size_;
const char* cstr_;
};
} // namespace fixed_containers
| 29.508772 | 94 | 0.670036 | alexkaratarakis |
f7c3eb87e6c02fedf1319f2c1e43eaabae102c57 | 2,641 | cpp | C++ | src/galfunc/Functions.cpp | ranjeethmahankali/GeomAlgoLib | 21f1374f5a6adf8daa207999a4354ecad5254b5f | [
"Apache-2.0"
] | 9 | 2020-06-03T10:27:01.000Z | 2021-06-03T16:18:35.000Z | src/galfunc/Functions.cpp | ranjeethmahankali/GeomAlgoLib | 21f1374f5a6adf8daa207999a4354ecad5254b5f | [
"Apache-2.0"
] | null | null | null | src/galfunc/Functions.cpp | ranjeethmahankali/GeomAlgoLib | 21f1374f5a6adf8daa207999a4354ecad5254b5f | [
"Apache-2.0"
] | 2 | 2020-03-18T05:20:13.000Z | 2021-02-17T17:15:07.000Z | #include <string>
#include <boost/python/class.hpp>
#include <boost/python/import.hpp>
#include <galcore/Annotations.h>
#include <galcore/Circle2d.h>
#include <galcore/Line.h>
#include <galcore/Types.h>
#include <galcore/Util.h>
#include <galfunc/Functions.h>
#include <galfunc/MapMacro.h>
#include <galfunc/TypeHelper.h>
namespace gal {
namespace func {
namespace store {
static std::unordered_map<uint64_t, std::shared_ptr<Function>, CustomSizeTHash>
sFunctionMap;
static std::unordered_map<uint64_t,
std::vector<std::reference_wrapper<std::atomic_bool>>,
CustomSizeTHash>
sSubscriberMap;
std::shared_ptr<Function> addFunction(const std::shared_ptr<Function>& fn)
{
sFunctionMap.emplace(uint64_t(fn.get()), fn);
return fn;
};
void addSubscriber(const Function* fn, std::atomic_bool& dirtyFlag)
{
sSubscriberMap[uint64_t(fn)].push_back(dirtyFlag);
}
void markDirty(const Function* fn)
{
auto match = sSubscriberMap.find(uint64_t(fn));
if (match != sSubscriberMap.end()) {
auto& flags = std::get<1>(*match);
for (std::atomic_bool& flag : flags) {
flag = true;
}
}
}
void unloadAllFunctions()
{
std::cout << "Unloading all functions...\n";
store::sFunctionMap.clear();
}
} // namespace store
namespace python {
fs::path getcontextpath()
{
using namespace boost::python;
auto traceback = import("traceback");
auto summary = list(traceback.attr("extract_stack")());
int n = int(len(summary));
fs::path result;
fs::path filename, cfn;
std::string name;
for (int i = n - 1; i > -1; i--) {
cfn = fs::path(std::string(extract<std::string>(summary[i].attr("filename"))));
if (filename != cfn || filename.empty()) {
if (!filename.empty()) {
result = filename.stem() / result;
}
filename = cfn;
}
name = extract<std::string>(summary[i].attr("name"));
if (name != "<module>") {
result = name / result;
}
}
result = filename.stem() / result;
return result;
}
} // namespace python
// Forward declare the binding functions.
void bind_UtilFunctions();
void bind_GeomFunctions();
void bind_CircleFunctions();
void bind_SphereFunctions();
void bind_LineFunctions();
void bind_MeshFunctions();
} // namespace func
} // namespace gal
BOOST_PYTHON_MODULE(pygalfunc)
{
using namespace boost::python;
using namespace gal::func::python;
using namespace gal::func;
typemanager::invoke<defClass>();
bind_UtilFunctions();
bind_GeomFunctions();
bind_CircleFunctions();
bind_SphereFunctions();
bind_LineFunctions();
bind_MeshFunctions();
};
| 23.371681 | 83 | 0.670579 | ranjeethmahankali |
f7c4e11ab51a34b8c28c7793f568b2fb27a348c3 | 1,034 | cpp | C++ | UVa 11503 - Virtual Friends/sample/11503 - Virtual Friends.cpp | tadvi/uva | 0ac0cbdf593879b4fb02a3efc09adbb031cb47d5 | [
"MIT"
] | 1 | 2020-11-24T03:17:21.000Z | 2020-11-24T03:17:21.000Z | UVa 11503 - Virtual Friends/sample/11503 - Virtual Friends.cpp | tadvi/uva | 0ac0cbdf593879b4fb02a3efc09adbb031cb47d5 | [
"MIT"
] | null | null | null | UVa 11503 - Virtual Friends/sample/11503 - Virtual Friends.cpp | tadvi/uva | 0ac0cbdf593879b4fb02a3efc09adbb031cb47d5 | [
"MIT"
] | 1 | 2021-04-11T16:22:31.000Z | 2021-04-11T16:22:31.000Z | #include <stdio.h>
#include <map>
#include <iostream>
#include <algorithm>
using namespace std;
int r[100005], p[100005];
void init(int n) {
for(int i = 0; i <= n; i++)
r[i] = 1, p[i] = i;
}
int findp(int x) {
return p[x] == x ? x : (p[x]=findp(p[x]));
}
int joint(int x, int y) {
x = findp(x), y = findp(y);
if(x != y) {
if(r[x] > r[y]) {
r[x] += r[y], p[y] = x;
return r[x];
}
r[y] += r[x], p[x] = y;
return r[y];
}
return r[x];
}
int main() {
int t, n, tx, ty;
char x[30], y[30];
scanf("%d", &t);
while(t--) {
scanf("%d", &n);
init(min(2*n, 100000));
map<string, int> R;
int size = 0;
while(n--) {
scanf("%s %s", &x, &y);
tx = R[x];
if(tx == 0)
R[x] = ++size, tx = size;
ty = R[y];
if(ty == 0)
R[y] = ++size, ty = size;
printf("%d\n", joint(tx, ty));
}
}
return 0;
}
| 21.541667 | 46 | 0.376209 | tadvi |
f7c4e3bf0308c996f826b4fa1fb4ba17ef1a22e1 | 1,111 | cpp | C++ | src/svgdom/elements/gradients.cpp | JaimeIvanCervantes/svgdom | 8339d6d84a573cbeb0e235f4c828f4f898d67a6c | [
"MIT"
] | null | null | null | src/svgdom/elements/gradients.cpp | JaimeIvanCervantes/svgdom | 8339d6d84a573cbeb0e235f4c828f4f898d67a6c | [
"MIT"
] | null | null | null | src/svgdom/elements/gradients.cpp | JaimeIvanCervantes/svgdom | 8339d6d84a573cbeb0e235f4c828f4f898d67a6c | [
"MIT"
] | null | null | null | #include "gradients.hpp"
#include <utki/debug.hpp>
#include "../util.hxx"
#include "../visitor.hpp"
using namespace svgdom;
const std::string gradient::stop_element::tag = "stop";
const std::string linear_gradient_element::tag = "linearGradient";
const std::string radial_gradient_element::tag = "radialGradient";
void radial_gradient_element::accept(visitor& v){
v.visit(*this);
}
void radial_gradient_element::accept(const_visitor& v) const {
v.visit(*this);
}
void linear_gradient_element::accept(visitor& v){
v.visit(*this);
}
void linear_gradient_element::accept(const_visitor& v) const {
v.visit(*this);
}
void gradient::stop_element::accept(visitor& v){
v.visit(*this);
}
void gradient::stop_element::accept(const_visitor& v) const {
v.visit(*this);
}
std::string gradient::spread_method_to_string() const {
switch(this->spread_method_){
default:
case gradient::spread_method::default_:
return "";
case gradient::spread_method::pad:
return "pad";
case gradient::spread_method::reflect:
return "reflect";
case gradient::spread_method::repeat:
return "repeat";
}
}
| 21.784314 | 66 | 0.729973 | JaimeIvanCervantes |
f7c52caee377985e78b6f39eeea27ff6b7251b1c | 420 | cpp | C++ | Engine/Source/Editor/UnrealEd/Private/SoundCueGraph.cpp | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | null | null | null | Engine/Source/Editor/UnrealEd/Private/SoundCueGraph.cpp | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | 2 | 2015-06-21T17:38:11.000Z | 2015-06-22T20:54:42.000Z | Engine/Source/Editor/UnrealEd/Private/SoundCueGraph.cpp | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | null | null | null | // Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
/////////////////////////////////////////////////////
// USoundCueGraph
#include "UnrealEd.h"
#include "SoundDefinitions.h"
#include "Sound/SoundCue.h"
USoundCueGraph::USoundCueGraph(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
}
USoundCue* USoundCueGraph::GetSoundCue() const
{
return CastChecked<USoundCue>(GetOuter());
}
| 22.105263 | 75 | 0.67619 | PopCap |
f7c7864fc4a01ff355ded3d2c7f3d68fca70942b | 930 | hpp | C++ | include/t9/timer.hpp | yweweler/cpp-t9 | 179e58c473f95fc84edc45f7f69392b40eb047c0 | [
"MIT"
] | 1 | 2019-09-22T08:08:14.000Z | 2019-09-22T08:08:14.000Z | include/t9/timer.hpp | yweweler/cpp-t9 | 179e58c473f95fc84edc45f7f69392b40eb047c0 | [
"MIT"
] | 1 | 2019-03-29T12:19:23.000Z | 2019-03-29T12:19:23.000Z | include/t9/timer.hpp | yweweler/cpp-t9 | 179e58c473f95fc84edc45f7f69392b40eb047c0 | [
"MIT"
] | null | null | null | // T9 performance profiling timers -*- C++ -*-
// Copyright (C) 2019 Yves-Noel Weweler.
// All Rights Reserved.
//
// Licensed under the MIT License.
// See LICENSE file in the project root for full license information.
#ifndef CPP_T9_TIMER_HPP
#define CPP_T9_TIMER_HPP
#include <iostream>
#include <chrono>
using namespace std::chrono;
namespace t9 {
class timer {
public:
/**
* Start a timer.
*/
void start();
/**
* Stop a timer.
*/
void stop();
/**
* Restart a timer. The timer gets reinitialized and starts.
*/
void restart();
/**
* Query the elapsed time in milliseconds.
* @note The timer has to be stopped manually before querying the elapsed duration.
* @return Elapsed duration in milliseconds.
*/
double duration_ms() const;
protected:
high_resolution_clock::time_point start_time;
high_resolution_clock::time_point stop_time;
};
}
#endif //CPP_T9_TIMER_HPP
| 18.979592 | 85 | 0.689247 | yweweler |
f7c842142c324965ab1574612727cd99a68a97ad | 2,418 | cpp | C++ | CsPlugin/Source/CsCore/Public/Managers/Sense/CsSenseInfo.cpp | closedsum/core | c3cae44a177b9684585043a275130f9c7b67fef0 | [
"Unlicense"
] | 2 | 2019-03-17T10:43:53.000Z | 2021-04-20T21:24:19.000Z | CsPlugin/Source/CsCore/Public/Managers/Sense/CsSenseInfo.cpp | closedsum/core | c3cae44a177b9684585043a275130f9c7b67fef0 | [
"Unlicense"
] | null | null | null | CsPlugin/Source/CsCore/Public/Managers/Sense/CsSenseInfo.cpp | closedsum/core | c3cae44a177b9684585043a275130f9c7b67fef0 | [
"Unlicense"
] | null | null | null | // Copyright 2017-2021 Closed Sum Games, LLC. All Rights Reserved.
#include "Managers/Sense/CsSenseInfo.h"
#include "CsCore.h"
#include "Managers/Sense/CsSensingObject.h"
// ICsSenseInfo
#pragma region
const FCsSensedObject& FCsSenseInfo::GetObject() const
{
return Object;
}
void FCsSenseInfo::SetObject(ICsSensedObject* InSenseObject, UObject* InObject)
{
Object.SetInterface(InSenseObject);
Object.SetObject(InObject);
}
#pragma endregion ICsSenseInfo
void FCsSenseInfo::Update(const float& CurrentTime, ICsSensingObject* SensingObject)
{
ICsSensedObject* SensedObject = Object.GetInterface();
for (TPair<FCsSenseInfoKey, FCsSenseInfoValue>& Pair : Data)
{
const FCsSenseInfoKey& Key = Pair.Key;
FCsSenseInfoValue& Value = Pair.Value;
FVector& MeToObject = Value.MeToObject;
float& Distance = Value.Distance;
float& DistanceSq = Value.DistanceSq;
float& DistanceXY = Value.DistanceXY;
float& DistanceSqXY = Value.DistanceSqXY;
FVector& Direction = Value.Direction;
FVector& DirectionXY = Value.DirectionXY;
float& Dot = Value.Dot;
float& DotXY = Value.DotXY;
const FVector FromLocation = SensingObject->GetCustomLocation(Key.From);
const FVector ToLocation = SensedObject->GetCustomLocation(Key.To);
MeToObject = ToLocation - FromLocation;
// Distance
DistanceSqXY = MeToObject.SizeSquared2D();
DistanceSq = DistanceSqXY + FMath::Square(MeToObject.Z);
Distance = FMath::Sqrt(DistanceSq);
DistanceXY = FMath::Sqrt(DistanceSqXY);
// Direction
Direction = MeToObject;
{
if (DistanceSq == 1.f)
{
// Do Nothing
}
else
if (DistanceSq < SMALL_NUMBER)
{
Direction = FVector::ZeroVector;
}
else
{
const float Scale = FMath::InvSqrt(DistanceSq);
Direction *= Scale;
}
}
DirectionXY = MeToObject;
DirectionXY.Z = 0.0f;
{
if (DistanceSqXY == 1.f)
{
// Do Nothing
}
else
if (DistanceSqXY < SMALL_NUMBER)
{
DirectionXY = FVector::ZeroVector;
}
else
{
const float Scale = FMath::InvSqrt(DistanceSqXY);
DirectionXY *= Scale;
}
}
// Dot
const FVector DotDirection = SensingObject->GetCustomDirection(Key.Direction);
if (DotDirection != FVector::ZeroVector)
{
Dot = FVector::DotProduct(DotDirection, Direction);
DotXY = DotDirection.X * Direction.X + DotDirection.Y * Direction.Y;
}
else
{
Dot = 0.0f;
DotXY = 0.0f;
}
}
} | 23.940594 | 84 | 0.696857 | closedsum |
f7c88deaa67ea3c09d7696b87401ea312e7601b9 | 63,244 | cpp | C++ | src/js/frontend/FoldConstants.cpp | fengjixuchui/blazefox | d5c732ac7305a79fe20704c2d134c130f14eca83 | [
"MIT"
] | 149 | 2018-12-23T09:08:00.000Z | 2022-02-02T09:18:38.000Z | src/js/frontend/FoldConstants.cpp | fengjixuchui/blazefox | d5c732ac7305a79fe20704c2d134c130f14eca83 | [
"MIT"
] | null | null | null | src/js/frontend/FoldConstants.cpp | fengjixuchui/blazefox | d5c732ac7305a79fe20704c2d134c130f14eca83 | [
"MIT"
] | 56 | 2018-12-23T18:11:40.000Z | 2021-11-30T13:18:17.000Z | /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
* vim: set ts=8 sts=4 et sw=4 tw=99:
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "frontend/FoldConstants.h"
#include "mozilla/FloatingPoint.h"
#include "jslibmath.h"
#include "jsnum.h"
#include "frontend/ParseNode.h"
#include "frontend/Parser.h"
#include "js/Conversions.h"
#include "vm/StringType.h"
using namespace js;
using namespace js::frontend;
using mozilla::IsNaN;
using mozilla::IsNegative;
using mozilla::NegativeInfinity;
using mozilla::PositiveInfinity;
using JS::GenericNaN;
using JS::ToInt32;
using JS::ToUint32;
static bool
ContainsHoistedDeclaration(JSContext* cx, ParseNode* node, bool* result);
static bool
ListContainsHoistedDeclaration(JSContext* cx, ListNode* list, bool* result)
{
for (ParseNode* node : list->contents()) {
if (!ContainsHoistedDeclaration(cx, node, result)) {
return false;
}
if (*result) {
return true;
}
}
*result = false;
return true;
}
// Determines whether the given ParseNode contains any declarations whose
// visibility will extend outside the node itself -- that is, whether the
// ParseNode contains any var statements.
//
// THIS IS NOT A GENERAL-PURPOSE FUNCTION. It is only written to work in the
// specific context of deciding that |node|, as one arm of a ParseNodeKind::If
// controlled by a constant condition, contains a declaration that forbids
// |node| being completely eliminated as dead.
static bool
ContainsHoistedDeclaration(JSContext* cx, ParseNode* node, bool* result)
{
if (!CheckRecursionLimit(cx)) {
return false;
}
restart:
// With a better-typed AST, we would have distinct parse node classes for
// expressions and for statements and would characterize expressions with
// ExpressionKind and statements with StatementKind. Perhaps someday. In
// the meantime we must characterize every ParseNodeKind, even the
// expression/sub-expression ones that, if we handle all statement kinds
// correctly, we'll never see.
switch (node->getKind()) {
// Base case.
case ParseNodeKind::Var:
*result = true;
return true;
// Non-global lexical declarations are block-scoped (ergo not hoistable).
case ParseNodeKind::Let:
case ParseNodeKind::Const:
MOZ_ASSERT(node->is<ListNode>());
*result = false;
return true;
// Similarly to the lexical declarations above, classes cannot add hoisted
// declarations
case ParseNodeKind::Class:
MOZ_ASSERT(node->is<ClassNode>());
*result = false;
return true;
// Function declarations *can* be hoisted declarations. But in the
// magical world of the rewritten frontend, the declaration necessitated
// by a nested function statement, not at body level, doesn't require
// that we preserve an unreachable function declaration node against
// dead-code removal.
case ParseNodeKind::Function:
MOZ_ASSERT(node->is<CodeNode>());
*result = false;
return true;
case ParseNodeKind::Module:
*result = false;
return true;
// Statements with no sub-components at all.
case ParseNodeKind::EmptyStatement:
MOZ_ASSERT(node->is<NullaryNode>());
*result = false;
return true;
case ParseNodeKind::Debugger:
MOZ_ASSERT(node->is<DebuggerStatement>());
*result = false;
return true;
// Statements containing only an expression have no declarations.
case ParseNodeKind::ExpressionStatement:
case ParseNodeKind::Throw:
case ParseNodeKind::Return:
MOZ_ASSERT(node->is<UnaryNode>());
*result = false;
return true;
// These two aren't statements in the spec, but we sometimes insert them
// in statement lists anyway.
case ParseNodeKind::InitialYield:
case ParseNodeKind::YieldStar:
case ParseNodeKind::Yield:
MOZ_ASSERT(node->is<UnaryNode>());
*result = false;
return true;
// Other statements with no sub-statement components.
case ParseNodeKind::Break:
case ParseNodeKind::Continue:
case ParseNodeKind::Import:
case ParseNodeKind::ImportSpecList:
case ParseNodeKind::ImportSpec:
case ParseNodeKind::ExportFrom:
case ParseNodeKind::ExportDefault:
case ParseNodeKind::ExportSpecList:
case ParseNodeKind::ExportSpec:
case ParseNodeKind::Export:
case ParseNodeKind::ExportBatchSpec:
case ParseNodeKind::CallImport:
*result = false;
return true;
// Statements possibly containing hoistable declarations only in the left
// half, in ParseNode terms -- the loop body in AST terms.
case ParseNodeKind::DoWhile:
return ContainsHoistedDeclaration(cx, node->as<BinaryNode>().left(), result);
// Statements possibly containing hoistable declarations only in the
// right half, in ParseNode terms -- the loop body or nested statement
// (usually a block statement), in AST terms.
case ParseNodeKind::While:
case ParseNodeKind::With:
return ContainsHoistedDeclaration(cx, node->as<BinaryNode>().right(), result);
case ParseNodeKind::Label:
return ContainsHoistedDeclaration(cx, node->as<LabeledStatement>().statement(), result);
// Statements with more complicated structures.
// if-statement nodes may have hoisted declarations in their consequent
// and alternative components.
case ParseNodeKind::If: {
TernaryNode* ifNode = &node->as<TernaryNode>();
ParseNode* consequent = ifNode->kid2();
if (!ContainsHoistedDeclaration(cx, consequent, result)) {
return false;
}
if (*result) {
return true;
}
if ((node = ifNode->kid3())) {
goto restart;
}
*result = false;
return true;
}
// try-statements have statements to execute, and one or both of a
// catch-list and a finally-block.
case ParseNodeKind::Try: {
TernaryNode* tryNode = &node->as<TernaryNode>();
MOZ_ASSERT(tryNode->kid2() || tryNode->kid3(),
"must have either catch or finally");
ParseNode* tryBlock = tryNode->kid1();
if (!ContainsHoistedDeclaration(cx, tryBlock, result)) {
return false;
}
if (*result) {
return true;
}
if (ParseNode* catchScope = tryNode->kid2()) {
BinaryNode* catchNode =
&catchScope->as<LexicalScopeNode>().scopeBody()->as<BinaryNode>();
MOZ_ASSERT(catchNode->isKind(ParseNodeKind::Catch));
ParseNode* catchStatements = catchNode->right();
if (!ContainsHoistedDeclaration(cx, catchStatements, result)) {
return false;
}
if (*result) {
return true;
}
}
if (ParseNode* finallyBlock = tryNode->kid3()) {
return ContainsHoistedDeclaration(cx, finallyBlock, result);
}
*result = false;
return true;
}
// A switch node's left half is an expression; only its right half (a
// list of cases/defaults, or a block node) could contain hoisted
// declarations.
case ParseNodeKind::Switch: {
SwitchStatement* switchNode = &node->as<SwitchStatement>();
return ContainsHoistedDeclaration(cx, &switchNode->lexicalForCaseList(), result);
}
case ParseNodeKind::Case: {
CaseClause* caseClause = &node->as<CaseClause>();
return ContainsHoistedDeclaration(cx, caseClause->statementList(), result);
}
case ParseNodeKind::For: {
ForNode* forNode = &node->as<ForNode>();
TernaryNode* loopHead = forNode->head();
MOZ_ASSERT(loopHead->isKind(ParseNodeKind::ForHead) ||
loopHead->isKind(ParseNodeKind::ForIn) ||
loopHead->isKind(ParseNodeKind::ForOf));
if (loopHead->isKind(ParseNodeKind::ForHead)) {
// for (init?; cond?; update?), with only init possibly containing
// a hoisted declaration. (Note: a lexical-declaration |init| is
// (at present) hoisted in SpiderMonkey parlance -- but such
// hoisting doesn't extend outside of this statement, so it is not
// hoisting in the sense meant by ContainsHoistedDeclaration.)
ParseNode* init = loopHead->kid1();
if (init && init->isKind(ParseNodeKind::Var)) {
*result = true;
return true;
}
} else {
MOZ_ASSERT(loopHead->isKind(ParseNodeKind::ForIn) ||
loopHead->isKind(ParseNodeKind::ForOf));
// for each? (target in ...), where only target may introduce
// hoisted declarations.
//
// -- or --
//
// for (target of ...), where only target may introduce hoisted
// declarations.
//
// Either way, if |target| contains a declaration, it's |loopHead|'s
// first kid.
ParseNode* decl = loopHead->kid1();
if (decl && decl->isKind(ParseNodeKind::Var)) {
*result = true;
return true;
}
}
ParseNode* loopBody = forNode->body();
return ContainsHoistedDeclaration(cx, loopBody, result);
}
case ParseNodeKind::LexicalScope: {
LexicalScopeNode* scope = &node->as<LexicalScopeNode>();
ParseNode* expr = scope->scopeBody();
if (expr->isKind(ParseNodeKind::For) || expr->isKind(ParseNodeKind::Function)) {
return ContainsHoistedDeclaration(cx, expr, result);
}
MOZ_ASSERT(expr->isKind(ParseNodeKind::StatementList));
return ListContainsHoistedDeclaration(cx, &scope->scopeBody()->as<ListNode>(), result);
}
// List nodes with all non-null children.
case ParseNodeKind::StatementList:
return ListContainsHoistedDeclaration(cx, &node->as<ListNode>(), result);
// Grammar sub-components that should never be reached directly by this
// method, because some parent component should have asserted itself.
case ParseNodeKind::ObjectPropertyName:
case ParseNodeKind::ComputedName:
case ParseNodeKind::Spread:
case ParseNodeKind::MutateProto:
case ParseNodeKind::Colon:
case ParseNodeKind::Shorthand:
case ParseNodeKind::Conditional:
case ParseNodeKind::TypeOfName:
case ParseNodeKind::TypeOfExpr:
case ParseNodeKind::Await:
case ParseNodeKind::Void:
case ParseNodeKind::Not:
case ParseNodeKind::BitNot:
case ParseNodeKind::DeleteName:
case ParseNodeKind::DeleteProp:
case ParseNodeKind::DeleteElem:
case ParseNodeKind::DeleteExpr:
case ParseNodeKind::Pos:
case ParseNodeKind::Neg:
case ParseNodeKind::PreIncrement:
case ParseNodeKind::PostIncrement:
case ParseNodeKind::PreDecrement:
case ParseNodeKind::PostDecrement:
case ParseNodeKind::Or:
case ParseNodeKind::And:
case ParseNodeKind::BitOr:
case ParseNodeKind::BitXor:
case ParseNodeKind::BitAnd:
case ParseNodeKind::StrictEq:
case ParseNodeKind::Eq:
case ParseNodeKind::StrictNe:
case ParseNodeKind::Ne:
case ParseNodeKind::Lt:
case ParseNodeKind::Le:
case ParseNodeKind::Gt:
case ParseNodeKind::Ge:
case ParseNodeKind::InstanceOf:
case ParseNodeKind::In:
case ParseNodeKind::Lsh:
case ParseNodeKind::Rsh:
case ParseNodeKind::Ursh:
case ParseNodeKind::Add:
case ParseNodeKind::Sub:
case ParseNodeKind::Star:
case ParseNodeKind::Div:
case ParseNodeKind::Mod:
case ParseNodeKind::Pow:
case ParseNodeKind::Assign:
case ParseNodeKind::AddAssign:
case ParseNodeKind::SubAssign:
case ParseNodeKind::BitOrAssign:
case ParseNodeKind::BitXorAssign:
case ParseNodeKind::BitAndAssign:
case ParseNodeKind::LshAssign:
case ParseNodeKind::RshAssign:
case ParseNodeKind::UrshAssign:
case ParseNodeKind::MulAssign:
case ParseNodeKind::DivAssign:
case ParseNodeKind::ModAssign:
case ParseNodeKind::PowAssign:
case ParseNodeKind::Comma:
case ParseNodeKind::Array:
case ParseNodeKind::Object:
case ParseNodeKind::PropertyName:
case ParseNodeKind::Dot:
case ParseNodeKind::Elem:
case ParseNodeKind::Arguments:
case ParseNodeKind::Call:
case ParseNodeKind::Name:
case ParseNodeKind::TemplateString:
case ParseNodeKind::TemplateStringList:
case ParseNodeKind::TaggedTemplate:
case ParseNodeKind::CallSiteObj:
case ParseNodeKind::String:
case ParseNodeKind::RegExp:
case ParseNodeKind::True:
case ParseNodeKind::False:
case ParseNodeKind::Null:
case ParseNodeKind::RawUndefined:
case ParseNodeKind::This:
case ParseNodeKind::Elision:
case ParseNodeKind::Number:
case ParseNodeKind::New:
case ParseNodeKind::Generator:
case ParseNodeKind::ParamsBody:
case ParseNodeKind::Catch:
case ParseNodeKind::ForIn:
case ParseNodeKind::ForOf:
case ParseNodeKind::ForHead:
case ParseNodeKind::ClassMethod:
case ParseNodeKind::ClassMethodList:
case ParseNodeKind::ClassNames:
case ParseNodeKind::NewTarget:
case ParseNodeKind::ImportMeta:
case ParseNodeKind::PosHolder:
case ParseNodeKind::SuperCall:
case ParseNodeKind::SuperBase:
case ParseNodeKind::SetThis:
MOZ_CRASH("ContainsHoistedDeclaration should have indicated false on "
"some parent node without recurring to test this node");
case ParseNodeKind::Pipeline:
MOZ_ASSERT(node->is<ListNode>());
*result = false;
return true;
case ParseNodeKind::Limit: // invalid sentinel value
MOZ_CRASH("unexpected ParseNodeKind::Limit in node");
}
MOZ_CRASH("invalid node kind");
}
/*
* Fold from one constant type to another.
* XXX handles only strings and numbers for now
*/
static bool
FoldType(JSContext* cx, ParseNode* pn, ParseNodeKind kind)
{
if (!pn->isKind(kind)) {
switch (kind) {
case ParseNodeKind::Number:
if (pn->isKind(ParseNodeKind::String)) {
double d;
if (!StringToNumber(cx, pn->as<NameNode>().atom(), &d)) {
return false;
}
pn->setKind(ParseNodeKind::Number);
pn->setArity(PN_NUMBER);
pn->setOp(JSOP_DOUBLE);
pn->as<NumericLiteral>().setValue(d);
}
break;
case ParseNodeKind::String:
if (pn->isKind(ParseNodeKind::Number)) {
JSAtom* atom = NumberToAtom(cx, pn->as<NumericLiteral>().value());
if (!atom) {
return false;
}
pn->setKind(ParseNodeKind::String);
pn->setArity(PN_NAME);
pn->setOp(JSOP_STRING);
pn->as<NameNode>().setAtom(atom);
}
break;
default:;
}
}
return true;
}
// Remove a ParseNode, **pnp, from a parse tree, putting another ParseNode,
// *pn, in its place.
//
// pnp points to a ParseNode pointer. This must be the only pointer that points
// to the parse node being replaced. The replacement, *pn, is unchanged except
// for its pn_next pointer; updating that is necessary if *pn's new parent is a
// list node.
static void
ReplaceNode(ParseNode** pnp, ParseNode* pn)
{
pn->pn_next = (*pnp)->pn_next;
*pnp = pn;
}
static bool
IsEffectless(ParseNode* node)
{
return node->isKind(ParseNodeKind::True) ||
node->isKind(ParseNodeKind::False) ||
node->isKind(ParseNodeKind::String) ||
node->isKind(ParseNodeKind::TemplateString) ||
node->isKind(ParseNodeKind::Number) ||
node->isKind(ParseNodeKind::Null) ||
node->isKind(ParseNodeKind::RawUndefined) ||
node->isKind(ParseNodeKind::Function);
}
enum Truthiness { Truthy, Falsy, Unknown };
static Truthiness
Boolish(ParseNode* pn)
{
switch (pn->getKind()) {
case ParseNodeKind::Number:
return (pn->as<NumericLiteral>().value() != 0 && !IsNaN(pn->as<NumericLiteral>().value())) ? Truthy : Falsy;
case ParseNodeKind::String:
case ParseNodeKind::TemplateString:
return (pn->as<NameNode>().atom()->length() > 0) ? Truthy : Falsy;
case ParseNodeKind::True:
case ParseNodeKind::Function:
return Truthy;
case ParseNodeKind::False:
case ParseNodeKind::Null:
case ParseNodeKind::RawUndefined:
return Falsy;
case ParseNodeKind::Void: {
// |void <foo>| evaluates to |undefined| which isn't truthy. But the
// sense of this method requires that the expression be literally
// replaceable with true/false: not the case if the nested expression
// is effectful, might throw, &c. Walk past the |void| (and nested
// |void| expressions, for good measure) and check that the nested
// expression doesn't break this requirement before indicating falsity.
do {
pn = pn->as<UnaryNode>().kid();
} while (pn->isKind(ParseNodeKind::Void));
return IsEffectless(pn) ? Falsy : Unknown;
}
default:
return Unknown;
}
}
static bool
Fold(JSContext* cx, ParseNode** pnp, PerHandlerParser<FullParseHandler>& parser);
static bool
FoldCondition(JSContext* cx, ParseNode** nodePtr, PerHandlerParser<FullParseHandler>& parser)
{
// Conditions fold like any other expression...
if (!Fold(cx, nodePtr, parser)) {
return false;
}
// ...but then they sometimes can be further folded to constants.
ParseNode* node = *nodePtr;
Truthiness t = Boolish(node);
if (t != Unknown) {
// We can turn function nodes into constant nodes here, but mutating
// function nodes is tricky --- in particular, mutating a function node
// that appears on a method list corrupts the method list. However,
// methods are M's in statements of the form 'this.foo = M;', which we
// never fold, so we're okay.
if (t == Truthy) {
node->setKind(ParseNodeKind::True);
node->setOp(JSOP_TRUE);
} else {
node->setKind(ParseNodeKind::False);
node->setOp(JSOP_FALSE);
}
node->setArity(PN_NULLARY);
}
return true;
}
static bool
FoldTypeOfExpr(JSContext* cx, UnaryNode* node, PerHandlerParser<FullParseHandler>& parser)
{
MOZ_ASSERT(node->isKind(ParseNodeKind::TypeOfExpr));
if (!Fold(cx, node->unsafeKidReference(), parser)) {
return false;
}
ParseNode* expr = node->kid();
// Constant-fold the entire |typeof| if given a constant with known type.
RootedPropertyName result(cx);
if (expr->isKind(ParseNodeKind::String) || expr->isKind(ParseNodeKind::TemplateString)) {
result = cx->names().string;
} else if (expr->isKind(ParseNodeKind::Number)) {
result = cx->names().number;
} else if (expr->isKind(ParseNodeKind::Null)) {
result = cx->names().object;
} else if (expr->isKind(ParseNodeKind::True) || expr->isKind(ParseNodeKind::False)) {
result = cx->names().boolean;
} else if (expr->isKind(ParseNodeKind::Function)) {
result = cx->names().function;
}
if (result) {
node->setKind(ParseNodeKind::String);
node->setArity(PN_NAME);
node->setOp(JSOP_NOP);
node->as<NameNode>().setAtom(result);
}
return true;
}
static bool
FoldDeleteExpr(JSContext* cx, UnaryNode* node, PerHandlerParser<FullParseHandler>& parser)
{
MOZ_ASSERT(node->isKind(ParseNodeKind::DeleteExpr));
if (!Fold(cx, node->unsafeKidReference(), parser)) {
return false;
}
ParseNode* expr = node->kid();
// Expression deletion evaluates the expression, then evaluates to true.
// For effectless expressions, eliminate the expression evaluation.
if (IsEffectless(expr)) {
node->setKind(ParseNodeKind::True);
node->setArity(PN_NULLARY);
node->setOp(JSOP_TRUE);
}
return true;
}
static bool
FoldDeleteElement(JSContext* cx, UnaryNode* node, PerHandlerParser<FullParseHandler>& parser)
{
MOZ_ASSERT(node->isKind(ParseNodeKind::DeleteElem));
MOZ_ASSERT(node->kid()->isKind(ParseNodeKind::Elem));
if (!Fold(cx, node->unsafeKidReference(), parser)) {
return false;
}
ParseNode* expr = node->kid();
// If we're deleting an element, but constant-folding converted our
// element reference into a dotted property access, we must *also*
// morph the node's kind.
//
// In principle this also applies to |super["foo"] -> super.foo|,
// but we don't constant-fold |super["foo"]| yet.
MOZ_ASSERT(expr->isKind(ParseNodeKind::Elem) || expr->isKind(ParseNodeKind::Dot));
if (expr->isKind(ParseNodeKind::Dot)) {
node->setKind(ParseNodeKind::DeleteProp);
}
return true;
}
static bool
FoldDeleteProperty(JSContext* cx, UnaryNode* node, PerHandlerParser<FullParseHandler>& parser)
{
MOZ_ASSERT(node->isKind(ParseNodeKind::DeleteProp));
MOZ_ASSERT(node->kid()->isKind(ParseNodeKind::Dot));
#ifdef DEBUG
ParseNodeKind oldKind = node->kid()->getKind();
#endif
if (!Fold(cx, node->unsafeKidReference(), parser)) {
return false;
}
MOZ_ASSERT(node->kid()->isKind(oldKind),
"kind should have remained invariant under folding");
return true;
}
static bool
FoldNot(JSContext* cx, UnaryNode* node, PerHandlerParser<FullParseHandler>& parser)
{
MOZ_ASSERT(node->isKind(ParseNodeKind::Not));
if (!FoldCondition(cx, node->unsafeKidReference(), parser)) {
return false;
}
ParseNode* expr = node->kid();
if (expr->isKind(ParseNodeKind::Number)) {
double d = expr->as<NumericLiteral>().value();
if (d == 0 || IsNaN(d)) {
node->setKind(ParseNodeKind::True);
node->setOp(JSOP_TRUE);
} else {
node->setKind(ParseNodeKind::False);
node->setOp(JSOP_FALSE);
}
node->setArity(PN_NULLARY);
} else if (expr->isKind(ParseNodeKind::True) || expr->isKind(ParseNodeKind::False)) {
bool newval = !expr->isKind(ParseNodeKind::True);
node->setKind(newval ? ParseNodeKind::True : ParseNodeKind::False);
node->setArity(PN_NULLARY);
node->setOp(newval ? JSOP_TRUE : JSOP_FALSE);
}
return true;
}
static bool
FoldUnaryArithmetic(JSContext* cx, UnaryNode* node, PerHandlerParser<FullParseHandler>& parser)
{
MOZ_ASSERT(node->isKind(ParseNodeKind::BitNot) ||
node->isKind(ParseNodeKind::Pos) ||
node->isKind(ParseNodeKind::Neg),
"need a different method for this node kind");
if (!Fold(cx, node->unsafeKidReference(), parser)) {
return false;
}
ParseNode* expr = node->kid();
if (expr->isKind(ParseNodeKind::Number) ||
expr->isKind(ParseNodeKind::True) ||
expr->isKind(ParseNodeKind::False))
{
double d = expr->isKind(ParseNodeKind::Number)
? expr->as<NumericLiteral>().value()
: double(expr->isKind(ParseNodeKind::True));
if (node->isKind(ParseNodeKind::BitNot)) {
d = ~ToInt32(d);
} else if (node->isKind(ParseNodeKind::Neg)) {
d = -d;
} else {
MOZ_ASSERT(node->isKind(ParseNodeKind::Pos)); // nothing to do
}
node->setKind(ParseNodeKind::Number);
node->setArity(PN_NUMBER);
node->setOp(JSOP_DOUBLE);
node->as<NumericLiteral>().setValue(d);
}
return true;
}
static bool
FoldIncrementDecrement(JSContext* cx, UnaryNode* incDec,
PerHandlerParser<FullParseHandler>& parser)
{
MOZ_ASSERT(incDec->isKind(ParseNodeKind::PreIncrement) ||
incDec->isKind(ParseNodeKind::PostIncrement) ||
incDec->isKind(ParseNodeKind::PreDecrement) ||
incDec->isKind(ParseNodeKind::PostDecrement));
MOZ_ASSERT(parser.isValidSimpleAssignmentTarget(incDec->kid(),
PermitAssignmentToFunctionCalls));
if (!Fold(cx, incDec->unsafeKidReference(), parser)) {
return false;
}
MOZ_ASSERT(parser.isValidSimpleAssignmentTarget(incDec->kid(),
PermitAssignmentToFunctionCalls));
return true;
}
static bool
FoldAndOr(JSContext* cx, ParseNode** nodePtr, PerHandlerParser<FullParseHandler>& parser)
{
ListNode* node = &(*nodePtr)->as<ListNode>();
MOZ_ASSERT(node->isKind(ParseNodeKind::And) || node->isKind(ParseNodeKind::Or));
bool isOrNode = node->isKind(ParseNodeKind::Or);
ParseNode** elem = node->unsafeHeadReference();
do {
if (!Fold(cx, elem, parser)) {
return false;
}
Truthiness t = Boolish(*elem);
// If we don't know the constant-folded node's truthiness, we can't
// reduce this node with its surroundings. Continue folding any
// remaining nodes.
if (t == Unknown) {
elem = &(*elem)->pn_next;
continue;
}
// If the constant-folded node's truthiness will terminate the
// condition -- `a || true || expr` or |b && false && expr| -- then
// trailing nodes will never be evaluated. Truncate the list after
// the known-truthiness node, as it's the overall result.
if ((t == Truthy) == isOrNode) {
for (ParseNode* next = (*elem)->pn_next; next; next = next->pn_next) {
node->unsafeDecrementCount();
}
// Terminate the original and/or list at the known-truthiness
// node.
(*elem)->pn_next = nullptr;
elem = &(*elem)->pn_next;
break;
}
MOZ_ASSERT((t == Truthy) == !isOrNode);
// We've encountered a vacuous node that'll never short-circuit
// evaluation.
if ((*elem)->pn_next) {
// This node is never the overall result when there are
// subsequent nodes. Remove it.
ParseNode* elt = *elem;
*elem = elt->pn_next;
node->unsafeDecrementCount();
} else {
// Otherwise this node is the result of the overall expression,
// so leave it alone. And we're done.
elem = &(*elem)->pn_next;
break;
}
} while (*elem);
node->unsafeReplaceTail(elem);
// If we removed nodes, we may have to replace a one-element list with
// its element.
if (node->count() == 1) {
ParseNode* first = node->head();
ReplaceNode(nodePtr, first);
}
return true;
}
static bool
FoldConditional(JSContext* cx, ParseNode** nodePtr, PerHandlerParser<FullParseHandler>& parser)
{
ParseNode** nextNode = nodePtr;
do {
// |nextNode| on entry points to the C?T:F expression to be folded.
// Reset it to exit the loop in the common case where F isn't another
// ?: expression.
nodePtr = nextNode;
nextNode = nullptr;
TernaryNode* node = &(*nodePtr)->as<TernaryNode>();
MOZ_ASSERT(node->isKind(ParseNodeKind::Conditional));
ParseNode** expr = node->unsafeKid1Reference();
if (!FoldCondition(cx, expr, parser)) {
return false;
}
ParseNode** ifTruthy = node->unsafeKid2Reference();
if (!Fold(cx, ifTruthy, parser)) {
return false;
}
ParseNode** ifFalsy = node->unsafeKid3Reference();
// If our C?T:F node has F as another ?: node, *iteratively* constant-
// fold F *after* folding C and T (and possibly eliminating C and one
// of T/F entirely); otherwise fold F normally. Making |nextNode| non-
// null causes this loop to run again to fold F.
//
// Conceivably we could instead/also iteratively constant-fold T, if T
// were more complex than F. Such an optimization is unimplemented.
if ((*ifFalsy)->isKind(ParseNodeKind::Conditional)) {
MOZ_ASSERT((*ifFalsy)->is<TernaryNode>());
nextNode = ifFalsy;
} else {
if (!Fold(cx, ifFalsy, parser)) {
return false;
}
}
// Try to constant-fold based on the condition expression.
Truthiness t = Boolish(*expr);
if (t == Unknown) {
continue;
}
// Otherwise reduce 'C ? T : F' to T or F as directed by C.
ParseNode* replacement = t == Truthy ? *ifTruthy : *ifFalsy;
// Otherwise perform a replacement. This invalidates |nextNode|, so
// reset it (if the replacement requires folding) or clear it (if
// |ifFalsy| is dead code) as needed.
if (nextNode) {
nextNode = (*nextNode == replacement) ? nodePtr : nullptr;
}
ReplaceNode(nodePtr, replacement);
} while (nextNode);
return true;
}
static bool
FoldIf(JSContext* cx, ParseNode** nodePtr, PerHandlerParser<FullParseHandler>& parser)
{
ParseNode** nextNode = nodePtr;
do {
// |nextNode| on entry points to the initial |if| to be folded. Reset
// it to exit the loop when the |else| arm isn't another |if|.
nodePtr = nextNode;
nextNode = nullptr;
TernaryNode* node = &(*nodePtr)->as<TernaryNode>();
MOZ_ASSERT(node->isKind(ParseNodeKind::If));
ParseNode** expr = node->unsafeKid1Reference();
if (!FoldCondition(cx, expr, parser)) {
return false;
}
ParseNode** consequent = node->unsafeKid2Reference();
if (!Fold(cx, consequent, parser)) {
return false;
}
ParseNode** alternative = node->unsafeKid3Reference();
if (*alternative) {
// If in |if (C) T; else F;| we have |F| as another |if|,
// *iteratively* constant-fold |F| *after* folding |C| and |T| (and
// possibly completely replacing the whole thing with |T| or |F|);
// otherwise fold F normally. Making |nextNode| non-null causes
// this loop to run again to fold F.
if ((*alternative)->isKind(ParseNodeKind::If)) {
MOZ_ASSERT((*alternative)->is<TernaryNode>());
nextNode = alternative;
} else {
if (!Fold(cx, alternative, parser)) {
return false;
}
}
}
// Eliminate the consequent or alternative if the condition has
// constant truthiness.
Truthiness t = Boolish(*expr);
if (t == Unknown) {
continue;
}
// Careful! Either of these can be null: |replacement| in |if (0) T;|,
// and |discarded| in |if (true) T;|.
ParseNode* replacement;
ParseNode* discarded;
if (t == Truthy) {
replacement = *consequent;
discarded = *alternative;
} else {
replacement = *alternative;
discarded = *consequent;
}
bool performReplacement = true;
if (discarded) {
// A declaration that hoists outside the discarded arm prevents the
// |if| from being folded away.
bool containsHoistedDecls;
if (!ContainsHoistedDeclaration(cx, discarded, &containsHoistedDecls)) {
return false;
}
performReplacement = !containsHoistedDecls;
}
if (!performReplacement) {
continue;
}
if (!replacement) {
// If there's no replacement node, we have a constantly-false |if|
// with no |else|. Replace the entire thing with an empty
// statement list.
node->setKind(ParseNodeKind::StatementList);
node->setArity(PN_LIST);
node->as<ListNode>().makeEmpty();
} else {
// Replacement invalidates |nextNode|, so reset it (if the
// replacement requires folding) or clear it (if |alternative|
// is dead code) as needed.
if (nextNode) {
nextNode = (*nextNode == replacement) ? nodePtr : nullptr;
}
ReplaceNode(nodePtr, replacement);
}
} while (nextNode);
return true;
}
static bool
FoldFunction(JSContext* cx, CodeNode* node, PerHandlerParser<FullParseHandler>& parser)
{
MOZ_ASSERT(node->isKind(ParseNodeKind::Function));
// Don't constant-fold inside "use asm" code, as this could create a parse
// tree that doesn't type-check as asm.js.
if (node->funbox()->useAsmOrInsideUseAsm()) {
return true;
}
// Note: body is null for lazily-parsed functions.
if (node->body()) {
if (!Fold(cx, node->unsafeBodyReference(), parser)) {
return false;
}
}
return true;
}
static double
ComputeBinary(ParseNodeKind kind, double left, double right)
{
if (kind == ParseNodeKind::Add) {
return left + right;
}
if (kind == ParseNodeKind::Sub) {
return left - right;
}
if (kind == ParseNodeKind::Star) {
return left * right;
}
if (kind == ParseNodeKind::Mod) {
return NumberMod(left, right);
}
if (kind == ParseNodeKind::Ursh) {
return ToUint32(left) >> (ToUint32(right) & 31);
}
if (kind == ParseNodeKind::Div) {
return NumberDiv(left, right);
}
MOZ_ASSERT(kind == ParseNodeKind::Lsh || kind == ParseNodeKind::Rsh);
int32_t i = ToInt32(left);
uint32_t j = ToUint32(right) & 31;
return int32_t((kind == ParseNodeKind::Lsh) ? uint32_t(i) << j : i >> j);
}
static bool
FoldModule(JSContext* cx, CodeNode* node, PerHandlerParser<FullParseHandler>& parser)
{
MOZ_ASSERT(node->isKind(ParseNodeKind::Module));
MOZ_ASSERT(node->body());
return Fold(cx, node->unsafeBodyReference(), parser);
}
static bool
FoldBinaryArithmetic(JSContext* cx, ListNode* node, PerHandlerParser<FullParseHandler>& parser)
{
MOZ_ASSERT(node->isKind(ParseNodeKind::Sub) ||
node->isKind(ParseNodeKind::Star) ||
node->isKind(ParseNodeKind::Lsh) ||
node->isKind(ParseNodeKind::Rsh) ||
node->isKind(ParseNodeKind::Ursh) ||
node->isKind(ParseNodeKind::Div) ||
node->isKind(ParseNodeKind::Mod));
MOZ_ASSERT(node->count() >= 2);
// Fold each operand, ideally into a number.
ParseNode** listp = node->unsafeHeadReference();
for (; *listp; listp = &(*listp)->pn_next) {
if (!Fold(cx, listp, parser)) {
return false;
}
if (!FoldType(cx, *listp, ParseNodeKind::Number)) {
return false;
}
}
node->unsafeReplaceTail(listp);
// Now fold all leading numeric terms together into a single number.
// (Trailing terms for the non-shift operations can't be folded together
// due to floating point imprecision. For example, if |x === -2**53|,
// |x - 1 - 1 === -2**53| but |x - 2 === -2**53 - 2|. Shifts could be
// folded, but it doesn't seem worth the effort.)
ParseNode* elem = node->head();
ParseNode* next = elem->pn_next;
if (elem->isKind(ParseNodeKind::Number)) {
ParseNodeKind kind = node->getKind();
while (true) {
if (!next || !next->isKind(ParseNodeKind::Number)) {
break;
}
double d = ComputeBinary(kind, elem->as<NumericLiteral>().value(), next->as<NumericLiteral>().value());
next = next->pn_next;
elem->pn_next = next;
elem->setKind(ParseNodeKind::Number);
elem->setArity(PN_NUMBER);
elem->setOp(JSOP_DOUBLE);
elem->as<NumericLiteral>().setValue(d);
node->unsafeDecrementCount();
}
if (node->count() == 1) {
MOZ_ASSERT(node->head() == elem);
MOZ_ASSERT(elem->isKind(ParseNodeKind::Number));
double d = elem->as<NumericLiteral>().value();
node->setKind(ParseNodeKind::Number);
node->setArity(PN_NUMBER);
node->setOp(JSOP_DOUBLE);
node->as<NumericLiteral>().setValue(d);
}
}
return true;
}
static bool
FoldExponentiation(JSContext* cx, ListNode* node, PerHandlerParser<FullParseHandler>& parser)
{
MOZ_ASSERT(node->isKind(ParseNodeKind::Pow));
MOZ_ASSERT(node->count() >= 2);
// Fold each operand, ideally into a number.
ParseNode** listp = node->unsafeHeadReference();
for (; *listp; listp = &(*listp)->pn_next) {
if (!Fold(cx, listp, parser)) {
return false;
}
if (!FoldType(cx, *listp, ParseNodeKind::Number)) {
return false;
}
}
node->unsafeReplaceTail(listp);
// Unlike all other binary arithmetic operators, ** is right-associative:
// 2**3**5 is 2**(3**5), not (2**3)**5. As list nodes singly-link their
// children, full constant-folding requires either linear space or dodgy
// in-place linked list reversal. So we only fold one exponentiation: it's
// easy and addresses common cases like |2**32|.
if (node->count() > 2) {
return true;
}
ParseNode* base = node->head();
ParseNode* exponent = base->pn_next;
if (!base->isKind(ParseNodeKind::Number) || !exponent->isKind(ParseNodeKind::Number)) {
return true;
}
double d1 = base->as<NumericLiteral>().value();
double d2 = exponent->as<NumericLiteral>().value();
node->setKind(ParseNodeKind::Number);
node->setArity(PN_NUMBER);
node->setOp(JSOP_DOUBLE);
node->as<NumericLiteral>().setValue(ecmaPow(d1, d2));
return true;
}
static bool
FoldList(JSContext* cx, ListNode* list, PerHandlerParser<FullParseHandler>& parser)
{
ParseNode** elem = list->unsafeHeadReference();
for (; *elem; elem = &(*elem)->pn_next) {
if (!Fold(cx, elem, parser)) {
return false;
}
}
list->unsafeReplaceTail(elem);
return true;
}
static bool
FoldReturn(JSContext* cx, UnaryNode* node, PerHandlerParser<FullParseHandler>& parser)
{
MOZ_ASSERT(node->isKind(ParseNodeKind::Return));
if (node->kid()) {
if (!Fold(cx, node->unsafeKidReference(), parser)) {
return false;
}
}
return true;
}
static bool
FoldTry(JSContext* cx, TryNode* node, PerHandlerParser<FullParseHandler>& parser)
{
ParseNode** statements = node->unsafeKid1Reference();
if (!Fold(cx, statements, parser)) {
return false;
}
ParseNode** catchScope = node->unsafeKid2Reference();
if (*catchScope) {
if (!Fold(cx, catchScope, parser)) {
return false;
}
}
ParseNode** finally = node->unsafeKid3Reference();
if (*finally) {
if (!Fold(cx, finally, parser)) {
return false;
}
}
return true;
}
static bool
FoldCatch(JSContext* cx, BinaryNode* node, PerHandlerParser<FullParseHandler>& parser)
{
ParseNode** declPattern = node->unsafeLeftReference();
if (*declPattern) {
if (!Fold(cx, declPattern, parser)) {
return false;
}
}
ParseNode** statements = node->unsafeRightReference();
if (*statements) {
if (!Fold(cx, statements, parser)) {
return false;
}
}
return true;
}
static bool
FoldClass(JSContext* cx, ClassNode* node, PerHandlerParser<FullParseHandler>& parser)
{
MOZ_ASSERT(node->isKind(ParseNodeKind::Class));
ParseNode** classNames = node->unsafeKid1Reference();
if (*classNames) {
if (!Fold(cx, classNames, parser)) {
return false;
}
}
ParseNode** heritage = node->unsafeKid2Reference();
if (*heritage) {
if (!Fold(cx, heritage, parser)) {
return false;
}
}
ParseNode** body = node->unsafeKid3Reference();
return Fold(cx, body, parser);
}
static bool
FoldElement(JSContext* cx, ParseNode** nodePtr, PerHandlerParser<FullParseHandler>& parser)
{
PropertyByValue* elem = &(*nodePtr)->as<PropertyByValue>();
if (!Fold(cx, elem->unsafeLeftReference(), parser)) {
return false;
}
if (!Fold(cx, elem->unsafeRightReference(), parser)) {
return false;
}
ParseNode* expr = &elem->expression();
ParseNode* key = &elem->key();
PropertyName* name = nullptr;
if (key->isKind(ParseNodeKind::String)) {
JSAtom* atom = key->as<NameNode>().atom();
uint32_t index;
if (atom->isIndex(&index)) {
// Optimization 1: We have something like expr["100"]. This is
// equivalent to expr[100] which is faster.
key->setKind(ParseNodeKind::Number);
key->setArity(PN_NUMBER);
key->setOp(JSOP_DOUBLE);
key->as<NumericLiteral>().setValue(index);
} else {
name = atom->asPropertyName();
}
} else if (key->isKind(ParseNodeKind::Number)) {
double number = key->as<NumericLiteral>().value();
if (number != ToUint32(number)) {
// Optimization 2: We have something like expr[3.14]. The number
// isn't an array index, so it converts to a string ("3.14"),
// enabling optimization 3 below.
JSAtom* atom = NumberToAtom(cx, number);
if (!atom) {
return false;
}
name = atom->asPropertyName();
}
}
// If we don't have a name, we can't optimize to getprop.
if (!name) {
return true;
}
// Optimization 3: We have expr["foo"] where foo is not an index. Convert
// to a property access (like expr.foo) that optimizes better downstream.
NameNode* nameNode = parser.newPropertyName(name, key->pn_pos);
if (!nameNode) {
return false;
}
ParseNode* dottedAccess = parser.newPropertyAccess(expr, nameNode);
if (!dottedAccess) {
return false;
}
dottedAccess->setInParens(elem->isInParens());
ReplaceNode(nodePtr, dottedAccess);
return true;
}
static bool
FoldAdd(JSContext* cx, ParseNode** nodePtr, PerHandlerParser<FullParseHandler>& parser)
{
ListNode* node = &(*nodePtr)->as<ListNode>();
MOZ_ASSERT(node->isKind(ParseNodeKind::Add));
MOZ_ASSERT(node->count() >= 2);
// Generically fold all operands first.
if (!FoldList(cx, node, parser)) {
return false;
}
// Fold leading numeric operands together:
//
// (1 + 2 + x) becomes (3 + x)
//
// Don't go past the leading operands: additions after a string are
// string concatenations, not additions: ("1" + 2 + 3 === "123").
ParseNode* current = node->head();
ParseNode* next = current->pn_next;
if (current->isKind(ParseNodeKind::Number)) {
do {
if (!next->isKind(ParseNodeKind::Number)) {
break;
}
NumericLiteral* num = ¤t->as<NumericLiteral>();
num->setValue(num->value() + next->as<NumericLiteral>().value());
current->pn_next = next->pn_next;
next = current->pn_next;
node->unsafeDecrementCount();
} while (next);
}
// If any operands remain, attempt string concatenation folding.
do {
// If no operands remain, we're done.
if (!next) {
break;
}
// (number + string) is string concatenation *only* at the start of
// the list: (x + 1 + "2" !== x + "12") when x is a number.
if (current->isKind(ParseNodeKind::Number) && next->isKind(ParseNodeKind::String)) {
if (!FoldType(cx, current, ParseNodeKind::String)) {
return false;
}
next = current->pn_next;
}
// The first string forces all subsequent additions to be
// string concatenations.
do {
if (current->isKind(ParseNodeKind::String)) {
break;
}
current = next;
next = next->pn_next;
} while (next);
// If there's nothing left to fold, we're done.
if (!next) {
break;
}
RootedString combination(cx);
RootedString tmp(cx);
do {
// Create a rope of the current string and all succeeding
// constants that we can convert to strings, then atomize it
// and replace them all with that fresh string.
MOZ_ASSERT(current->isKind(ParseNodeKind::String));
combination = current->as<NameNode>().atom();
do {
// Try folding the next operand to a string.
if (!FoldType(cx, next, ParseNodeKind::String)) {
return false;
}
// Stop glomming once folding doesn't produce a string.
if (!next->isKind(ParseNodeKind::String)) {
break;
}
// Add this string to the combination and remove the node.
tmp = next->as<NameNode>().atom();
combination = ConcatStrings<CanGC>(cx, combination, tmp);
if (!combination) {
return false;
}
next = next->pn_next;
current->pn_next = next;
node->unsafeDecrementCount();
} while (next);
// Replace |current|'s string with the entire combination.
MOZ_ASSERT(current->isKind(ParseNodeKind::String));
combination = AtomizeString(cx, combination);
if (!combination) {
return false;
}
current->as<NameNode>().setAtom(&combination->asAtom());
// If we're out of nodes, we're done.
if (!next) {
break;
}
current = next;
next = current->pn_next;
// If we're out of nodes *after* the non-foldable-to-string
// node, we're done.
if (!next) {
break;
}
// Otherwise find the next node foldable to a string, and loop.
do {
current = next;
next = current->pn_next;
if (!FoldType(cx, current, ParseNodeKind::String)) {
return false;
}
next = current->pn_next;
} while (!current->isKind(ParseNodeKind::String) && next);
} while (next);
} while (false);
MOZ_ASSERT(!next, "must have considered all nodes here");
MOZ_ASSERT(!current->pn_next, "current node must be the last node");
node->unsafeReplaceTail(¤t->pn_next);
if (node->count() == 1) {
// We reduced the list to a constant. Replace the ParseNodeKind::Add node
// with that constant.
ReplaceNode(nodePtr, current);
}
return true;
}
static bool
FoldCall(JSContext* cx, BinaryNode* node, PerHandlerParser<FullParseHandler>& parser)
{
MOZ_ASSERT(node->isKind(ParseNodeKind::Call) ||
node->isKind(ParseNodeKind::SuperCall) ||
node->isKind(ParseNodeKind::New) ||
node->isKind(ParseNodeKind::TaggedTemplate));
// Don't fold a parenthesized callable component in an invocation, as this
// might cause a different |this| value to be used, changing semantics:
//
// var prop = "global";
// var obj = { prop: "obj", f: function() { return this.prop; } };
// assertEq((true ? obj.f : null)(), "global");
// assertEq(obj.f(), "obj");
// assertEq((true ? obj.f : null)``, "global");
// assertEq(obj.f``, "obj");
//
// As an exception to this, we do allow folding the function in
// `(function() { ... })()` (the module pattern), because that lets us
// constant fold code inside that function.
//
// See bug 537673 and bug 1182373.
ParseNode* callee = node->left();
if (node->isKind(ParseNodeKind::New) ||
!callee->isInParens() ||
callee->isKind(ParseNodeKind::Function))
{
if (!Fold(cx, node->unsafeLeftReference(), parser)) {
return false;
}
}
if (!Fold(cx, node->unsafeRightReference(), parser)) {
return false;
}
return true;
}
static bool
FoldArguments(JSContext* cx, ListNode* node, PerHandlerParser<FullParseHandler>& parser)
{
MOZ_ASSERT(node->isKind(ParseNodeKind::Arguments));
ParseNode** listp = node->unsafeHeadReference();
for (; *listp; listp = &(*listp)->pn_next) {
if (!Fold(cx, listp, parser)) {
return false;
}
}
node->unsafeReplaceTail(listp);
return true;
}
static bool
FoldForInOrOf(JSContext* cx, TernaryNode* node, PerHandlerParser<FullParseHandler>& parser)
{
MOZ_ASSERT(node->isKind(ParseNodeKind::ForIn) ||
node->isKind(ParseNodeKind::ForOf));
MOZ_ASSERT(!node->kid2());
return Fold(cx, node->unsafeKid1Reference(), parser) &&
Fold(cx, node->unsafeKid3Reference(), parser);
}
static bool
FoldForHead(JSContext* cx, TernaryNode* node, PerHandlerParser<FullParseHandler>& parser)
{
MOZ_ASSERT(node->isKind(ParseNodeKind::ForHead));
ParseNode** init = node->unsafeKid1Reference();
if (*init) {
if (!Fold(cx, init, parser)) {
return false;
}
}
ParseNode** test = node->unsafeKid2Reference();
if (*test) {
if (!FoldCondition(cx, test, parser)) {
return false;
}
if ((*test)->isKind(ParseNodeKind::True)) {
(*test) = nullptr;
}
}
ParseNode** update = node->unsafeKid3Reference();
if (*update) {
if (!Fold(cx, update, parser)) {
return false;
}
}
return true;
}
static bool
FoldDottedProperty(JSContext* cx, PropertyAccess* prop, PerHandlerParser<FullParseHandler>& parser)
{
// Iterate through a long chain of dotted property accesses to find the
// most-nested non-dotted property node, then fold that.
ParseNode** nested = prop->unsafeLeftReference();
while ((*nested)->isKind(ParseNodeKind::Dot)) {
nested = (*nested)->as<PropertyAccess>().unsafeLeftReference();
}
return Fold(cx, nested, parser);
}
static bool
FoldName(JSContext* cx, NameNode* nameNode, PerHandlerParser<FullParseHandler>& parser)
{
MOZ_ASSERT(nameNode->isKind(ParseNodeKind::Name));
if (!nameNode->initializer()) {
return true;
}
return Fold(cx, nameNode->unsafeInitializerReference(), parser);
}
bool
Fold(JSContext* cx, ParseNode** pnp, PerHandlerParser<FullParseHandler>& parser)
{
if (!CheckRecursionLimit(cx)) {
return false;
}
ParseNode* pn = *pnp;
switch (pn->getKind()) {
case ParseNodeKind::EmptyStatement:
case ParseNodeKind::True:
case ParseNodeKind::False:
case ParseNodeKind::Null:
case ParseNodeKind::RawUndefined:
case ParseNodeKind::Elision:
case ParseNodeKind::Generator:
case ParseNodeKind::ExportBatchSpec:
case ParseNodeKind::PosHolder:
MOZ_ASSERT(pn->is<NullaryNode>());
return true;
case ParseNodeKind::Debugger:
MOZ_ASSERT(pn->is<DebuggerStatement>());
return true;
case ParseNodeKind::Break:
MOZ_ASSERT(pn->is<BreakStatement>());
return true;
case ParseNodeKind::Continue:
MOZ_ASSERT(pn->is<ContinueStatement>());
return true;
case ParseNodeKind::ObjectPropertyName:
case ParseNodeKind::String:
case ParseNodeKind::TemplateString:
MOZ_ASSERT(pn->is<NameNode>());
return true;
case ParseNodeKind::RegExp:
MOZ_ASSERT(pn->is<RegExpLiteral>());
return true;
case ParseNodeKind::Number:
MOZ_ASSERT(pn->is<NumericLiteral>());
return true;
case ParseNodeKind::SuperBase:
case ParseNodeKind::TypeOfName: {
#ifdef DEBUG
UnaryNode* node = &pn->as<UnaryNode>();
NameNode* nameNode = &node->kid()->as<NameNode>();
MOZ_ASSERT(nameNode->isKind(ParseNodeKind::Name));
MOZ_ASSERT(!nameNode->initializer());
#endif
return true;
}
case ParseNodeKind::TypeOfExpr:
return FoldTypeOfExpr(cx, &pn->as<UnaryNode>(), parser);
case ParseNodeKind::DeleteName:
MOZ_ASSERT(pn->as<UnaryNode>().kid()->isKind(ParseNodeKind::Name));
return true;
case ParseNodeKind::DeleteExpr:
return FoldDeleteExpr(cx, &pn->as<UnaryNode>(), parser);
case ParseNodeKind::DeleteElem:
return FoldDeleteElement(cx, &pn->as<UnaryNode>(), parser);
case ParseNodeKind::DeleteProp:
return FoldDeleteProperty(cx, &pn->as<UnaryNode>(), parser);
case ParseNodeKind::Conditional:
MOZ_ASSERT((*pnp)->is<TernaryNode>());
return FoldConditional(cx, pnp, parser);
case ParseNodeKind::If:
MOZ_ASSERT((*pnp)->is<TernaryNode>());
return FoldIf(cx, pnp, parser);
case ParseNodeKind::Not:
return FoldNot(cx, &pn->as<UnaryNode>(), parser);
case ParseNodeKind::BitNot:
case ParseNodeKind::Pos:
case ParseNodeKind::Neg:
return FoldUnaryArithmetic(cx, &pn->as<UnaryNode>(), parser);
case ParseNodeKind::PreIncrement:
case ParseNodeKind::PostIncrement:
case ParseNodeKind::PreDecrement:
case ParseNodeKind::PostDecrement:
return FoldIncrementDecrement(cx, &pn->as<UnaryNode>(), parser);
case ParseNodeKind::ExpressionStatement:
case ParseNodeKind::Throw:
case ParseNodeKind::MutateProto:
case ParseNodeKind::ComputedName:
case ParseNodeKind::Spread:
case ParseNodeKind::Export:
case ParseNodeKind::Void:
return Fold(cx, pn->as<UnaryNode>().unsafeKidReference(), parser);
case ParseNodeKind::ExportDefault:
return Fold(cx, pn->as<BinaryNode>().unsafeLeftReference(), parser);
case ParseNodeKind::This: {
ThisLiteral* node = &pn->as<ThisLiteral>();
ParseNode** expr = node->unsafeKidReference();
if (*expr) {
return Fold(cx, expr, parser);
}
return true;
}
case ParseNodeKind::Pipeline:
return true;
case ParseNodeKind::And:
case ParseNodeKind::Or:
MOZ_ASSERT((*pnp)->is<ListNode>());
return FoldAndOr(cx, pnp, parser);
case ParseNodeKind::Function:
return FoldFunction(cx, &pn->as<CodeNode>(), parser);
case ParseNodeKind::Module:
return FoldModule(cx, &pn->as<CodeNode>(), parser);
case ParseNodeKind::Sub:
case ParseNodeKind::Star:
case ParseNodeKind::Lsh:
case ParseNodeKind::Rsh:
case ParseNodeKind::Ursh:
case ParseNodeKind::Div:
case ParseNodeKind::Mod:
return FoldBinaryArithmetic(cx, &pn->as<ListNode>(), parser);
case ParseNodeKind::Pow:
return FoldExponentiation(cx, &pn->as<ListNode>(), parser);
// Various list nodes not requiring care to minimally fold. Some of
// these could be further folded/optimized, but we don't make the effort.
case ParseNodeKind::BitOr:
case ParseNodeKind::BitXor:
case ParseNodeKind::BitAnd:
case ParseNodeKind::StrictEq:
case ParseNodeKind::Eq:
case ParseNodeKind::StrictNe:
case ParseNodeKind::Ne:
case ParseNodeKind::Lt:
case ParseNodeKind::Le:
case ParseNodeKind::Gt:
case ParseNodeKind::Ge:
case ParseNodeKind::InstanceOf:
case ParseNodeKind::In:
case ParseNodeKind::Comma:
case ParseNodeKind::Array:
case ParseNodeKind::Object:
case ParseNodeKind::StatementList:
case ParseNodeKind::ClassMethodList:
case ParseNodeKind::TemplateStringList:
case ParseNodeKind::Var:
case ParseNodeKind::Const:
case ParseNodeKind::Let:
case ParseNodeKind::ParamsBody:
case ParseNodeKind::CallSiteObj:
case ParseNodeKind::ExportSpecList:
case ParseNodeKind::ImportSpecList:
return FoldList(cx, &pn->as<ListNode>(), parser);
case ParseNodeKind::InitialYield: {
#ifdef DEBUG
AssignmentNode* assignNode = &pn->as<UnaryNode>().kid()->as<AssignmentNode>();
MOZ_ASSERT(assignNode->left()->isKind(ParseNodeKind::Name));
MOZ_ASSERT(assignNode->right()->isKind(ParseNodeKind::Generator));
#endif
return true;
}
case ParseNodeKind::YieldStar:
return Fold(cx, pn->as<UnaryNode>().unsafeKidReference(), parser);
case ParseNodeKind::Yield:
case ParseNodeKind::Await: {
UnaryNode* node = &pn->as<UnaryNode>();
if (!node->kid()) {
return true;
}
return Fold(cx, node->unsafeKidReference(), parser);
}
case ParseNodeKind::Return:
return FoldReturn(cx, &pn->as<UnaryNode>(), parser);
case ParseNodeKind::Try:
return FoldTry(cx, &pn->as<TryNode>(), parser);
case ParseNodeKind::Catch:
return FoldCatch(cx, &pn->as<BinaryNode>(), parser);
case ParseNodeKind::Class:
return FoldClass(cx, &pn->as<ClassNode>(), parser);
case ParseNodeKind::Elem: {
MOZ_ASSERT((*pnp)->is<PropertyByValue>());
return FoldElement(cx, pnp, parser);
}
case ParseNodeKind::Add:
MOZ_ASSERT((*pnp)->is<ListNode>());
return FoldAdd(cx, pnp, parser);
case ParseNodeKind::Call:
case ParseNodeKind::New:
case ParseNodeKind::SuperCall:
case ParseNodeKind::TaggedTemplate:
return FoldCall(cx, &pn->as<BinaryNode>(), parser);
case ParseNodeKind::Arguments:
return FoldArguments(cx, &pn->as<ListNode>(), parser);
case ParseNodeKind::Switch:
case ParseNodeKind::Colon:
case ParseNodeKind::Assign:
case ParseNodeKind::AddAssign:
case ParseNodeKind::SubAssign:
case ParseNodeKind::BitOrAssign:
case ParseNodeKind::BitAndAssign:
case ParseNodeKind::BitXorAssign:
case ParseNodeKind::LshAssign:
case ParseNodeKind::RshAssign:
case ParseNodeKind::UrshAssign:
case ParseNodeKind::DivAssign:
case ParseNodeKind::ModAssign:
case ParseNodeKind::MulAssign:
case ParseNodeKind::PowAssign:
case ParseNodeKind::Import:
case ParseNodeKind::ExportFrom:
case ParseNodeKind::Shorthand:
case ParseNodeKind::For:
case ParseNodeKind::ClassMethod:
case ParseNodeKind::ImportSpec:
case ParseNodeKind::ExportSpec:
case ParseNodeKind::SetThis: {
BinaryNode* node = &pn->as<BinaryNode>();
return Fold(cx, node->unsafeLeftReference(), parser) &&
Fold(cx, node->unsafeRightReference(), parser);
}
case ParseNodeKind::NewTarget:
case ParseNodeKind::ImportMeta: {
#ifdef DEBUG
BinaryNode* node = &pn->as<BinaryNode>();
MOZ_ASSERT(node->left()->isKind(ParseNodeKind::PosHolder));
MOZ_ASSERT(node->right()->isKind(ParseNodeKind::PosHolder));
#endif
return true;
}
case ParseNodeKind::CallImport: {
BinaryNode* node = &pn->as<BinaryNode>();
MOZ_ASSERT(node->left()->isKind(ParseNodeKind::PosHolder));
return Fold(cx, node->unsafeRightReference(), parser);
}
case ParseNodeKind::ClassNames: {
ClassNames* names = &pn->as<ClassNames>();
if (names->outerBinding()) {
if (!Fold(cx, names->unsafeLeftReference(), parser)) {
return false;
}
}
return Fold(cx, names->unsafeRightReference(), parser);
}
case ParseNodeKind::DoWhile: {
BinaryNode* node = &pn->as<BinaryNode>();
return Fold(cx, node->unsafeLeftReference(), parser) &&
FoldCondition(cx, node->unsafeRightReference(), parser);
}
case ParseNodeKind::While: {
BinaryNode* node = &pn->as<BinaryNode>();
return FoldCondition(cx, node->unsafeLeftReference(), parser) &&
Fold(cx, node->unsafeRightReference(), parser);
}
case ParseNodeKind::Case: {
CaseClause* caseClause = &pn->as<CaseClause>();
// left (caseExpression) is null for DefaultClauses.
if (caseClause->left()) {
if (!Fold(cx, caseClause->unsafeLeftReference(), parser)) {
return false;
}
}
return Fold(cx, caseClause->unsafeRightReference(), parser);
}
case ParseNodeKind::With: {
BinaryNode* node = &pn->as<BinaryNode>();
return Fold(cx, node->unsafeLeftReference(), parser) &&
Fold(cx, node->unsafeRightReference(), parser);
}
case ParseNodeKind::ForIn:
case ParseNodeKind::ForOf:
return FoldForInOrOf(cx, &pn->as<TernaryNode>(), parser);
case ParseNodeKind::ForHead:
return FoldForHead(cx, &pn->as<TernaryNode>(), parser);
case ParseNodeKind::Label:
return Fold(cx, pn->as<LabeledStatement>().unsafeStatementReference(), parser);
case ParseNodeKind::PropertyName:
MOZ_CRASH("unreachable, handled by ::Dot");
case ParseNodeKind::Dot:
return FoldDottedProperty(cx, &pn->as<PropertyAccess>(), parser);
case ParseNodeKind::LexicalScope: {
LexicalScopeNode* node = &pn->as<LexicalScopeNode>();
if (!node->scopeBody()) {
return true;
}
return Fold(cx, node->unsafeScopeBodyReference(), parser);
}
case ParseNodeKind::Name:
return FoldName(cx, &pn->as<NameNode>(), parser);
case ParseNodeKind::Limit: // invalid sentinel value
MOZ_CRASH("invalid node kind");
}
MOZ_CRASH("shouldn't reach here");
return false;
}
bool
frontend::FoldConstants(JSContext* cx, ParseNode** pnp, PerHandlerParser<FullParseHandler>* parser)
{
// Don't constant-fold inside "use asm" code, as this could create a parse
// tree that doesn't type-check as asm.js.
if (parser->pc->useAsmOrInsideUseAsm()) {
return true;
}
AutoTraceLog traceLog(TraceLoggerForCurrentThread(cx), TraceLogger_BytecodeFoldConstants);
return Fold(cx, pnp, *parser);
}
| 32.349872 | 116 | 0.60586 | fengjixuchui |
f7cb2b54a8491271663c4b9d4b25c7c89fb86598 | 6,558 | cpp | C++ | src/main.cpp | DawidPietrykowski/GPURayTracer | 66f150441d68587ddb3d4d73a7620310c5e26959 | [
"MIT"
] | null | null | null | src/main.cpp | DawidPietrykowski/GPURayTracer | 66f150441d68587ddb3d4d73a7620310c5e26959 | [
"MIT"
] | null | null | null | src/main.cpp | DawidPietrykowski/GPURayTracer | 66f150441d68587ddb3d4d73a7620310c5e26959 | [
"MIT"
] | null | null | null | #include <array>
#include <string>
#include <vector>
#include <iostream>
#include <ComputeEngine.h>
#include "Utils.h"
#include "DataStructures.h"
#include "Config.h"
#include "Scene.h"
#define UPDATE_OBJECT_BUFFERS 0
void UpdateKeys(ComputeEngine& renderer, CameraData& camera, std::vector<SceneObject>& objects, ShaderData& shader_data, Texture& tex_output) {
if (renderer.IsKeyClicked(GLFW_KEY_P)) {
renderer.SwitchInput();
}
if (renderer.GetInput()) {
if (renderer.IsKeyPressed(GLFW_KEY_W))
camera.AccelerateCamera(new float[3]{ 0, 0, 1.0f });
if (renderer.IsKeyPressed(GLFW_KEY_A))
camera.AccelerateCamera(new float[3]{ -1.0f, 0, 0 });
if (renderer.IsKeyPressed(GLFW_KEY_S))
camera.AccelerateCamera(new float[3]{ 0, 0, -1.0f });
if (renderer.IsKeyPressed(GLFW_KEY_D))
camera.AccelerateCamera(new float[3]{ 1.0f, 0, 0 });
if (renderer.IsKeyPressed(GLFW_KEY_SPACE))
camera.AccelerateCamera(new float[3]{ 0, 1.0f, 0 });
if (renderer.IsKeyPressed(GLFW_KEY_LEFT_CONTROL))
camera.AccelerateCamera(new float[3]{ 0, -1.0f, 0 });
if (renderer.IsKeyPressed(GLFW_KEY_E)) {
}
if (renderer.IsKeyPressed(GLFW_KEY_Q)) {
}
if (renderer.IsKeyClicked(GLFW_KEY_F11)) {
renderer.SwitchFullScreen();
}
if (renderer.IsKeyClicked(GLFW_KEY_ESCAPE))
renderer.CloseWindow();
if (renderer.IsKeyClicked(GLFW_KEY_L)) {
renderer.SaveScreen("screenshot");
}
}
int width, height;
shader_data.GetWindowSize(width, height);
renderer.GetWindowSize(shader_data._screen_size[0], shader_data._screen_size[1]);
if (width != shader_data.GetWidth() || height != shader_data.GetHeight())
tex_output.Resize(shader_data.GetWidth(), shader_data.GetHeight());
}
void UpdateInput(ComputeEngine& renderer, CameraData& camera, std::vector<SceneObject>& objects, ShaderData& shader_data, Texture& tex_output) {
renderer.PollEvents();
UpdateKeys(renderer, camera, objects, shader_data, tex_output);
double dx, dy;
renderer.GetMouseDelta(dx, dy);
dx *= (renderer.GetFrametime() / 1000.0);
dy *= (renderer.GetFrametime() / 1000.0);
double xp, yp;
int w, h;
renderer.GetWindowSize(w, h);
renderer.GetMousePos(xp, yp);
bool in_window = xp > 0 && yp > 0 && xp < w && yp < h;
if (renderer.IsMouseButtonClicked(GLFW_MOUSE_BUTTON_1) && !renderer.GetInput())
{
renderer.SetInput(true);
}
camera.RotateCamera((float)dx, (float)dy);
camera.UpdateCameraData((float)(renderer.GetFrametime() / 1000.0));
}
int main(int argc, char** argv)
{
srand((unsigned)time(0));
std::string config_filename = "configs/config.txt";
if (argc > 1)
config_filename = argv[1];
if (!FileExists(config_filename)) {
LOG_ERROR(config_filename + " does not exist");
return -1;
}
std::cout << "config file name: " << config_filename << std::endl;
Config config(config_filename);
int width = config.m_window_width;
int height = config.m_window_height;
// init renderer
ComputeEngine renderer(width, height, config.m_window_name, config.m_start_focused, true);
Shader pixel_compute_shader(config.m_pixel_shader_path);
if (!pixel_compute_shader.Compiled()) {
LOG_ERROR("shader compilation fail");
return -1;
}
Program pixel_compute_program(pixel_compute_shader);
// init data for shader
ShaderData shader_data = {};
shader_data._screen_size = { width, height };
shader_data._iterations = config.m_iterations;
shader_data._samples = config.m_samples_per_frame;
shader_data._fov = config.m_fov;
// init textures
Texture tex_output("img_output", width, height);
// bind textures
pixel_compute_program.BindTextureImage(tex_output, 0);
config.BindTextures(pixel_compute_program);
// init buffers
UBO data_buffer(2);
UBO objects_buffer(3);
SSBO index_buffer(4);
SSBO vert_buffer(5);
SSBO texture_vert_buffer(6);
// fill buffers with data
data_buffer.Set(&shader_data);
objects_buffer.Set(config.GetObjects());
index_buffer.Set(config.GetIndexBuffer());
vert_buffer.Set(config.GetVertexBuffer());
texture_vert_buffer.Set(config.GetTextureBuffer());
// init camera
CameraData camera;
camera.position = config.m_camera_position;
camera.rotation = config.m_camera_rotation;
camera.sensitivity = config.m_camera_sensitivity;
camera.m_width = width;
camera.m_height = height;
camera.CopyData(shader_data);
printf("faces: %d\nvertices: %d\nobjects: %d\n", config.GetFaceCount(), config.GetVertexCount(), config.GetObjectCount());
while (!renderer.ShouldClose()) {
// update input
camera.SetChanged(false);
UpdateInput(renderer, camera, *config.GetObjects(), shader_data, tex_output);
// update data for shader
if (camera.HasChanged()) {
shader_data._sample = 1;
shader_data._pixel_offset = { 0.5f, 0.5f };
}
else {
shader_data._sample++;
shader_data._pixel_offset = { (GetRand() - 0.5f), (GetRand() - 0.5f) };
}
shader_data.UpdateSeed();
shader_data._objectcount = config.GetObjectCount();
camera.UpdateWindowSize(shader_data.GetWidth(), shader_data.GetHeight());
camera.CopyData(shader_data);
// update buffers
data_buffer.Update(&shader_data);
#if UPDATE_OBJECT_BUFFERS
objects_buffer.Update(config.GetObjects());
index_buffer.Update(config.GetIndexBuffer());
vert_buffer.Update(config.GetVertexBuffer());
texture_vert_buffer.Update(config.GetTextureBuffer());
#endif
// dispatch compute shader
pixel_compute_program.DispatchCompute(shader_data.GetWidth(), shader_data.GetHeight());
renderer.UpdateFrametime();
// draw rendered image
renderer.DrawTexture(tex_output);
// glFinish call
renderer.Finish();
//print frametime every 50 frames
if(renderer.GetFramecount()%50 == 0)
printf("f:%.2fms w:%d h:%d samples:%d\n", renderer.GetFrametime(), renderer.GetWidth(), renderer.GetHeight(), shader_data._sample * shader_data._samples);
}
//print average frametime
printf("average frametime: %.3fms", renderer.GetAverageFrametime());
return 0;
} | 33.28934 | 166 | 0.660415 | DawidPietrykowski |
f7ccc8fc1b326c450e3792c6f82a27abe7234e7b | 585 | cpp | C++ | Data Structures/Arrays/11. BUGGY Merge two Sorted arrays without using extra space.cpp | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 36 | 2019-12-27T08:23:08.000Z | 2022-01-24T20:35:47.000Z | Data Structures/Arrays/11. BUGGY Merge two Sorted arrays without using extra space.cpp | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 10 | 2019-11-13T02:55:18.000Z | 2021-10-13T23:28:09.000Z | Data Structures/Arrays/11. BUGGY Merge two Sorted arrays without using extra space.cpp | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 53 | 2020-08-15T11:08:40.000Z | 2021-10-09T15:51:38.000Z | #include<iostream>
#include<cstring>
#include<cstdlib>
using namespace std;
// Given an array of m+n elements , second array has n elements.
// THIS CODE IS BUGGY
void print(int *a){
for(int i=0;i<10;i++)
cout<<a[i]<<" ";
}
void mergeArrays(int *a,int *b){
int la = 10;
int lb = 5;
int start = lb;
int i,j,n=la;
for(i=0,j=start;j<la;i++,j++){
a[j] = a[i];
}
int k=0;
i=0;j=lb;
while(k<n){
if(b[i]<a[j])
a[k++]=b[i++];
else
a[k++]=a[j++];
}
}
int main(){
int a[10] = {-5.-4,-3,-2,-1};//{2,3,5,8,9};
int b[5] = { 1,4,6,10,11};
mergeArrays(a,b);
print(a);
return 0;
}
| 13.604651 | 64 | 0.552137 | Ashwanigupta9125 |
f7cdb776f05cded77cea56aa65bec9d95207d44c | 1,647 | cpp | C++ | src/ButtonInfoBar.cpp | xaviarmengol/M5Stack-GUI | ae7ad8897a0d695b0784f4a25cc5469c9e8a14ce | [
"MIT"
] | 71 | 2018-03-17T17:38:48.000Z | 2022-02-18T04:43:41.000Z | src/ButtonInfoBar.cpp | xaviarmengol/M5Stack-GUI | ae7ad8897a0d695b0784f4a25cc5469c9e8a14ce | [
"MIT"
] | 6 | 2018-09-03T18:47:51.000Z | 2021-01-18T10:03:33.000Z | src/ButtonInfoBar.cpp | xaviarmengol/M5Stack-GUI | ae7ad8897a0d695b0784f4a25cc5469c9e8a14ce | [
"MIT"
] | 20 | 2018-04-28T23:06:31.000Z | 2022-02-17T23:56:14.000Z | #include "ButtonInfoBar.h"
using namespace Codingfield::UI;
void ButtonInfoBar::SetButtonAText(const std::string& t) {
if(btnAText != t) {
oldBtnAText = btnAText;
btnAText = t;
}
}
void ButtonInfoBar::SetButtonBText(const std::string& t) {
if(btnBText != t) {
oldBtnBText = btnBText;
btnBText = t;
}
}
void ButtonInfoBar::SetButtonCText(const std::string& t) {
if(btnCText != t) {
oldBtnCText = btnCText;
btnCText = t;
}
}
void ButtonInfoBar::Draw() {
if(IsHidden()) return;
bool oldIsInvalidated = isInvalidated;
Bar::Draw();
if(oldIsInvalidated || (oldBtnAText != btnAText)) {
M5.Lcd.setTextDatum(TC_DATUM);
M5.Lcd.setTextColor(color);
M5.Lcd.drawString(oldBtnAText.c_str(), (size.width/6), position.y + 5);
M5.Lcd.setTextColor(BLACK);
M5.Lcd.drawString(btnAText.c_str(), (size.width/6), position.y + 5);
oldBtnAText = btnAText;
}
if(oldIsInvalidated || (oldBtnBText != btnBText)) {
M5.Lcd.setTextDatum(TC_DATUM);
M5.Lcd.setTextColor(color);
M5.Lcd.drawString(oldBtnBText.c_str(), size.width/2, position.y + 5);
M5.Lcd.setTextColor(BLACK);
M5.Lcd.drawString(btnBText.c_str(), size.width/2, position.y + 5);
oldBtnBText = btnBText;
}
if(oldIsInvalidated || (oldBtnCText != btnCText)) {
M5.Lcd.setTextDatum(TC_DATUM);
M5.Lcd.setTextColor(color);
M5.Lcd.drawString(oldBtnCText.c_str(), ((size.width/3)*2) + (size.width/6), position.y + 5);
M5.Lcd.setTextColor(BLACK);
M5.Lcd.drawString(btnCText.c_str(), ((size.width/3)*2) + (size.width/6), position.y + 5);
oldBtnCText = btnCText;
}
isInvalidated = false;
}
| 26.564516 | 96 | 0.663024 | xaviarmengol |
f7d03a1dfca8fdb87023a96b83d76e980731f132 | 230 | cpp | C++ | src/system/libroot/posix/string/ffs.cpp | Kirishikesan/haiku | 835565c55830f2dab01e6e332cc7e2d9c015b51e | [
"MIT"
] | 2 | 2021-06-05T20:29:57.000Z | 2021-06-20T10:46:56.000Z | src/system/libroot/posix/string/ffs.cpp | Kirishikesan/haiku | 835565c55830f2dab01e6e332cc7e2d9c015b51e | [
"MIT"
] | null | null | null | src/system/libroot/posix/string/ffs.cpp | Kirishikesan/haiku | 835565c55830f2dab01e6e332cc7e2d9c015b51e | [
"MIT"
] | null | null | null | /*
* Copyright 2020, Adrien Destugues <pulkomandy@pulkomandy.tk>.
* Distributed under the terms of the MIT License.
*/
// find first (least significant) set bit
extern "C" int
ffs(int value)
{
return __builtin_ffs(value);
}
| 17.692308 | 63 | 0.717391 | Kirishikesan |
f7d173e94c252ca127e58a36ec96a85202fd959c | 6,737 | hpp | C++ | include/engine/script/luascriptsystem.hpp | eXl-Nic/eXl | a5a0f77f47db3179365c107a184bb38b80280279 | [
"MIT"
] | null | null | null | include/engine/script/luascriptsystem.hpp | eXl-Nic/eXl | a5a0f77f47db3179365c107a184bb38b80280279 | [
"MIT"
] | null | null | null | include/engine/script/luascriptsystem.hpp | eXl-Nic/eXl | a5a0f77f47db3179365c107a184bb38b80280279 | [
"MIT"
] | null | null | null | /*
Copyright 2009-2021 Nicolas Colombe
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.
*/
#pragma once
#ifdef EXL_LUA
#include <core/lua/luamanager.hpp>
#include <core/lua/luascript.hpp>
#include <core/type/fundesc.hpp>
#include <engine/common/world.hpp>
#include <boost/optional.hpp>
#include <core/path.hpp>
namespace eXl
{
class LuaScriptBehaviour;
struct BehaviourDesc
{
Name behaviourName;
UnorderedMap<Name, FunDesc> functions;
};
class EXL_ENGINE_API LuaScriptSystem : public ComponentManager
{
DECLARE_RTTI(LuaScriptSystem, ComponentManager);
public:
LuaScriptSystem();
~LuaScriptSystem();
static void AddBehaviourDesc(BehaviourDesc iDesc);
static BehaviourDesc const* GetBehaviourDesc(Name iName);
static Vector<Name> GetBehaviourNames();
void LoadScript(const LuaScriptBehaviour& iBehaviour);
void AddBehaviour(ObjectHandle, const LuaScriptBehaviour& iBehaviour);
void DeleteComponent(ObjectHandle) override;
static World* GetWorld();
template <typename Ret, typename... Args>
static bool ValidateCall(Name iBehaviour, Name iFunction)
{
BehaviourDesc const* desc = GetBehaviourDesc(iBehaviour);
if (desc == nullptr)
{
return false;
}
auto iter = desc->functions.find(iFunction);
if (iter == desc->functions.end())
{
return false;
}
if (!iter->second.ValidateSignature<Ret, Args...>())
{
return false;
}
return true;
}
template <typename Ret, typename... Args>
struct Caller
{
static boost::optional<Ret> Call(LuaScriptSystem& iSys, ObjectHandle iHandle, Name iBehaviour, Name iFunction, Args&&... iArgs)
{
if (!iSys.ValidateCall<Ret, Args...>(iBehaviour, iFunction))
{
return {};
}
LuaStateHandle stateHandle = iSys.m_LuaWorld.GetState();
lua_State* state = stateHandle.GetState();
int32_t curTop = lua_gettop(state);
luabind::object scriptObject;
luabind::object function = iSys.FindFunction(iHandle, iBehaviour, iFunction, scriptObject);
if (!function.is_valid())
{
return {};
}
boost::optional<Ret> res;
{
auto call = stateHandle.PrepareCall(function);
call.Push(scriptObject);
call.PushArgs(std::forward<Args>(iArgs)...);
auto res = call.Call(1);
if (!res || *res == 0)
{
return {};
}
luabind::object retObj(luabind::from_stack(state, -1));
luabind::default_converter<Ret> converter;
if (converter.match(state, luabind::decorate_type_t<Ret>(), -1) < 0)
{
luabind::detail::cast_error<Ret>(state);
return {};
}
//return converter.to_cpp(state, luabind::decorate_type_t<Ret>(), -1);
res = converter.to_cpp(state, luabind::decorate_type_t<Ret>(), -1);
}
eXl_ASSERT(curTop == lua_gettop(state));
return res;
}
};
template <typename... Args>
struct Caller<void, Args...>
{
static Err Call(LuaScriptSystem& iSys, ObjectHandle iHandle, Name iBehaviour, Name iFunction, Args&&... iArgs)
{
if (!iSys.ValidateCall<void, Args...>(iBehaviour, iFunction))
{
return Err::Failure;
}
LuaStateHandle stateHandle = iSys.m_LuaWorld.GetState();
lua_State* state = stateHandle.GetState();
int32_t curTop = lua_gettop(state);
luabind::object scriptObject;
luabind::object function = iSys.FindFunction(iHandle, iBehaviour, iFunction, scriptObject);
if (!function.is_valid())
{
return Err::Failure;
}
{
auto call = stateHandle.PrepareCall(function);
call.Push(scriptObject);
call.PushArgs(std::forward<Args>(iArgs)...);
auto res = call.Call(0);
if (!res)
{
return Err::Failure;
}
}
eXl_ASSERT(curTop == lua_gettop(state));
return Err::Success;
}
};
template <typename Ret, typename... Args, typename std::enable_if<!std::is_same<Ret, void>::value, bool>::type = true>
boost::optional<Ret> CallBehaviour(ObjectHandle iHandle, Name iBehaviour, Name iFunction, Args&&... iArgs)
{
return Caller<Ret, Args...>::Call(*this, iHandle, iBehaviour, iFunction, std::forward<Args>(iArgs)...);
}
template <typename Ret, typename... Args, typename std::enable_if<std::is_same<Ret, void>::value, bool>::type = true>
Err CallBehaviour(ObjectHandle iHandle, Name iBehaviour, Name iFunction, Args&&... iArgs)
{
return Caller<void, Args...>::Call(*this, iHandle, iBehaviour, iFunction, std::forward<Args>(iArgs)...);
}
protected:
luabind::object FindFunction(ObjectHandle iHandle, Name iBehaviour, Name iFunction, luabind::object& oScriptObj);
struct ScriptEntry
{
ResourceHandle<LuaScriptBehaviour> m_ScriptHandle;
luabind::object m_ScriptObject;
luabind::object m_InitFunction;
UnorderedMap<Name, luabind::object> m_ScriptFunctions;
};
ObjectTable<ScriptEntry> m_Scripts;
using ScriptHandle = ObjectTableHandle<ScriptEntry>;
UnorderedMap<Resource::UUID, ScriptHandle> m_LoadedScripts;
ScriptHandle LoadScript_Internal(const LuaScriptBehaviour& iBehaviour);
struct ObjectEntry
{
ScriptHandle m_Script;
luabind::object m_ScriptData;
};
struct BehaviourReg
{
UnorderedMap<ObjectHandle, ObjectEntry> m_RegisteredObjects;
};
UnorderedMap<Name, BehaviourReg> m_ObjectToBehaviour;
LuaWorld m_LuaWorld;
};
}
#endif | 32.863415 | 460 | 0.658008 | eXl-Nic |
f7d189fd792cf2f5f514da97367a04b17e389bca | 1,349 | cpp | C++ | Demo/src/main.cpp | billy4479/BillyEngine | df7d519f740d5862c4743872dbf89b3654eeb423 | [
"MIT"
] | 1 | 2021-09-05T20:50:59.000Z | 2021-09-05T20:50:59.000Z | Demo/src/main.cpp | billy4479/sdl-tests | df7d519f740d5862c4743872dbf89b3654eeb423 | [
"MIT"
] | null | null | null | Demo/src/main.cpp | billy4479/sdl-tests | df7d519f740d5862c4743872dbf89b3654eeb423 | [
"MIT"
] | null | null | null | #include <BillyEngine.hpp>
#include "FPSCounter.hpp"
#include "MouseChaser.hpp"
#include "Spawner.hpp"
#include "SpinningQuad.hpp"
int main() {
BillyEngine::AppConfig appConfig;
appConfig.Maximized = true;
appConfig.AssetsPath = "assets";
BillyEngine::Application app(appConfig);
app.LoadFont("OpenSans-Regular.ttf", "OpenSans", 28);
app.LoadFont("JetBrains Mono Regular Nerd Font Complete Mono.ttf",
"JetBrainsMono", 34);
app.CreateEntityAndAddBehavior<SpinningQuad>();
app.CreateEntityAndAddBehavior<FPSCounter>();
app.CreateEntityAndAddBehavior<MouseChaser>();
app.CreateEntityAndAddBehavior<Spawner>();
{
auto e = app.CreateEntity();
e.AddComponent<BillyEngine::Components::Text>(
"BillyEngine!", app.GetFont("JetBrainsMono"));
auto& t = e.GetComponentM<BillyEngine::Components::Transform>();
t.Position = app.GetSize() / 2;
app.RegisterEventListenerFor<BillyEngine::WindowResizeEvent>(
[&e, &app](BillyEngine::WindowResizeEvent&) -> bool {
auto& t = e.GetComponentM<BillyEngine::Components::Transform>();
t.Position = app.GetSize() / 2;
return false;
});
t.Anchor = BillyEngine::CenterPoint::CENTER_CENTER;
}
app.Run();
return 0;
}
| 32.119048 | 80 | 0.644181 | billy4479 |
f7d2d0746c75afa58e6d8203f21176da0de199d4 | 6,181 | cpp | C++ | jam/src/Mesh.cpp | gzito/jamengine | 451ab1e1d74231a3239a56aed4c40dc445fa6db8 | [
"MIT"
] | null | null | null | jam/src/Mesh.cpp | gzito/jamengine | 451ab1e1d74231a3239a56aed4c40dc445fa6db8 | [
"MIT"
] | null | null | null | jam/src/Mesh.cpp | gzito/jamengine | 451ab1e1d74231a3239a56aed4c40dc445fa6db8 | [
"MIT"
] | null | null | null | /**********************************************************************************
*
* Mesh.cpp
*
* This file is part of Jam
*
* Copyright (c) 2014-2019 Giovanni Zito.
* Copyright (c) 2014-2019 Jam contributors (cf. AUTHORS.md)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
**********************************************************************************/
#include "stdafx.h"
#include <jam/Mesh.h>
#include <jam/Gfx.h>
#include <jam/Shader.h>
namespace jam
{
//*******************
//
// Class Mesh
//
//*******************
Mesh::Mesh() :
m_pMaterial(0),
m_vertices(0),
m_normals(0),
m_texCoords(0),
m_tangents(0),
m_bitangents(0),
m_elements(0),
m_vbos(),
m_elementsVbo(),
m_vao(),
m_uploaded(false),
m_tangentsDisabled(true),
m_needsCalculateTangents(true)
{
m_pMaterial = new Material() ;
for( size_t i=0; i<m_vbos.length()-1; i++ ) {
m_vbos[i].setTarget(GL_ARRAY_BUFFER) ;
}
m_elementsVbo.setTarget(GL_ELEMENT_ARRAY_BUFFER) ;
}
Mesh::~Mesh()
{
}
void Mesh::setMaterial( Material* pMaterial )
{
m_pMaterial.assign( pMaterial, true ) ;
}
void Mesh::create(int numOfVertices, int numOfElements)
{
m_vertices.create( numOfVertices ) ;
m_normals.create( numOfVertices ) ;
m_texCoords.create( numOfVertices ) ;
m_tangents.create( numOfVertices ) ;
m_bitangents.create( numOfVertices ) ;
m_elements.create( numOfElements ) ;
}
void Mesh::destroy()
{
for( size_t i=0; i<m_vbos.length(); i++ ) {
m_vbos[i].destroy() ;
}
m_elementsVbo.destroy() ;
m_vao.destroy() ;
m_vertices.destroy() ;
m_normals.destroy() ;
m_texCoords.destroy() ;
m_tangents.destroy() ;
m_bitangents.destroy() ;
m_elements.destroy() ;
}
void Mesh::upload()
{
if( m_uploaded ) {
return ;
}
if( !m_tangentsDisabled && m_needsCalculateTangents ) {
calculateTangents() ;
}
Shader* pShader = m_pMaterial->getShader() ;
pShader->use();
for( size_t i=0; i<m_vbos.length(); i++ ) {
m_vbos[i].create() ;
}
m_vao.create() ;
// bind vao
// all glBindBuffer, glVertexAttribPointer, and glEnableVertexAttribArray calls are tracked and stored in the vao
m_vao.bind() ;
int vboIdx = 0 ;
// upload vertices
m_vbos[vboIdx].bind() ;
m_vbos[vboIdx].bufferData( m_vertices.byteSize(), m_vertices.data() ) ;
pShader->setVertexAttribPointer(JAM_PROGRAM_ATTRIB_POSITION, 3, GL_FLOAT, GL_FALSE, sizeof(Vector3), 0) ;
pShader->enableVertexAttribArray(JAM_PROGRAM_ATTRIB_POSITION) ;
// upload normals
vboIdx++;
m_vbos[vboIdx].bind() ;
m_vbos[vboIdx].bufferData( m_normals.byteSize(), m_normals.data() ) ;
pShader->setVertexAttribPointer(JAM_PROGRAM_ATTRIB_NORMAL, 3, GL_FLOAT, GL_FALSE, sizeof(Vector3), 0) ;
pShader->enableVertexAttribArray(JAM_PROGRAM_ATTRIB_NORMAL) ;
// upload texture coordinates
vboIdx++;
m_vbos[vboIdx].bind() ;
m_vbos[vboIdx].bufferData( m_texCoords.byteSize(), m_texCoords.data() ) ;
pShader->setVertexAttribPointer(JAM_PROGRAM_ATTRIB_TEXCOORDS, 2, GL_FLOAT, GL_FALSE, sizeof(Vector2), 0) ;
pShader->enableVertexAttribArray(JAM_PROGRAM_ATTRIB_TEXCOORDS) ;
// upload tangents
if( !m_tangentsDisabled ) {
vboIdx++;
m_vbos[vboIdx].bind() ;
m_vbos[vboIdx].bufferData( m_tangents.byteSize(), m_tangents.data() ) ;
pShader->setVertexAttribPointer(JAM_PROGRAM_ATTRIB_TANGENT, 3, GL_FLOAT, GL_FALSE, sizeof(Vector3), 0) ;
pShader->enableVertexAttribArray(JAM_PROGRAM_ATTRIB_TANGENT) ;
}
// upload indices
m_elementsVbo.bind() ;
m_elementsVbo.bufferData( m_elements.byteSize(), m_elements.data() ) ;
// unbind vao
m_vao.unbind() ;
// unbind ARRAY_BUFFER and ELEMENT_ARRAY_BUFFER
m_vbos[vboIdx].unbind() ;
m_elementsVbo.unbind() ;
m_uploaded = true ;
}
void Mesh::draw()
{
if( !isUploaded() ) {
upload() ;
}
GetGfx().drawIndexedPrimitive( &m_vao, getElementsArray().length(), m_pMaterial ) ;
}
void jam::Mesh::disableTangents( bool value )
{
m_tangentsDisabled = value ;
}
void Mesh::calculateTangents()
{
m_tangents.setZero() ;
m_bitangents.setZero() ;
U16* triangle = m_elements.data() ;
Vector3* vertex = m_vertices.data() ;
Vector2* texcoord = m_texCoords.data() ;
for (U16 a = 0; a < m_elements.length(); a += 3)
{
U16 i1 = triangle[a];
U16 i2 = triangle[a+1];
U16 i3 = triangle[a+2];
const Vector3& v1 = vertex[i1];
const Vector3& v2 = vertex[i2];
const Vector3& v3 = vertex[i3];
const Vector2& w1 = texcoord[i1];
const Vector2& w2 = texcoord[i2];
const Vector2& w3 = texcoord[i3];
F32 x1 = v2.x - v1.x;
F32 x2 = v3.x - v1.x;
F32 y1 = v2.y - v1.y;
F32 y2 = v3.y - v1.y;
F32 z1 = v2.z - v1.z;
F32 z2 = v3.z - v1.z;
F32 s1 = w2.x - w1.x;
F32 s2 = w3.x - w1.x;
F32 t1 = w2.y - w1.y;
F32 t2 = w3.y - w1.y;
F32 r = 1.0f / (s1 * t2 - s2 * t1);
Vector3 sdir( (t2 * x1 - t1 * x2) * r, (t2 * y1 - t1 * y2) * r, (t2 * z1 - t1 * z2) * r ) ;
Vector3 tdir( (s1 * x2 - s2 * x1) * r, (s1 * y2 - s2 * y1) * r, (s1 * z2 - s2 * z1) * r ) ;
m_tangents[i1] += sdir;
m_tangents[i2] += sdir;
m_tangents[i3] += sdir;
m_bitangents[i1] += tdir;
m_bitangents[i2] += tdir;
m_bitangents[i3] += tdir;
}
m_needsCalculateTangents = false ;
}
void Mesh::doNotCalculateTangents()
{
m_needsCalculateTangents = false ;
}
}
| 25.861925 | 114 | 0.671089 | gzito |
f7d7049d6742e27e9e4a4d22bbf965c17bba297a | 3,607 | hh | C++ | t6/src/SWE_WavePropagationBlockCuda.hh | PhuNH/hpc-aa | c1d184ec7c04b6ce7078c22d7a03091a95a4a2be | [
"MIT"
] | 1 | 2020-05-11T18:28:17.000Z | 2020-05-11T18:28:17.000Z | t6/src/SWE_WavePropagationBlockCuda.hh | PhuNH/hpc-aa | c1d184ec7c04b6ce7078c22d7a03091a95a4a2be | [
"MIT"
] | null | null | null | t6/src/SWE_WavePropagationBlockCuda.hh | PhuNH/hpc-aa | c1d184ec7c04b6ce7078c22d7a03091a95a4a2be | [
"MIT"
] | null | null | null | /**
* @file
* This file is part of SWE.
*
* @author Alexander Breuer (breuera AT in.tum.de, http://www5.in.tum.de/wiki/index.php/Dipl.-Math._Alexander_Breuer)
* @author Sebastian Rettenberger (rettenbs AT in.tum.de, http://www5.in.tum.de/wiki/index.php/Sebastian_Rettenberger,_M.Sc.)
*
* @section LICENSE
*
* SWE 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.
*
* SWE 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 SWE. If not, see <http://www.gnu.org/licenses/>.
*
*
* @section DESCRIPTION
*
* SWE_Block in CUDA, which uses solvers in the wave propagation formulation.
*/
#ifndef SWEWAVEPROPAGATIONBLOCKCUDA_HH_
#define SWEWAVEPROPAGATIONBLOCKCUDA_HH_
#include <cassert>
#include "SWE_BlockCUDA.hh"
/**
* SWE_WavePropagationBlockCuda is an implementation of the SWE_BlockCuda abstract class.
* It uses a wave propagation solver which is defined with the pre-compiler flag WAVE_PROPAGATION_SOLVER (see above).
*
* Possible wave propagation solvers are:
* F-Wave, <strike>Approximate Augmented Riemann, Hybrid (f-wave + augmented).</strike>
* (details can be found in the corresponding source files)
*/
class SWE_WavePropagationBlockCuda: public SWE_BlockCUDA {
//private:
//! "2D array" which holds the net-updates for the water height (wave propagating to the left).
float* hNetUpdatesLeftD;
//! "2D array" which holds the net-updates for the water height (wave propagating to the right).
float* hNetUpdatesRightD;
//! "2D array" which holds the net-updates for the momentum in x-direction (wave propagating to the left).
float* huNetUpdatesLeftD;
//! "2D array" which holds the net-updates for the momentum in x-direction (wave propagating to the right).
float* huNetUpdatesRightD;
//! "2D array" which holds the net-updates for the water height (wave propagating to the top).
float* hNetUpdatesBelowD;
//! "2D array" which holds the net-updates for the water height (wave propagating to the bottom).
float* hNetUpdatesAboveD;
//! "2D array" which holds the net-updates for the momentum in y-direction (wave propagating to the top).
float* hvNetUpdatesBelowD;
//! "2D array" which holds the net-updates for the momentum in y-direction (wave propagating to the bottom).
float* hvNetUpdatesAboveD;
public:
// constructor of SWE_WavePropagationBlockCuda
SWE_WavePropagationBlockCuda( const int i_cudaDevice = 0 );
// destructor of SWE_WavePropagationBlockCuda
~SWE_WavePropagationBlockCuda();
// compute a single time step (net-updates + update of the cells).
void simulateTimestep( float i_dT );
// simulate multiple time steps (start and end time provided as parameters)
float simulate(float, float);
// TODO: not implemented, max time step reduction is done in each call of computeNumericalFluxes(...)
//void computeMaxTimestep() {
// assert(false);
//};
// compute the numerical fluxes (net-update formulation here).
void computeNumericalFluxes();
// compute the new cell values.
void updateUnknowns(const float i_deltaT);
};
#endif /* SWEWAVEPROPAGATIONBLOCKCUDA_HH_ */
| 39.206522 | 125 | 0.73191 | PhuNH |
f7d970d0ec992544da3f6ca5196ae68e4bd81195 | 7,381 | hpp | C++ | Old/tests/fept_test.hpp | waterswims/MC_HAMR | eb0492bc12a6eb67ec1709e5b59bdd53ee999892 | [
"MIT"
] | 1 | 2021-08-02T23:14:45.000Z | 2021-08-02T23:14:45.000Z | Old/tests/fept_test.hpp | waterswims/MC_HAMR | eb0492bc12a6eb67ec1709e5b59bdd53ee999892 | [
"MIT"
] | null | null | null | Old/tests/fept_test.hpp | waterswims/MC_HAMR | eb0492bc12a6eb67ec1709e5b59bdd53ee999892 | [
"MIT"
] | 1 | 2021-08-02T23:14:45.000Z | 2021-08-02T23:14:45.000Z | #ifndef _FEPTTEST
#define _FEPTTEST
#include "test_functions.hpp"
///////////////////////////////////////////////////////
// FePt model tests - 3D
///////////////////////////////////////////////////////
TEST(FePt, 3d_energy_zero_field)
{
field_3d_h field = gen_3d_heis_fm(1, 0, 0);
ham_FePt hamil;
hamil.init_dim(&field);
EXPECT_FLOAT_EQ(-94845.01392843794, hamil.calc_E(&field));
field = gen_3d_heis_fm(0, 1, 0);
EXPECT_FLOAT_EQ(-94845.01392843794, hamil.calc_E(&field));
field = gen_3d_heis_fm(0, 0, 1);
EXPECT_FLOAT_EQ(-96045.87686933874, hamil.calc_E(&field));
field = gen_3d_heis_fm(-1, 0, 0);
EXPECT_FLOAT_EQ(-94845.01392843794, hamil.calc_E(&field));
field = gen_3d_heis_fm(0, -1, 0);
EXPECT_FLOAT_EQ(-94845.01392843794, hamil.calc_E(&field));
field = gen_3d_heis_fm(0, 0, -1);
EXPECT_FLOAT_EQ(-96045.87686933874, hamil.calc_E(&field));
// Anti
field = gen_3d_heis_afm(1, 0, 0);
EXPECT_FLOAT_EQ(14349.191660944736, hamil.calc_E(&field));
field = gen_3d_heis_afm(0, 1, 0);
EXPECT_FLOAT_EQ(14349.191660944736, hamil.calc_E(&field));
field = gen_3d_heis_afm(0, 0, 1);
EXPECT_FLOAT_EQ(14481.605270298143, hamil.calc_E(&field));
field = gen_3d_heis_afm(-1, 0, 0);
EXPECT_FLOAT_EQ(14349.191660944736, hamil.calc_E(&field));
field = gen_3d_heis_afm(0, -1, 0);
EXPECT_FLOAT_EQ(14349.191660944736, hamil.calc_E(&field));
field = gen_3d_heis_afm(0, 0, -1);
EXPECT_FLOAT_EQ(14481.605270298143, hamil.calc_E(&field));
}
TEST(FePt, 3d_energy_ext_field)
{
field_3d_h field = gen_3d_heis_fm(1, 0, 0);
ham_FePt hamil(1);
hamil.init_dim(&field);
EXPECT_FLOAT_EQ(-94845.01392843794, hamil.calc_E(&field));
field = gen_3d_heis_fm(0, 1, 0);
EXPECT_FLOAT_EQ(-94845.01392843794, hamil.calc_E(&field));
field = gen_3d_heis_fm(0, 0, 1);
EXPECT_FLOAT_EQ(-97045.87686933874, hamil.calc_E(&field));
field = gen_3d_heis_fm(-1, 0, 0);
EXPECT_FLOAT_EQ(-94845.01392843794, hamil.calc_E(&field));
field = gen_3d_heis_fm(0, -1, 0);
EXPECT_FLOAT_EQ(-94845.01392843794, hamil.calc_E(&field));
field = gen_3d_heis_fm(0, 0, -1);
EXPECT_FLOAT_EQ(-95045.87686933874, hamil.calc_E(&field));
// Anti
field = gen_3d_heis_afm(1, 0, 0);
EXPECT_FLOAT_EQ(14349.191660944736, hamil.calc_E(&field));
field = gen_3d_heis_afm(0, 1, 0);
EXPECT_FLOAT_EQ(14349.191660944736, hamil.calc_E(&field));
field = gen_3d_heis_afm(0, 0, 1);
EXPECT_FLOAT_EQ(14481.605270298143, hamil.calc_E(&field));
field = gen_3d_heis_afm(-1, 0, 0);
EXPECT_FLOAT_EQ(14349.191660944736, hamil.calc_E(&field));
field = gen_3d_heis_afm(0, -1, 0);
EXPECT_FLOAT_EQ(14349.191660944736, hamil.calc_E(&field));
field = gen_3d_heis_afm(0, 0, -1);
EXPECT_FLOAT_EQ(14481.605270298143, hamil.calc_E(&field));
}
TEST(FePt, 3d_mag)
{
field_3d_h field = gen_3d_heis_fm(1, 0, 0);
ham_FePt hamil;
hamil.init_dim(&field);
std::vector<double> mag = hamil.calc_M(&field);
EXPECT_EQ(1000, mag[0]);
EXPECT_EQ(0, mag[1]);
EXPECT_EQ(0, mag[2]);
field = gen_3d_heis_fm(-1, 0, 0);
mag = hamil.calc_M(&field);
EXPECT_EQ(-1000, mag[0]);
EXPECT_EQ(0, mag[1]);
EXPECT_EQ(0, mag[2]);
field = gen_3d_heis_fm(0, 1, 0);
mag = hamil.calc_M(&field);
EXPECT_EQ(0, mag[0]);
EXPECT_EQ(1000, mag[1]);
EXPECT_EQ(0, mag[2]);
field = gen_3d_heis_fm(0, -1, 0);
mag = hamil.calc_M(&field);
EXPECT_EQ(0, mag[0]);
EXPECT_EQ(-1000, mag[1]);
EXPECT_EQ(0, mag[2]);
field = gen_3d_heis_fm(0, 0, 1);
mag = hamil.calc_M(&field);
EXPECT_EQ(0, mag[0]);
EXPECT_EQ(0, mag[1]);
EXPECT_EQ(1000, mag[2]);
field = gen_3d_heis_fm(0, 0, -1);
mag = hamil.calc_M(&field);
EXPECT_EQ(0, mag[0]);
EXPECT_EQ(0, mag[1]);
EXPECT_EQ(-1000, mag[2]);
field = gen_3d_heis_afm(1, 0, 0);
mag = hamil.calc_M(&field);
EXPECT_EQ(0, mag[0]);
EXPECT_EQ(0, mag[1]);
EXPECT_EQ(0, mag[2]);
field = gen_3d_heis_afm(-1, 0, 0);
mag = hamil.calc_M(&field);
EXPECT_EQ(0, mag[0]);
EXPECT_EQ(0, mag[1]);
EXPECT_EQ(0, mag[2]);
field = gen_3d_heis_afm(0, 1, 0);
mag = hamil.calc_M(&field);
EXPECT_EQ(0, mag[0]);
EXPECT_EQ(0, mag[1]);
EXPECT_EQ(0, mag[2]);
field = gen_3d_heis_afm(0, -1, 0);
mag = hamil.calc_M(&field);
EXPECT_EQ(0, mag[0]);
EXPECT_EQ(0, mag[1]);
EXPECT_EQ(0, mag[2]);
field = gen_3d_heis_afm(0, 0, 1);
mag = hamil.calc_M(&field);
EXPECT_EQ(0, mag[0]);
EXPECT_EQ(0, mag[1]);
EXPECT_EQ(0, mag[2]);
field = gen_3d_heis_afm(0, 0, -1);
mag = hamil.calc_M(&field);
EXPECT_EQ(0, mag[0]);
EXPECT_EQ(0, mag[1]);
EXPECT_EQ(0, mag[2]);
}
TEST(FePt, 3d_submag)
{
field_3d_h field = gen_3d_heis_fm(1, 0, 0);
ham_FePt hamil;
hamil.init_dim(&field);
std::vector<double> mag = hamil.calc_subM(&field, 1);
EXPECT_EQ(500, mag[0]);
EXPECT_EQ(0, mag[1]);
EXPECT_EQ(0, mag[2]);
field = gen_3d_heis_fm(-1, 0, 0);
mag = hamil.calc_subM(&field, 1);
EXPECT_EQ(-500, mag[0]);
EXPECT_EQ(0, mag[1]);
EXPECT_EQ(0, mag[2]);
field = gen_3d_heis_fm(0, 1, 0);
mag = hamil.calc_subM(&field, 1);
EXPECT_EQ(0, mag[0]);
EXPECT_EQ(500, mag[1]);
EXPECT_EQ(0, mag[2]);
field = gen_3d_heis_fm(0, -1, 0);
mag = hamil.calc_subM(&field, 1);
EXPECT_EQ(0, mag[0]);
EXPECT_EQ(-500, mag[1]);
EXPECT_EQ(0, mag[2]);
field = gen_3d_heis_fm(0, 0, 1);
mag = hamil.calc_subM(&field, 1);
EXPECT_EQ(0, mag[0]);
EXPECT_EQ(0, mag[1]);
EXPECT_EQ(500, mag[2]);
field = gen_3d_heis_fm(0, 0, -1);
mag = hamil.calc_subM(&field, 1);
EXPECT_EQ(0, mag[0]);
EXPECT_EQ(0, mag[1]);
EXPECT_EQ(-500, mag[2]);
field = gen_3d_heis_afm(1, 0, 0);
mag = hamil.calc_subM(&field, 1);
EXPECT_EQ(500, mag[0]);
EXPECT_EQ(0, mag[1]);
EXPECT_EQ(0, mag[2]);
field = gen_3d_heis_afm(-1, 0, 0);
mag = hamil.calc_subM(&field, 1);
EXPECT_EQ(-500, mag[0]);
EXPECT_EQ(0, mag[1]);
EXPECT_EQ(0, mag[2]);
field = gen_3d_heis_afm(0, 1, 0);
mag = hamil.calc_subM(&field, 1);
EXPECT_EQ(0, mag[0]);
EXPECT_EQ(500, mag[1]);
EXPECT_EQ(0, mag[2]);
field = gen_3d_heis_afm(0, -1, 0);
mag = hamil.calc_subM(&field, 1);
EXPECT_EQ(0, mag[0]);
EXPECT_EQ(-500, mag[1]);
EXPECT_EQ(0, mag[2]);
field = gen_3d_heis_afm(0, 0, 1);
mag = hamil.calc_subM(&field, 1);
EXPECT_EQ(0, mag[0]);
EXPECT_EQ(0, mag[1]);
EXPECT_EQ(500, mag[2]);
field = gen_3d_heis_afm(0, 0, -1);
mag = hamil.calc_subM(&field, 1);
EXPECT_EQ(0, mag[0]);
EXPECT_EQ(0, mag[1]);
EXPECT_EQ(-500, mag[2]);
}
TEST(FePt, 3d_dE_consist)
{
field_3d_h field = gen_3d_heis_fm(1, 0, 0);
ham_FePt hamil(4);
hamil.init_dim(&field);
std::vector<int> pos(3);
double old_E = hamil.calc_E(&field);
for(int i = 0; i < 100; i++)
{
pos[0] = int(st_rand_double.gen()*10 + 1);
pos[1] = int(st_rand_double.gen()*10 + 1);
pos[2] = int(st_rand_double.gen()*10 + 1);
double dE = hamil.dE(&field, pos);
field.change_to_test(pos, &hamil);
double new_E = hamil.calc_E(&field);
EXPECT_FLOAT_EQ(old_E + dE, new_E);
old_E = new_E;
}
}
#endif
| 27.438662 | 62 | 0.606151 | waterswims |
f7dbce953e61954bc8871fe27a97e70b08f5e4d2 | 3,757 | cc | C++ | src/mesh/mesh_moab/test/test_hex_2x2x1.cc | ajkhattak/amanzi | fed8cae6af3f9dfa5984381d34b98401c3b47655 | [
"RSA-MD"
] | 1 | 2021-02-23T18:34:47.000Z | 2021-02-23T18:34:47.000Z | src/mesh/mesh_moab/test/test_hex_2x2x1.cc | ajkhattak/amanzi | fed8cae6af3f9dfa5984381d34b98401c3b47655 | [
"RSA-MD"
] | null | null | null | src/mesh/mesh_moab/test/test_hex_2x2x1.cc | ajkhattak/amanzi | fed8cae6af3f9dfa5984381d34b98401c3b47655 | [
"RSA-MD"
] | null | null | null | #include <iostream>
#include "Epetra_Map.h"
#include "mpi.h"
#include "UnitTest++.h"
#include "AmanziComm.hh"
#include "../Mesh_MOAB.hh"
TEST(MOAB_HEX_2x2x1)
{
int i, j, k, nc, nf, nv;
Amanzi::AmanziMesh::Entity_ID_List faces, cnodes, fnodes;
std::vector<int> facedirs;
std::vector<Amanzi::AmanziGeometry::Point> ccoords, fcoords;
int NV = 18;
int NF = 20;
int NC = 4;
double xyz[18][3] = {{-0.5,-0.5, 0.25},
{-0.5,-0.5,-0.25},
{-0.5, 0, -0.25},
{-0.5, 0, 0.25},
{ 0, -0.5, 0.25},
{ 0, -0.5,-0.25},
{ 0, 0, -0.25},
{ 0, 0, 0.25},
{-0.5, 0.5,-0.25},
{-0.5, 0.5, 0.25},
{ 0, 0.5,-0.25},
{ 0, 0.5, 0.25},
{ 0.5,-0.5, 0.25},
{ 0.5,-0.5,-0.25},
{ 0.5, 0, -0.25},
{ 0.5, 0, 0.25},
{ 0.5, 0.5,-0.25},
{ 0.5, 0.5, 0.25}};
unsigned int cellnodes[4][8] = {{0,1,2,3,4,5,6,7},
{3,2,8,9,7,6,10,11},
{4,5,6,7,12,13,14,15},
{7,6,10,11,15,14,16,17}};
unsigned int cellfaces[4][6] = {{8,4,16,0,10,17},
{16,5,12,1,11,18},
{9,6,19,2,17,14},
{19,7,13,3,18,15}};
int cellfacedirs[4][6] = {{1,1,1,1,1,1},
{-1,1,1,1,1,1},
{1,1,1,1,-1,1},
{-1,1,1,1,-1,1}};
unsigned int facenodes[20][4] = {{3,0,4,7},
{9,3,7,11},
{7,4,12,15},
{11,7,15,17},
{1,2,6,5},
{2,8,10,6},
{5,6,14,13},
{6,10,16,14},
{0,1,5,4},
{4,5,13,12},
{0,3,2,1},
{3,9,8,2},
{8,9,11,10},
{10,11,17,16},
{12,13,14,15},
{15,14,16,17},
{2,3,7,6},
{4,5,6,7},
{7,6,10,11},
{6,7,15,14}};
unsigned int cfstd[6][4] = {{0,1,5,4}, // Expected cell-face-node pattern
{1,2,6,5},
{2,3,7,6},
{3,0,4,7},
{0,3,2,1},
{4,5,6,7}};
auto comm = Amanzi::getDefaultComm();
// Load four hexes from the ExodusII file
Amanzi::AmanziMesh::Mesh_MOAB mesh("test/hex_2x2x1_ss.exo",comm);
nv = mesh.num_entities(Amanzi::AmanziMesh::NODE,Amanzi::AmanziMesh::Parallel_type::OWNED);
CHECK_EQUAL(NV,nv);
for (i = 0; i < nv; i++) {
Amanzi::AmanziGeometry::Point coords;
mesh.node_get_coordinates(i,&coords);
CHECK_ARRAY_EQUAL(xyz[i],coords,3);
}
nf = mesh.num_entities(Amanzi::AmanziMesh::FACE,Amanzi::AmanziMesh::Parallel_type::OWNED);
CHECK_EQUAL(NF,nf);
nc = mesh.num_entities(Amanzi::AmanziMesh::CELL,Amanzi::AmanziMesh::Parallel_type::OWNED);
CHECK_EQUAL(NC,nc);
for (i = 0; i < nc; i++) {
mesh.cell_get_nodes(i,&cnodes);
mesh.cell_get_faces_and_dirs(i,&faces,&facedirs,true);
CHECK_ARRAY_EQUAL(cellfaces[i],faces,6);
CHECK_ARRAY_EQUAL(cellfacedirs[i],facedirs,6);
for (j = 0; j < 6; j++) {
mesh.face_get_nodes(faces[j],&fnodes);
mesh.face_get_coordinates(faces[j],&fcoords);
for (k = 0; k < 4; k++) {
CHECK_EQUAL(facenodes[faces[j]][k],fnodes[k]);
CHECK_ARRAY_EQUAL(xyz[facenodes[faces[j]][k]],&(fcoords[k][0]),3);
}
}
mesh.cell_get_coordinates(i,&ccoords);
for (j = 0; j < 8; j++) {
CHECK_EQUAL(cellnodes[i][j],cnodes[j]);
CHECK_ARRAY_EQUAL(xyz[cellnodes[i][j]],&(ccoords[j][0]),3);
}
}
// verify global IDs
Amanzi::AmanziMesh::Entity_ID_List c2f;
Epetra_Map cell_map(mesh.cell_map(true));
Epetra_Map face_map(mesh.face_map(false));
for (int c = cell_map.MinLID(); c <= cell_map.MaxLID(); c++) {
CHECK_EQUAL(cell_map.GID(c),mesh.GID(c,Amanzi::AmanziMesh::CELL));
mesh.cell_get_faces( c, &c2f, true );
for (j = 0; j < 6; ++j) {
int f = face_map.LID(mesh.GID(c2f[j],Amanzi::AmanziMesh::FACE));
CHECK(f == c2f[j]);
}
}
}
| 25.910345 | 92 | 0.519031 | ajkhattak |
f7e0c6d004b5f8e9f0805e3566a8a2c6f6d75b4c | 935 | cpp | C++ | Broccoli/src/Broccoli/Renderer/Texture.cpp | tross2552/broccoli | d7afc472e076fa801d0e7745e209553b73c34486 | [
"Apache-2.0"
] | 1 | 2021-08-03T01:38:41.000Z | 2021-08-03T01:38:41.000Z | Broccoli/src/Broccoli/Renderer/Texture.cpp | tross2552/broccoli | d7afc472e076fa801d0e7745e209553b73c34486 | [
"Apache-2.0"
] | null | null | null | Broccoli/src/Broccoli/Renderer/Texture.cpp | tross2552/broccoli | d7afc472e076fa801d0e7745e209553b73c34486 | [
"Apache-2.0"
] | null | null | null | #include "brclpch.h"
#include "Texture.h"
#include "Renderer.h"
#include "Platform/OpenGL/OpenGLTexture2D.h"
namespace brcl
{
std::unique_ptr<Texture2D> Texture2D::Create(uint32_t width, uint32_t height)
{
switch (renderer::GetAPI())
{
case RendererAPI::API::None: BRCL_CORE_ASSERT(false, "RendererAPI::None is currently not supported!"); return nullptr;
case RendererAPI::API::OpenGL: return std::make_unique<OpenGLTexture2D>(width, height);
}
BRCL_CORE_ASSERT(false, "Unknown RendererAPI!");
return nullptr;
}
std::unique_ptr<Texture2D> Texture2D::Create(const std::string& path)
{
switch (renderer::GetAPI())
{
case RendererAPI::API::None: BRCL_CORE_ASSERT(false, "RendererAPI::None is currently not supported!"); return nullptr;
case RendererAPI::API::OpenGL: return std::make_unique<OpenGLTexture2D>(path);
}
BRCL_CORE_ASSERT(false, "Unknown RendererAPI!");
return nullptr;
}
}
| 26.714286 | 123 | 0.727273 | tross2552 |
f7e46bdfad7e6ac25dfba5aeb2c6ae0fa1f3440d | 5,216 | cpp | C++ | OSS13 Server/Sources/Player/PlayerCommandsProcessor.cpp | edge-fortress/OSS-13 | eaf8f000b0049656939a82a38e5d6fc836178bde | [
"MIT"
] | 21 | 2019-05-07T23:39:11.000Z | 2021-11-16T13:08:36.000Z | OSS13 Server/Sources/Player/PlayerCommandsProcessor.cpp | edge-fortress/OSS-13 | eaf8f000b0049656939a82a38e5d6fc836178bde | [
"MIT"
] | 52 | 2019-04-28T21:42:10.000Z | 2021-08-06T07:56:55.000Z | OSS13 Server/Sources/Player/PlayerCommandsProcessor.cpp | edge-fortress/OSS-13 | eaf8f000b0049656939a82a38e5d6fc836178bde | [
"MIT"
] | 5 | 2019-05-09T16:03:53.000Z | 2021-07-27T08:48:02.000Z | #include "PlayerCommandsProcessor.h"
#include "Player.h"
#include <Game.h>
#include <IScriptEngine.h>
#include <World/Objects/Object.hpp>
#include <World/Objects/Control.hpp>
#include <Shared/ErrorHandling.h>
#include <Shared/Network/Protocol/ServerToClient/Commands.h>
using namespace std::string_literals;
PlayerCommandsProcessor::PlayerCommandsProcessor(Player *player)
: player(player)
{ }
void PlayerCommandsProcessor::ProcessCommand(network::protocol::Command &generalCommand) {
using namespace network::protocol::client;
_REGISTRATE_COMMAND_PROCESSOR(MoveCommand);
_REGISTRATE_COMMAND_PROCESSOR(MoveZCommand);
_REGISTRATE_COMMAND_PROCESSOR(ClickObjectCommand);
_REGISTRATE_COMMAND_PROCESSOR(ClickTileCommand);
_REGISTRATE_COMMAND_PROCESSOR(ClickControlUICommand);
_REGISTRATE_COMMAND_PROCESSOR(SendChatMessageCommand);
_REGISTRATE_COMMAND_PROCESSOR(UIInputCommand);
_REGISTRATE_COMMAND_PROCESSOR(UITriggerCommand);
_REGISTRATE_COMMAND_PROCESSOR(CallVerbCommand);
_REGISTRATE_COMMAND_PROCESSOR(SpawnWindowSearchCommand);
_REGISTRATE_COMMAND_PROCESSOR(SpawnWindowSpawnCommand);
_REGISTRATE_COMMAND_PROCESSOR(ContextMenuUpdateCommand);
_REGISTRATE_COMMAND_PROCESSOR(ContextMenuClickCommand);
LOGE << __FUNCTION__ << ": unknown command (ser id is 0x" << std::hex << generalCommand.SerID() << ") was not processed! "
<< "Player: " << player->GetCKey();
}
void PlayerCommandsProcessor::commandProcessor_MoveCommand(network::protocol::client::MoveCommand &command) {
auto control = player->GetControl();
if (control) {
control->MoveCommand(uf::DirectionToVect(command.direction).xy());
}
}
void PlayerCommandsProcessor::commandProcessor_MoveZCommand(network::protocol::client::MoveZCommand &command) {
auto control = player->GetControl();
if (control) {
control->MoveZCommand(command.up);
}
}
void PlayerCommandsProcessor::commandProcessor_ClickObjectCommand(network::protocol::client::ClickObjectCommand &command) {
auto control = player->GetControl();
if (control) {
control->ClickObjectCommand(command.id);
}
}
void PlayerCommandsProcessor::commandProcessor_ClickTileCommand(network::protocol::client::ClickTileCommand &command) {
auto control = player->GetControl();
if (control) {
control->ClickTileCommand(player->camera->ViewCoordsToWorldCoords(command.pos));
}
}
void PlayerCommandsProcessor::commandProcessor_ClickControlUICommand(network::protocol::client::ClickControlUICommand &command) {
auto control = player->GetControl();
if (control) {
control->ClickUICommand(command.id);
}
}
void PlayerCommandsProcessor::commandProcessor_SendChatMessageCommand(network::protocol::client::SendChatMessageCommand &command) {
GGame->GetChat()->AddMessage("<" + player->GetCKey() + ">" + command.message);
}
void PlayerCommandsProcessor::commandProcessor_UIInputCommand(network::protocol::client::UIInputCommand &command) {
auto iter = player->uiSinks.find(command.data->window);
if (iter != player->uiSinks.end())
iter->second->OnInput(command.data->handle, std::forward<std::unique_ptr<network::protocol::UIData>>(command.data));
}
void PlayerCommandsProcessor::commandProcessor_UITriggerCommand(network::protocol::client::UITriggerCommand &command) {
auto iter = player->uiSinks.find(command.window);
if (iter != player->uiSinks.end())
iter->second->OnTrigger(command.trigger);
}
void PlayerCommandsProcessor::commandProcessor_CallVerbCommand(network::protocol::client::CallVerbCommand &command) {
auto &verb = command.verb;
try {
auto delimiter = verb.find(".");
EXPECT(delimiter != verb.npos);
std::string verbHolder = verb.substr(0, delimiter);
std::string verbName = verb.substr(delimiter + 1);
auto nameAndVerbHolder = player->verbsHolders.find(verbHolder);
EXPECT_WITH_MSG(nameAndVerbHolder != player->verbsHolders.end(), "VerbHolder \""s + verbHolder + "\" doesn't exist!");
nameAndVerbHolder->second->CallVerb(player, verbName);
} catch (const std::exception &e) {
MANAGE_EXCEPTION(e);
}
}
void PlayerCommandsProcessor::commandProcessor_SpawnWindowSearchCommand(network::protocol::client::SpawnWindowSearchCommand &command) {
auto types = GGame->GetScriptEngine()->GetTypesInfo(command.searchBuffer);
auto answer = std::make_unique<network::protocol::server::UpdateSpawnWindowCommand>();
for (auto type : types)
answer->types.push_back(*type);
player->AddCommandToClient(answer.release());
}
void PlayerCommandsProcessor::commandProcessor_SpawnWindowSpawnCommand(network::protocol::client::SpawnWindowSpawnCommand &command) {
auto control = player->GetControl();
if (control) {
auto *obj = GGame->GetScriptEngine()->CreateObject(command.typeKey);
if (obj)
obj->SetTile(control->GetOwner()->GetTile());
}
}
void PlayerCommandsProcessor::commandProcessor_ContextMenuUpdateCommand(network::protocol::client::ContextMenuUpdateCommand &command) {
auto camera = player->GetCamera();
EXPECT(camera);
camera->AskUpdateContextMenu(command.tileCoords);
}
void PlayerCommandsProcessor::commandProcessor_ContextMenuClickCommand(network::protocol::client::ContextMenuClickCommand &command) {
auto camera = player->GetCamera();
EXPECT(camera);
camera->ClickContextMenu(command.node, command.verb);
}
| 37.797101 | 135 | 0.786235 | edge-fortress |
f7e8b11ae57f39a2e2bbadad65377a146cf1e02d | 570 | cpp | C++ | Classes/Hole.cpp | khanhdrag9/TetrisHole | d2773cb9da0756c4d8a2f0e8ef7823fb7de8584c | [
"MIT"
] | null | null | null | Classes/Hole.cpp | khanhdrag9/TetrisHole | d2773cb9da0756c4d8a2f0e8ef7823fb7de8584c | [
"MIT"
] | null | null | null | Classes/Hole.cpp | khanhdrag9/TetrisHole | d2773cb9da0756c4d8a2f0e8ef7823fb7de8584c | [
"MIT"
] | null | null | null | #include "Hole.h"
#include "Skill.h"
#include "Board.h"
#include "Templates.h"
Hole::Hole():
_spriteNode(nullptr),
_boardParrent(nullptr),
_skill(nullptr)
{
_spriteNode = Node::create();
}
Hole::~Hole()
{
CC_SAFE_DELETE(_spriteNode);
_boardParrent = nullptr;
_skill = nullptr;
}
void Hole::useSkill(float dt)
{
if (_skill && _boardParrent)
{
this->_skill->use(dt);
}
}
void Hole::setSkill(const skill skill, std::function<void()> callback)
{
if (skill == skill::stuck)
{
_skill = make_unique<Suck>(shared_from_this(), callback);
}
}
| 15.405405 | 70 | 0.659649 | khanhdrag9 |
f7e8b64b0a7a4fe217770f73ffee035b4abcf3b0 | 871 | cpp | C++ | Snippets/lazy-segtree.cpp | KerakTelor86/CP-Stuff | 31269195a913d55826fd2e34b091d0cd186c7af9 | [
"Unlicense"
] | null | null | null | Snippets/lazy-segtree.cpp | KerakTelor86/CP-Stuff | 31269195a913d55826fd2e34b091d0cd186c7af9 | [
"Unlicense"
] | null | null | null | Snippets/lazy-segtree.cpp | KerakTelor86/CP-Stuff | 31269195a913d55826fd2e34b091d0cd186c7af9 | [
"Unlicense"
] | null | null | null | int n;
vector<ll> seg,lazy;
void propagate(int idx,int l,int r)
{
if(!lazy[idx])
return;
int lc=(idx<<1)+1,rc=lc+1;
seg[idx]+=(r-l+1)*lazy[idx];
if(l!=r)
{
lazy[lc]+=lazy[idx];
lazy[rc]+=lazy[idx];
}
lazy[idx]=0;
}
void update(int u,int v,int w,int idx=0,int l=0,int r=n-1)
{
propagate(idx,l,r);
if(u>r||v<l)
return;
if(u<=l&&v>=r)
{
lazy[idx]+=w;
propagate(idx,l,r);
return;
}
int lc=(idx<<1)+1,rc=lc+1,m=l+((r-l)>>1);
update(u,v,w,lc,l,m);
update(u,v,w,rc,m+1,r);
seg[idx]=seg[lc]+seg[rc];
}
ll query(int u,int v,int idx=0,int l=0,int r=n-1)
{
propagate(idx,l,r);
if(u>r||v<l)
return 0;
if(u<=l&&v>=r)
return seg[idx];
int lc=(idx<<1)+1,rc=lc+1,m=l+((r-l)>>1);
return query(u,v,lc,l,m)+query(u,v,rc,m+1,r);
}
| 18.934783 | 58 | 0.482204 | KerakTelor86 |