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 float64 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 float64 1 77k ⌀ | 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 float64 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 653k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bd4ad8dd12486df8755c5e838cff0515b5743778 | 471 | cpp | C++ | 1877/main.cpp | exaw/timustasks | d0c4cb797e6063d35f25842712a8417fdfd8f4d4 | [
"MIT"
] | null | null | null | 1877/main.cpp | exaw/timustasks | d0c4cb797e6063d35f25842712a8417fdfd8f4d4 | [
"MIT"
] | null | null | null | 1877/main.cpp | exaw/timustasks | d0c4cb797e6063d35f25842712a8417fdfd8f4d4 | [
"MIT"
] | null | null | null |
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <iostream>
#include <map>
#include <numeric>
#include <set>
#include <string>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
using namespace std;
int main ()
{
ios_base::sync_with_stdio (false);
int k1 = 0, k2 = 0;
cin>>k1>>k2;
if ( k1 % 2 == 0 || k2 % 2 == 1 )
cout<<"yes"<<endl;
else
cout<<"no"<<endl;
return 0;
}
| 13.083333 | 38 | 0.592357 |
bd4c88fc07fc54030e8fdb491e4e92333d27d6db | 5,124 | cc | C++ | src/test/test-mysql.cc | lujingwei002/coord | cb5e5723293d8529663ca89e0c1d6b8c348fffff | [
"MIT"
] | null | null | null | src/test/test-mysql.cc | lujingwei002/coord | cb5e5723293d8529663ca89e0c1d6b8c348fffff | [
"MIT"
] | null | null | null | src/test/test-mysql.cc | lujingwei002/coord | cb5e5723293d8529663ca89e0c1d6b8c348fffff | [
"MIT"
] | null | null | null | #include "coord/coord.h"
#include "gtest/gtest.h"
#include "coord/builtin/slice.h"
#include "coord/sql/init.h"
#include "coord/sql/mysql/init.h"
#include "coord/config/config.h"
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <cstdlib>
class TestMySQL : public testing::Test {
public:
static void SetUpTestCase() {
}
static void TearDownTestCase() {
}
void SetUp() {
auto coord = coord::NewCoord();
int err = coord->beforeTest("test/test.ini");
ASSERT_EQ(err, 0);
this->sqlMgr = coord::sql::newSQLMgr(coord);
this->coord = coord;
}
void TearDown() {
int err = this->coord->afterTest();
ASSERT_EQ(err, 0);
delete this->coord;
}
public:
coord::Coord* coord;
coord::sql::sql_mgr* sqlMgr;
};
class Test1 {
public:
Test1(const char* name) {
this->name = name;
}
void hello1(const char* w) {
printf("aaa %s %s\n", this->name.c_str(), w);
}
void hello2(const char* w) {
printf("aaa %s %s\n", this->name.c_str(), w);
}
public:
std::string name;
};
typedef std::function<void (const char* w)> TestFunction;
TEST_F(TestMySQL, TestSetGet) {
Test1* t1 = new Test1("t1");
Test1* t2 = new Test1("t2");
TestFunction f1 = std::bind(&Test1::hello1, t1, std::placeholders::_1);
TestFunction f2 = std::bind(&Test1::hello2, t2, std::placeholders::_1);
if (f1.target<void(*)(const char*)>() == f2.target<void(*)(const char*)>()) {
printf("ffffffffffffffffffffffffffffffffff1\n");
} else {
printf("ffffffffffffffffffffffffffffffffff2\n");
}
int err = this->coord->Proto->ImportDir(this->coord->config->Basic.Proto.c_str());
ASSERT_EQ(err, 0);
auto client = this->sqlMgr->getClient("DB");
ASSERT_NE(client, nullptr);
err = client->Ping();
ASSERT_EQ(err, 0);
ASSERT_STREQ(client->Format("aa ?, ?", 1, "你好"), "aa 1, '你好'");
ASSERT_STREQ(client->Format("aa ?, ?", 1, (char*)"你好"), "aa 1, '你好'");
ASSERT_STREQ(client->Format("aa ?, ?,?", 1, "你好"), "aa 1, '你好',?");
ASSERT_STREQ(client->Format("aa ?, ?", 1, "你好", "2"), "aa 1, '你好'");
auto result = client->Execute("DROP TABLE `testcoord`");
//ASSERT_NE(result, nullptr);
result = client->Execute("CREATE TABLE `testcoord` (\
`userid` bigint(11) NOT NULL AUTO_INCREMENT COMMENT '用户id',\
`openid` varchar(64) NOT NULL DEFAULT '' COMMENT 'openid',\
`nickname` varchar(128) NOT NULL DEFAULT '' COMMENT '昵称',\
`avatar` varchar(128) NOT NULL DEFAULT '' COMMENT '头像',\
`diamond` bigint(11) NOT NULL DEFAULT '0' COMMENT '钻石',\
`score` decimal(11, 2) NOT NULL DEFAULT '0' COMMENT '分类',\
`rank` enum('one', 'two', 'three') NOT NULL DEFAULT 'two' COMMENT '排名',\
`catalog` set('c1', 'c2', 'c3') NOT NULL DEFAULT 'c1,c3' COMMENT '分类',\
`coin` bigint(11) NOT NULL DEFAULT '0' COMMENT '金币',\
`createtime` int(11) NOT NULL DEFAULT '0' COMMENT '创建时间',\
`updatetime` int(11) NOT NULL DEFAULT '0' COMMENT '更新时间',\
PRIMARY KEY (`userid`)\
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户表';\
");
ASSERT_NE(result, nullptr);
result = client->Execute("INSERT INTO testcoord(userid, nickname, score, rank, catalog) VALUES (1, '你好a', 3.123, 'three', 'c2,c3')");
ASSERT_NE(result, nullptr);
ASSERT_EQ(result.RowsAffected(), (uint64_t)1);
result = client->Execute("INSERT INTO testcoord(userid, nickname) VALUES (?, ?)", 2, "你好b", 4);
ASSERT_NE(result, nullptr);
ASSERT_EQ(result.RowsAffected(), (uint64_t)1);
auto rows = client->Query("SELECT userid, nickname, avatar, score, rank, catalog, createtime FROM testcoord ORDER BY userid asc LIMIT 10");
while (rows.Next()) {
if (rows.Index() == 0){
ASSERT_STREQ(rows.String("nickname"), "你好a");
ASSERT_EQ(rows.Number("score"), 3.12);
ASSERT_STREQ(rows.String("rank"), "three");
ASSERT_STREQ(rows.String("catalog"), "c2,c3");
} else if(rows.Index() == 1){
ASSERT_STREQ(rows.String("nickname"), "你好b");
}
}
auto user = this->coord->Proto->NewReflect("test.User");
ASSERT_NE(user, nullptr);
err = client->Get(user, "SELECT * FROM testcoord WHERE userid=?", 1);
ASSERT_EQ(err, 0);
//printf("ppppppp %s\n", user.DebugString());
//coord::slice<coord::protobuf::Reflect> userArr;
//err = client->Query(userArr, "SELECT * FROM testcoord");
//ASSERT_EQ(err, 0);
rows = client->Query("SELECT userid1, nickname, avatar, createtime FROM testcoord LIMIT 10");
ASSERT_EQ(rows, nullptr);
result = client->Execute("UPDATE testcoord SET nickname=? WHERE userid=2", "你好c");
ASSERT_NE(result, nullptr);
ASSERT_EQ(result.RowsAffected(), (uint64_t)1);
result = client->Execute("UPDATE testcoord SET nickname=?", "你好");
ASSERT_NE(result, nullptr);
ASSERT_EQ(result.RowsAffected(), (uint64_t)2);
result = client->Execute("DROP TABLE `testcoord`");
ASSERT_NE(result, nullptr);
}
| 37.40146 | 143 | 0.607143 |
bd4d2132e05e6ca55063ad9d7d23f5134d47d30e | 506 | cc | C++ | arc/vm/libvda/decode/test/decode_unittest_common.cc | strassek/chromiumos-platform2 | 12c953f41f48b8a6b0bd1c181d09bdb1de38325c | [
"BSD-3-Clause"
] | 4 | 2020-07-24T06:54:16.000Z | 2021-06-16T17:13:53.000Z | arc/vm/libvda/decode/test/decode_unittest_common.cc | strassek/chromiumos-platform2 | 12c953f41f48b8a6b0bd1c181d09bdb1de38325c | [
"BSD-3-Clause"
] | 1 | 2021-04-02T17:35:07.000Z | 2021-04-02T17:35:07.000Z | arc/vm/libvda/decode/test/decode_unittest_common.cc | strassek/chromiumos-platform2 | 12c953f41f48b8a6b0bd1c181d09bdb1de38325c | [
"BSD-3-Clause"
] | 1 | 2020-11-04T22:31:45.000Z | 2020-11-04T22:31:45.000Z | // Copyright 2019 The Chromium OS 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 "arc/vm/libvda/decode/test/decode_unittest_common.h"
ImplPtr SetupImpl(vda_impl_type_t impl_type) {
return ImplPtr(initialize(impl_type));
}
SessionPtr SetupSession(const ImplPtr& impl, vda_profile_t profile) {
return SessionPtr(init_decode_session(impl.get(), profile),
SessionDeleter(impl.get()));
}
| 33.733333 | 73 | 0.747036 |
bd4fac1aad8eedc82407c52dac94f031cdffced2 | 464 | hpp | C++ | include/uitsl/polyfill/filesystem.hpp | mmore500/pipe-profile | 861babd819909d1bda5e933269e7bc64018272d6 | [
"MIT"
] | 15 | 2020-07-31T23:06:09.000Z | 2022-01-13T18:05:33.000Z | include/uitsl/polyfill/filesystem.hpp | mmore500/pipe-profile | 861babd819909d1bda5e933269e7bc64018272d6 | [
"MIT"
] | 137 | 2020-08-13T23:32:17.000Z | 2021-10-16T04:00:40.000Z | include/uitsl/polyfill/filesystem.hpp | mmore500/pipe-profile | 861babd819909d1bda5e933269e7bc64018272d6 | [
"MIT"
] | 3 | 2020-08-09T01:52:03.000Z | 2020-10-02T02:13:47.000Z | #pragma once
#ifndef UITSL_POLYFILL_FILESYSTEM_HPP_INCLUDE
#define UITSL_POLYFILL_FILESYSTEM_HPP_INCLUDE
#if defined(__EMSCRIPTEN__) \
&& __EMSCRIPTEN_major__ == 1 && __EMSCRIPTEN_minor__ <= 38
#include <experimental/filesystem>
namespace std {
namespace filesystem {
using namespace std::experimental::filesystem;
} // namespace filesystem
} // namespace std
#else
#include <filesystem>
#endif
#endif // #ifndef UITSL_POLYFILL_FILESYSTEM_HPP_INCLUDE
| 18.56 | 60 | 0.788793 |
bd4ff33907f456a6d566c8012e96165c2566cbae | 1,402 | cpp | C++ | instanceedr.cpp | slist/cbapi-qt-demo | b44e31824a5b9973aa0ccff39c15ff7805902b8b | [
"MIT"
] | 3 | 2020-09-14T19:39:53.000Z | 2021-01-19T11:58:27.000Z | instanceedr.cpp | slist/cbapi-qt-demo | b44e31824a5b9973aa0ccff39c15ff7805902b8b | [
"MIT"
] | null | null | null | instanceedr.cpp | slist/cbapi-qt-demo | b44e31824a5b9973aa0ccff39c15ff7805902b8b | [
"MIT"
] | null | null | null | // Copyright 2020 VMware, Inc.
// SPDX-License-Identifier: MIT
#include "instanceedr.h"
#include "ui_instanceedr.h"
InstanceEdr::InstanceEdr(QWidget *parent) :
QWidget(parent),
ui(new Ui::InstanceEdr)
{
ui->setupUi(this);
}
InstanceEdr::~InstanceEdr()
{
delete ui;
}
void InstanceEdr::set_name(const QString & name)
{
ui->lineEdit_name->setText(name);
}
void InstanceEdr::set_api(const QString & api)
{
ui->lineEdit_api->setText(api);
}
void InstanceEdr::set_url(const QString & url)
{
ui->lineEdit_url->setText(url);
check_validity();
}
QString InstanceEdr::get_name()
{
return ui->lineEdit_name->text();
}
QString InstanceEdr::get_api()
{
return ui->lineEdit_api->text();
}
QString InstanceEdr::get_url()
{
return ui->lineEdit_url->text();
}
bool InstanceEdr::isValid()
{
if (get_name().isEmpty() || get_api().isEmpty() || get_url().isEmpty())
return false;
return true;
}
void InstanceEdr::check_validity()
{
if (!isValid()) {
ui->label_invalid->show();
} else {
ui->label_invalid->hide();
}
}
void InstanceEdr::on_lineEdit_name_textChanged(const QString & /* arg1 */)
{
check_validity();
}
void InstanceEdr::on_lineEdit_url_textChanged(const QString & /* arg1 */)
{
check_validity();
}
void InstanceEdr::on_lineEdit_api_textChanged(const QString & /* arg1 */)
{
check_validity();
}
| 17.308642 | 75 | 0.664051 |
bd54b467c25f3b14a6178edd3ef1d5130470ef69 | 703 | cc | C++ | test/Airflow/readfile.cc | fstudio/Phoenix | 28a7c6a3932fd7d6fea12770d0aa1e20bc70db7d | [
"MIT"
] | 8 | 2015-01-23T05:41:46.000Z | 2019-11-20T05:10:27.000Z | test/Airflow/readfile.cc | fstudio/Phoenix | 28a7c6a3932fd7d6fea12770d0aa1e20bc70db7d | [
"MIT"
] | null | null | null | test/Airflow/readfile.cc | fstudio/Phoenix | 28a7c6a3932fd7d6fea12770d0aa1e20bc70db7d | [
"MIT"
] | 4 | 2015-05-05T05:15:43.000Z | 2020-03-07T11:10:56.000Z | #include <stdio.h>
#include <stdlib.h>
int main(int argc,char **argv)
{
char buffer[20]={0};
FILE *fp=nullptr;
if(fopen_s(&fp,argv[1],"rb")!=0)
return -1;
if(fread_s(buffer,20,1,20,fp)<0)
{
fclose(fp);
return -2;
}
fclose(fp);
printf("%02X-%02X-%02X-%02X-%02X-%02X-%02X-%02X-%02X-%02X",
(unsigned char)buffer[0],
(unsigned char)buffer[1],
(unsigned char)buffer[2],
(unsigned char)buffer[3],
(unsigned char)buffer[4],
(unsigned char)buffer[5],
(unsigned char)buffer[6],
(unsigned char)buffer[7],
(unsigned char)buffer[8],
(unsigned char)buffer[9]);
return 0;
}
| 22.677419 | 63 | 0.540541 |
bd554be511e64a23f37feb066bc4ffc856d41c26 | 4,002 | cpp | C++ | enhanced/buildtest/tests/vts/vm/src/test/vm/jvmti/funcs/GetPhase/GetPhase0101/GetPhase0101.cpp | qinFamily/freeVM | 9caa0256b4089d74186f84b8fb2afc95a0afc7bc | [
"Apache-2.0"
] | 5 | 2017-03-08T20:32:39.000Z | 2021-07-10T10:12:38.000Z | enhanced/buildtest/tests/vts/vm/src/test/vm/jvmti/funcs/GetPhase/GetPhase0101/GetPhase0101.cpp | qinFamily/freeVM | 9caa0256b4089d74186f84b8fb2afc95a0afc7bc | [
"Apache-2.0"
] | null | null | null | enhanced/buildtest/tests/vts/vm/src/test/vm/jvmti/funcs/GetPhase/GetPhase0101/GetPhase0101.cpp | qinFamily/freeVM | 9caa0256b4089d74186f84b8fb2afc95a0afc7bc | [
"Apache-2.0"
] | 4 | 2015-07-07T07:06:59.000Z | 2018-06-19T22:38:04.000Z | /*
Copyright 2005-2006 The Apache Software Foundation or its licensors, as applicable
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.
*/
/**
* @author Valentin Al. Sitnick
* @version $Revision: 1.1 $
*
*/
/* *********************************************************************** */
#include "events.h"
#include "utils.h"
#include "fake.h"
static bool test = false;
static bool util = false;
static bool test_phase_onload = false;
static bool test_phase_init = false;
static bool test_phase_start = false;
static bool test_phase_live = false;
static jvmtiPhase phase_onload;
static jvmtiPhase phase_init;
static jvmtiPhase phase_start;
static jvmtiPhase phase_live;
static jvmtiError err_phase_onload = JVMTI_ERROR_NONE;
static jvmtiError err_phase_init = JVMTI_ERROR_NONE;
static jvmtiError err_phase_start = JVMTI_ERROR_NONE;
static jvmtiError err_phase_live = JVMTI_ERROR_NONE;
const char test_case_name[] = "GetPhase0101";
/* *********************************************************************** */
JNIEXPORT jint JNICALL Agent_OnLoad(prms_AGENT_ONLOAD)
{
Callbacks CB;
check_AGENT_ONLOAD;
jvmtiEvent events[] = { JVMTI_EVENT_VM_INIT, JVMTI_EVENT_VM_START, JVMTI_EVENT_VM_DEATH };
cb_start;
cb_init;
cb_death;
jvmtiEnv *jvmti;
jvmtiError result;
jint res = func_for_Agent_OnLoad_JVMTI(vm, options, reserved, &CB,
events, sizeof(events)/4, test_case_name, DEBUG_OUT, &jvmti);
err_phase_onload = jvmti->GetPhase(&phase_onload);
fprintf(stderr, "\tnative: GetPhase (onload) result = %d (must be zero) \n", err_phase_onload);
fprintf(stderr, "\tnative: phase_onload is %d \n", phase_onload);
fflush(stderr);
if ((err_phase_onload == JVMTI_ERROR_NONE) &&
(phase_onload == JVMTI_PHASE_ONLOAD))
test_phase_onload = true;
return JNI_OK;
}
/* *********************************************************************** */
void JNICALL callbackVMInit(prms_VMINIT)
{
check_VMINIT;
err_phase_init = jvmti_env->GetPhase(&phase_init);
fprintf(stderr, "\tnative: GetPhase (init) result = %d (must be zero) \n", err_phase_init);
fprintf(stderr, "\tnative: phase_init is %d \n", phase_init);
if ((err_phase_init == JVMTI_ERROR_NONE) &&
(phase_init == JVMTI_PHASE_LIVE))
test_phase_init = true;
}
void JNICALL callbackVMStart(prms_VMSTART)
{
check_VMSTART;
err_phase_start = jvmti_env->GetPhase(&phase_start);
fprintf(stderr, "\tnative: GetPhase (start) result = %d (must be zero) \n", err_phase_start);
fprintf(stderr, "\tnative: phase_start is %d \n", phase_start);
if ((err_phase_start == JVMTI_ERROR_NONE) &&
(phase_start == JVMTI_PHASE_START))
test_phase_start = true;
}
void JNICALL callbackVMDeath(prms_VMDEATH)
{
check_VMDEATH;
err_phase_live = jvmti_env->GetPhase(&phase_live);
fprintf(stderr, "\tnative: GetPhase (death) result = %d (must be zero) \n", err_phase_live);
fprintf(stderr, "\tnative: phase_live is %d \n", phase_live);
if ((err_phase_live == JVMTI_ERROR_NONE) &&
(phase_live == JVMTI_PHASE_LIVE))
test_phase_live = true;
util = true;
if (test_phase_onload &&
test_phase_init &&
test_phase_start &&
test_phase_live ) test = true;
func_for_callback_VMDeath(jni_env, jvmti_env, test_case_name, test, util);
}
/* *********************************************************************** */
| 32.016 | 99 | 0.651924 |
32e3cc4e727858a1b23d68c676147a1712e8d336 | 392 | cpp | C++ | C++/if/01 Password .cpp | Noob-coder-07/DeepAlgo | b7f5f8eacefff561648b476946d80948b3f69f51 | [
"Apache-2.0"
] | null | null | null | C++/if/01 Password .cpp | Noob-coder-07/DeepAlgo | b7f5f8eacefff561648b476946d80948b3f69f51 | [
"Apache-2.0"
] | null | null | null | C++/if/01 Password .cpp | Noob-coder-07/DeepAlgo | b7f5f8eacefff561648b476946d80948b3f69f51 | [
"Apache-2.0"
] | 1 | 2021-09-07T03:12:49.000Z | 2021-09-07T03:12:49.000Z | #include<iostream>
#include<conio.h>
using namespace std;
int main()
{
string Password = "Hello";
cout << "Enter a Password => " << flush;
string input;
cin >> input;
if(Password == input)
{
cout << "Password Accepted....." << endl;
}
if(Password != input)
{
cout << "Access Denied....." << endl;
}
getch();
return 0;
}
| 13.517241 | 49 | 0.507653 |
32e6f9d88e0a2d6b0f315308cf4cd752786b05c5 | 1,903 | cpp | C++ | data/transcoder_evaluation_gfg/cpp/FIND_A_TRIPLET_THAT_SUM_TO_A_GIVEN_VALUE.cpp | mxl1n/CodeGen | e5101dd5c5e9c3720c70c80f78b18f13e118335a | [
"MIT"
] | 241 | 2021-07-20T08:35:20.000Z | 2022-03-31T02:39:08.000Z | data/transcoder_evaluation_gfg/cpp/FIND_A_TRIPLET_THAT_SUM_TO_A_GIVEN_VALUE.cpp | mxl1n/CodeGen | e5101dd5c5e9c3720c70c80f78b18f13e118335a | [
"MIT"
] | 49 | 2021-07-22T23:18:42.000Z | 2022-03-24T09:15:26.000Z | data/transcoder_evaluation_gfg/cpp/FIND_A_TRIPLET_THAT_SUM_TO_A_GIVEN_VALUE.cpp | mxl1n/CodeGen | e5101dd5c5e9c3720c70c80f78b18f13e118335a | [
"MIT"
] | 71 | 2021-07-21T05:17:52.000Z | 2022-03-29T23:49:28.000Z | // Copyright (c) 2019-present, Facebook, Inc.
// All rights reserved.
//
// This source code is licensed under the license found in the
// LICENSE file in the root directory of this source tree.
//
#include <iostream>
#include <cstdlib>
#include <string>
#include <vector>
#include <fstream>
#include <iomanip>
#include <bits/stdc++.h>
using namespace std;
bool f_gold ( int A [ ], int arr_size, int sum ) {
int l, r;
for ( int i = 0;
i < arr_size - 2;
i ++ ) {
for ( int j = i + 1;
j < arr_size - 1;
j ++ ) {
for ( int k = j + 1;
k < arr_size;
k ++ ) {
if ( A [ i ] + A [ j ] + A [ k ] == sum ) {
cout << "Triplet is " << A [ i ] << ", " << A [ j ] << ", " << A [ k ];
return true;
}
}
}
}
return false;
}
//TOFILL
int main() {
int n_success = 0;
vector<vector<int>> param0 {{15,18,38,47,75,88},{28,-2,62,38,86,-86,56,58,96,6,-28,8,68,-16,-80,-4,98,-92,4,-4,58,-62,46,64},{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},{19,77,17,91,6,35,22,4,30,23,97,56,78,16,22,23,95,57,43,27,47,44,23,10,3,94,55,22,93,32,89,28,64,22,13,24,38,44,6,1,80},{-98,-98,-94,-88,-80,-74,-68,-68,-64,-44,-36,-24,-10,-8,-8,0,4,6,8,8,12,14,16,38,50,52,54,56,66,68,76,88},{1,1,0,0,1,0,1,1},{7,22,24,30,42,44,49,49,65,70,70,74,74,75,90,95,96},{40,-76,-68,-86,-14,82,-20,54,-26,56,-24,-44,44,60,52,-20,80,-24,-90,-30,-2},{0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1},{33,92,6,99,83,97,49,97,85,52}};
vector<int> param1 {5,22,27,22,18,4,8,11,15,6};
vector<int> param2 {4,18,23,29,19,5,13,18,17,7};
for(int i = 0; i < param0.size(); ++i)
{
if(f_filled(¶m0[i].front(),param1[i],param2[i]) == f_gold(¶m0[i].front(),param1[i],param2[i]))
{
n_success+=1;
}
}
cout << "#Results:" << " " << n_success << ", " << param0.size();
return 0;
} | 35.240741 | 656 | 0.52391 |
32e9035bece31b37ed27ed859bd066a1d7ae64f2 | 1,768 | cpp | C++ | mvp_tips/CPUID/CPUID/ExtendedCPU0.cpp | allen7575/The-CPUID-Explorer | 77d0feef70482b2e36cff300ea24271384329f60 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 9 | 2017-08-31T06:03:18.000Z | 2019-01-06T05:07:26.000Z | mvp_tips/CPUID/CPUID/ExtendedCPU0.cpp | allen7575/The-CPUID-Explorer | 77d0feef70482b2e36cff300ea24271384329f60 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | mvp_tips/CPUID/CPUID/ExtendedCPU0.cpp | allen7575/The-CPUID-Explorer | 77d0feef70482b2e36cff300ea24271384329f60 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 8 | 2017-08-31T06:23:22.000Z | 2022-01-24T06:47:19.000Z | // ExtendedCPU0.cpp : implementation file
//
#include "stdafx.h"
#include "resource.h"
#include "ExtendedCPU0.h"
#include "CPUIDx86.h"
#include "ReportRegs.h"
#include "CurrentProcessor.h"
// CExtendedCPU0 dialog
IMPLEMENT_DYNCREATE(CExtendedCPU0, CLeaves)
CExtendedCPU0::CExtendedCPU0()
: CLeaves(CExtendedCPU0::IDD)
{
}
CExtendedCPU0::~CExtendedCPU0()
{
}
void CExtendedCPU0::DoDataExchange(CDataExchange* pDX)
{
CLeaves::DoDataExchange(pDX);
DDX_Control(pDX, IDC_EAX, c_EAX);
DDX_Control(pDX, IDC_EBX, c_EBX);
DDX_Control(pDX, IDC_ECX, c_ECX);
DDX_Control(pDX, IDC_EDX, c_EDX);
}
BEGIN_MESSAGE_MAP(CExtendedCPU0, CLeaves)
END_MESSAGE_MAP()
// CExtendedCPU0 message handlers
/****************************************************************************
* CExtendedCPU0::OnSetActive
* Result: BOOL
*
* Effect:
* Reports the registers
****************************************************************************/
BOOL CExtendedCPU0::OnSetActive()
{
CPUregs regs;
GetAndReport(0x80000000, regs);
CString s;
s.Format(_T("%08x"), regs.EAX);
c_EAX.SetWindowText(s);
return CLeaves::OnSetActive();
}
/****************************************************************************
* CExtendedCPU0::OnInitDialog
* Result: BOOL
* TRUE, always
* Effect:
* Initializes the dialog
****************************************************************************/
BOOL CExtendedCPU0::OnInitDialog()
{
CLeaves::OnInitDialog();
SetFixedFont(c_EBX);
SetFixedFont(c_ECX);
SetFixedFont(c_EDX);
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
| 22.961039 | 77 | 0.557127 |
32f91bccb96b86a022267acb0fa41e009dc08275 | 8,913 | hpp | C++ | jdu_source_collection/jsc/bioinfo/psl.hpp | gersteinlab/LESSeq | bfc0a9aae081682a176e26d9804b980999595f16 | [
"MIT"
] | 7 | 2016-06-19T21:14:55.000Z | 2020-09-15T03:04:41.000Z | jdu_source_collection/jsc/bioinfo/psl.hpp | gersteinlab/LESSeq | bfc0a9aae081682a176e26d9804b980999595f16 | [
"MIT"
] | 3 | 2015-02-12T21:17:00.000Z | 2020-03-20T13:50:38.000Z | jdu_source_collection/jsc/bioinfo/psl.hpp | gersteinlab/LESSeq | bfc0a9aae081682a176e26d9804b980999595f16 | [
"MIT"
] | null | null | null | #ifndef _jsc_bioinfo_psl_hpp_included_
#define _jsc_bioinfo_psl_hpp_included_
#include <boost/config.hpp>
#include <math.h>
#include <iostream>
#include <map>
#include <set>
#include <sstream>
#include <vector>
#include <boost/lambda/bind.hpp>
#include <boost/lambda/lambda.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/tokenizer.hpp>
#include "jsc/util/interval_list.hpp"
using namespace std;
using namespace boost;
using namespace boost::lambda;
using namespace jsc::util;
namespace jsc
{
namespace bioinfo
{
/*!
* the format of a psl_entry.
* according to the description at:
* http://genome.ucsc.edu/FAQ/FAQformat
*/
class psl_entry
{
public:
double identity; // identity score
double score; // psl score
long matches; /* 1 */
long misMatches; /* 2 */
long repMatches; /* 3 */
long nCount; /* 4 */
long qNumInsert; /* 5 */
long qBaseInsert; /* 6 */
long tNumInsert; /* 7 */
long tBaseInsert; /* 8 */
string strand; /* 9 */
string qName; /* 10 */
long qSize; /* 11 */
long qStart; /* 12 */
long qEnd; /* 13 */
string tName; /* 14 */
long tSize; /* 15 */
long tStart; /* 16 */
long tEnd; /* 17 */
unsigned long blockCount; /* 18 */
vector<long> blockSizes; /* 19 */
vector<long> qStarts; /* 20 */
vector<long> tStarts; /* 21 */
};
typedef shared_ptr<psl_entry> psl_ptr;
typedef vector<psl_ptr> vec_pslp;
typedef map<psl_ptr, double> map_pslp_fitness;
typedef multimap<string, psl_ptr> map_qname_pslp;
typedef set<string> set_qname;
/*!
* print a psl entry
*/
void print_pslp(psl_ptr const & pslp, ostream & os)
{
os << pslp->matches /* 1 */
<< "\t" << pslp->misMatches /* 2 */
<< "\t" << pslp->repMatches /* 3 */
<< "\t" << pslp->nCount /* 4 */
<< "\t" << pslp->qNumInsert /* 5 */
<< "\t" << pslp->qBaseInsert /* 6 */
<< "\t" << pslp->tNumInsert /* 7 */
<< "\t" << pslp->tBaseInsert /* 8 */
<< "\t" << pslp->strand /* 9 */
<< "\t" << pslp->qName /* 10 */
<< "\t" << pslp->qSize /* 11 */
<< "\t" << pslp->qStart /* 12 */
<< "\t" << pslp->qEnd /* 13 */
<< "\t" << pslp->tName /* 14 */
<< "\t" << pslp->tSize /* 15 */
<< "\t" << pslp->tStart /* 16 */
<< "\t" << pslp->tEnd /* 17 */
<< "\t" << pslp->blockCount /* 18 */
<< "\t";
// blockSizes /* 19 */
for (unsigned int i = 0; i < pslp->blockCount; ++i)
{
os << pslp->blockSizes[i] << ",";
}
os << "\t";
// qStarts /* 20 */
for (unsigned int i = 0; i < pslp->blockCount; ++i)
{
os << pslp->qStarts[i] << ",";
}
os << "\t";
// tStarts /* 21 */
for (unsigned int i = 0; i < pslp->blockCount; ++i)
{
os << pslp->tStarts[i] << ",";
}
os << endl;
}
/*!
* convert a psl line to psl_entry
*/
psl_ptr str2pslp(string const & line)
{
psl_ptr pslp(new psl_entry());
istringstream iss(line);
string strBlockSizes, strQStarts, strTStarts;
iss >> pslp->matches /* 1 */
>> pslp->misMatches /* 2 */
>> pslp->repMatches /* 3 */
>> pslp->nCount /* 4 */
>> pslp->qNumInsert /* 5 */
>> pslp->qBaseInsert /* 6 */
>> pslp->tNumInsert /* 7 */
>> pslp->tBaseInsert /* 8 */
>> pslp->strand /* 9 */
>> pslp->qName /* 10 */
>> pslp->qSize /* 11 */
>> pslp->qStart /* 12 */
>> pslp->qEnd /* 13 */
>> pslp->tName /* 14 */
>> pslp->tSize /* 15 */
>> pslp->tStart /* 16 */
>> pslp->tEnd /* 17 */
>> pslp->blockCount /* 18 */
>> strBlockSizes /* 19 */
>> strQStarts /* 20 */
>> strTStarts; /* 21 */
/* deal with blockSizes, qStarts, and TStarts */
typedef tokenizer<char_separator<char> > tok;
char_separator<char> sep(",");
tok tBlockSizes(strBlockSizes, sep);
tok tQStarts(strQStarts, sep);
tok tTStarts(strTStarts, sep);
for_each(tBlockSizes.begin(), tBlockSizes.end(),
bind(&vector<long>::push_back,
ref(pslp->blockSizes),
bind(atol,
bind(&string::c_str, _1))));
for_each(tQStarts.begin(), tQStarts.end(),
bind(&vector<long>::push_back,
ref(pslp->qStarts),
bind(atol,
bind(&string::c_str, _1))));
for_each(tTStarts.begin(), tTStarts.end(),
bind(&vector<long>::push_back,
ref(pslp->tStarts),
bind(atol,
bind(&string::c_str, _1))));
assert(pslp->qSize >= pslp->qEnd - pslp->qStart);
assert(pslp->blockCount == pslp->blockSizes.size()
&& pslp->blockCount == pslp->qStarts.size()
&& pslp->blockCount == pslp->tStarts.size());
return pslp;
}
/*!
* load a vector of psl_ptrs from an istream (w/o the psl header)
*/
vec_pslp load_pslps_noheader(istream & is)
{
string line;
/* read content */
vec_pslp pslps;
while (getline(is, line) && !is.eof())
{
pslps.push_back(str2pslp(line));
}
return pslps;
}
/*!
* a fitness score simulating the percent identity score defined at:
* http://genome.ucsc.edu/FAQ/FAQblat.html
*
* here we assume that the psl_entry is a dna vs. dna blat result,
* and we focus on the fitness of the query sequence.
*/
double psl_q_fitness_ucsc(psl_ptr const & pslp, bool const & consider_ins_factor = true)
{
double badness = 0;
double qAliSize = pslp->qEnd - pslp->qStart;
double tAliSize = pslp->tEnd - pslp->tStart;
double aliSize = min(qAliSize, tAliSize);
if (aliSize <= 0) {
return 0;
}
double sizeDif = qAliSize - tAliSize;
if (sizeDif < 0) {
sizeDif = 0;
}
double insertFactor = pslp->qNumInsert;
if (!consider_ins_factor) {
insertFactor = 0;
}
long total = pslp->matches + pslp->repMatches + pslp->misMatches;
assert(total != 0);
badness = (1000 * ((double)pslp->misMatches + insertFactor + round(3 * log(1 + sizeDif)))) / (double)total;
return (100.0 - (long)badness * 0.1);
}
double psl_score_ucsc(psl_ptr const & pslp) {
return pslp->matches +
(pslp->repMatches >> 1) -
pslp->misMatches -
pslp->qNumInsert -
pslp->tNumInsert;
}
double psl_identity(psl_ptr const & pslp) {
return (double)(pslp->matches + pslp->repMatches) / (double)(pslp->matches + pslp->repMatches + pslp->misMatches);
}
/*!
* a fitness score that is similar to the percent identity score
* defined at:
* http://genome.ucsc.edu/FAQ/FAQblat.html
*
* here we assume that the psl_entry is a dna vs. dna blat result,
* and we focus on the fitness of the query sequence.
*/
double psl_q_fitness(psl_ptr const & pslp)
{
double badness = 0;
double sizeDif = abs((pslp->tEnd - pslp->tStart) - (pslp->qEnd - pslp->qStart))
+ abs(pslp->qSize - (pslp->qEnd - pslp->qStart));
double insertFactor = pslp->qNumInsert + pslp->tNumInsert;
long total = pslp->matches + pslp->repMatches + pslp->misMatches;
assert(total != 0);
badness = (1000 * ((double)pslp->misMatches + (double)insertFactor + 3 * log(1 + sizeDif))) / (double)total;
return (100 - badness * 0.1);
}
/*!
* Note that the returned psl_entry may not be fully filled:
* only strand, tName, tStart, tEnd, blockCount, blockSizes, tStarts
* will be filled.
*/
psl_ptr combine_forward_reverse_reads(psl_ptr const & forward_pslp, psl_ptr const & reverse_pslp, bool & combined)
{
assert(forward_pslp->strand != reverse_pslp->strand);
psl_ptr combined_pslp(new psl_entry());
combined_pslp->qName = forward_pslp->qName + "::" + reverse_pslp->qName;
combined_pslp->strand = forward_pslp->strand;
combined_pslp->tName = forward_pslp->tName;
combined = true;
interval_list<long> il_f, il_r;
il_f.add_starts_sizes(forward_pslp->tStarts, forward_pslp->blockSizes);
il_r.add_starts_sizes(reverse_pslp->tStarts, reverse_pslp->blockSizes);
if (!il_f.coverage_overlap(il_r))
{
combined = false;
}
interval_list<long> il;
il.add_interval_list(il_f);
il.add_interval_list(il_r);
unsigned long n = il.get_starts().size();
assert(n > 0);
combined_pslp->tStart = il.get_starts()[0];
combined_pslp->tEnd = il.get_ends()[n - 1];
combined_pslp->blockCount = n;
for (unsigned long i = 0; i < n; i++)
{
combined_pslp->tStarts.push_back(il.get_starts()[i]);
combined_pslp->blockSizes.push_back(il.get_ends()[i] - il.get_starts()[i]);
}
return combined_pslp;
}
/*!
* Note that the returned psl_entry may not be fully filled:
* only qName, strand, tName, tStart, tEnd, blockCount, blockSizes, tStarts
* will be filled.
*/
psl_ptr fill_in_gaps(psl_ptr const & pslp, double const & threshold)
{
psl_ptr processed_pslp(new psl_entry());
processed_pslp->qName = pslp->qName;
processed_pslp->strand = pslp->strand;
processed_pslp->tName = pslp->tName;
interval_list<long> il;
il.add_starts_sizes(pslp->tStarts, pslp->blockSizes);
il.fill_in_gaps(threshold);
unsigned long n = il.get_starts().size();
assert(n > 0);
processed_pslp->tStart = il.get_starts()[0];
processed_pslp->tEnd = il.get_ends()[n - 1];
processed_pslp->blockCount = n;
for (unsigned long i = 0; i < n; i++)
{
processed_pslp->tStarts.push_back(il.get_starts()[i]);
processed_pslp->blockSizes.push_back(il.get_ends()[i] - il.get_starts()[i]);
}
return processed_pslp;
}
} /* end of bioinfo */
} /* end of jsc */
#endif
| 26.292035 | 115 | 0.638393 |
32f9da81fc1b47d01e67640f41095fe53770a14f | 1,600 | cpp | C++ | programManager.cpp | mircodezorzi/cli-password-manager | 1c47fd2317495159b7b3b7df2a2c7dfd265fad27 | [
"MIT"
] | 1 | 2019-06-18T18:47:25.000Z | 2019-06-18T18:47:25.000Z | programManager.cpp | mircodezorzi/cli-password-manager | 1c47fd2317495159b7b3b7df2a2c7dfd265fad27 | [
"MIT"
] | null | null | null | programManager.cpp | mircodezorzi/cli-password-manager | 1c47fd2317495159b7b3b7df2a2c7dfd265fad27 | [
"MIT"
] | null | null | null | #include "programManager.h"
ProgramManager::ProgramManager(std::string dbFilepath)
: DatabaseSystemManagment()
, DisplayManager(){
mDbFilepath = dbFilepath;
}
void ProgramManager::start(){
mSelected = 0;
mState = Running;
import(mDbFilepath);
loop();
}
void ProgramManager::loop(){
while(mState != Exiting){
update();
draw();
events();
}
}
void ProgramManager::draw(){
printFrame();
switch(mState){
case Running:
printTable(query()["userdata"], mSelected);
break;
}
}
void ProgramManager::events(){
switch(checkInput()){
case KEY_UP:
mSelected--;
break;
case KEY_DOWN:
mSelected++;
break;
case KEY_RIGHT:
break;
case KEY_LEFT:
break;
case 'a':
//copyToClipboard(boost::get<std::string>(query("userdata", "001")["password"]));
break;
case 'q':
mState = Exiting;
break;
}
}
void ProgramManager::update(){
checkForWindowResize();
}
/*
void copyToClipboard(std::string s){
try{
std::string command = "echo \"" + s + "\" | xsel -b";
system(command.c_str());
}catch(int e){
}
}
*/
/*
std::string Manager::generatePassword(size_t lenght, std::string blacklistedCharacters){
blacklistedCharacters += mBlacklistedCharacters;
std::string password, randomCharacter;
for(int i = 0; i < lenght; i++){
randomCharacter = (char) (rand() % 93) + 34;
if(randomCharacter.find_first_of(blacklistedCharacters) != -1)
password += randomCharacter;
else
i--;
}
//debug(generatingPassword);
return password;
}
*/
| 18.823529 | 89 | 0.62125 |
32fe35711a448776c1f557ab7439386b0df423da | 7,680 | cpp | C++ | external/activemq-cpp-library-3.4.1/src/main/decaf/net/InetAddress.cpp | framos-gemini/giapi-glue-cc | f59e1ce572494b57aad6985f3233f0e51167bb42 | [
"BSD-3-Clause"
] | null | null | null | external/activemq-cpp-library-3.4.1/src/main/decaf/net/InetAddress.cpp | framos-gemini/giapi-glue-cc | f59e1ce572494b57aad6985f3233f0e51167bb42 | [
"BSD-3-Clause"
] | 3 | 2017-06-14T15:21:50.000Z | 2020-08-03T19:51:57.000Z | external/activemq-cpp-library-3.4.1/src/main/decaf/net/InetAddress.cpp | framos-gemini/giapi-glue-cc | f59e1ce572494b57aad6985f3233f0e51167bb42 | [
"BSD-3-Clause"
] | 3 | 2017-06-13T13:59:36.000Z | 2021-02-09T02:01:14.000Z | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "InetAddress.h"
#include <decaf/lang/System.h>
#include <decaf/lang/Byte.h>
#include <decaf/net/Inet4Address.h>
#include <decaf/net/Inet6Address.h>
#include <decaf/net/UnknownHostException.h>
#include <decaf/lang/exceptions/RuntimeException.h>
#include <apr_network_io.h>
#include <decaf/internal/AprPool.h>
using namespace decaf;
using namespace decaf::net;
using namespace decaf::lang;
using namespace decaf::lang::exceptions;
using namespace decaf::internal;
////////////////////////////////////////////////////////////////////////////////
const unsigned char InetAddress::loopbackBytes[4] = { 127, 0, 0, 1 };
const unsigned char InetAddress::anyBytes[4] = { 0, 0, 0, 0 };
////////////////////////////////////////////////////////////////////////////////
InetAddress::InetAddress() : hostname(), reached(false), addressBytes() {
}
////////////////////////////////////////////////////////////////////////////////
InetAddress::InetAddress( const unsigned char* ipAddress, int numBytes ) :
hostname(), reached(false), addressBytes() {
if( ipAddress == NULL ) {
throw NullPointerException(
__FILE__, __LINE__, "InetAddress constructor called with null address array." );
}
if( numBytes < 0 ) {
throw IllegalArgumentException(
__FILE__, __LINE__, "Number of bytes value is invalid: %d", numBytes );
}
unsigned char* copy = new unsigned char[numBytes];
System::arraycopy( ipAddress, 0, copy, 0, numBytes );
this->addressBytes.reset( copy, numBytes );
}
////////////////////////////////////////////////////////////////////////////////
InetAddress::InetAddress( const std::string& hostname, const unsigned char* ipAddress, int numBytes ) :
hostname(hostname), reached(false), addressBytes() {
if( ipAddress == NULL ) {
throw NullPointerException(
__FILE__, __LINE__, "InetAddress constructor called with null address array." );
}
if( numBytes < 0 ) {
throw IllegalArgumentException(
__FILE__, __LINE__, "Number of bytes value is invalid: %d", numBytes );
}
unsigned char* copy = new unsigned char[numBytes];
System::arraycopy( ipAddress, 0, copy, 0, numBytes );
this->addressBytes.reset( copy, numBytes );
}
////////////////////////////////////////////////////////////////////////////////
InetAddress::~InetAddress() {
}
////////////////////////////////////////////////////////////////////////////////
InetAddress* InetAddress::clone() const {
return new InetAddress( *this );
}
////////////////////////////////////////////////////////////////////////////////
ArrayPointer<unsigned char> InetAddress::getAddress() const {
return this->addressBytes.clone();
}
////////////////////////////////////////////////////////////////////////////////
std::string InetAddress::getHostAddress() const {
std::string address;
for( int ix = 0; ix < this->addressBytes.length(); ix++ ) {
address.append( Byte::toString( addressBytes[ix] ) );
if( ix < this->addressBytes.length() - 1 ) {
address.append(".");
}
}
return address;
}
////////////////////////////////////////////////////////////////////////////////
std::string InetAddress::getHostName() const {
if( !this->hostname.empty() ) {
return this->hostname;
}
return this->getHostAddress();
}
////////////////////////////////////////////////////////////////////////////////
std::string InetAddress::toString() const {
return getHostName() + " / " + getHostAddress();
}
////////////////////////////////////////////////////////////////////////////////
InetAddress InetAddress::getByAddress( const std::string& hostname, const unsigned char* bytes, int numBytes ) {
if( numBytes == 4 ) {
return Inet4Address( hostname, bytes, numBytes );
} else if( numBytes == 16 ) {
return Inet6Address( hostname, bytes, numBytes );
} else {
throw UnknownHostException(
__FILE__, __LINE__, "Number of Bytes passed was invalid: %d", numBytes );
}
}
////////////////////////////////////////////////////////////////////////////////
InetAddress InetAddress::getByAddress( const unsigned char* bytes, int numBytes ) {
if( numBytes == 4 ) {
return Inet4Address( bytes, numBytes );
} else if( numBytes == 16 ) {
return Inet6Address( bytes, numBytes );
} else {
throw UnknownHostException(
__FILE__, __LINE__, "Number of Bytes passed was invalid: %d", numBytes );
}
}
////////////////////////////////////////////////////////////////////////////////
InetAddress InetAddress::getLocalHost() {
char hostname[APRMAXHOSTLEN + 1] = {0};
try{
AprPool pool;
apr_status_t result = APR_SUCCESS;
try {
result = apr_gethostname( hostname, APRMAXHOSTLEN+1, pool.getAprPool() );
if( result != APR_SUCCESS ) {
return getLoopbackAddress();
}
} catch(...) {}
apr_sockaddr_t* address = NULL;
result = apr_sockaddr_info_get( &address, hostname, APR_UNSPEC, 0, APR_IPV4_ADDR_OK, pool.getAprPool() );
if( result != APR_SUCCESS ) {
throw UnknownHostException(
__FILE__, __LINE__, "Could not resolve the IP Address of this host." );
}
if( address->family == APR_INET ) {
return Inet4Address( hostname, (const unsigned char*)address->ipaddr_ptr, address->ipaddr_len );
} else {
return Inet6Address( hostname, (const unsigned char*)address->ipaddr_ptr, address->ipaddr_len );
}
}
DECAF_CATCH_RETHROW( UnknownHostException )
DECAF_CATCH_EXCEPTION_CONVERT( Exception, UnknownHostException )
DECAF_CATCHALL_THROW( UnknownHostException )
}
////////////////////////////////////////////////////////////////////////////////
unsigned int InetAddress::bytesToInt( const unsigned char* bytes, int start ) {
// First mask the byte with 255, as when a negative
// signed byte converts to an integer, it has bits
// on in the first 3 bytes, we are only concerned
// about the right-most 8 bits.
// Then shift the rightmost byte to align with its
// position in the integer.
int value = ( ( bytes[start + 3] & 255 ) ) |
( ( bytes[start + 2] & 255 ) << 8 ) |
( ( bytes[start + 1] & 255 ) << 16 ) |
( ( bytes[start] & 255 ) << 24 );
return value;
}
////////////////////////////////////////////////////////////////////////////////
InetAddress InetAddress::getAnyAddress() {
return Inet4Address( "localhost", InetAddress::loopbackBytes, 4 );
}
////////////////////////////////////////////////////////////////////////////////
InetAddress InetAddress::getLoopbackAddress() {
return Inet4Address( InetAddress::anyBytes, 4 );
}
| 35.229358 | 113 | 0.546094 |
32fe586ac7e10e7d2ffd43b1d75d5faa54be0fdf | 13,241 | cpp | C++ | src/prompt.cpp | aparks5/synthcastle | ebb542d014c87a11a83b9e212668eca75a333fbf | [
"MIT"
] | 2 | 2021-12-20T03:20:05.000Z | 2021-12-28T16:15:20.000Z | src/prompt.cpp | aparks5/synthcastle | ebb542d014c87a11a83b9e212668eca75a333fbf | [
"MIT"
] | 69 | 2021-08-30T13:09:01.000Z | 2022-01-15T17:41:40.000Z | src/prompt.cpp | aparks5/synthcastle | ebb542d014c87a11a83b9e212668eca75a333fbf | [
"MIT"
] | null | null | null | #include "prompt.h"
#include "util.h"
#include "windows.h"
#include <deque>
#include "spdlog/spdlog.h"
#include "spdlog/sinks/stdout_color_sinks.h"
#include "spdlog/sinks/rotating_file_sink.h"
static void logVoiceParams(VoiceParams params) {
spdlog::info("voice params updated");
spdlog::info("bpm: {}", params.bpm);
spdlog::info("filter cutoff (Hz): {}", params.filtFreq);
spdlog::info("osc2-enable: {}", params.bEnableOsc2);
}
static void logFxParams(FxParams fxparams) {
spdlog::info("fx params updated");
spdlog::info("delay1-enable: {}", fxparams.bEnableDelay1);
spdlog::info("delay2-enable: {}", fxparams.bEnableDelay2);
spdlog::info("chorus-enable: {}", fxparams.bEnableChorus);
}
Prompt::Prompt(std::shared_ptr<MixerStream> s)
: stream(s)
{
}
void Prompt::open()
{
std::string prompt;
VoiceParams params;
FxParams fxparams;
params.envParams = { 1,250,0,0 };
stream->update(params);
std::deque<NoteEvent> notes;
NoteGenerator gen;
bool bParamChanged = false;
bool bFxParamChanged = false;
std::cout << ">>> type 'help' to list commands" << std::endl;
std::vector<spdlog::sink_ptr> sinks;
sinks.push_back(std::make_shared<spdlog::sinks::stdout_color_sink_st>());
sinks.push_back(std::make_shared<spdlog::sinks::rotating_file_sink_mt>("history.log",1024*1024,5,false));
auto logger = std::make_shared<spdlog::logger>("logger", begin(sinks), end(sinks));
//register it if you need to access it globally
spdlog::register_logger(logger);
spdlog::set_default_logger(logger);
spdlog::flush_on(spdlog::level::info);
spdlog::info("opening history log...");
while (true) {
std::cout << ">>> ";
std::cin >> prompt;
if (prompt == "help") {
spdlog::info(">>> commands: stop, tracks, mix, osc, freq, filt-freq, filt-q, filt-lfo-freq, pitch/filt-lfo-on/off, ");
spdlog::info(">>> pitch-lfo-freq, pitch-lfo-depth, reverb-on/off, chorus-on/off, delay-on/off");
spdlog::info(">>> delay-time, delay-feedback, delay-mix");
spdlog::info(">>> osc2-enable, osc2-coarse, osc2-fine, env [attackMs decayMs susdB]");
spdlog::info(">>> play [note] [note-note2-note3:duration,note4:duration2...], loop loopNumTimes");
}
if (prompt == "stop") {
stream->stopLoop();
}
if (prompt == "start") {
stream->start();
}
if (prompt == "midilog-on") {
stream->enableMidiLogging();
}
if (prompt == "midilog-off") {
stream->disableMidiLogging();
}
if (prompt == "tracks") {
spdlog::info(">> list of tracks");
size_t trackCount = 0;
std::vector<std::string> trackList = stream->getTrackList();
for (auto track : trackList) {
std::cout << trackCount << ": " << track << std::endl;
trackCount++;
}
}
if (prompt == "bpm") {
std::cout << ">> enter bpm (20-200 beats per minute)" << std::endl;
std::cin >> prompt;
auto bpm = std::stof(prompt);
bpm = clamp(bpm, 20.f, 200.f);
params.bpm = bpm;
bParamChanged = true;
}
if (prompt == "exit") {
break;
}
if (prompt == "freq") {
std::cout << ">> enter frequency in Hz" << std::endl;
std::cin >> prompt;
auto freq = std::stof(prompt);
freq = clamp(freq, 0.f, 10000.f);
params.freq = freq;
bParamChanged = true;
}
if (prompt == "filt-freq") {
std::cout << ">> enter filter cutoff frequency in Hz" << std::endl;
std::cin >> prompt;
auto freq = std::stof(prompt);
freq = clamp(freq, 0.f, 10000.f);
params.filtFreq = freq;
bParamChanged = true;
}
if (prompt == "filt-q") {
std::cout << ">> enter filter resonance (0 - 10)" << std::endl;
std::cin >> prompt;
auto q = std::stof(prompt);
q = clamp(q, 0.f, 10.f);
params.filtQ = q;
bParamChanged = true;
}
if (prompt == "filt-lfo-freq") {
std::cout << ">> enter filter LFO frequency (0 - 40)" << std::endl;
std::cin >> prompt;
auto freq = std::stof(prompt);
freq = clamp(freq, 0.f, 40.f);
params.filtLFOFreq = freq;
bParamChanged = true;
}
if (prompt == "pitch-lfo-freq") {
std::cout << ">> enter pitch LFO frequency (0 - 40)" << std::endl;
std::cin >> prompt;
auto freq = std::stof(prompt);
freq = clamp(freq, 0.f, 40.f);
params.pitchLFOFreq = freq;
bParamChanged = true;
}
if (prompt == "track") {
auto trackCount = 0;
std::vector<std::string> trackList = stream->getTrackList();
spdlog::info(">> list of tracks");
for (auto track : trackList) {
spdlog::info("{}: {}", trackCount, track);
trackCount++;
}
std::cin >> prompt;
auto trackNum = 0;
bool bErr = false;
try {
trackNum = std::stoi(prompt);
}
// Catch stoi errors
catch (const std::invalid_argument& e) {
spdlog::error("invalid argument");
bErr = true;
}
catch (const std::out_of_range& e) {
spdlog::error("input out of range");
bErr = true;
}
trackNum = clamp(trackNum, 0, trackCount);
std::string trackName;
trackCount = 0;
for (auto track : trackList) {
if (trackNum == trackCount) {
stream->setActiveTrackName(track);
spdlog::info("setting active track name to: {}", track);
break;
}
else {
trackCount++;
}
}
}
if (prompt == "pitch-lfo-depth") {
std::cout << ">> enter pitch LFO depth (0. - 1.)" << std::endl;
std::cin >> prompt;
auto depth = std::stof(prompt);
depth = clamp(depth, 0.f, 1.f);
params.pitchLFOdepth = depth;
bParamChanged = true;
}
if (prompt == "filt-lfo-on") {
params.bEnableFiltLFO = true;
bParamChanged = true;
}
if (prompt == "filt-lfo-off") {
params.bEnableFiltLFO = false;
bParamChanged = true;
}
if (prompt == "pitch-lfo-on") {
params.bEnablePitchLFO = true;
bParamChanged = true;
}
if (prompt == "pitch-lfo-off") {
params.bEnablePitchLFO = false;
bParamChanged = true;
}
if (prompt == "chorus-on") {
fxparams.bEnableChorus = true;
bFxParamChanged = true;
}
if (prompt == "chorus-off") {
fxparams.bEnableChorus = false;
bFxParamChanged = true;
}
if (prompt == "delay-on") {
fxparams.bEnableDelay1 = true;
bFxParamChanged = true;
}
if (prompt == "delay-off") {
fxparams.bEnableDelay1 = false;
bFxParamChanged = true;
}
if (prompt == "delay-time") {
std::cout << ">> enter delay time in milliseconds (0. - 1000.)" << std::endl;
std::cin >> prompt;
auto delayTimeMs = std::stof(prompt);
delayTimeMs = clamp(delayTimeMs, 0.f, 1000.f);
fxparams.delay1time = delayTimeMs;
bFxParamChanged = true;
}
if (prompt == "delay-feedback") {
std::cout << ">> enter delay feedback as a ratio (0. - 1.)" << std::endl;
std::cin >> prompt;
auto delayFeedbackRatio = std::stof(prompt);
delayFeedbackRatio = clamp(delayFeedbackRatio, 0.f, 1.f);
fxparams.delay1feedback = delayFeedbackRatio;
bFxParamChanged = true;
}
if (prompt == "delay-mix") {
std::cout << ">> enter delay wet/dry mix as a ratio (0. - 1.)" << std::endl;
std::cin >> prompt;
auto delayMix = std::stof(prompt);
delayMix = clamp(delayMix, 0.f, 1.f);
fxparams.delay1level = delayMix;
bParamChanged = true;
}
if (prompt == "reverb-on") {
fxparams.bEnableReverb = true;
bFxParamChanged = true;
}
if (prompt == "reverb-off") {
fxparams.bEnableReverb = false;
bFxParamChanged = true;
}
if (prompt == "record-start") {
stream->record(true);
}
if (prompt == "record-stop") {
stream->record(false);
}
if (prompt == "bitcrusher-on") {
fxparams.bEnableBitcrusher = true;
bFxParamChanged = true;
}
if (prompt == "bitcrusher-off") {
fxparams.bEnableBitcrusher = false;
bFxParamChanged = true;
}
if (prompt == "bitcrusher-bits") {
std::cout << ">> enter bit depth (1-32)" << std::endl;
std::cin >> prompt;
auto depth = std::stoi(prompt);
depth = clamp(depth, 0, 32);
fxparams.bitCrusherNBits = depth;
bFxParamChanged = true;
}
if (prompt == "osc") {
std::cout << ">> enter sine, saw, tri, square" << std::endl;
std::cin >> prompt;
OscillatorType osc = OscillatorType::SINE;
if (prompt == "sine") {
osc = OscillatorType::SINE;
}
if (prompt == "saw") {
osc = OscillatorType::SAW;
}
if (prompt == "tri") {
osc = OscillatorType::TRIANGLE;
}
if (prompt == "square") {
osc = OscillatorType::SQUARE;
}
params.osc = osc;
bParamChanged = true;
}
if (prompt == "osc2-enable") {
params.bEnableOsc2 = true;
bParamChanged = true;
}
if (prompt == "osc2-disable") {
params.bEnableOsc2 = false;
bParamChanged = true;
}
if (prompt == "osc2") {
std::cout << ">> enter sine, saw, tri, square" << std::endl;
std::cin >> prompt;
OscillatorType osc = OscillatorType::SINE;
if (prompt == "sine") {
osc = OscillatorType::SINE;
}
if (prompt == "saw") {
osc = OscillatorType::SAW;
}
if (prompt == "tri") {
osc = OscillatorType::TRIANGLE;
}
if (prompt == "square") {
osc = OscillatorType::SQUARE;
}
params.osc2 = osc;
bParamChanged = true;
}
if (prompt == "osc2-coarse") {
std::cin >> prompt;
auto coarse = std::stof(prompt);
coarse = clamp(coarse, -24.f, 24.f);
params.osc2coarse = coarse;
bParamChanged = true;
}
if (prompt == "osc2-fine") {
std::cin >> prompt;
auto fine = std::stof(prompt);
fine = clamp(fine, -1.f, 1.f);
params.osc2fine = fine;
bParamChanged = true;
}
if (prompt == "env") {
std::cout << ">> enter adsr envelope parameters (attack ms, decay ms, sustain dB (< 0), release ms) (e.g. 250 10 -10 500) " << std::endl;
std::vector<std::string> param;
size_t paramCount = 0;
std::string envP;
while (paramCount < 4 && std::cin >> envP) {
param.push_back(envP);
paramCount++;
}
size_t attMs = 0;
size_t decMs = 0;
int susdB = 0;
size_t relMs = 0;
std::sscanf(param[0].c_str(), "%zu", &attMs);
std::sscanf(param[1].c_str(), "%zu", &decMs);
std::sscanf(param[2].c_str(), "%d", &susdB);
std::sscanf(param[3].c_str(), "%zu", &relMs);
attMs = (attMs > 5000) ? 500 : attMs;
decMs = (decMs > 5000) ? 500 : decMs;
susdB = (susdB > 0) ? 0 : susdB;
relMs = (relMs > 5000) ? 500 : relMs;
EnvelopeParams env(attMs, decMs, susdB, relMs);
params.envParams = env;
bParamChanged = true;
}
if (prompt == "play") {
std::string pattern;
std::cin >> pattern;
std::vector<std::string> trackList = stream->getTrackList();
NoteGenerator gen;
spdlog::info("play " + pattern);
auto temp = gen.makeSequence(pattern, trackList);
while (!temp.empty()) {
notes.push_back(temp.front());
temp.pop_front();
}
}
if (prompt == "randompattern") {
std::cout << "usage: randompattern <scale>. generated random pattern N times. play with 'pattern' command" << std::endl;
NoteGenerator gen;
std::string keyStr, patStr, modeStr;
std::cin >> keyStr >> patStr >> modeStr;
// TODO: combine these to method. populate key, pattern, mode
Key key = Scale::strToKey(keyStr);
ScalePattern pattern = Scale::strToScalePattern(patStr);
ScaleMode mode = Scale::strToScaleMode(modeStr);
Scale scale = Scale(key, pattern, mode);
auto temp = gen.randomPattern("synth1", 8, scale);
notes = temp;
std::cout << "generated random pattern, play with 'pattern' command" << std::endl;
}
if (prompt == "scale") {
std::cout << "usage: scale <key pattern mode>. e.g. scale C# maj lydian" << std::endl;
NoteGenerator gen;
std::string keyStr, patStr, modeStr;
std::cin >> keyStr >> patStr >> modeStr;
// populate key, pattern, mode
Key key = Scale::strToKey(keyStr);
ScalePattern pattern = Scale::strToScalePattern(patStr);
ScaleMode mode = Scale::strToScaleMode(modeStr);
auto temp = gen.scalePattern(key, pattern, mode);
stream->queueLoop(1, temp, params.bpm);
std::cout << "now playing scale" << std::endl;
}
if (prompt == "loop") {
std::cin >> prompt;
int loopCount = std::stod(prompt);
if (notes.size() == 0) {
std::cout << "nothing to loop, use play to declare a sequence..." << std::endl;
}
else {
stream->queueLoop(loopCount, notes, params.bpm);
}
}
if (prompt == "pattern") {
auto temp = NoteGenerator::sortTimeVal(notes);
spdlog::info("(notes in pattern sorted by timestamp)");
if (temp.size() > 0) {
for (auto note : temp) {
spdlog::info("{}", note);
}
stream->queueLoop(1, notes, params.bpm);
}
else {
std::cout << "no notes to play!" << std::endl;
}
}
if (prompt == "clear") {
notes = {};
}
if (prompt == "mix") {
std::cout << ">> mix <trackname> <dB (-60...0)>" << std::endl;
std::vector<std::string> param;
size_t paramCount = 0;
std::string gainParams;
while (paramCount < 2 && std::cin >> gainParams) {
param.push_back(gainParams);
paramCount++;
}
std::string track;
track = param[0];
float fGainDB = 0.f;
std::sscanf(param[1].c_str(), "%f", &fGainDB);
fGainDB = clamp(fGainDB, -60.f, 0.f);
stream->updateTrackGainDB(track, fGainDB);
bParamChanged = true;
}
if (bParamChanged) {
logVoiceParams(params);
stream->update(params);
bParamChanged = false;
}
if (bFxParamChanged) {
logFxParams(fxparams);
stream->update(fxparams);
bFxParamChanged = false;
}
}
}
| 27.357438 | 140 | 0.61083 |
32fe5c733afef97b59aa68bebecf411d6038ac13 | 13,835 | cc | C++ | Source/Plugins/GraphicsPlugins/BladeImageFI/source/ETC2EAC.cc | OscarGame/blade | 6987708cb011813eb38e5c262c7a83888635f002 | [
"MIT"
] | 146 | 2018-12-03T08:08:17.000Z | 2022-03-21T06:04:06.000Z | Source/Plugins/GraphicsPlugins/BladeImageFI/source/ETC2EAC.cc | huangx916/blade | 3fa398f4d32215bbc7e292d61e38bb92aad1ee1c | [
"MIT"
] | 1 | 2019-01-18T03:35:49.000Z | 2019-01-18T03:36:08.000Z | Source/Plugins/GraphicsPlugins/BladeImageFI/source/ETC2EAC.cc | huangx916/blade | 3fa398f4d32215bbc7e292d61e38bb92aad1ee1c | [
"MIT"
] | 31 | 2018-12-03T10:32:43.000Z | 2021-10-04T06:31:44.000Z | /********************************************************************
created: 2015/01/28
filename: ETC2EAC.cc
author: Crazii
purpose: ETC2/EAC block compression
reference:
*********************************************************************/
#include <BladePCH.h>
#include "ETC2EAC.h"
#include "ETC2EACCommon.h"
namespace Blade
{
namespace ETC2EAC
{
/************************************************************************/
/* compression */
/************************************************************************/
/** @brief compress input 4x4 colors in given format, to ETC2 - RGB */
void compressBlockETC2(uint8 *outBlock, const uint8* colors, PixelFormat format)
{
Color::RGBA BLADE_ALIGNED(64) decodeBuffer[4*4];
Color::RGB BLADE_ALIGNED(64) colorBuffer[4*4];
extractBlockRGB(colorBuffer, colors, format, 4);
uint32 c[2];
compressBlockETC2RGB(colorBuffer, decodeBuffer, 4, 4, 0, 0, (uint8*)&c[0]);
std::memcpy(outBlock, c, sizeof(c) );
}
/** @brief compress input 4x4 colors in given format, to ETC2 - RGBA */
void compressBlockETC2EAC(uint8 *outBlock, const uint8* colors, PixelFormat format)
{
Color::RGBA BLADE_ALIGNED(64) decodeBuffer[4*4];
Color::RGB BLADE_ALIGNED(64) colorBuffer[4*4];
uint8 BLADE_ALIGNED(64) alphaBuffer[4*4];
extractBlockRGBA(colorBuffer, alphaBuffer, colors, format, 4);
uint32 c[4];
compressBlockAlphaFast(alphaBuffer, 0, 0, 4, 4, (uint8*)&c[0]);
compressBlockETC2RGB(colorBuffer, decodeBuffer, 4, 4, 0, 0, (uint8*)&c[2]);
std::memcpy(outBlock, c, sizeof(c) );
}
/** @brief compress input 4x4 colors in given format, to EAC, using only the R channel */
void compressBlockR11EAC(uint8 *outBlock, const uint8* colors, PixelFormat format)
{
uint8 BLADE_ALIGNED(64) redBuffer[4*4];
extractBlockR(redBuffer, colors, format, 4);
uint32 c[2];
compressBlockAlphaFast(redBuffer, 0, 0, 4, 4, (uint8*)&c[0]);
std::memcpy(outBlock, c, sizeof(c) );
}
/** @brief compress input 4x4 colors in given format, to EAC, using only the R,G channel */
void compressBlockRG11EAC(uint8 *outBlock, const uint8* colors, PixelFormat format, bool normalize)
{
uint8 BLADE_ALIGNED(64) redBuffer[4*4];
uint8 BLADE_ALIGNED(64) greenBuffer[4*4];
if( normalize )
extractBlockRGNormalize(redBuffer, greenBuffer, colors, format, 4);
else
extractBlockRG(redBuffer, greenBuffer, colors, format, 4);
uint32 c[4];
compressBlockAlphaFast(redBuffer, 0, 0, 4, 4, (uint8*)&c[0]);
compressBlockAlphaFast(greenBuffer, 0, 0, 4, 4, (uint8*)&c[2]);
std::memcpy(outBlock, c, sizeof(c) );
}
/** @brief */
size_t compressImageETC2(uint8 *outBuffer, const uint8* colors, int width, int height, PixelFormat format)
{
assert( width % 4 == 0 );
assert( height % 4 == 0 );
uint8 BLADE_ALIGNED(64) *outData = outBuffer;
Color::RGBA BLADE_ALIGNED(64) decodeBuffer[4*4];
Color::RGB BLADE_ALIGNED(64) colorBuffer[4*4];
uint32 c[2];
size_t pixelBytes = format.getSizeBytes();
assert( PixelFormat(PF_RGB_ETC2).getSizeBytes() == sizeof(c) );
for (int j = 0; j < height; j += 4)
{
for (int i = 0; i < width; i += 4)
{
IPlatformManager::prefetch<PM_READ>(colors + pixelBytes*4);
IPlatformManager::prefetch<PM_WRITE>(outData + sizeof(c));
extractBlockRGB(colorBuffer, colors, format, width);
compressBlockETC2RGB(colorBuffer, decodeBuffer, 4, 4, 0, 0, (uint8*)&c[0]);
std::memcpy(outData, c, sizeof(c) );
colors += pixelBytes*4;
outData += sizeof(c);
}
colors += pixelBytes*width*3;
}
return (size_t)(outData - outBuffer);
}
/** @brief */
size_t compressImageETC2EAC(uint8 *outBuffer, const uint8* colors, int width, int height, PixelFormat format)
{
assert( width % 4 == 0 );
assert( height % 4 == 0 );
uint8 BLADE_ALIGNED(64) *outData = outBuffer;
Color::RGBA BLADE_ALIGNED(64) decodeBuffer[4*4];
Color::RGB BLADE_ALIGNED(64) colorBuffer[4*4];
uint8 BLADE_ALIGNED(64) alphaBuffer[4*4];
uint32 c[4];
size_t pixelBytes = format.getSizeBytes();
assert( PixelFormat(PF_RGBA_ETC2EAC).getSizeBytes() == sizeof(c) );
for (int j = 0; j < height; j += 4)
{
for (int i = 0; i < width; i += 4)
{
IPlatformManager::prefetch<PM_READ>(colors + pixelBytes*4);
IPlatformManager::prefetch<PM_WRITE>(outData + sizeof(c));
extractBlockRGBA(colorBuffer, alphaBuffer, colors, format, width);
compressBlockAlphaFast(alphaBuffer, 0, 0, 4, 4, (uint8*)&c[0]);
compressBlockETC2RGB(colorBuffer, decodeBuffer, 4, 4, 0, 0, (uint8*)&c[2]);
std::memcpy(outData, c, sizeof(c) );
colors += pixelBytes*4;
outData += sizeof(c);
}
colors += pixelBytes*width*3;
}
return (size_t)(outData - outBuffer);
}
/** @brief */
size_t compressImageR11EAC(uint8 *outBuffer, const uint8* colors, int width, int height, PixelFormat format)
{
assert( width % 4 == 0 );
assert( height % 4 == 0 );
uint8 BLADE_ALIGNED(64) *outData = outBuffer;
uint8 BLADE_ALIGNED(64) redBuffer[4*4];
uint32 c[2];
size_t pixelBytes = format.getSizeBytes();
assert( PixelFormat(PF_R_EAC).getSizeBytes() == sizeof(c) );
for (int j = 0; j < height; j += 4)
{
for (int i = 0; i < width; i += 4)
{
IPlatformManager::prefetch<PM_READ>(colors + 4*pixelBytes);
IPlatformManager::prefetch<PM_WRITE>(outData + sizeof(c));
extractBlockR(redBuffer, colors, format, width);
compressBlockAlphaFast(redBuffer, 0, 0, 4, 4, (uint8*)&c[0]);
std::memcpy(outData, c, sizeof(c) );
colors += pixelBytes*4;
outData += sizeof(c);
}
colors += pixelBytes*width*3;
}
return (size_t)(outData - outBuffer);
}
/** @brief */
size_t compressImageRG11EAC(uint8 *outBuffer, const uint8* colors, int width, int height, PixelFormat format, bool normalize)
{
assert( width % 4 == 0 );
assert( height % 4 == 0 );
uint8 BLADE_ALIGNED(64) *outData = outBuffer;
uint8 BLADE_ALIGNED(64) redBuffer[4*4];
uint8 BLADE_ALIGNED(64) greenBuffer[4*4];
uint32 c[4];
size_t pixelBytes = format.getSizeBytes();
assert( PixelFormat(PF_RG_EAC).getSizeBytes() == sizeof(c) );
for (int j = 0; j < height; j += 4)
{
for (int i = 0; i < width; i += 4)
{
IPlatformManager::prefetch<PM_READ>(colors + 4*pixelBytes);
IPlatformManager::prefetch<PM_WRITE>(outData + sizeof(c));
if( normalize )
extractBlockRGNormalize(redBuffer, greenBuffer, colors, format, width);
else
extractBlockRG(redBuffer, greenBuffer, colors, format, width);
compressBlockAlphaFast(redBuffer, 0, 0, 4, 4, (uint8*)&c[0]);
compressBlockAlphaFast(greenBuffer, 0, 0, 4, 4, (uint8*)&c[2]);
std::memcpy(outData, c, sizeof(c) );
colors += pixelBytes*4;
outData += sizeof(c);
}
colors += pixelBytes*width*3;
}
return (size_t)(outData - outBuffer);
}
/************************************************************************/
/* decompression */
/************************************************************************/
/** @brief */
void decompressBlockETC2(uint8* outColors, const uint8 *block, PixelFormat format)
{
Color::RGBA BLADE_ALIGNED(64) colorBuffer[4*4];
std::memset(colorBuffer, 0, sizeof(colorBuffer) );
uint32 c[2];
std::memcpy(c, block, sizeof(c));
decompressBlockETC2RGB((uint8*)&c[0], (uint8*)colorBuffer, 4, 4, 0, 0, 4);
insertBlock(outColors, colorBuffer, format, 4);
}
/** @brief */
void decompressBlockETC2EAC(uint8* outColors, const uint8 *block, PixelFormat format)
{
Color::RGBA BLADE_ALIGNED(64) colorBuffer[4*4];
std::memset(colorBuffer, 0, sizeof(colorBuffer) );
uint32 c[4];
std::memcpy(c, block, sizeof(c));
decompressBlockAlphaC((uint8*)&c[0], (uint8*)&colorBuffer[0].a, 4, 4, 0, 0, 4);
decompressBlockETC2RGB((uint8*)&c[2], (uint8*)colorBuffer, 4, 4, 0, 0, 4);
insertBlock(outColors, colorBuffer, format, 4);
}
/** @brief */
void decompressBlockR11EAC(uint8* outColors, const uint8 *block, PixelFormat format)
{
Color::RGBA BLADE_ALIGNED(64) colorBuffer[4*4];
std::memset(colorBuffer, 0, sizeof(colorBuffer) );
uint32 c[2];
std::memcpy(c, block, sizeof(c));
decompressBlockAlphaC((uint8*)&c[0], (uint8*)&(colorBuffer[0].r), 4, 4, 0, 0, 4);
insertBlock(outColors, colorBuffer, format, 4);
}
/** @brief */
void decompressBlockRG11EAC(uint8* outColors, const uint8 *block, PixelFormat format)
{
Color::RGBA BLADE_ALIGNED(64) colorBuffer[4*4];
std::memset(colorBuffer, 0, sizeof(colorBuffer) );
uint32 c[4];
std::memcpy(c, block, sizeof(c));
decompressBlockAlphaC((uint8*)&c[0], (uint8*)&(colorBuffer[0].r), 4, 4, 0, 0, 4);
decompressBlockAlphaC((uint8*)&c[2], (uint8*)&(colorBuffer[0].g), 4, 4, 0, 0, 4);
insertBlock(outColors, colorBuffer, format, 4);
}
/** @brief return output bytes */
/* @note width & height are in original source image dimensions */
size_t decompressImageETC2(uint8 *outBuffer, const uint8* blocks, int width, int height, PixelFormat format)
{
assert(width % 4 == 0);
assert(height % 4 == 0);
Color::RGBA BLADE_ALIGNED(64) colorBuffer[4*4];
std::memset(colorBuffer, 0, sizeof(colorBuffer) );
uint32 c[2];
BLADE_ALIGNED(64) uint8* buffer = outBuffer;
size_t pixelBytes = format.getSizeBytes();
assert( PixelFormat(PF_RGB_ETC2).getSizeBytes() == sizeof(c));
size_t blockWidth = size_t((width+3)/4);
size_t blockHeight = size_t((height+3)/4);
for (size_t j = 0; j < blockHeight; ++j)
{
for (size_t i = 0; i < blockWidth; ++i)
{
IPlatformManager::prefetch<PM_READ>(blocks + sizeof(c));
IPlatformManager::prefetch<PM_WRITE>(buffer + 4*pixelBytes);
std::memcpy(c, blocks, sizeof(c));
decompressBlockETC2RGB((uint8*)&c[0], (uint8*)colorBuffer, 4, 4, 0, 0, 4);
insertBlock(buffer, colorBuffer, format, width);
blocks += sizeof(c);
buffer += 4*pixelBytes;
}
buffer += width*pixelBytes*3;
}
return (size_t)(buffer - outBuffer);
}
/** @brief */
size_t decompressImageETC2EAC(uint8 *outBuffer, const uint8* blocks, int width, int height, PixelFormat format)
{
assert(width % 4 == 0);
assert(height % 4 == 0);
Color::RGBA BLADE_ALIGNED(64) colorBuffer[4*4];
std::memset(colorBuffer, 0, sizeof(colorBuffer) );
uint32 c[4];
BLADE_ALIGNED(64) uint8* buffer = outBuffer;
size_t pixelBytes = format.getSizeBytes();
assert( PixelFormat(PF_RGBA_ETC2EAC).getSizeBytes() == sizeof(c));
size_t blockWidth = (size_t)((width+3)/4);
size_t blockHeight = (size_t)((height+3)/4);
for (size_t j = 0; j < blockHeight; ++j)
{
for (size_t i = 0; i < blockWidth; ++i)
{
IPlatformManager::prefetch<PM_READ>(blocks + sizeof(c));
IPlatformManager::prefetch<PM_WRITE>(buffer + 4*pixelBytes);
std::memcpy(c, blocks, sizeof(c));
decompressBlockAlphaC((uint8*)&c[0], (uint8*)&colorBuffer[0].a, 4, 4, 0, 0, 4);
decompressBlockETC2RGB((uint8*)&c[2], (uint8*)colorBuffer, 4, 4, 0, 0, 4);
insertBlock(buffer, colorBuffer, format, width);
blocks += sizeof(c);
buffer += 4*pixelBytes;
}
buffer += width*pixelBytes*3;
}
return (size_t)(buffer - outBuffer);
}
/** @brief */
size_t decompressImageR11EAC(uint8 *outBuffer, const uint8* blocks, int width, int height, PixelFormat format)
{
assert(width % 4 == 0);
assert(height % 4 == 0);
Color::RGBA BLADE_ALIGNED(64) colorBuffer[4*4];
std::memset(colorBuffer, 0, sizeof(colorBuffer) );
uint32 c[2];
BLADE_ALIGNED(64) uint8* buffer = outBuffer;
size_t pixelBytes = format.getSizeBytes();
assert( PixelFormat(PF_R_EAC).getSizeBytes() == sizeof(c));
size_t blockWidth = (size_t)((width+3)/4);
size_t blockHeight = (size_t)((height+3)/4);
for (size_t j = 0; j < blockHeight; ++j)
{
for (size_t i = 0; i < blockWidth; ++i)
{
IPlatformManager::prefetch<PM_READ>(blocks + sizeof(c));
IPlatformManager::prefetch<PM_WRITE>(buffer + 4*pixelBytes);
std::memcpy(c, blocks, sizeof(c));
decompressBlockAlphaC((uint8*)&c[0], (uint8*)&(colorBuffer[0].r), 4, 4, 0, 0, 4);
insertBlock(buffer, colorBuffer, format, width);
blocks += sizeof(c);
buffer += 4*pixelBytes;
}
buffer += width*pixelBytes*3;
}
return (size_t)(buffer - outBuffer);
}
/** @brief */
size_t decompressImageRG11EAC(uint8 *outBuffer, const uint8* blocks, int width, int height, PixelFormat format)
{
assert(width % 4 == 0);
assert(height % 4 == 0);
Color::RGBA BLADE_ALIGNED(64) colorBuffer[4*4];
std::memset(colorBuffer, 0, sizeof(colorBuffer) );
uint32 c[4];
BLADE_ALIGNED(64) uint8* buffer = outBuffer;
size_t pixelBytes = format.getSizeBytes();
assert( PixelFormat(PF_RG_EAC).getSizeBytes() == sizeof(c));
size_t blockWidth = (size_t)((width+3)/4);
size_t blockHeight = (size_t)((height+3)/4);
for (size_t j = 0; j < blockHeight; ++j)
{
for (size_t i = 0; i < blockWidth; ++i)
{
IPlatformManager::prefetch<PM_READ>(blocks + sizeof(c));
IPlatformManager::prefetch<PM_WRITE>(buffer + 4*pixelBytes);
std::memcpy(c, blocks, sizeof(c));
decompressBlockAlphaC((uint8*)&c[0], (uint8*)&(colorBuffer[0].r), 4, 4, 0, 0, 4);
decompressBlockAlphaC((uint8*)&c[2], (uint8*)&(colorBuffer[0].g), 4, 4, 0, 0, 4);
insertBlock(buffer, colorBuffer, format, width);
blocks += sizeof(c);
buffer += 4*pixelBytes;
}
buffer += width*pixelBytes*3;
}
return (size_t)(buffer - outBuffer);
}
}//namespace ETC2EAC
}//namespace Blade | 32.78436 | 127 | 0.622551 |
32ff64c1d17f46a71a1c44627d62f6b5911a16f4 | 618 | hpp | C++ | src/widgets/PlayerFrame.hpp | filipdjordjevic/music_player | a0d66005a2fe0b8f277662a37d8d1c2912196536 | [
"MIT"
] | null | null | null | src/widgets/PlayerFrame.hpp | filipdjordjevic/music_player | a0d66005a2fe0b8f277662a37d8d1c2912196536 | [
"MIT"
] | null | null | null | src/widgets/PlayerFrame.hpp | filipdjordjevic/music_player | a0d66005a2fe0b8f277662a37d8d1c2912196536 | [
"MIT"
] | null | null | null | #pragma once
#include <QtWidgets>
#include "VolumeSlider.hpp"
#include "SeekBar.hpp"
#include "LcdLabel.hpp"
#include "CircleButton.hpp"
namespace ui
{
class PlayerFrame : public QFrame
{
Q_OBJECT
private:
CircleButton *playBtn_;
CircleButton *soundBtn_;
VolumeSlider *volumeSlider_;
SeekBar *seekBar_;
LcdLabel *durationLbl_;
LcdLabel *songLbl_;
bool playing_;
QTimer *timer_;
void connectWidgetsToActions();
public:
PlayerFrame(QWidget *parent = NULL);
void loadSongData();
};
} // namespace ui | 19.3125 | 44 | 0.627832 |
fd065cb4c52b896a29c94642cf6a8389f0e88c7b | 1,663 | cpp | C++ | src/uMOOSArduinoLib/NetClientComm.cpp | mandad/moos-ivp-manda | 6bc81d14aba7c537b7932d6135eed7a5b39c3c52 | [
"MIT"
] | 9 | 2016-02-25T03:25:53.000Z | 2022-03-27T09:47:50.000Z | src/uMOOSArduinoLib/NetClientComm.cpp | mandad/moos-ivp-manda | 6bc81d14aba7c537b7932d6135eed7a5b39c3c52 | [
"MIT"
] | null | null | null | src/uMOOSArduinoLib/NetClientComm.cpp | mandad/moos-ivp-manda | 6bc81d14aba7c537b7932d6135eed7a5b39c3c52 | [
"MIT"
] | 4 | 2016-06-02T17:42:42.000Z | 2021-12-15T09:37:55.000Z | /************************************************************/
/* NAME: Mike Bogochow, Jeff Masucci, Cody Noel */
/* ORGN: UNH */
/* FILE: NetClientComm.cpp */
/* DATE: April 2014 */
/************************************************************/
/* This is an implementation of IMOOSComm for communicating */
/* over a network as a client. */
/************************************************************/
#include "NetClientComm.h"
#include "NetUtil/tcpblockio.h"
#include "NetUtil/no_sigpipe.h"
#ifdef WIN32
#else
#include <unistd.h>
#endif
#include <fcntl.h>
#include <sys/stat.h>
#include <sstream>
#include <string.h>
using namespace std;
/**
* Create a new client communications object.
*
* @param serverPort
* the port number the server is running on
* @param serverNode
* either an IPv4 address or a DNS name for the server
* @param delimiter
* the delimiter character for messages between client and server
*/
NetClientComm::NetClientComm(char *serverPort, char *serverNode,
const char *delimiter)
//: delim(delimiter)
{
this->delim = delimiter;
this->serverPort = serverPort;
this->serverNode = serverNode;
socketFD = -1;
}
NetClientComm::~NetClientComm()
{
if (socketFD > -1)
close(socketFD);
}
/**
* Open socket.
*
* @return true on successful open of socket
* false otherwise
*/
bool NetClientComm::openComm()
{
no_sigpipe();
socketFD = openclient(serverPort, serverNode, serverIP, clientIP);
return socketFD >= 0;
}
| 24.820896 | 70 | 0.542995 |
fd0a820283e8bfe74856d5e202860089b96f9e70 | 1,984 | cpp | C++ | std-regex/id-scanners/AdvancedIdScanner.cpp | PS-Group/compiler-theory-samples | c916af50eb42020024257ecd17f9be1580db7bf0 | [
"MIT"
] | null | null | null | std-regex/id-scanners/AdvancedIdScanner.cpp | PS-Group/compiler-theory-samples | c916af50eb42020024257ecd17f9be1580db7bf0 | [
"MIT"
] | null | null | null | std-regex/id-scanners/AdvancedIdScanner.cpp | PS-Group/compiler-theory-samples | c916af50eb42020024257ecd17f9be1580db7bf0 | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "AdvancedIdScanner.h"
CAdvancedIdScanner::CAdvancedIdScanner()
: m_pattern("[a-zA-Z_][a-zA-Z0-9_]*")
, m_commentBegin("/\\*")
, m_commentEnd("\\*/")
{
}
void CAdvancedIdScanner::ScanLine(std::string const& text)
{
// У функции regex_search есть вариант, принимающий 2 итератора вместо строки,
// то есть можно использовать итераторы для последовательного движения по строке.
auto from = text.cbegin();
auto to = text.cend();
if (m_isInComment)
{
AdvanceInComment(from, to);
}
else
{
AdvanceNormal(from, to);
}
}
std::vector<std::string> CAdvancedIdScanner::GetIds()const
{
std::vector<std::string> result;
result.reserve(m_ids.size());
for (std::string const& id : m_ids)
{
result.emplace_back(id);
}
return result;
}
void CAdvancedIdScanner::AdvanceInComment(string_iterator from, string_iterator to)
{
std::smatch match;
if (std::regex_search(from, to, match, m_commentEnd))
{
m_isInComment = false;
from += match.prefix().length() + match.length(0);
AdvanceNormal(from, to);
}
}
void CAdvancedIdScanner::AdvanceNormal(string_iterator from, string_iterator to)
{
std::smatch match;
if (std::regex_search(from, to, match, m_commentBegin))
{
auto commentStart = from + match.prefix().length();
AdvanceNoComment(from, commentStart);
m_isInComment = true;
AdvanceInComment(commentStart + match.length(0), to);
}
else
{
AdvanceNoComment(from, to);
}
}
void CAdvancedIdScanner::AdvanceNoComment(string_iterator from, string_iterator to)
{
std::smatch match;
while (std::regex_search(from, to, match, m_pattern))
{
// Сохраняем сопоставленный ID в std::set.
m_ids.insert(match[0]);
// Перемещаем позицию начала поиска за конец найденного ID.
from += match.prefix().length() + match.length(0);
}
}
| 25.766234 | 85 | 0.645161 |
fd0b368d9ea7dce625164111fef15ff04f969087 | 1,463 | cpp | C++ | tcp_example/tcp_client.cpp | damianrusinek/classes-pas | 571fa436672da653ed8fad1f5af5eb5fd60503b0 | [
"MIT"
] | 11 | 2018-03-22T07:39:10.000Z | 2021-03-21T19:24:30.000Z | tcp_example/tcp_client.cpp | damianrusinek/classes-pas | 571fa436672da653ed8fad1f5af5eb5fd60503b0 | [
"MIT"
] | null | null | null | tcp_example/tcp_client.cpp | damianrusinek/classes-pas | 571fa436672da653ed8fad1f5af5eb5fd60503b0 | [
"MIT"
] | 8 | 2018-03-22T23:24:43.000Z | 2022-01-09T11:31:13.000Z | #include <iostream>
#include <stdexcept>
#include <string>
#include <QCoreApplication>
#include <QString>
#include <QtNetwork>
#define BUF_SIZE 1024
int main(int argc, char *argv[])
{
if (argc != 3) {
throw std::domain_error("Invalid number of arguments - expected ip address and port");
}
QCoreApplication a(argc, argv);
QString ipAddr = argv[1];
bool portOk = true;
quint16 port = QString(argv[2]).toUInt(&portOk);
if (port <= 0 || !portOk) {
throw std::domain_error("Invalid port");
}
QTcpSocket socket;
socket.connectToHost(ipAddr, port);
if(socket.waitForConnected() ) {
std::cout << "Connected to " << ipAddr.toStdString() << " port " << port << std::endl;
}
std::string data;
QByteArray data_srv;
std::cout << "Leave empty line to quit" << std::endl;
while(true) {
if(socket.isWritable()) {
std::cout << "Message to send: ";
std::getline(std::cin, data);
if (data == "") {
break;
}
socket.write(QString::fromStdString(data).toLatin1());
}
socket.waitForReadyRead(-1);
data_srv = socket.read(BUF_SIZE);
if (data_srv == "") {
break;
}
std::cout << "Answer: ";
std::cout << data_srv.constData() << std::endl;
}
socket.close();
std::cout << "Connection closed" << std::endl;
return a.exec();
}
| 24.79661 | 94 | 0.555707 |
fd0cff23ba42c34f86a8fad3935131911e52ff77 | 24,793 | cpp | C++ | src/idl_parser.cpp | waderly/flatbuffers | 59043114ac2931e4b77c3c5b2c2022cda809c6d4 | [
"Apache-2.0"
] | 1 | 2015-11-05T18:38:14.000Z | 2015-11-05T18:38:14.000Z | src/idl_parser.cpp | waderly/flatbuffers | 59043114ac2931e4b77c3c5b2c2022cda809c6d4 | [
"Apache-2.0"
] | null | null | null | src/idl_parser.cpp | waderly/flatbuffers | 59043114ac2931e4b77c3c5b2c2022cda809c6d4 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2014 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <algorithm>
#include "flatbuffers/flatbuffers.h"
#include "flatbuffers/idl.h"
#include "flatbuffers/util.h"
namespace flatbuffers {
const char *const kTypeNames[] = {
#define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE) IDLTYPE,
FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
#undef FLATBUFFERS_TD
nullptr
};
const char kTypeSizes[] = {
#define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE) sizeof(CTYPE),
FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
#undef FLATBUFFERS_TD
};
static void Error(const std::string &msg) {
throw msg;
}
// Ensure that integer values we parse fit inside the declared integer type.
static void CheckBitsFit(int64_t val, size_t bits) {
auto mask = (1ll << bits) - 1; // Bits we allow to be used.
if (bits < 64 &&
(val & ~mask) != 0 && // Positive or unsigned.
(val | mask) != -1) // Negative.
Error("constant does not fit in a " + NumToString(bits) + "-bit field");
}
// atot: templated version of atoi/atof: convert a string to an instance of T.
template<typename T> inline T atot(const char *s) {
auto val = StringToInt(s);
CheckBitsFit(val, sizeof(T) * 8);
return (T)val;
}
template<> inline bool atot<bool>(const char *s) {
return 0 != atoi(s);
}
template<> inline float atot<float>(const char *s) {
return static_cast<float>(strtod(s, nullptr));
}
template<> inline double atot<double>(const char *s) {
return strtod(s, nullptr);
}
template<> inline Offset<void> atot<Offset<void>>(const char *s) {
return Offset<void>(atoi(s));
}
// Declare tokens we'll use. Single character tokens are represented by their
// ascii character code (e.g. '{'), others above 256.
#define FLATBUFFERS_GEN_TOKENS(TD) \
TD(Eof, 256, "end of file") \
TD(StringConstant, 257, "string constant") \
TD(IntegerConstant, 258, "integer constant") \
TD(FloatConstant, 259, "float constant") \
TD(Identifier, 260, "identifier") \
TD(Table, 261, "table") \
TD(Struct, 262, "struct") \
TD(Enum, 263, "enum") \
TD(Union, 264, "union") \
TD(NameSpace, 265, "namespace") \
TD(RootType, 266, "root_type")
enum {
#define FLATBUFFERS_TOKEN(NAME, VALUE, STRING) kToken ## NAME,
FLATBUFFERS_GEN_TOKENS(FLATBUFFERS_TOKEN)
#undef FLATBUFFERS_TOKEN
#define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE) kToken ## ENUM,
FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
#undef FLATBUFFERS_TD
};
static std::string TokenToString(int t) {
static const char *tokens[] = {
#define FLATBUFFERS_TOKEN(NAME, VALUE, STRING) STRING,
FLATBUFFERS_GEN_TOKENS(FLATBUFFERS_TOKEN)
#undef FLATBUFFERS_TOKEN
#define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE) IDLTYPE,
FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
#undef FLATBUFFERS_TD
};
if (t < 256) { // A single ascii char token.
std::string s;
s.append(1, t);
return s;
} else { // Other tokens.
return tokens[t - 256];
}
}
void Parser::Next() {
doc_comment_.clear();
bool seen_newline = false;
for (;;) {
char c = *cursor_++;
token_ = c;
switch (c) {
case '\0': cursor_--; token_ = kTokenEof; return;
case ' ': case '\r': case '\t': break;
case '\n': line_++; seen_newline = true; break;
case '{': case '}': case '(': case ')': case '[': case ']': return;
case ',': case ':': case ';': case '=': return;
case '.':
if(!isdigit(*cursor_)) return;
Error("floating point constant can\'t start with \".\"");
break;
case '\"':
attribute_ = "";
while (*cursor_ != '\"') {
if (*cursor_ < ' ' && *cursor_ >= 0)
Error("illegal character in string constant");
if (*cursor_ == '\\') {
cursor_++;
switch (*cursor_) {
case 'n': attribute_ += '\n'; cursor_++; break;
case 't': attribute_ += '\t'; cursor_++; break;
case 'r': attribute_ += '\r'; cursor_++; break;
case '\"': attribute_ += '\"'; cursor_++; break;
case '\\': attribute_ += '\\'; cursor_++; break;
default: Error("unknown escape code in string constant"); break;
}
} else { // printable chars + UTF-8 bytes
attribute_ += *cursor_++;
}
}
cursor_++;
token_ = kTokenStringConstant;
return;
case '/':
if (*cursor_ == '/') {
const char *start = ++cursor_;
while (*cursor_ && *cursor_ != '\n') cursor_++;
if (*start == '/') { // documentation comment
if (!seen_newline)
Error("a documentation comment should be on a line on its own");
// todo: do we want to support multiline comments instead?
doc_comment_ += std::string(start + 1, cursor_);
}
break;
}
// fall thru
default:
if (isalpha(static_cast<unsigned char>(c))) {
// Collect all chars of an identifier:
const char *start = cursor_ - 1;
while (isalnum(static_cast<unsigned char>(*cursor_)) ||
*cursor_ == '_')
cursor_++;
attribute_.clear();
attribute_.append(start, cursor_);
// First, see if it is a type keyword from the table of types:
#define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE) \
if (attribute_ == IDLTYPE) { \
token_ = kToken ## ENUM; \
return; \
}
FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
#undef FLATBUFFERS_TD
// If it's a boolean constant keyword, turn those into integers,
// which simplifies our logic downstream.
if (attribute_ == "true" || attribute_ == "false") {
attribute_ = NumToString(attribute_ == "true");
token_ = kTokenIntegerConstant;
return;
}
// Check for declaration keywords:
if (attribute_ == "table") { token_ = kTokenTable; return; }
if (attribute_ == "struct") { token_ = kTokenStruct; return; }
if (attribute_ == "enum") { token_ = kTokenEnum; return; }
if (attribute_ == "union") { token_ = kTokenUnion; return; }
if (attribute_ == "namespace") { token_ = kTokenNameSpace; return; }
if (attribute_ == "root_type") { token_ = kTokenRootType; return; }
// If not, it is a user-defined identifier:
token_ = kTokenIdentifier;
return;
} else if (isdigit(static_cast<unsigned char>(c)) || c == '-') {
const char *start = cursor_ - 1;
while (isdigit(static_cast<unsigned char>(*cursor_))) cursor_++;
if (*cursor_ == '.') {
cursor_++;
while (isdigit(static_cast<unsigned char>(*cursor_))) cursor_++;
token_ = kTokenFloatConstant;
} else {
token_ = kTokenIntegerConstant;
}
attribute_.clear();
attribute_.append(start, cursor_);
return;
}
std::string ch;
ch = c;
if (c < ' ' || c > '~') ch = "code: " + NumToString(c);
Error("illegal character: " + ch);
break;
}
}
}
// Check if a given token is next, if so, consume it as well.
bool Parser::IsNext(int t) {
bool isnext = t == token_;
if (isnext) Next();
return isnext;
}
// Expect a given token to be next, consume it, or error if not present.
void Parser::Expect(int t) {
if (t != token_) {
Error("expecting: " + TokenToString(t) + " instead got: " +
TokenToString(token_));
}
Next();
}
// Parse any IDL type.
void Parser::ParseType(Type &type) {
if (token_ >= kTokenBOOL && token_ <= kTokenSTRING) {
type.base_type = static_cast<BaseType>(token_ - kTokenNONE);
} else {
if (token_ == kTokenIdentifier) {
auto enum_def = enums_.Lookup(attribute_);
if (enum_def) {
type = enum_def->underlying_type;
if (enum_def->is_union) type.base_type = BASE_TYPE_UNION;
} else {
type.base_type = BASE_TYPE_STRUCT;
type.struct_def = LookupCreateStruct(attribute_);
}
} else if (token_ == '[') {
Next();
Type subtype;
ParseType(subtype);
if (subtype.base_type == BASE_TYPE_VECTOR) {
// We could support this, but it will complicate things, and it's
// easier to work around with a struct around the inner vector.
Error("nested vector types not supported (wrap in table first).");
}
if (subtype.base_type == BASE_TYPE_UNION) {
// We could support this if we stored a struct of 2 elements per
// union element.
Error("vector of union types not supported (wrap in table first).");
}
type = Type(BASE_TYPE_VECTOR, subtype.struct_def);
type.element = subtype.base_type;
Expect(']');
return;
} else {
Error("illegal type syntax");
}
}
Next();
}
FieldDef &Parser::AddField(StructDef &struct_def,
const std::string &name,
const Type &type) {
auto &field = *new FieldDef();
field.value.offset =
FieldIndexToOffset(static_cast<voffset_t>(struct_def.fields.vec.size()));
field.name = name;
field.value.type = type;
if (struct_def.fixed) { // statically compute the field offset
auto size = InlineSize(type);
auto alignment = InlineAlignment(type);
// structs_ need to have a predictable format, so we need to align to
// the largest scalar
struct_def.minalign = std::max(struct_def.minalign, alignment);
struct_def.PadLastField(alignment);
field.value.offset = static_cast<uoffset_t>(struct_def.bytesize);
struct_def.bytesize += size;
}
if (struct_def.fields.Add(name, &field))
Error("field already exists: " + name);
return field;
}
void Parser::ParseField(StructDef &struct_def) {
std::string name = attribute_;
std::string dc = doc_comment_;
Expect(kTokenIdentifier);
Expect(':');
Type type;
ParseType(type);
if (struct_def.fixed && !IsScalar(type.base_type) && !IsStruct(type))
Error("structs_ may contain only scalar or struct fields");
if (type.base_type == BASE_TYPE_UNION) {
// For union fields, add a second auto-generated field to hold the type,
// with _type appended as the name.
AddField(struct_def, name + "_type", type.enum_def->underlying_type);
}
auto &field = AddField(struct_def, name, type);
if (token_ == '=') {
Next();
ParseSingleValue(field.value);
}
field.doc_comment = dc;
ParseMetaData(field);
field.deprecated = field.attributes.Lookup("deprecated") != nullptr;
if (field.deprecated && struct_def.fixed)
Error("can't deprecate fields in a struct");
Expect(';');
}
void Parser::ParseAnyValue(Value &val, FieldDef *field) {
switch (val.type.base_type) {
case BASE_TYPE_UNION: {
assert(field);
if (!field_stack_.size() ||
field_stack_.back().second->value.type.base_type != BASE_TYPE_UTYPE)
Error("missing type field before this union value: " + field->name);
auto enum_idx = atot<unsigned char>(
field_stack_.back().first.constant.c_str());
auto struct_def = val.type.enum_def->ReverseLookup(enum_idx);
if (!struct_def) Error("illegal type id for: " + field->name);
val.constant = NumToString(ParseTable(*struct_def));
break;
}
case BASE_TYPE_STRUCT:
val.constant = NumToString(ParseTable(*val.type.struct_def));
break;
case BASE_TYPE_STRING: {
auto s = attribute_;
Expect(kTokenStringConstant);
val.constant = NumToString(builder_.CreateString(s).o);
break;
}
case BASE_TYPE_VECTOR: {
Expect('[');
val.constant = NumToString(ParseVector(val.type.VectorType()));
break;
}
default:
ParseSingleValue(val);
break;
}
}
void Parser::SerializeStruct(const StructDef &struct_def, const Value &val) {
auto off = atot<uoffset_t>(val.constant.c_str());
assert(struct_stack_.size() - off == struct_def.bytesize);
builder_.Align(struct_def.minalign);
builder_.PushBytes(&struct_stack_[off], struct_def.bytesize);
struct_stack_.resize(struct_stack_.size() - struct_def.bytesize);
builder_.AddStructOffset(val.offset, builder_.GetSize());
}
uoffset_t Parser::ParseTable(const StructDef &struct_def) {
Expect('{');
size_t fieldn = 0;
for (;;) {
std::string name = attribute_;
if (!IsNext(kTokenStringConstant)) Expect(kTokenIdentifier);
auto field = struct_def.fields.Lookup(name);
if (!field) Error("unknown field: " + name);
if (struct_def.fixed && (fieldn >= struct_def.fields.vec.size()
|| struct_def.fields.vec[fieldn] != field)) {
Error("struct field appearing out of order: " + name);
}
Expect(':');
Value val = field->value;
ParseAnyValue(val, field);
field_stack_.push_back(std::make_pair(val, field));
fieldn++;
if (IsNext('}')) break;
Expect(',');
}
if (struct_def.fixed && fieldn != struct_def.fields.vec.size())
Error("incomplete struct initialization: " + struct_def.name);
auto start = struct_def.fixed
? builder_.StartStruct(struct_def.minalign)
: builder_.StartTable();
for (size_t size = struct_def.sortbysize ? sizeof(largest_scalar_t) : 1;
size;
size /= 2) {
// Go through elements in reverse, since we're building the data backwards.
for (auto it = field_stack_.rbegin();
it != field_stack_.rbegin() + fieldn; ++it) {
auto &value = it->first;
auto field = it->second;
if (!struct_def.sortbysize || size == SizeOf(value.type.base_type)) {
switch (value.type.base_type) {
#define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE) \
case BASE_TYPE_ ## ENUM: \
builder_.Pad(field->padding); \
builder_.AddElement(value.offset, \
atot<CTYPE>( value.constant.c_str()), \
atot<CTYPE>(field->value.constant.c_str())); \
break;
FLATBUFFERS_GEN_TYPES_SCALAR(FLATBUFFERS_TD);
#undef FLATBUFFERS_TD
#define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE) \
case BASE_TYPE_ ## ENUM: \
builder_.Pad(field->padding); \
if (IsStruct(field->value.type)) { \
SerializeStruct(*field->value.type.struct_def, value); \
} else { \
builder_.AddOffset(value.offset, \
atot<CTYPE>(value.constant.c_str())); \
} \
break;
FLATBUFFERS_GEN_TYPES_POINTER(FLATBUFFERS_TD);
#undef FLATBUFFERS_TD
}
}
}
}
for (size_t i = 0; i < fieldn; i++) field_stack_.pop_back();
if (struct_def.fixed) {
builder_.ClearOffsets();
builder_.EndStruct();
// Temporarily store this struct in a side buffer, since this data has to
// be stored in-line later in the parent object.
auto off = struct_stack_.size();
struct_stack_.insert(struct_stack_.end(),
builder_.GetBufferPointer(),
builder_.GetBufferPointer() + struct_def.bytesize);
builder_.PopBytes(struct_def.bytesize);
return static_cast<uoffset_t>(off);
} else {
return builder_.EndTable(
start,
static_cast<voffset_t>(struct_def.fields.vec.size()));
}
}
uoffset_t Parser::ParseVector(const Type &type) {
int count = 0;
if (token_ != ']') for (;;) {
Value val;
val.type = type;
ParseAnyValue(val, NULL);
field_stack_.push_back(std::make_pair(val, nullptr));
count++;
if (token_ == ']') break;
Expect(',');
}
Next();
builder_.StartVector(count * InlineSize(type), InlineAlignment((type)));
for (int i = 0; i < count; i++) {
// start at the back, since we're building the data backwards.
auto &val = field_stack_.back().first;
switch (val.type.base_type) {
#define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE) \
case BASE_TYPE_ ## ENUM: \
if (IsStruct(val.type)) SerializeStruct(*val.type.struct_def, val); \
else builder_.PushElement(atot<CTYPE>(val.constant.c_str())); \
break;
FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
#undef FLATBUFFERS_TD
}
field_stack_.pop_back();
}
builder_.ClearOffsets();
return builder_.EndVector(count);
}
void Parser::ParseMetaData(Definition &def) {
if (IsNext('(')) {
for (;;) {
auto name = attribute_;
Expect(kTokenIdentifier);
auto e = new Value();
def.attributes.Add(name, e);
if (IsNext(':')) {
ParseSingleValue(*e);
}
if (IsNext(')')) break;
Expect(',');
}
}
}
bool Parser::TryTypedValue(int dtoken,
bool check,
Value &e,
BaseType req) {
bool match = dtoken == token_;
if (match) {
e.constant = attribute_;
if (!check) {
if (e.type.base_type == BASE_TYPE_NONE) {
e.type.base_type = req;
} else {
Error(std::string("type mismatch: expecting: ") +
kTypeNames[e.type.base_type] +
", found: " +
kTypeNames[req]);
}
}
Next();
}
return match;
}
void Parser::ParseSingleValue(Value &e) {
if (TryTypedValue(kTokenIntegerConstant,
IsScalar(e.type.base_type),
e,
BASE_TYPE_INT) ||
TryTypedValue(kTokenFloatConstant,
IsFloat(e.type.base_type),
e,
BASE_TYPE_FLOAT) ||
TryTypedValue(kTokenStringConstant,
e.type.base_type == BASE_TYPE_STRING,
e,
BASE_TYPE_STRING)) {
} else if (token_ == kTokenIdentifier) {
for (auto it = enums_.vec.begin(); it != enums_.vec.end(); ++it) {
auto ev = (*it)->vals.Lookup(attribute_);
if (ev) {
attribute_ = NumToString(ev->value);
TryTypedValue(kTokenIdentifier,
IsInteger(e.type.base_type),
e,
BASE_TYPE_INT);
return;
}
}
Error("not valid enum value: " + attribute_);
} else {
Error("cannot parse value starting with: " + TokenToString(token_));
}
}
StructDef *Parser::LookupCreateStruct(const std::string &name) {
auto struct_def = structs_.Lookup(name);
if (!struct_def) {
// Rather than failing, we create a "pre declared" StructDef, due to
// circular references, and check for errors at the end of parsing.
struct_def = new StructDef();
structs_.Add(name, struct_def);
struct_def->name = name;
struct_def->predecl = true;
}
return struct_def;
}
void Parser::ParseEnum(bool is_union) {
std::string dc = doc_comment_;
Next();
std::string name = attribute_;
Expect(kTokenIdentifier);
auto &enum_def = *new EnumDef();
enum_def.name = name;
enum_def.doc_comment = dc;
enum_def.is_union = is_union;
if (enums_.Add(name, &enum_def)) Error("enum already exists: " + name);
if (is_union) {
enum_def.underlying_type.base_type = BASE_TYPE_UTYPE;
enum_def.underlying_type.enum_def = &enum_def;
} else if (IsNext(':')) {
// short is the default type for fields when you use enums,
// though people are encouraged to pick any integer type instead.
ParseType(enum_def.underlying_type);
if (!IsInteger(enum_def.underlying_type.base_type))
Error("underlying enum type must be integral");
} else {
enum_def.underlying_type.base_type = BASE_TYPE_SHORT;
}
ParseMetaData(enum_def);
Expect('{');
if (is_union) enum_def.vals.Add("NONE", new EnumVal("NONE", 0));
do {
std::string name = attribute_;
std::string dc = doc_comment_;
Expect(kTokenIdentifier);
auto prevsize = enum_def.vals.vec.size();
auto &ev = *new EnumVal(name, static_cast<int>(
enum_def.vals.vec.size()
? enum_def.vals.vec.back()->value + 1
: 0));
if (enum_def.vals.Add(name, &ev))
Error("enum value already exists: " + name);
ev.doc_comment = dc;
if (is_union) {
ev.struct_def = LookupCreateStruct(name);
}
if (IsNext('=')) {
ev.value = atoi(attribute_.c_str());
Expect(kTokenIntegerConstant);
if (prevsize && enum_def.vals.vec[prevsize - 1]->value >= ev.value)
Error("enum values must be specified in ascending order");
}
} while (IsNext(','));
Expect('}');
}
void Parser::ParseDecl() {
std::string dc = doc_comment_;
bool fixed = IsNext(kTokenStruct);
if (!fixed) Expect(kTokenTable);
std::string name = attribute_;
Expect(kTokenIdentifier);
auto &struct_def = *LookupCreateStruct(name);
if (!struct_def.predecl) Error("datatype already exists: " + name);
struct_def.predecl = false;
struct_def.name = name;
struct_def.doc_comment = dc;
struct_def.fixed = fixed;
// Move this struct to the back of the vector just in case it was predeclared,
// to preserve declartion order.
remove(structs_.vec.begin(), structs_.vec.end(), &struct_def);
structs_.vec.back() = &struct_def;
ParseMetaData(struct_def);
struct_def.sortbysize =
struct_def.attributes.Lookup("original_order") == nullptr && !fixed;
Expect('{');
while (token_ != '}') ParseField(struct_def);
auto force_align = struct_def.attributes.Lookup("force_align");
if (fixed && force_align) {
auto align = static_cast<size_t>(atoi(force_align->constant.c_str()));
if (force_align->type.base_type != BASE_TYPE_INT ||
align < struct_def.minalign ||
align > 256 ||
align & (align - 1))
Error("force_align must be a power of two integer ranging from the"
"struct\'s natural alignment to 256");
struct_def.minalign = align;
}
struct_def.PadLastField(struct_def.minalign);
Expect('}');
}
bool Parser::SetRootType(const char *name) {
root_struct_def = structs_.Lookup(name);
return root_struct_def != nullptr;
}
bool Parser::Parse(const char *source) {
source_ = cursor_ = source;
line_ = 1;
error_.clear();
builder_.Clear();
try {
Next();
while (token_ != kTokenEof) {
if (token_ == kTokenNameSpace) {
Next();
for (;;) {
name_space_.push_back(attribute_);
Expect(kTokenIdentifier);
if (!IsNext('.')) break;
}
Expect(';');
} else if (token_ == '{') {
if (!root_struct_def) Error("no root type set to parse json with");
if (builder_.GetSize()) {
Error("cannot have more than one json object in a file");
}
builder_.Finish(Offset<Table>(ParseTable(*root_struct_def)));
} else if (token_ == kTokenEnum) {
ParseEnum(false);
} else if (token_ == kTokenUnion) {
ParseEnum(true);
} else if (token_ == kTokenRootType) {
Next();
auto root_type = attribute_;
Expect(kTokenIdentifier);
Expect(';');
if (!SetRootType(root_type.c_str()))
Error("unknown root type: " + root_type);
if (root_struct_def->fixed)
Error("root type must be a table");
} else {
ParseDecl();
}
}
for (auto it = structs_.vec.begin(); it != structs_.vec.end(); ++it) {
if ((*it)->predecl)
Error("type referenced but not defined: " + (*it)->name);
}
for (auto it = enums_.vec.begin(); it != enums_.vec.end(); ++it) {
auto &enum_def = **it;
if (enum_def.is_union) {
for (auto it = enum_def.vals.vec.begin();
it != enum_def.vals.vec.end();
++it) {
auto &val = **it;
if (val.struct_def && val.struct_def->fixed)
Error("only tables can be union elements: " + val.name);
}
}
}
} catch (const std::string &msg) {
error_ = "line " + NumToString(line_) + ": " + msg;
return false;
}
assert(!struct_stack_.size());
return true;
}
} // namespace flatbuffers
| 34.197241 | 80 | 0.600895 |
fd0f037b8fb5ccdf8bf6d7801765eefd56de0437 | 664 | cpp | C++ | src/system/Logger.cpp | hugomarquez/cpp-toolkit | 83797f34313b04a4dad931ee1648dcb37b50f64c | [
"MIT"
] | null | null | null | src/system/Logger.cpp | hugomarquez/cpp-toolkit | 83797f34313b04a4dad931ee1648dcb37b50f64c | [
"MIT"
] | null | null | null | src/system/Logger.cpp | hugomarquez/cpp-toolkit | 83797f34313b04a4dad931ee1648dcb37b50f64c | [
"MIT"
] | null | null | null | #include "include/hm/system/Logger.h"
#include <spdlog/spdlog.h>
#include "spdlog/sinks/stdout_color_sinks.h"
namespace hm {
Logger* Logger::instance = 0;
void Logger::setLevel(int level)
{
switch (level) {
case 1: spdlog::set_level(spdlog::level::debug); break;
default: spdlog::set_level(spdlog::level::debug); break;
}
}
void Logger::debug(std::string msg) { spdlog::debug(msg);}
void Logger::info(std::string msg) { spdlog::info(msg);}
void Logger::warn(std::string msg) { spdlog::warn(msg);}
void Logger::error(std::string msg) { spdlog::error(msg);}
void Logger::critical(std::string msg) { spdlog::critical(msg);}
} | 30.181818 | 66 | 0.671687 |
fd10a6c90233d653b2f9a04a3e9e494efb6c659b | 3,274 | cpp | C++ | src/my_opencv/src/image_converter.cpp | t11706m-chukyo/MyTraining | 57a42ddee285b3c2516c14a864699fafbb04e7bb | [
"MIT"
] | null | null | null | src/my_opencv/src/image_converter.cpp | t11706m-chukyo/MyTraining | 57a42ddee285b3c2516c14a864699fafbb04e7bb | [
"MIT"
] | null | null | null | src/my_opencv/src/image_converter.cpp | t11706m-chukyo/MyTraining | 57a42ddee285b3c2516c14a864699fafbb04e7bb | [
"MIT"
] | null | null | null | #include <ros/ros.h>
#include <image_transport/image_transport.h>
#include <cv_bridge/cv_bridge.h>
#include <sensor_msgs/image_encodings.h>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
static const std::string OPENCV_WINDOW = "Image window";
class ImageConverter
{
ros::NodeHandle nh_;
image_transport::ImageTransport it_;
image_transport::Subscriber image_sub_;
image_transport::Publisher image_pub_;
public:
ImageConverter()
: it_(nh_)
{
// Subscrive to input video feed and publish output video feed
// image_sub_ = it_.subscribe("/pioneer3at_ros/camera_ros/image", 1,
image_sub_ = it_.subscribe("/usb_cam/image_raw", 1,
&ImageConverter::imageCb, this);
image_pub_ = it_.advertise("/image_converter/output_video", 1);
cv::namedWindow(OPENCV_WINDOW);
}
~ImageConverter()
{
cv::destroyWindow(OPENCV_WINDOW);
}
void imageCb(const sensor_msgs::ImageConstPtr& msg)
{
cv_bridge::CvImagePtr cv_ptr;
try
{
cv_ptr = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::BGR8);
}
catch (cv_bridge::Exception& e)
{
ROS_ERROR("cv_bridge exception: %s", e.what());
return;
}
// Draw an example circle on the video stream
if (cv_ptr->image.rows > 60 && cv_ptr->image.cols > 60)
cv::circle(cv_ptr->image, cv::Point(50, 50), 10, CV_RGB(255,0,0));
//cv::Mat gray;
//cv_bridge::CvImage gray;
//cv::cvtColor(cv_ptr->image, gray.image, CV_BGR2GRAY);
////////////////////////////////////////////////////////
cv_bridge::CvImage preview, nextview;
cv::cvtColor(cv_ptr->image, nextview.image, CV_BGR2GRAY);
//2color white/black
//cv::threshold(gray.image, gray.image, 127, 255, cv::THRESH_BINARY);
if(&preview.image != 0){
std::vector<cv::KeyPoint> keypoints;
std::vector<cv::Point2f> prepoints;
cv::GoodFeaturesToTrackDetector detector(100, 0.05, 3);
detector.detect(preview.image, keypoints);
for(std::vector<cv::KeyPoint>::iterator itk = keypoints.begin(); itk != keypoints.end(); ++itk){
prepoints.push_back(itk->pt);
}
std::vector<cv::Point2f> newpoints;
std::vector<unsigned char> status;
std::vector<float> errors;
cv::calcOpticalFlowPyrLK(preview.image, nextview.image, prepoints, newpoints, status, errors, cv::Size(21,21), 3, cvTermCriteria(CV_TERMCRIT_ITER | CV_TERMCRIT_EPS, 20, 0.05), 0);
}
cv::cvtColor(nextview.image, preview.image, CV_BGR2GRAY);
//////////////////////////////////////////////////////
// Update GUI Window
//cv::imshow(OPENCV_WINDOW, cv_ptr->image);
cv::imshow(OPENCV_WINDOW, nextview.image);
cv::waitKey(3);
// Output modified video stream
//image_pub_.publish(cv_ptr->toImageMsg());
//When you with publish color
//image_pub_.publish(gray.toImageMsg());
//When you with publish mono
image_pub_.publish(cv_bridge::CvImage(std_msgs::Header(),"mono8",nextview.image).toImageMsg());
}
};
int main(int argc, char** argv)
{
ros::init(argc, argv, "image_converter");
ImageConverter ic;
ros::spin();
return 0;
}
| 28.719298 | 183 | 0.628589 |
fd1153f488fedb3836584591952e31cc4f041863 | 4,444 | cpp | C++ | plugins/community/repos/bsp/src/DownSampler.cpp | guillaume-plantevin/VeeSeeVSTRack | 76fafc8e721613669d6f5ae82a0f58ce923a91e1 | [
"Zlib",
"BSD-3-Clause"
] | 233 | 2018-07-02T16:49:36.000Z | 2022-02-27T21:45:39.000Z | plugins/community/repos/bsp/src/DownSampler.cpp | guillaume-plantevin/VeeSeeVSTRack | 76fafc8e721613669d6f5ae82a0f58ce923a91e1 | [
"Zlib",
"BSD-3-Clause"
] | 24 | 2018-07-09T11:32:15.000Z | 2022-01-07T01:45:43.000Z | plugins/community/repos/bsp/src/DownSampler.cpp | guillaume-plantevin/VeeSeeVSTRack | 76fafc8e721613669d6f5ae82a0f58ce923a91e1 | [
"Zlib",
"BSD-3-Clause"
] | 24 | 2018-07-14T21:55:30.000Z | 2021-05-04T04:20:34.000Z | /*
Copyright (c) 2018 bsp
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 <math.h>
#include "dsp/digital.hpp"
#include "bsp.hpp"
namespace rack_plugin_bsp {
struct DownSampler : Module {
enum ParamIds {
RATE_PARAM,
NUM_PARAMS
};
enum InputIds {
AUDIO_INPUT,
TRIG_INPUT,
RATE_MOD_INPUT,
NUM_INPUTS
};
enum OutputIds {
AUDIO_OUTPUT,
NUM_OUTPUTS
};
static const uint32_t BUFFER_SIZE = (512*1024u); // ~11.8sec @ 44.1kHz
static const uint32_t BUFFER_SIZE_MASK = (BUFFER_SIZE - 1u);
float *buf;
uint32_t buf_write_idx;
int32_t rate_read_left;
uint32_t buf_read_idx;
SchmittTrigger trigger;
float sample_rate;
DownSampler() : Module(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS) {
buf_read_idx = ~0u;
rate_read_left = 0;
buf_write_idx = 0u;
buf = new float[BUFFER_SIZE];
handleSampleRateChanged();
}
~DownSampler() {
delete [] buf;
buf = NULL;
}
void handleSampleRateChanged(void) {
sample_rate = engineGetSampleRate();
}
void onSampleRateChange() override {
Module::onSampleRateChange();
handleSampleRateChanged();
}
void step() override;
};
void DownSampler::step() {
if(trigger.process(inputs[TRIG_INPUT].value))
{
// printf("xxx DownSampler: trig\n");
buf_read_idx = ~0u;
buf_write_idx = 0u;
rate_read_left = 0;
}
// Append new input to ring buffer
float inVal = inputs[AUDIO_INPUT].value;
buf[buf_write_idx] = inVal;
buf_write_idx = (buf_write_idx + 1u) & BUFFER_SIZE_MASK;
if(--rate_read_left < 0)
{
buf_read_idx = (buf_read_idx + 1u) & BUFFER_SIZE_MASK;
float rateF = params[RATE_PARAM].value;
if(inputs[RATE_MOD_INPUT].active)
{
rateF += inputs[RATE_MOD_INPUT].value * (7.0f / 5.0f);
}
rate_read_left = int32_t(rateF);
}
float outVal = buf[buf_read_idx];
outputs[AUDIO_OUTPUT].value = outVal;
#if 0
static int xxx = 0;
if(0 == (++xxx & 32767))
{
printf("xxx readIdx=%u writeIdx=%u readLeft=%d\n", buf_read_idx, buf_write_idx, rate_read_left);
}
#endif
}
struct DownSamplerWidget : ModuleWidget {
DownSamplerWidget(DownSampler *module);
};
DownSamplerWidget::DownSamplerWidget(DownSampler *module) : ModuleWidget(module) {
setPanel(SVG::load(assetPlugin(plugin, "res/DownSampler.svg")));
addChild(Widget::create<ScrewSilver>(Vec(15, 0)));
addChild(Widget::create<ScrewSilver>(Vec(15, 365)));
float cx;
float cy;
#define STY 60.0f
cx = 12.0f;
cy = 66.0f;
addInput(Port::create<PJ301MPort>(Vec(11.0f, cy), Port::INPUT, module, DownSampler::AUDIO_INPUT));
cy += STY;
addInput(Port::create<PJ301MPort>(Vec(11.0f, cy), Port::INPUT, module, DownSampler::TRIG_INPUT));
#undef STY
#define STY 32.0f
cx = 12.0f;
cy = 200.0f;
addParam(ParamWidget::create<RoundSmallBlackKnob>(Vec(cx, cy), module, DownSampler::RATE_PARAM, 0.0f, 7.0f, 1.0f));
cy += STY;
addInput(Port::create<PJ301MPort>(Vec(11.0f, cy), Port::INPUT, module, DownSampler::RATE_MOD_INPUT));
#undef STX
#undef STY
addOutput(Port::create<PJ301MPort>(Vec(11, 325), Port::OUTPUT, module, DownSampler::AUDIO_OUTPUT));
}
} // namespace rack_plugin_bsp
using namespace rack_plugin_bsp;
RACK_PLUGIN_MODEL_INIT(bsp, DownSampler) {
Model *modelDownSampler = Model::create<DownSampler, DownSamplerWidget>("bsp", "DownSampler", "DownSampler", SAMPLER_TAG);
return modelDownSampler;
}
| 26.610778 | 125 | 0.70432 |
fd145a50b7e69bfd7dd569504eddd393c15c56b7 | 130 | hpp | C++ | include/chasm/chasm.hpp | Ostoic/chasm | 9ffab5686cac79158699d704368c67ec29551327 | [
"MIT"
] | null | null | null | include/chasm/chasm.hpp | Ostoic/chasm | 9ffab5686cac79158699d704368c67ec29551327 | [
"MIT"
] | null | null | null | include/chasm/chasm.hpp | Ostoic/chasm | 9ffab5686cac79158699d704368c67ec29551327 | [
"MIT"
] | null | null | null | #pragma once
#include "lex/split.hpp"
#include "parser/parser.hpp"
namespace chasm
{
using lex::split;
using parse::parser;
}
| 11.818182 | 28 | 0.715385 |
fd15c01332fe13368019c7f5b5945fbdc679a301 | 498 | cpp | C++ | sdk/boost_1_30_0/tools/build/test/v1-testing/c.cpp | acidicMercury8/xray-1.0 | 65e85c0e31e82d612c793d980dc4b73fa186c76c | [
"Linux-OpenIB"
] | 2 | 2020-01-30T12:51:49.000Z | 2020-08-31T08:36:49.000Z | sdk/boost_1_30_0/tools/build/test/v1-testing/c.cpp | acidicMercury8/xray-1.0 | 65e85c0e31e82d612c793d980dc4b73fa186c76c | [
"Linux-OpenIB"
] | null | null | null | sdk/boost_1_30_0/tools/build/test/v1-testing/c.cpp | acidicMercury8/xray-1.0 | 65e85c0e31e82d612c793d980dc4b73fa186c76c | [
"Linux-OpenIB"
] | null | null | null | // 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.
#include <iostream>
#ifndef RESULTCODE
# define RESULTCODE 0
#endif
int main()
{
std::cout << "returning result: " << RESULTCODE << std::endl;
return RESULTCODE;
}
| 27.666667 | 70 | 0.704819 |
fd1983cc538893f22cd20591540994a3599c69de | 399 | cpp | C++ | Dummy_device/create_Dummy_device.cpp | dekieras/GLEANApp | 3cae6aa53f90f0c950f3097edcda5193b6b89fe8 | [
"MIT"
] | 3 | 2017-04-06T21:37:22.000Z | 2020-10-05T12:46:50.000Z | Dummy_device/create_Dummy_device.cpp | dekieras/GLEANApp | 3cae6aa53f90f0c950f3097edcda5193b6b89fe8 | [
"MIT"
] | null | null | null | Dummy_device/create_Dummy_device.cpp | dekieras/GLEANApp | 3cae6aa53f90f0c950f3097edcda5193b6b89fe8 | [
"MIT"
] | null | null | null | #include "GLEANKernel/Output_tee_globals.h"
#include "Dummy_device.h"
// for use in non-dynamically loaded models
Device_base * create_Dummy_device()
{
return new Dummy_device(Normal_out);
}
// the class factory functions to be accessed with dlsym
extern "C" Device_base * create_device()
{
return create_Dummy_device();
}
extern "C" void destroy_device(Device_base * p)
{
delete p;
}
| 19.95 | 56 | 0.744361 |
fd1a68499337a52e0a2e7a47af158b2f45aa6ffe | 604 | hpp | C++ | library/ATF/CPtrList.hpp | lemkova/Yorozuya | f445d800078d9aba5de28f122cedfa03f26a38e4 | [
"MIT"
] | 29 | 2017-07-01T23:08:31.000Z | 2022-02-19T10:22:45.000Z | library/ATF/CPtrList.hpp | kotopes/Yorozuya | 605c97d3a627a8f6545cc09f2a1b0a8afdedd33a | [
"MIT"
] | 90 | 2017-10-18T21:24:51.000Z | 2019-06-06T02:30:33.000Z | library/ATF/CPtrList.hpp | kotopes/Yorozuya | 605c97d3a627a8f6545cc09f2a1b0a8afdedd33a | [
"MIT"
] | 44 | 2017-12-19T08:02:59.000Z | 2022-02-24T23:15:01.000Z | // This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually
#pragma once
#include <common/common.h>
#include <CObject.hpp>
#include <CPlex.hpp>
START_ATF_NAMESPACE
struct CPtrList : CObject
{
struct CNode
{
struct CNode *pNext;
struct CNode *pPrev;
void *data;
};
struct CNode *m_pNodeHead;
struct CNode *m_pNodeTail;
__int64 m_nCount;
struct CNode *m_pNodeFree;
struct CPlex *m_pBlocks;
__int64 m_nBlockSize;
};
END_ATF_NAMESPACE
| 23.230769 | 108 | 0.620861 |
fd1ea221aea7ee6bfe58b94a66dbb17d3877794c | 5,201 | cpp | C++ | FDRV/src/DFXML_creator.cpp | AlexXandreE/Autopsy-Plugin-2017 | a3027e7c431b23b3e9a5144a6e2cc89d0da331ce | [
"BSL-1.0"
] | 2 | 2018-05-01T14:09:21.000Z | 2018-06-27T11:49:41.000Z | FDRV/src/DFXML_creator.cpp | AlexXandreE/Autopsy-Plugin-2017 | a3027e7c431b23b3e9a5144a6e2cc89d0da331ce | [
"BSL-1.0"
] | 1 | 2020-04-18T00:11:54.000Z | 2020-04-18T00:11:54.000Z | FDRV/src/DFXML_creator.cpp | AlexXandreE/Autopsy-Plugin-2017-FaceDetection | a3027e7c431b23b3e9a5144a6e2cc89d0da331ce | [
"BSL-1.0"
] | null | null | null |
#include <chrono>
#include <ctime>
#include <Lmcons.h>
#include <boost/filesystem.hpp>
#include <boost/version.hpp>
#include <boost/format.hpp>
#include <dlib/image_processing.h>
#include <dlib/gui_widgets.h>
#include <dlib/string.h>
#include <dlib/image_io.h>
#include <openssl/sha.h>
#include <FDRV/DFXML_creator.hpp>
using namespace std;
using namespace boost;
using namespace dlib;
using std::ofstream;
// PRIVATE FUNCTION
int DFXMLCreator::openssl_sha1(char *name, unsigned char *out)
{
FILE *f;
unsigned char buf[8192];
SHA_CTX sc;
int err;
f = fopen(name, "rb");
if (f == NULL)
{
cout << "Couldn't open file" << endl;
return -1;
}
SHA1_Init(&sc);
for (;;)
{
size_t len;
len = fread(buf, 1, sizeof buf, f);
if (len == 0)
break;
SHA1_Update(&sc, buf, len);
}
err = ferror(f);
fclose(f);
if (err)
{
cout << "Error hashing file" << endl;
return -1;
}
SHA1_Final(out, &sc);
return 0;
}
// CONSTRUCTOR
// NONE
pugi::xml_document DFXMLCreator::create_document()
{
pugi::xml_document doc;
doc.load_string("<?xml version='1.0' encoding='UTF-8'?>\n");
pugi::xml_node dfxml_node = doc.append_child("dfxml");
dfxml_node.append_attribute("xmlns") = "http://www.forensicswiki.org/wiki/Category:Digital_Forensics_XML";
dfxml_node.append_attribute("xmlns:dc") = "http://purl.org/dc/elements/1.1/";
dfxml_node.append_attribute("xmlns:xsi") = "http://www.w3.org/2001/XMLSchema-instance";
dfxml_node.append_attribute("version") = "1.1.1";
return doc;
}
void DFXMLCreator::add_DFXML_creator(pugi::xml_node &parent,
const char *program_name,
const char *program_version)
{
pugi::xml_node creator_node = parent.append_child("creator");
creator_node.append_attribute("version") = "1.0";
creator_node.append_child("program").text().set(program_name);
creator_node.append_child("version").text().set(program_version);
pugi::xml_node build_node = creator_node.append_child("build_environment");
#ifdef BOOST_VERSION
{
char buf[64];
snprintf(buf, sizeof(buf), "%d", BOOST_VERSION);
pugi::xml_node lib_node = build_node.append_child("library");
lib_node.append_attribute("name") = "boost";
lib_node.append_attribute("version") = buf;
}
#endif
pugi::xml_node lib_node = build_node.append_child("library");
lib_node.append_attribute("name") = "pugixml";
lib_node.append_attribute("version") = "1.9";
lib_node = build_node.append_child("library");
lib_node.append_attribute("name") = "dlib";
lib_node.append_attribute("version") = "19.10";
pugi::xml_node exe_node = creator_node.append_child("execution_environment");
chrono::system_clock::time_point p = chrono::system_clock::now();
time_t t = chrono::system_clock::to_time_t(p);
exe_node.append_child("start_date").text().set(ctime(&t));
char username[UNLEN + 1];
DWORD username_len = UNLEN + 1;
GetUserName(username, &username_len);
exe_node.append_child("username").text().set(username);
}
void DFXMLCreator::add_fileobject(pugi::xml_node &parent,
const char *file_path,
const int number_faces,
const long original_width,
const long original_height,
const long working_width,
const long working_height,
const std::vector<dlib::mmod_rect, std::allocator<dlib::mmod_rect>> detected_faces)
{
// TODO: Check why is this giving error
filesystem::path p(file_path);
uintmax_t f_size = filesystem::file_size(p);
pugi::xml_node file_obj = parent.append_child("fileobject");
file_obj.append_child("filesize").text().set(f_size);
string delimiter = "__id__";
string aux_name(p.filename().string());
string img_n = aux_name.substr(0, aux_name.find(delimiter));
file_obj.append_child("filename").text().set(img_n.c_str());
// incluir as hashs
unsigned char hash_buff[SHA_DIGEST_LENGTH];
if (openssl_sha1((char *)file_path, hash_buff))
{
cout << "Error getting file hash" << endl;//dlog << LWARN << "Error getting file hash";
}
else
{
pugi::xml_node hash_nodeMD5 = file_obj.append_child("hashdigest");
hash_nodeMD5.append_attribute("type") = "sha1";
char tmphash[SHA_DIGEST_LENGTH];
for (size_t i = 0; i < SHA_DIGEST_LENGTH; i++)
{
sprintf((char *)&(tmphash[i * 2]), "%02x", hash_buff[i]);
}
hash_nodeMD5.text().set(tmphash);
}
pugi::xml_node detection_node = file_obj.append_child("facialdetection");
detection_node.append_child("number_faces").text().set(number_faces);
std::stringstream ss;
ss << original_width << "x" << original_height;
detection_node.append_child("original_size").text().set(ss.str().c_str());
ss.clear();
ss.str("");
ss << working_width << "x" << working_height;
detection_node.append_child("working_size").text().set(ss.str().c_str());
for (int i = 1; i <= detected_faces.size(); i++)
{
std::stringstream ss;
rectangle rec = detected_faces[i - 1];
ss << rec.left() << " "
<< rec.top() << " "
<< rec.right() << " "
<< rec.bottom();
pugi::xml_node face_node = detection_node.append_child("face");
face_node.text().set(ss.str().c_str());
pugi::xml_node score = face_node.append_child("confidence_score");
// TODO:: Converter / arredondar
score.text().set(detected_faces[i].detection_confidence);
}
}
| 27.812834 | 107 | 0.698135 |
fd2410d646360c792463ce53d98290865390a08b | 9,868 | cc | C++ | src/delay_escape.cc | DouglasRMiles/QuProlog | 798d86f87fb4372b8918ef582ef2f0fc0181af2d | [
"Apache-2.0"
] | 5 | 2019-11-20T02:05:31.000Z | 2022-01-06T18:59:16.000Z | src/delay_escape.cc | logicmoo/QuProlog | 798d86f87fb4372b8918ef582ef2f0fc0181af2d | [
"Apache-2.0"
] | null | null | null | src/delay_escape.cc | logicmoo/QuProlog | 798d86f87fb4372b8918ef582ef2f0fc0181af2d | [
"Apache-2.0"
] | 2 | 2022-01-08T13:52:24.000Z | 2022-03-07T17:41:37.000Z | // delay_escape.cc - General delay mechanism.
//
// ##Copyright##
//
// Copyright 2000-2016 Peter Robinson (pjr@itee.uq.edu.au)
//
// 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.00
//
// 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.
//
// ##Copyright##
//
// $Id: delay_escape.cc,v 1.7 2006/01/31 23:17:49 qp Exp $
//#include "atom_table.h"
#include "global.h"
#include "thread_qp.h"
//
// psi_delay(variable, term)
// Delay the call to term and associate the problem with variable.
// mode(in,in)
//
Thread::ReturnValue
Thread::psi_delay(Object *& object1, Object *& object2)
{
assert(object1->variableDereference()->hasLegalSub());
assert(object2->variableDereference()->hasLegalSub());
Object* val1 = heap.dereference(object1);
Object* val2 = heap.dereference(object2);
assert(val1->isAnyVariable());
//
// Delay the problem.
//
delayProblem(val2, val1);
//
// Complete operation.
//
return(RV_SUCCESS);
}
//
// psi_delayed_problems_for_var(variable, term)
// Return the list of delayed problems associated with the given variable.
// mode(in,out)
//
Thread::ReturnValue
Thread::psi_delayed_problems_for_var(Object *& object1, Object *& object2)
{
Object* o = object1;
Object* delays = AtomTable::nil;
assert(o != NULL);
while (o->isAnyVariable())
{
delays = OBJECT_CAST(Reference*, o)->getDelays();
Object* n = OBJECT_CAST(Reference*, o)->getReference();
if ((n == o) || !delays->isNil())
{
object2 = delays;
return(RV_SUCCESS);
}
o = n;
}
object2 = delays;
return(RV_SUCCESS);
}
//
// psi_get_bound_structure(variable, variable)
// Return the dereferenced variable as the argument of a "bound" structure.
// mode(in,out)
//
Thread::ReturnValue
Thread::psi_get_bound_structure(Object *& object1, Object *& object2)
{
assert(object1->variableDereference()->hasLegalSub());
Object* val1 = heap.dereference(object1);
assert(val1->isAnyVariable());
if (val1->isVariable())
{
val1 = addExtraInfo(OBJECT_CAST(Variable*, val1));
}
Structure* newstruct = heap.newStructure(1);
newstruct->setFunctor(atoms->add("bound"));
newstruct->setArgument(1,val1);
Structure* boundstruct = heap.newStructure(1);
boundstruct->setFunctor(atoms->add("$bound"));
boundstruct->setArgument(1,newstruct);
object2 = boundstruct;
return(RV_SUCCESS);
}
//
// psi_psidelay_resume
// Restore the thread state after a retry delay from a pseudo instruction
// mode()
//
Thread::ReturnValue
Thread::psi_psidelay_resume(void)
{
assert(false);
status.resetNeckCutRetry();
RestoreXRegisters();
programCounter = savedPC;
return(RV_SUCCESS);
}
//
// psi_get_delays(delays,type,avoid)
// Return the list of delayed problems of given type
// type is 'all' or 'unify' other than those in avoid.
// mode(out,in,in)
//
Thread::ReturnValue
Thread::psi_get_delays(Object *& delaylist, Object*& type, Object*& avoid)
{
bool unify_only = (type->variableDereference() == atoms->add("unify"));
Object *delays = AtomTable::nil;
Object *avoid_list = avoid->variableDereference();
for (Object *global_delays =
ipTable.getImplicitPara(AtomTable::delays)->variableDereference();
global_delays->isCons();
global_delays = OBJECT_CAST(Cons *, global_delays)->getTail()->variableDereference())
{
assert(OBJECT_CAST(Cons *, global_delays)->getHead()->variableDereference()->isStructure());
Structure *delay
= OBJECT_CAST(Structure*, OBJECT_CAST(Cons *, global_delays)->getHead()->variableDereference());
assert(delay->getArity() == 2);
Object* status = delay->getArgument(1)->variableDereference();
if (!status->isVariable() || !OBJECT_CAST(Variable*,status)->isFrozen())
{
continue;
}
Object* var = delay->getArgument(2);
Object* vdelays;
(void)psi_delayed_problems_for_var(var, vdelays);
for (; vdelays->isCons();
vdelays = OBJECT_CAST(Cons*,
vdelays)->getTail()->variableDereference())
{
Object* vd =
OBJECT_CAST(Cons*, vdelays)->getHead()->variableDereference();
assert(vd->isStructure());
Structure* vdstruct = OBJECT_CAST(Structure *, vd);
assert(vdstruct->getArity() == 2);
Object* vdstatus = vdstruct->getArgument(1)->variableDereference();
assert(vdstatus->isVariable());
if (!OBJECT_CAST(Variable*,vdstatus)->isFrozen())
{
continue;
}
Object* problem = vdstruct->getArgument(2)->variableDereference();
if (avoid_list->inList(problem))
{
continue;
}
if (unify_only)
{
if (!problem->isStructure())
{
continue;
}
Structure* pstruct = OBJECT_CAST(Structure*, problem);
if (pstruct->getArity() == 2 &&
pstruct->getFunctor() == AtomTable::equal)
{
delays = heap.newCons(problem, delays);
}
}
else
{
if (!problem->isStructure())
{
delays = heap.newCons(problem, delays);
}
else
{
Structure* pstruct = OBJECT_CAST(Structure*, problem);
if (pstruct->getArity() == 2 &&
pstruct->getFunctor() == atoms->add("delay_until") &&
pstruct->getArgument(1)->variableDereference()->isStructure())
{
Structure* arg1struct = OBJECT_CAST(Structure*, pstruct->getArgument(1)->variableDereference());
if (arg1struct->getArity() == 1 &&
arg1struct->getFunctor() == atoms->add("$bound"))
{
Structure* newpstruct = heap.newStructure(2);
newpstruct->setFunctor(pstruct->getFunctor());
newpstruct->setArgument(1,arg1struct->getArgument(1));
newpstruct->setArgument(2,pstruct->getArgument(2));
delays = heap.newCons(newpstruct, delays);
continue;
}
}
delays = heap.newCons(problem, delays);
}
}
}
}
delaylist = delays;
return RV_SUCCESS;
}
//
// psi_bound(term)
// test if term is bound to something
// mode(in)
//
Thread::ReturnValue
Thread::psi_bound(Object *& object1)
{
Object* deref = object1->variableDereference();
return BOOL_TO_RV(deref != object1);
}
//
// Remove any solved problems associated with any variables.
//
Thread::ReturnValue
Thread::psi_compress_var_delays()
{
for (Object *global_delays =
ipTable.getImplicitPara(AtomTable::delays)->variableDereference();
global_delays->isCons();
global_delays = OBJECT_CAST(Cons *, global_delays)->getTail()->variableDereference())
{
assert(OBJECT_CAST(Cons *, global_delays)->getHead()->variableDereference()->isStructure());
Structure *delay = OBJECT_CAST(Structure*, OBJECT_CAST(Cons *, global_delays)->getHead()->variableDereference());
assert(delay->getArity() == 2);
Object* status = delay->getArgument(1)->variableDereference();
if (!status->isVariable() || !OBJECT_CAST(Variable*,status)->isFrozen())
{
continue;
}
// Get the variable with delays
Reference* var = OBJECT_CAST(Reference*, delay->getArgument(2)->variableDereference());
bool solved_found = false;
Object* var_delays = var->getDelays();
if (!var_delays->isNil())
{
// Compress delay list
// Find the first delay to keep
for ( ; var_delays->isCons();
var_delays = OBJECT_CAST(Cons *, var_delays)->getTail())
{
Structure *delay =
OBJECT_CAST(Structure *,
OBJECT_CAST(Cons *, var_delays)->getHead());
Variable *delay_status = OBJECT_CAST(Variable*,
delay->getArgument(1));
if (delay_status->isThawed())
{
// Solved problem
solved_found = true;
}
else
{
break;
}
}
if (solved_found)
{
updateAndTrailObject(reinterpret_cast<heapobject*>(var),
var_delays,
Reference::DelaysOffset);
}
// Scan the rest of the delay list
if (var_delays->isNil())
{
if (solved_found)
{
updateAndTrailObject(reinterpret_cast<heapobject*>(var),
var_delays,
Reference::DelaysOffset);
}
// Nothing to do
continue;
}
solved_found = false;
Object* look_ahead = OBJECT_CAST(Cons *, var_delays)->getTail();
for ( ; look_ahead->isCons();
look_ahead = OBJECT_CAST(Cons *, look_ahead)->getTail())
{
Structure *delay =
OBJECT_CAST(Structure *,
OBJECT_CAST(Cons *, look_ahead)->getHead());
Variable *delay_status = OBJECT_CAST(Variable*,
delay->getArgument(1));
if (delay_status->isThawed())
{
solved_found = true;
}
else
{
if (solved_found)
{
solved_found = false;
// point var_delays at next unsolved problem
updateAndTrailObject(reinterpret_cast<heapobject*>(var_delays), look_ahead, Cons::TailOffset);
}
var_delays = look_ahead;
}
}
if (solved_found)
{
solved_found = false;
// point var_delays at next unsolved problem
updateAndTrailObject(reinterpret_cast<heapobject*>(var_delays), look_ahead, Cons::TailOffset);
}
}
}
return RV_SUCCESS;
}
//
// Retry the delayed nfi problems.
//
Thread::ReturnValue
Thread::psi_retry_ov_delays(void)
{
return BOOL_TO_RV(retry_delays(NFI));
}
//
// Retry the delayed nfi and = problems.
//
Thread::ReturnValue
Thread::psi_retry_ov_eq_delays(void)
{
bool result = retry_delays(BOTH);
if (result)
{
(void)psi_compress_var_delays();
return RV_SUCCESS;
}
else
{
return RV_FAIL;
}
}
| 26.67027 | 119 | 0.654439 |
fd24130091c95702bdddbf67f6066a6b29613804 | 5,098 | cc | C++ | src/lib/tools/main-rewrite-ids.cc | oslab-swrc/cytom | c4952843cc11cac64b421b7d47706d534b566208 | [
"MIT"
] | null | null | null | src/lib/tools/main-rewrite-ids.cc | oslab-swrc/cytom | c4952843cc11cac64b421b7d47706d534b566208 | [
"MIT"
] | null | null | null | src/lib/tools/main-rewrite-ids.cc | oslab-swrc/cytom | c4952843cc11cac64b421b7d47706d534b566208 | [
"MIT"
] | null | null | null | #include <cmath>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <time.h>
#include <sys/mman.h>
#include <pthread.h>
#include <getopt.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unordered_map>
#include "util/datatypes.h"
#include "util/util.h"
#include "util/config.h"
#include "core/meta-tile-store.h"
#include "core/vertex-store.h"
#include "edge-inserter/edge-inserter.h"
#include "edge-inserter/rmat-edge-provider.h"
#include "core/tile-store.h"
#include "perf-event/perf-event-manager.h"
#include "traversal/traversal.h"
#include "traversal/hilbert.h"
#include "traversal/row_first.h"
#include "traversal/column_first.h"
#include "edge-inserter/binary-edge-provider.h"
#include "core/continuous-algorithm-executor.h"
#include <flatbuffers/flatbuffers.h>
using namespace evolving_graphs;
struct rewrite_options_t {
std::string input_graph;
std::string output_graph;
};
static int parseOption(int argc, char* argv[], rewrite_options_t* rewrite_options) {
static struct option options[] = {
{"input-graph", required_argument, nullptr, 'a'},
{"output-graph", required_argument, nullptr, 'b'},
{nullptr, 0, nullptr, 0},
};
int arg_cnt;
for (arg_cnt = 0; true; ++arg_cnt) {
int c, idx = 0;
c = getopt_long(argc, argv, "a:b:", options, &idx);
if (c == -1) {
break;
}
switch (c) {
case 'a':
rewrite_options->input_graph = std::string(optarg);
break;
case 'b':
rewrite_options->output_graph = std::string(optarg);
break;
default:
return -EINVAL;
}
}
return arg_cnt;
}
file_edge_t* createVertexMapping(const rewrite_options_t& options) {
std::unordered_map<uint64_t, uint64_t> old_to_new_vertex_ids;
uint64_t current_id = 0;
int fd = open(options.input_graph.c_str(), O_RDONLY);
struct stat file_stats{};
fstat(fd, &file_stats);
auto file_size = static_cast<size_t>(file_stats.st_size);
auto file_edges = (file_edge_t*) mmap(nullptr, file_size, PROT_READ, MAP_PRIVATE, fd, 0);
if (file_edges == MAP_FAILED) {
sg_err("Could not open file %s: %d\n", options.input_graph.c_str(), errno);
util::die(1);
}
uint64_t count_edges = file_size / sizeof(file_edge_t);
auto* new_edges = new file_edge_t[count_edges];
for (uint64_t i = 0; i < count_edges; ++i) {
file_edge_t edge = file_edges[i];
file_edge_t new_edge{};
auto find_src = old_to_new_vertex_ids.find(edge.src);
auto find_tgt = old_to_new_vertex_ids.find(edge.tgt);
if (find_src != old_to_new_vertex_ids.end()) {
new_edge.src = find_src->second;
} else {
old_to_new_vertex_ids[edge.src] = current_id;
new_edge.src = current_id;
++current_id;
}
if (find_tgt != old_to_new_vertex_ids.end()) {
new_edge.tgt = find_tgt->second;
} else {
old_to_new_vertex_ids[edge.tgt] = current_id;
new_edge.tgt = current_id;
++current_id;
}
new_edges[i] = new_edge;
}
close(fd);
sg_log("Unique vertices: %lu\n", old_to_new_vertex_ids.size());
sg_log("Count edges: %lu\n", count_edges);
return new_edges;
}
void writeNewEdges(const rewrite_options_t& options, file_edge_t* new_edges) {
int fd = open(options.input_graph.c_str(), O_RDONLY);
int fd_new = open(options.output_graph.c_str(), O_RDWR | O_CREAT, (mode_t) 0777);
struct stat file_stats{};
fstat(fd, &file_stats);
auto file_size = static_cast<size_t>(file_stats.st_size);
uint64_t count_edges = file_size / sizeof(file_edge_t);
size_t size_to_write = count_edges * sizeof(file_edge_t);
size_t individual_size_to_write = PAGE_SIZE * sizeof(file_edge_t);
file_edge_t* edges_pointer = new_edges;
while (size_to_write > 0) {
size_t current_write = std::min(individual_size_to_write, size_to_write);
size_to_write -= current_write;
int ret = write(fd_new, edges_pointer, current_write);
if (ret != current_write) {
sg_err("Could not write to %s: %d, %s\n",
options.output_graph.c_str(),
errno,
strerror(errno));
util::die(1);
}
edges_pointer = &edges_pointer[PAGE_SIZE];
}
close(fd);
close(fd_new);
}
int main(int argc, char** argv) {
// Parse command line options.
rewrite_options_t options;
int count_expected_arguments = 2;
int count_parsed_arguments = parseOption(argc, argv, &options);
if (count_parsed_arguments != count_expected_arguments) {
sg_err("Wrong number of arguments, %d, expected count: %d \n",
count_parsed_arguments,
count_expected_arguments);
return 1;
}
double time_before = util::get_time_usec();
file_edge_t* new_edges = createVertexMapping(options);
sg_log("Read input in %f seconds.\n", (util::get_time_usec() - time_before) / 1000000.0);
time_before = util::get_time_usec();
writeNewEdges(options, new_edges);
sg_log("Written output in %f seconds.\n", (util::get_time_usec() - time_before) / 1000000.0);
return 0;
}
| 28.480447 | 95 | 0.680071 |
fd2800700bc7399c059178e0cf7a11648c28c198 | 6,819 | hpp | C++ | mainframe/simd.hpp | tedmiddleton/mainframe | 0d0537e8936d60c30573f08506f92bd6e8455fcf | [
"BSL-1.0"
] | null | null | null | mainframe/simd.hpp | tedmiddleton/mainframe | 0d0537e8936d60c30573f08506f92bd6e8455fcf | [
"BSL-1.0"
] | null | null | null | mainframe/simd.hpp | tedmiddleton/mainframe | 0d0537e8936d60c30573f08506f92bd6e8455fcf | [
"BSL-1.0"
] | null | null | null |
// Copyright Ted Middleton 2022.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// https://www.boost.org/LICENSE_1_0.txt)
#ifndef INCLUDED_mainframe_simd_h
#define INCLUDED_mainframe_simd_h
#include <iostream>
#if __AVX__
#include <immintrin.h>
#endif
#include "mainframe/base.hpp"
namespace mf { namespace detail
{
template< typename T >
T
mean( const T* t, size_t num )
{
const T* e = t + num;
T m = static_cast<T>(0);
for ( const T* c = t ; c != e; c++ ) {
m += *c;
}
return static_cast<T>(m / num);
}
#ifdef __AVX__
float
mean( const float* t, size_t num )
{
size_t i = 0;
__m256 accum = _mm256_setzero_ps();
for ( ; i+8 < num; i += 8 ) {
__m256 vals = _mm256_loadu_ps( t + i );
accum = _mm256_add_ps( accum, vals );
}
float ms[8];
_mm256_storeu_ps( ms, accum );
float m = ms[0] + ms[1] + ms[2] + ms[3] + ms[4] + ms[5] + ms[6] + ms[7];
for ( ; i < num; i += 1 ) {
m += t[ i ];
}
return m / num;
}
double
mean( const double* t, size_t num )
{
size_t i = 0;
__m256d accum = _mm256_setzero_pd();
for ( ; i+4 < num; i += 4 ) {
__m256d vals = _mm256_loadu_pd( t + i );
accum = _mm256_add_pd( accum, vals );
}
double ms[4];
_mm256_storeu_pd( ms, accum );
double m = ms[0] + ms[1] + ms[2] + ms[3];
for ( ; i < num; i += 1 ) {
m += t[ i ];
}
return m / num;
}
#endif
template< typename A, typename B >
auto
correlate_pearson( const A* a, const B* b, size_t num ) -> decltype( a[0] * b[0] )
{
using T = decltype(a[0] * b[0]);
A amean = mean( a, num );
B bmean = mean( b, num );
const A* aend = a + num;
const A* acurr = a;
const B* bcurr = b;
A aaccum = static_cast<A>( 0 );
B baccum = static_cast<B>( 0 );
double cov = 0.0;
for ( ; acurr != aend; ++acurr, ++bcurr ) {
A xa = *acurr;
B xb = *bcurr;
A adiff = xa - amean;
B bdiff = xb - bmean;
A adiffsq = adiff * adiff;
B bdiffsq = bdiff * bdiff;
T abdiff = adiff * bdiff;
aaccum += adiffsq;
baccum += bdiffsq;
cov += abdiff;
}
T corr = static_cast<T>(cov / std::sqrt( aaccum * baccum ));
return corr;
}
#ifdef __AVX__
double
correlate_pearson( const double* a, const double* b, size_t num )
{
double samean = mean( a, num );
double sbmean = mean( b, num );
__m256d amean = _mm256_set1_pd( samean );
__m256d bmean = _mm256_set1_pd( sbmean );
__m256d aaccum = _mm256_setzero_pd();
__m256d baccum = _mm256_setzero_pd();
__m256d cov = _mm256_setzero_pd();
size_t k = 0;
for ( ; k + 4 < num; k += 4 ) {
__m256d xa, xb, adiff, bdiff, adiffsq, bdiffsq, abdiff;
xa = _mm256_loadu_pd( a + k );
xb = _mm256_loadu_pd( b + k );
adiff = _mm256_sub_pd( xa, amean );
bdiff = _mm256_sub_pd( xb, bmean );
adiffsq = _mm256_mul_pd( adiff, adiff );
bdiffsq = _mm256_mul_pd( bdiff, bdiff );
abdiff = _mm256_mul_pd( adiff, bdiff );
aaccum = _mm256_add_pd( aaccum, adiffsq );
baccum = _mm256_add_pd( baccum, bdiffsq );
cov = _mm256_add_pd( cov, abdiff );
}
double mcov[4];
_mm256_storeu_pd( mcov, cov );
double fcov = mcov[0] + mcov[1] + mcov[2] + mcov[3];
double maaccum[4];
_mm256_storeu_pd( maaccum, aaccum );
double faaccum = maaccum[0] + maaccum[1] + maaccum[2] + maaccum[3];
double mbaccum[4];
_mm256_storeu_pd( mbaccum, baccum );
double fbaccum = mbaccum[0] + mbaccum[1] + mbaccum[2] + mbaccum[3];
for ( ; k < num; k+=1 ) {
double xa = a[k];
double xb = b[k];
double adiff = xa - samean;
double bdiff = xb - sbmean;
double adiffsq = adiff * adiff;
double bdiffsq = bdiff * bdiff;
double abdiff = adiff * bdiff;
faaccum += adiffsq;
fbaccum += bdiffsq;
fcov += abdiff;
}
double corr = fcov / std::sqrt( faaccum * fbaccum );
return corr;
}
float
correlate_pearson( const float* a, const float* b, size_t num )
{
float samean = mean( a, num );
float sbmean = mean( b, num );
__m256 amean = _mm256_set1_ps( samean );
__m256 bmean = _mm256_set1_ps( sbmean );
__m256 aaccum = _mm256_setzero_ps();
__m256 baccum = _mm256_setzero_ps();
__m256 cov = _mm256_setzero_ps();
size_t k = 0;
for ( ; k + 8 < num; k += 8 ) {
__m256 xa, xb, adiff, bdiff, adiffsq, bdiffsq, abdiff;
xa = _mm256_loadu_ps( a + k );
xb = _mm256_loadu_ps( b + k );
adiff = _mm256_sub_ps( xa, amean );
bdiff = _mm256_sub_ps( xb, bmean );
adiffsq = _mm256_mul_ps( adiff, adiff );
bdiffsq = _mm256_mul_ps( bdiff, bdiff );
abdiff = _mm256_mul_ps( adiff, bdiff );
aaccum = _mm256_add_ps( aaccum, adiffsq );
baccum = _mm256_add_ps( baccum, bdiffsq );
cov = _mm256_add_ps( cov, abdiff );
}
float mcov[8];
_mm256_storeu_ps( mcov, cov );
float fcov = mcov[0] + mcov[1] + mcov[2] + mcov[3]
+ mcov[4] + mcov[5] + mcov[6] + mcov[7];
float maaccum[8];
_mm256_storeu_ps( maaccum, aaccum );
float faaccum = maaccum[0] + maaccum[1] + maaccum[2] + maaccum[3]
+ maaccum[4] + maaccum[5] + maaccum[6] + maaccum[7];
float mbaccum[8];
_mm256_storeu_ps( mbaccum, baccum );
float fbaccum = mbaccum[0] + mbaccum[1] + mbaccum[2] + mbaccum[3]
+ mbaccum[4] + mbaccum[5] + mbaccum[6] + mbaccum[7];
for ( ; k < num; k+=1 ) {
float xa = a[k];
float xb = b[k];
float adiff = xa - samean;
float bdiff = xb - sbmean;
float adiffsq = adiff * adiff;
float bdiffsq = bdiff * bdiff;
float abdiff = adiff * bdiff;
faaccum += adiffsq;
fbaccum += bdiffsq;
fcov += abdiff;
}
float corr = fcov / std::sqrt( faaccum * fbaccum );
return corr;
}
#endif
}} // namespace mf::detail
#endif // INCLUDED_mainframe_simd_h
| 32.317536 | 86 | 0.504326 |
fd2a77db46def7cf2708c55c3f3ec58c70354ea2 | 8,404 | cpp | C++ | src/Spells/SpellCreator.cpp | tizian/Cendric2 | 5b0438c73a751bcc0d63c3af839af04ab0fb21a3 | [
"MIT"
] | 279 | 2015-05-06T19:04:07.000Z | 2022-03-21T21:33:38.000Z | src/Spells/SpellCreator.cpp | tizian/Cendric2 | 5b0438c73a751bcc0d63c3af839af04ab0fb21a3 | [
"MIT"
] | 222 | 2016-10-26T15:56:25.000Z | 2021-10-03T15:30:18.000Z | src/Spells/SpellCreator.cpp | tizian/Cendric2 | 5b0438c73a751bcc0d63c3af839af04ab0fb21a3 | [
"MIT"
] | 49 | 2015-10-01T21:23:03.000Z | 2022-03-19T20:11:31.000Z | #include "Spells/SpellCreator.h"
#include "Screens/LevelScreen.h"
SpellCreator::SpellCreator(const SpellData& spellData, LevelMovableGameObject* owner) {
m_owner = owner;
if (m_owner != nullptr) m_level = owner->getLevel();
if (m_owner != nullptr) m_attributeData = owner->getAttributes();
if (m_owner != nullptr && !(m_screen = dynamic_cast<LevelScreen*>(owner->getScreen()))) {
g_logger->logError("SpellCreator", "spell owner has no (level)screen.");
}
m_spellData = spellData;
m_allowedModifiers = SpellData::getAllowedModifiers(spellData.id);
g_resourceManager->loadTexture(m_spellData.spritesheetPath, ResourceType::Level);
for (auto const& sound : m_spellData.creatorSoundPaths) {
g_resourceManager->loadSoundbuffer(sound, ResourceType::Level);
}
for (auto const& sound : m_spellData.spellSoundPaths) {
g_resourceManager->loadSoundbuffer(sound, ResourceType::Level);
}
}
SpellCreator::~SpellCreator() {
}
void SpellCreator::update(const sf::Time& frametime) {
if (m_currentCastingTime == sf::Time::Zero) return;
m_currentCastingTime -= frametime;
if (m_currentCastingTime <= sf::Time::Zero) {
m_currentCastingTime = sf::Time::Zero;
if (!m_owner->isDead()) {
for (auto& target : m_futureTargets) {
m_owner->setFacingRight(target.x - m_owner->getCenter().x > 0);
execExecuteSpell(target);
}
if (m_target != nullptr) {
m_owner->setFacingRight(m_target->getCenter().x - m_owner->getCenter().x > 0);
execExecuteSpell(m_target->getCenter());
}
m_owner->executeFightAnimation(m_spellData.fightingTime, m_spellData.fightAnimation, m_spellData.isBlocking);
m_isReady = true;
m_futureTargets.clear();
m_target = nullptr;
if (!m_spellData.creatorSoundPaths.empty()) {
g_resourceManager->playSound(m_spellData.creatorSoundPaths.at(rand() % m_spellData.creatorSoundPaths.size()));
}
}
}
}
void SpellCreator::executeSpell(const sf::Vector2f& target) {
m_isReady = false;
if (!m_spellData.attachedToMob && norm(target) > 0.f) {
m_owner->setFacingRight(target.x - m_owner->getCenter().x > 0);
}
if (m_spellData.castingTime > sf::Time::Zero) {
m_currentCastingTime = m_spellData.castingTime;
m_futureTargets.push_back(target);
m_owner->executeFightAnimation(m_spellData.castingTime + sf::milliseconds(100), m_spellData.castingAnimation, m_spellData.isBlocking);
return;
}
if (!m_spellData.creatorSoundPaths.empty()) {
g_resourceManager->playSound(m_spellData.creatorSoundPaths.at(rand() % m_spellData.creatorSoundPaths.size()));
}
execExecuteSpell(target);
m_owner->executeFightAnimation(m_spellData.fightingTime, m_spellData.fightAnimation, m_spellData.isBlocking);
m_isReady = true;
}
void SpellCreator::executeSpell(const LevelMovableGameObject* target) {
if (target == nullptr) return;
m_isReady = false;
m_owner->setFacingRight(target->getCenter().x - m_owner->getCenter().x > 0);
if (m_spellData.castingTime > sf::Time::Zero) {
m_currentCastingTime = m_spellData.castingTime;
m_target = target;
target->registerSpellCreator(this);
m_owner->executeFightAnimation(m_spellData.castingTime + sf::milliseconds(100), m_spellData.castingAnimation, m_spellData.isBlocking);
return;
}
if (!m_spellData.creatorSoundPaths.empty()) {
g_resourceManager->playSound(m_spellData.creatorSoundPaths.at(rand() % m_spellData.creatorSoundPaths.size()));
}
execExecuteSpell(target->getCenter());
m_owner->executeFightAnimation(m_spellData.fightingTime, m_spellData.fightAnimation, m_spellData.isBlocking);
m_isReady = true;
}
void SpellCreator::notifyMobDeath(LevelMovableGameObject* mob) {
if (mob == m_target) {
m_target = nullptr;
}
}
void SpellCreator::addModifiers(const std::vector<SpellModifier>& modifiers) {
for (auto& it : modifiers) {
if (it.type == SpellModifierType::VOID) continue;
// some security checks
if (!contains(m_allowedModifiers, it.type)) {
g_logger->logWarning("SpellCreator", "Modifier of an unallowed type was ignored.");
continue;
}
if (it.level < 1 || it.level > 3) {
g_logger->logWarning("SpellCreator", "Modifier of an unallowed level was ignored.");
continue;
}
switch (it.type) {
case SpellModifierType::Count:
addCountModifier(it.level);
break;
case SpellModifierType::Range:
addRangeModifier(it.level);
break;
case SpellModifierType::Reflect:
addReflectModifier(it.level);
break;
case SpellModifierType::Speed:
addSpeedModifier(it.level);
break;
case SpellModifierType::Strength:
addStrengthModifier(it.level);
break;
case SpellModifierType::Duration:
addDurationModifier(it.level);
break;
default:
g_logger->logWarning("SpellCreator", "Modifier of an unknown type was ignored.");
break;
}
}
}
void SpellCreator::addSpeedModifier(int level) {
m_spellData.speed += m_spellData.speedModifierAddition * level;
}
void SpellCreator::addDurationModifier(int level) {
m_spellData.activeDuration += static_cast<float>(level) * m_spellData.durationModifierAddition;
}
void SpellCreator::addRangeModifier(int level) {
m_spellData.range += m_spellData.rangeModifierAddition * level;
}
void SpellCreator::addCountModifier(int level) {
m_spellData.count += m_spellData.countModifierAddition * level;
}
void SpellCreator::addReflectModifier(int level) {
m_spellData.reflectCount += m_spellData.reflectModifierAddition * level;
}
void SpellCreator::addStrengthModifier(int level) {
m_spellData.ccStrength += level;
}
SpellData& SpellCreator::getSpellData() {
return m_spellData;
}
void SpellCreator::setSpellAllied(bool allied) {
m_spellData.isAlly = allied;
}
void SpellCreator::updateDamageAndHeal(SpellData& bean) const {
updateDamageAndHeal(bean, m_attributeData, true);
}
bool SpellCreator::isReady() const {
return m_isReady;
}
int SpellCreator::getStrengthModifierValue() const {
return m_spellData.ccStrength;
}
std::string SpellCreator::getStrengthModifierName() const {
return "";
}
void SpellCreator::updateDamageAndHeal(SpellData& bean, const AttributeData* attributes, bool includeRngAndCrit) {
if (attributes == nullptr) return;
// handle heal
if (bean.heal > 0) {
bean.heal += attributes->heal;
}
// handle instant damage
if (bean.damage > 0) {
switch (bean.damageType) {
case DamageType::Physical:
bean.damage += attributes->damagePhysical;
break;
case DamageType::Fire:
bean.damage += attributes->damageFire;
break;
case DamageType::Ice:
bean.damage += attributes->damageIce;
break;
case DamageType::Shadow:
bean.damage += attributes->damageShadow;
break;
case DamageType::Light:
bean.damage += attributes->damageLight;
break;
default:
break;
}
}
// handle DOT damage
if (bean.damagePerSecond > 0 && bean.duration.asSeconds() > 0.f) {
float durationS = bean.duration.asSeconds();
switch (bean.damageType) {
case DamageType::Physical:
bean.damagePerSecond += static_cast<int>(attributes->damagePhysical / durationS);
break;
case DamageType::Fire:
bean.damagePerSecond += static_cast<int>(attributes->damageIce / durationS);
break;
case DamageType::Ice:
bean.damagePerSecond += static_cast<int>(attributes->damageFire / durationS);
break;
case DamageType::Shadow:
bean.damagePerSecond += static_cast<int>(attributes->damageShadow / durationS);
break;
case DamageType::Light:
bean.damagePerSecond += static_cast<int>(attributes->damageLight / durationS);
break;
default:
break;
}
}
if (!includeRngAndCrit) return;
// add randomness to damage (something from 80 - 120% of the base damage)
bean.damage = static_cast<int>(bean.damage * ((rand() % 41 + 80.f) / 100.f));
// add randomness to heal (something from 80 - 120% of the base heal)
bean.heal = static_cast<int>(bean.heal * ((rand() % 41 + 80.f) / 100.f));
// add critical hit to damage
int chance = rand() % 100 + 1;
if (bean.damage > 0 && chance <= attributes->criticalHitChance) {
bean.critical = true;
bean.damage *= 2;
}
// add critical hit to heal
chance = rand() % 100 + 1;
if (bean.heal > 0 && chance <= attributes->criticalHitChance) {
bean.critical = true;
bean.heal *= 2;
}
// divide damage and heal by count.
bean.damage = static_cast<int>(std::ceil(bean.damage / bean.count));
bean.heal = static_cast<int>(std::ceil(bean.heal / bean.count));
bean.damagePerSecond = static_cast<int>(std::ceil(bean.damagePerSecond / bean.count));
} | 31.241636 | 136 | 0.732151 |
fd2c00958ee0c29a9372d7d291a87f62e06360d7 | 608 | cpp | C++ | programa25.cpp | sclip/sis110-02-2020 | a4ef1ece3e9ed08058c829e421a54d38e210cdba | [
"MIT"
] | null | null | null | programa25.cpp | sclip/sis110-02-2020 | a4ef1ece3e9ed08058c829e421a54d38e210cdba | [
"MIT"
] | null | null | null | programa25.cpp | sclip/sis110-02-2020 | a4ef1ece3e9ed08058c829e421a54d38e210cdba | [
"MIT"
] | null | null | null | #include <iostream>
#include <iomanip>
using namespace std;
/**
Escribir un programa para leer un numero entero por teclado
y mostrar por pantalla la siguiente figura:
*
**
***
Ej. Entrada
3
4
Salida
*
**
***
*
**
***
****
*/
int main()
{
int n;
cin>>n;
/*for(int i=0;i<n;i++)
{
for(int j=0;j<i+1;j++)
cout<<"*";
cout<<endl;
}*/
/*for(int i=0;i<n;i++)
{
string puntos(i+1,'*');
cout<<puntos<<endl;
//cout<<string(i+1,'*')<<endl;
}*/
for(int i=0;i<n;i++)
cout<<setfill('*')<<setw(i+1)<<""<<endl;
return 0;
}
| 14.139535 | 59 | 0.481908 |
fd2cda45ca6cffd6827ca5976551252252ded072 | 836 | hpp | C++ | src/gpu/metal.hpp | DveloperY0115/FirstRayTracer | 9487bbf4a3c7ac0ad2343fdaca6b5d8548f1e332 | [
"MIT"
] | 1 | 2021-02-18T08:38:21.000Z | 2021-02-18T08:38:21.000Z | src/gpu/metal.hpp | DveloperY0115/RTFoundation | 9487bbf4a3c7ac0ad2343fdaca6b5d8548f1e332 | [
"MIT"
] | 1 | 2020-05-15T16:42:33.000Z | 2020-05-17T07:23:43.000Z | src/gpu/metal.hpp | DveloperY0115/ray-tracing-in-one-weekend-cpp | 4a293f8db7eefd1d62e6be46a53d65ff348eaa52 | [
"MIT"
] | null | null | null | //
// Created by dveloperY0115 on 1/28/2021.
//
#ifndef RAY_TRACING_IN_CPP_METAL_H
#define RAY_TRACING_IN_CPP_METAL_H
#include "material.hpp"
class metal : public material {
public:
__device__ metal(const vector3& a, float f) : albedo(a) { if (f < 1) fuzz = f; else fuzz = 1; }
__device__ virtual bool scatter(const ray& r_in, const hit_record& rec, vector3& attenuation,
ray& scattered, curandState *local_rand_state) const {
vector3 reflected = reflect(unit_vector(r_in.direction()), rec.normal);
scattered = ray(rec.p, reflected + fuzz * random_in_unit_sphere(local_rand_state), r_in.time());
attenuation = albedo;
return (dot(scattered.direction(), rec.normal) > 0.0f);
}
vector3 albedo;
float fuzz;
};
#endif //RAY_TRACING_IN_CPP_METAL_H
| 33.44 | 104 | 0.671053 |
fd2d436eb0a749e2aff868b3752eb523aeca493c | 127 | cpp | C++ | AtCoder/ABC053/A/abc053_a.cpp | object-oriented-human/competitive | 9e761020e887d8980a39a64eeaeaa39af0ecd777 | [
"MIT"
] | 2 | 2021-07-27T10:46:47.000Z | 2021-07-27T10:47:57.000Z | AtCoder/ABC053/A/abc053_a.cpp | foooop/competitive | 9e761020e887d8980a39a64eeaeaa39af0ecd777 | [
"MIT"
] | null | null | null | AtCoder/ABC053/A/abc053_a.cpp | foooop/competitive | 9e761020e887d8980a39a64eeaeaa39af0ecd777 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int main() {
int x; cin >> x;
x < 1200 ? cout << "ABC" : cout << "ARC";
} | 21.166667 | 45 | 0.527559 |
fd2fca42ac4233c6c7f31c5f4b012afe20f3aa79 | 10,173 | cpp | C++ | Source/AllProjects/Tests2/TestCIDMData/TestCIDMData_AttrData.cpp | MarkStega/CIDLib | 82014e064eef51cad998bf2c694ed9c1c8cceac6 | [
"MIT"
] | 216 | 2019-03-09T06:41:28.000Z | 2022-02-25T16:27:19.000Z | Source/AllProjects/Tests2/TestCIDMData/TestCIDMData_AttrData.cpp | MarkStega/CIDLib | 82014e064eef51cad998bf2c694ed9c1c8cceac6 | [
"MIT"
] | 9 | 2020-09-27T08:00:52.000Z | 2021-07-02T14:27:31.000Z | Source/AllProjects/Tests2/TestCIDMData/TestCIDMData_AttrData.cpp | MarkStega/CIDLib | 82014e064eef51cad998bf2c694ed9c1c8cceac6 | [
"MIT"
] | 29 | 2019-03-09T10:12:24.000Z | 2021-03-03T22:25:29.000Z | //
// FILE NAME: TestMData_AttrData.cpp
//
// AUTHOR: Dean Roddey
//
// CREATED: 08/07/2018
//
// COPYRIGHT: Charmed Quark Systems, Ltd @ 2019
//
// This software is copyrighted by 'Charmed Quark Systems, Ltd' and
// the author (Dean Roddey.) It is licensed under the MIT Open Source
// license:
//
// https://opensource.org/licenses/MIT
//
// DESCRIPTION:
//
// These are tests of the attribute data classes.
//
// CAVEATS/GOTCHAS:
//
// LOG:
//
// $_CIDLib_Log_$
//
// ---------------------------------------------------------------------------
// Include our public header and our own specific header
// ---------------------------------------------------------------------------
#include "TestCIDMData.hpp"
#include "TestCIDMData_AttrData.hpp"
// ---------------------------------------------------------------------------
// Magic macros
// ---------------------------------------------------------------------------
RTTIDecls(TTest_AttrDataBasic, TTestFWTest)
// ---------------------------------------------------------------------------
// CLASS: TTest_AttrDataBasic
// PREFIX: tfwt
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// TTest_AttrDataBasic: Constructor and Destructor
// ---------------------------------------------------------------------------
TTest_AttrDataBasic::TTest_AttrDataBasic() :
TTestFWTest
(
L"Attr Data 1", L"Basic tests of the attribute data class", 4
)
{
}
TTest_AttrDataBasic::~TTest_AttrDataBasic()
{
}
// ---------------------------------------------------------------------------
// TTest_AttrDataBasic: Public, inherited methods
// ---------------------------------------------------------------------------
tTestFWLib::ETestRes
TTest_AttrDataBasic::eRunTest(TTextStringOutStream& strmOut, tCIDLib::TBoolean& bWarning)
{
tTestFWLib::ETestRes eRes = tTestFWLib::ETestRes::Success;
tCIDLib::TBoolean bRes;
// Test a default constructed one for initial state
{
TAttrData adatDef;
bRes = bTestState3
(
strmOut
, L"def ctor"
, CID_LINE
, adatDef
, TString::strEmpty()
, TString::strEmpty()
, TString::strEmpty()
, tCIDMData::EAttrTypes::String
, tCIDMData::EAttrEdTypes::None
, TString::strEmpty()
, 0
, TString::strEmpty()
);
if (!bRes)
eRes = tTestFWLib::ETestRes::Failed;
}
// Test setting and reading back each value type
{
TAttrData adatType;
//
// Do boolean type
//
adatType.Set
(
L"Bool Test"
, L"/Test/Boolean"
, TString::strEmpty()
, tCIDMData::EAttrTypes::Bool
);
bRes = bTestState
(
strmOut
, L"Bool Test"
, CID_LINE
, adatType
, TString::strEmpty()
, tCIDMData::EAttrTypes::Bool
, L"False"
);
if (!bRes)
eRes = tTestFWLib::ETestRes::Failed;
adatType.SetBool(kCIDLib::True);
if (adatType.bVal() != kCIDLib::True)
{
strmOut << TFWCurLn << L"Did not get back set true value" << kCIDLib::NewLn;
eRes = tTestFWLib::ETestRes::Failed;
}
//
// Do Card type
//
adatType.Set
(
L"Card Test"
, L"/Test/Card"
, TString::strEmpty()
, tCIDMData::EAttrTypes::Card
);
bRes = bTestState
(
strmOut
, L"Card Test"
, CID_LINE
, adatType
, TString::strEmpty()
, tCIDMData::EAttrTypes::Card
, L"0"
);
if (!bRes)
eRes = tTestFWLib::ETestRes::Failed;
adatType.SetCard(11);
if (adatType.c4Val() != 11)
{
strmOut << TFWCurLn << L"Did not get back set 11 value" << kCIDLib::NewLn;
eRes = tTestFWLib::ETestRes::Failed;
}
}
return eRes;
}
// ---------------------------------------------------------------------------
// TTest_AttrDataBasic: Private, non-virtual methods
// ---------------------------------------------------------------------------
// Avoid some redundancy by providing a test for basic state of an attribute
tCIDLib::TBoolean
TTest_AttrDataBasic::bTestState( TTextOutStream& strmOut
, const TString& strTestName
, const tCIDLib::TCard4 c4Line
, const TAttrData& adatTest
, const TString& strLimits
, const tCIDMData::EAttrTypes eType
, const TString& strFmtValue)
{
tCIDLib::TBoolean bRet = kCIDLib::True;
if (eType != adatTest.eType())
{
strmOut << TTFWCurLn(CID_FILE, c4Line)
<< strTestName << L" should have type "
<< tCIDMData::strXlatEAttrTypes(eType)
<< L" but has "
<< tCIDMData::strXlatEAttrTypes(adatTest.eType())
<< kCIDLib::NewLn;
bRet = kCIDLib::False;
}
if (strLimits != adatTest.strLimits())
{
strmOut << TTFWCurLn(CID_FILE, c4Line)
<< strTestName << L" should have limit '"
<< strLimits
<< L"' but has '"
<< adatTest.strLimits()
<< L"'\n";
bRet = kCIDLib::False;
}
// Format the value to test
TString strTestVal;
adatTest.FormatToText(strTestVal);
if (strTestVal != strFmtValue)
{
strmOut << TTFWCurLn(CID_FILE, c4Line)
<< strTestName << L" should have value '"
<< strFmtValue
<< L"' but has '"
<< strTestVal
<< L"'\n";
bRet = kCIDLib::False;
}
return bRet;
}
tCIDLib::TBoolean
TTest_AttrDataBasic::bTestState2( TTextOutStream& strmOut
, const TString& strTestName
, const tCIDLib::TCard4 c4Line
, const TAttrData& adatTest
, const TString& strAttrId
, const TString& strSpecType
, const TString& strLimits
, const tCIDMData::EAttrTypes eType
, const tCIDMData::EAttrEdTypes eEditType
, const TString& strFmtValue)
{
// Call the other version first
tCIDLib::TBoolean bRet = bTestState
(
strmOut
, strTestName
, c4Line
, adatTest
, strLimits
, eType
, strFmtValue
);
if (strAttrId != adatTest.strId())
{
strmOut << TTFWCurLn(CID_FILE, c4Line)
<< strTestName << L" should have id '"
<< strAttrId
<< L"' but has '"
<< adatTest.strId()
<< L"'\n";
bRet = kCIDLib::False;
}
if (strSpecType != adatTest.strSpecType())
{
strmOut << TTFWCurLn(CID_FILE, c4Line)
<< strTestName << L" should have special type '"
<< strSpecType
<< L"' but has '"
<< adatTest.strSpecType()
<< L"'\n";
bRet = kCIDLib::False;
}
if (eEditType != adatTest.eEditType())
{
strmOut << TTFWCurLn(CID_FILE, c4Line)
<< strTestName << L" should have edit type "
<< tCIDMData::strXlatEAttrEdTypes(eEditType)
<< L" but has "
<< tCIDMData::strXlatEAttrEdTypes(adatTest.eEditType())
<< kCIDLib::NewLn;
bRet = kCIDLib::False;
}
return bRet;
}
tCIDLib::TBoolean
TTest_AttrDataBasic::bTestState3( TTextOutStream& strmOut
, const TString& strTestName
, const tCIDLib::TCard4 c4Line
, const TAttrData& adatTest
, const TString& strAttrId
, const TString& strSpecType
, const TString& strLimits
, const tCIDMData::EAttrTypes eType
, const tCIDMData::EAttrEdTypes eEditType
, const TString& strFmtValue
, const tCIDLib::TCard8 c8UserData
, const TString& strUserData)
{
// Call the other version first
tCIDLib::TBoolean bRet = bTestState2
(
strmOut
, strTestName
, c4Line
, adatTest
, strAttrId
, strSpecType
, strLimits
, eType
, eEditType
, strFmtValue
);
// And do our extra bits
if (c8UserData != adatTest.c8User())
{
strmOut << TTFWCurLn(CID_FILE, c4Line)
<< strTestName << L" should have TCard8 user data "
<< c8UserData
<< L" but has "
<< adatTest.c8User()
<< kCIDLib::NewLn;
bRet = kCIDLib::False;
}
if (strUserData != adatTest.strUserData())
{
strmOut << TTFWCurLn(CID_FILE, c4Line)
<< strTestName << L" should have string user data '"
<< strUserData
<< L"' but has '"
<< adatTest.strUserData()
<< L"'\n";
bRet = kCIDLib::False;
}
return bRet;
}
| 30.276786 | 89 | 0.433009 |
fd308e43d5783a3a00f7b1922d8f468429a6f363 | 5,015 | cpp | C++ | City/City/Testing/CCityTest.cpp | NicholsTyler/cse_335 | b8a46522c15a9881cb681ae94b4a5f737817b05e | [
"MIT"
] | null | null | null | City/City/Testing/CCityTest.cpp | NicholsTyler/cse_335 | b8a46522c15a9881cb681ae94b4a5f737817b05e | [
"MIT"
] | null | null | null | City/City/Testing/CCityTest.cpp | NicholsTyler/cse_335 | b8a46522c15a9881cb681ae94b4a5f737817b05e | [
"MIT"
] | null | null | null | #include "pch.h"
#include "CppUnitTest.h"
#include "City.h"
#include "TileRoad.h"
#include "TileLandscape.h"
#include "TileCoalmine.h"
#include "TileBuilding.h"
using namespace std;
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace Testing
{
class CTestVisitor : public CTileVisitor
{
public:
virtual void VisitRoad(CTileRoad* road) override { mNumRoads++; }
virtual void VisitLandscape(CTileLandscape* landScape) override { mNumLandScapes++; }
virtual void VisitCoalmine(CTileCoalmine* coalMine) override { mNumCoalMines++; }
virtual void VisitBuilding(CTileBuilding* building) override { mNumBuildings++; }
int mNumRoads = 0;
int mNumLandScapes = 0;
int mNumCoalMines = 0;
int mNumBuildings = 0;
};
TEST_CLASS(CCityTest)
{
public:
TEST_METHOD_INITIALIZE(methodName)
{
extern wchar_t g_dir[];
::SetCurrentDirectory(g_dir);
}
TEST_METHOD(TestCCityConstructor)
{
CCity city;
}
/** Tests for the GetAdjacent function
*/
TEST_METHOD(TestCCityAdjacent)
{
CCity city;
int grid = CCity::GridSpacing;
// Add a center tile to test
auto center = make_shared<CTileRoad>(&city);
center->SetLocation(grid * 10, grid * 17);
city.Add(center);
// Upper left
auto ul = make_shared<CTileRoad>(&city);
ul->SetLocation(grid * 8, grid * 16);
city.Add(ul);
city.SortTiles();
Assert::IsTrue(city.GetAdjacent(center, -1, -1) == ul, L"Upper left test");
Assert::IsTrue(city.GetAdjacent(center, 1, -1) == nullptr, L"Upper right null test");
// Upper right
auto ur = make_shared<CTileRoad>(&city);
ur->SetLocation(grid * 12, grid * 16);
city.Add(ur);
// Lower left
auto ll = make_shared<CTileRoad>(&city);
ll->SetLocation(grid * 8, grid * 18);
city.Add(ll);
// Lower right
auto lr = make_shared<CTileRoad>(&city);
lr->SetLocation(grid * 12, grid * 18);
city.Add(lr);
city.SortTiles();
Assert::IsTrue(city.GetAdjacent(center, 1, -1) == ur, L"Upper right test");
Assert::IsTrue(city.GetAdjacent(center, -1, 1) == ll, L"Lower left test");
Assert::IsTrue(city.GetAdjacent(center, 1, 1) == lr, L"Lower right test");
}
TEST_METHOD(TestCCityIterator)
{
// Construct a city object
CCity city;
// Add some tiles
auto tile1 = make_shared<CTileRoad>(&city);
auto tile2 = make_shared<CTileRoad>(&city);
auto tile3 = make_shared<CTileRoad>(&city);
city.Add(tile1);
city.Add(tile2);
city.Add(tile3);
// Does begin point to the first tile?
auto iter1 = city.begin();
auto iter2 = city.end();
Assert::IsTrue(tile1 == *iter1, L"First item correct");
++iter1;
Assert::IsTrue(tile2 == *iter1, L"Second item correct");
++iter1;
Assert::IsTrue(tile3 == *iter1, L"Third item correct");
++iter1;
Assert::IsFalse(iter1 != iter2);
}
TEST_METHOD(TestCCityVisitor)
{
// Construct a city object
CCity city;
// Add some tiles of each time
auto tile1 = make_shared<CTileRoad>(&city);
auto tile2 = make_shared<CTileBuilding>(&city);
auto tile3 = make_shared<CTileLandscape>(&city);
auto tile4 = make_shared<CTileCoalmine>(&city);
city.Add(tile1);
city.Add(tile2);
city.Add(tile3);
city.Add(tile4);
CTestVisitor visitor;
city.Accept(&visitor);
Assert::AreEqual(1, visitor.mNumRoads,
L"Visitor number of roads");
Assert::AreEqual(1, visitor.mNumLandScapes,
L"Visitor number of landscapes");
Assert::AreEqual(1, visitor.mNumCoalMines,
L"Visitor number of coalmines");
Assert::AreEqual(1, visitor.mNumBuildings,
L"Visitor number of buildings");
// Construct an empty city object
CCity emptyCity;
CTestVisitor emptyVisitor;
emptyCity.Accept(&emptyVisitor);
Assert::AreEqual(0, emptyVisitor.mNumRoads,
L"Visitor number of roads");
Assert::AreEqual(0, emptyVisitor.mNumLandScapes,
L"Visitor number of landscapes");
Assert::AreEqual(0, emptyVisitor.mNumCoalMines,
L"Visitor number of coalmines");
Assert::AreEqual(0, emptyVisitor.mNumBuildings,
L"Visitor number of buildings");
}
};
} | 31.740506 | 97 | 0.554935 |
fd38913ee6929ff670690ff8689318fe63932139 | 1,315 | cpp | C++ | cpp/301-310/Minimum Height Trees.cpp | KaiyuWei/leetcode | fd61f5df60cfc7086f7e85774704bacacb4aaa5c | [
"MIT"
] | 150 | 2015-04-04T06:53:49.000Z | 2022-03-21T13:32:08.000Z | cpp/301-310/Minimum Height Trees.cpp | yizhu1012/leetcode | d6fa443a8517956f1fcc149c8c4f42c0ad93a4a7 | [
"MIT"
] | 1 | 2015-04-13T15:15:40.000Z | 2015-04-21T20:23:16.000Z | cpp/301-310/Minimum Height Trees.cpp | yizhu1012/leetcode | d6fa443a8517956f1fcc149c8c4f42c0ad93a4a7 | [
"MIT"
] | 64 | 2015-06-30T08:00:07.000Z | 2022-01-01T16:44:14.000Z | class Solution {
public:
vector<int> findMinHeightTrees(int n, vector<pair<int, int>>& edges) {
vector<int> res;
if(n <= 2) {
for(int i = 0;i < n;i++)
res.push_back(i);
return res;
}
int k = 0;
vector<set<int>> myvec(n, set<int>());
queue<int> myqueue;
for(auto e : edges) {
myvec[e.first].insert(e.second);
myvec[e.second].insert(e.first);
}
for(int i = 0;i < n;i++) {
if(myvec[i].size() == 1) {
myqueue.push(i);
k++;
}
}
while(1) {
int j = myqueue.size();
for(int i = 0;i < j;i++) {
int v = myqueue.front();
myqueue.pop();
for(auto e : myvec[v]) {
myvec[e].erase(v);
if(myvec[e].size() == 1) {
myqueue.push(e);
k++;
}
}
}
if(n == k) break;
}
while(!myqueue.empty()) {
res.push_back(myqueue.front());
myqueue.pop();
}
sort(res.begin(), res.end());
return res;
}
}; | 25.784314 | 74 | 0.349049 |
fd3ad24c832a34d09a560531df4cb453e20a6f4e | 2,552 | hpp | C++ | Lib/Chip/MKL36Z4.hpp | cjsmeele/Kvasir | c8d2acd8313ae52d78259ee2d409b963925f77d7 | [
"Apache-2.0"
] | 376 | 2015-07-17T01:41:20.000Z | 2022-03-26T04:02:49.000Z | Lib/Chip/MKL36Z4.hpp | cjsmeele/Kvasir | c8d2acd8313ae52d78259ee2d409b963925f77d7 | [
"Apache-2.0"
] | 59 | 2015-07-03T21:30:13.000Z | 2021-03-05T11:30:08.000Z | Lib/Chip/MKL36Z4.hpp | cjsmeele/Kvasir | c8d2acd8313ae52d78259ee2d409b963925f77d7 | [
"Apache-2.0"
] | 53 | 2015-07-14T12:17:06.000Z | 2021-06-04T07:28:40.000Z | #pragma once
#include <Chip/CM0+/Freescale/MKL36Z4/FTFA_FlashConfig.hpp>
#include <Chip/CM0+/Freescale/MKL36Z4/DMA.hpp>
#include <Chip/CM0+/Freescale/MKL36Z4/FTFA.hpp>
#include <Chip/CM0+/Freescale/MKL36Z4/DMAMUX0.hpp>
#include <Chip/CM0+/Freescale/MKL36Z4/I2S0.hpp>
#include <Chip/CM0+/Freescale/MKL36Z4/PIT.hpp>
#include <Chip/CM0+/Freescale/MKL36Z4/TPM0.hpp>
#include <Chip/CM0+/Freescale/MKL36Z4/TPM1.hpp>
#include <Chip/CM0+/Freescale/MKL36Z4/TPM2.hpp>
#include <Chip/CM0+/Freescale/MKL36Z4/ADC0.hpp>
#include <Chip/CM0+/Freescale/MKL36Z4/RTC.hpp>
#include <Chip/CM0+/Freescale/MKL36Z4/DAC0.hpp>
#include <Chip/CM0+/Freescale/MKL36Z4/LPTMR0.hpp>
#include <Chip/CM0+/Freescale/MKL36Z4/TSI0.hpp>
#include <Chip/CM0+/Freescale/MKL36Z4/SIM.hpp>
#include <Chip/CM0+/Freescale/MKL36Z4/PORTA.hpp>
#include <Chip/CM0+/Freescale/MKL36Z4/PORTB.hpp>
#include <Chip/CM0+/Freescale/MKL36Z4/PORTC.hpp>
#include <Chip/CM0+/Freescale/MKL36Z4/PORTD.hpp>
#include <Chip/CM0+/Freescale/MKL36Z4/PORTE.hpp>
#include <Chip/CM0+/Freescale/MKL36Z4/LCD.hpp>
#include <Chip/CM0+/Freescale/MKL36Z4/MCG.hpp>
#include <Chip/CM0+/Freescale/MKL36Z4/OSC0.hpp>
#include <Chip/CM0+/Freescale/MKL36Z4/I2C0.hpp>
#include <Chip/CM0+/Freescale/MKL36Z4/I2C1.hpp>
#include <Chip/CM0+/Freescale/MKL36Z4/UART0.hpp>
#include <Chip/CM0+/Freescale/MKL36Z4/UART1.hpp>
#include <Chip/CM0+/Freescale/MKL36Z4/UART2.hpp>
#include <Chip/CM0+/Freescale/MKL36Z4/CMP0.hpp>
#include <Chip/CM0+/Freescale/MKL36Z4/SPI0.hpp>
#include <Chip/CM0+/Freescale/MKL36Z4/SPI1.hpp>
#include <Chip/CM0+/Freescale/MKL36Z4/LLWU.hpp>
#include <Chip/CM0+/Freescale/MKL36Z4/PMC.hpp>
#include <Chip/CM0+/Freescale/MKL36Z4/SMC.hpp>
#include <Chip/CM0+/Freescale/MKL36Z4/RCM.hpp>
#include <Chip/CM0+/Freescale/MKL36Z4/GPIOA.hpp>
#include <Chip/CM0+/Freescale/MKL36Z4/GPIOB.hpp>
#include <Chip/CM0+/Freescale/MKL36Z4/GPIOC.hpp>
#include <Chip/CM0+/Freescale/MKL36Z4/GPIOD.hpp>
#include <Chip/CM0+/Freescale/MKL36Z4/GPIOE.hpp>
#include <Chip/CM0+/Freescale/MKL36Z4/SystemControl.hpp>
#include <Chip/CM0+/Freescale/MKL36Z4/SysTick.hpp>
#include <Chip/CM0+/Freescale/MKL36Z4/NVIC.hpp>
#include <Chip/CM0+/Freescale/MKL36Z4/MTB.hpp>
#include <Chip/CM0+/Freescale/MKL36Z4/MTBDWT.hpp>
#include <Chip/CM0+/Freescale/MKL36Z4/ROM.hpp>
#include <Chip/CM0+/Freescale/MKL36Z4/MCM.hpp>
#include <Chip/CM0+/Freescale/MKL36Z4/FGPIOA.hpp>
#include <Chip/CM0+/Freescale/MKL36Z4/FGPIOB.hpp>
#include <Chip/CM0+/Freescale/MKL36Z4/FGPIOC.hpp>
#include <Chip/CM0+/Freescale/MKL36Z4/FGPIOD.hpp>
#include <Chip/CM0+/Freescale/MKL36Z4/FGPIOE.hpp>
| 47.259259 | 59 | 0.774295 |
fd3de0284634f25e8345852b89225993adb5fd8c | 21,395 | cpp | C++ | SpockLib/c_view.cpp | zachmakesgames/Spock | bb5a6a9b4ce2c86fe49c08b7aa1ae633b95443e4 | [
"MIT"
] | null | null | null | SpockLib/c_view.cpp | zachmakesgames/Spock | bb5a6a9b4ce2c86fe49c08b7aa1ae633b95443e4 | [
"MIT"
] | null | null | null | SpockLib/c_view.cpp | zachmakesgames/Spock | bb5a6a9b4ce2c86fe49c08b7aa1ae633b95443e4 | [
"MIT"
] | null | null | null | #include "c_view.h"
c_view::c_view(c_instance *instance, c_device *device, int x, int y) :
m_instance(instance), m_device(device), m_closing_callback(nullptr), m_resize_callback(nullptr),
m_extent_2D({})
{
VkResult result;
//Set up the window
this->m_extent_2D.height= y;
this->m_extent_2D.width= x;
this->m_window= glfwCreateWindow(x, y, m_instance->get_instance_name().c_str(), NULL, NULL);
result= glfwCreateWindowSurface(*this->m_instance->get_instance(), this->m_window, NULL, &this->m_window_surface);
if (result != VK_SUCCESS) {
#ifdef DEBUG
std::cout << "Vulkan encountered an error with glfwCreateWindowSurface: " << result << std::endl;
#endif
throw std::exception("Could not create GLFW window surface");
}
//Check for surface support, vulkan will complain if we dont
VkBool32 supported_surface= false;
result= vkGetPhysicalDeviceSurfaceSupportKHR(*this->m_device->get_physical_device(), this->m_device->get_graphics_queue_family_index(), this->m_window_surface, &supported_surface);
if (result != VK_SUCCESS) {
#ifdef DEBUG
std::cout << "Vulkan could not determine if surface is supported: " << result << std::endl;
#endif
throw std::exception("Could not create GLFW window surface");
}
if (!supported_surface) {
#ifdef DEBUG
std::cout << "SURFACE IS NOT SUPPORTED!!!!" << std::endl;
#endif
throw std::exception("GLFW surface is not supported by this device");
}
//Check which formats are available
//First find out how many there are
uint32_t format_count= -1;
vkGetPhysicalDeviceSurfaceFormatsKHR(*this->m_device->get_physical_device(), this->m_window_surface, &format_count, nullptr);
VkSurfaceFormatKHR *supported_formats= new VkSurfaceFormatKHR[format_count];
//Then populate the formats
vkGetPhysicalDeviceSurfaceFormatsKHR(*this->m_device->get_physical_device(), this->m_window_surface, &format_count, supported_formats);
#ifdef DEBUG
std::cout << "Found " << format_count << " supported formats" << std::endl;
for (int i= 0; i < format_count; i++) {
switch (supported_formats[i].format) {
case VK_FORMAT_R8G8B8A8_UNORM: std::cout << "Format: VK_FORMAT_R8G8B8A8_UNORM" << std::endl;
break;
case VK_FORMAT_R8G8B8A8_SNORM: std::cout << "Format: VK_FORMAT_R8G8B8A8_SNORM" << std::endl;
break;
case VK_FORMAT_R8G8B8A8_USCALED: std::cout << "Format: VK_FORMAT_R8G8B8A8_USCALED" << std::endl;
break;
case VK_FORMAT_R8G8B8A8_SSCALED: std::cout << "Format: VK_FORMAT_R8G8B8A8_SSCALED" << std::endl;
break;
case VK_FORMAT_R8G8B8A8_UINT: std::cout << "Format: VK_FORMAT_R8G8B8A8_UINT" << std::endl;
break;
case VK_FORMAT_R8G8B8A8_SINT: std::cout << "Format: VK_FORMAT_R8G8B8A8_SINT" << std::endl;
break;
case VK_FORMAT_R8G8B8A8_SRGB: std::cout << "Format: VK_FORMAT_R8G8B8A8_SRGB" << std::endl;
break;
case VK_FORMAT_B8G8R8A8_UNORM: std::cout << "Format: VK_FORMAT_B8G8R8A8_UNORM" << std::endl;
break;
case VK_FORMAT_B8G8R8A8_SNORM: std::cout << "Format: VK_FORMAT_B8G8R8A8_SNORM" << std::endl;
break;
case VK_FORMAT_B8G8R8A8_USCALED: std::cout << "Format: VK_FORMAT_B8G8R8A8_USCALED" << std::endl;
break;
case VK_FORMAT_B8G8R8A8_SSCALED: std::cout << "Format: VK_FORMAT_B8G8R8A8_SSCALED" << std::endl;
break;
case VK_FORMAT_B8G8R8A8_UINT: std::cout << "Format: VK_FORMAT_B8G8R8A8_UINT" << std::endl;
break;
case VK_FORMAT_B8G8R8A8_SINT: std::cout << "Format: VK_FORMAT_B8G8R8A8_SINT" << std::endl;
break;
case VK_FORMAT_B8G8R8A8_SRGB: std::cout << "Format: VK_FORMAT_B8G8R8A8_SRGB" << std::endl;
break;
}
switch (supported_formats[i].colorSpace) {
case VK_COLOR_SPACE_SRGB_NONLINEAR_KHR: std::cout << "Colorspace: VK_COLOR_SPACE_SRGB_NONLINEAR_KHR" << std::endl;
break;
case VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT: std::cout << "Colorspace: VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT" << std::endl;
break;
case VK_COLOR_SPACE_EXTENDED_SRGB_LINEAR_EXT: std::cout << "Colorspace: VK_COLOR_SPACE_EXTENDED_SRGB_LINEAR_EXT" << std::endl;
break;
case VK_COLOR_SPACE_DCI_P3_LINEAR_EXT: std::cout << "Colorspace: VK_COLOR_SPACE_DCI_P3_LINEAR_EXT" << std::endl;
break;
case VK_COLOR_SPACE_DCI_P3_NONLINEAR_EXT: std::cout << "Colorspace: VK_COLOR_SPACE_DCI_P3_NONLINEAR_EXT" << std::endl;
break;
case VK_COLOR_SPACE_BT709_LINEAR_EXT: std::cout << "Colorspace: VK_COLOR_SPACE_BT709_LINEAR_EXT" << std::endl;
break;
case VK_COLOR_SPACE_BT709_NONLINEAR_EXT: std::cout << "Colorspace: VK_COLOR_SPACE_BT709_NONLINEAR_EXT" << std::endl;
break;
case VK_COLOR_SPACE_BT2020_LINEAR_EXT: std::cout << "Colorspace: VK_COLOR_SPACE_BT2020_LINEAR_EXT" << std::endl;
break;
case VK_COLOR_SPACE_HDR10_ST2084_EXT: std::cout << "Colorspace: VK_COLOR_SPACE_HDR10_ST2084_EXT" << std::endl;
break;
case VK_COLOR_SPACE_DOLBYVISION_EXT: std::cout << "Colorspace: VK_COLOR_SPACE_DOLBYVISION_EXT" << std::endl;
break;
case VK_COLOR_SPACE_HDR10_HLG_EXT: std::cout << "Colorspace: VK_COLOR_SPACE_HDR10_HLG_EXT" << std::endl;
break;
}
}
#endif
//Check which present modes are available
uint32_t present_mode_count= -1;
vkGetPhysicalDeviceSurfacePresentModesKHR(*this->m_device->get_physical_device(), this->m_window_surface, &present_mode_count, nullptr);
VkPresentModeKHR *present_modes= new VkPresentModeKHR[present_mode_count];
//Then populate the present modes
vkGetPhysicalDeviceSurfacePresentModesKHR(*this->m_device->get_physical_device(), this->m_window_surface, &present_mode_count, present_modes);
#ifdef DEBUG
std::cout << "Found " << present_mode_count << " presentation modes" << std::endl;
for (int i= 0; i < present_mode_count; i++) {
switch (present_modes[i]) {
case VK_PRESENT_MODE_IMMEDIATE_KHR: std::cout << "VK_PRESENT_MODE_IMMEDIATE_KHR" << std::endl;
break;
case VK_PRESENT_MODE_MAILBOX_KHR: std::cout << "VK_PRESENT_MODE_MAILBOX_KHR" << std::endl;
break;
case VK_PRESENT_MODE_FIFO_KHR: std::cout << "VK_PRESENT_MODE_FIFO_KHR" << std::endl;
break;
case VK_PRESENT_MODE_FIFO_RELAXED_KHR: std::cout << "VK_PRESENT_MODE_FIFO_RELAXED_KHR" << std::endl;
break;
case VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR: std::cout << "VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR" << std::endl;
break;
case VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR: std::cout << "VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR" << std::endl;
break;
}
}
#endif
//Set up the swap chain creation info
///TODO: set this up more dynamically
this->m_swapchain_create_info.sType= VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
this->m_swapchain_create_info.pNext= nullptr;
this->m_swapchain_create_info.flags= 0;
this->m_swapchain_create_info.surface= this->m_window_surface;
this->m_swapchain_create_info.minImageCount= this->m_swapchain_image_count;
//VkFormat selectedFormat= this->GetImageFormat();
this->m_swapchain_create_info.imageFormat= VK_FORMAT_B8G8R8A8_SRGB;
this->m_swapchain_create_info.imageColorSpace= VK_COLOR_SPACE_SRGB_NONLINEAR_KHR;// this->GetColorSpaceFromFormat(selectedFormat);
this->m_swapchain_create_info.presentMode= VK_PRESENT_MODE_IMMEDIATE_KHR; ///TODO: Add method to use different present modes
this->m_swapchain_create_info.imageExtent= this->m_extent_2D;
this->m_swapchain_create_info.imageArrayLayers= 1;
this->m_swapchain_create_info.imageUsage= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
this->m_swapchain_create_info.preTransform= VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
this->m_swapchain_create_info.compositeAlpha= VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
this->m_swapchain_create_info.imageSharingMode= VK_SHARING_MODE_EXCLUSIVE;
this->m_swapchain_create_info.queueFamilyIndexCount= this->m_device->get_graphics_queue_family_index();
this->m_swapchain_create_info.pQueueFamilyIndices= nullptr;
this->m_swapchain_create_info.oldSwapchain= VK_NULL_HANDLE;
this->m_swapchain_create_info.clipped= VK_TRUE;
result= vkCreateSwapchainKHR(*this->m_device->get_logical_device(), &this->m_swapchain_create_info, nullptr, &this->m_swapchain);
if (result != VK_SUCCESS) {
#ifdef DEBUG
std::cout << "Vulkan encountered an error creating the swapchain: " << result << std::endl;
#endif
throw std::exception("Could not create swapchain");
}
//Next get the swapchain images
result= vkGetSwapchainImagesKHR(*this->m_device->get_logical_device(), this->m_swapchain, &this->m_swapchain_image_count, nullptr);
if (result != VK_SUCCESS) {
#ifdef DEBUG
std::cout << "Vulkan encountered an error getting the present image count: " << result << std::endl;
#endif
throw std::exception("Could not get swapchain images");
}
if (this->m_present_image_count < this->m_swapchain_image_count) {
#ifdef DEBUG
std::cout << "Did not get the number of requested swap chain images!" << std::endl;
#endif
throw std::exception("Swapchain/present image count mismatch");
}
this->m_present_images= new VkImage[this->m_present_image_count];
result= vkGetSwapchainImagesKHR(*this->m_device->get_logical_device(), this->m_swapchain, &this->m_present_image_count, this->m_present_images);
if (result != VK_SUCCESS) {
#ifdef DEBUG
std::cout << "Vulkan encountered an error getting the present images: " << result << std::endl;
#endif
throw std::exception("Error creating swapchain images");
}
//Set up Present Views
this->m_present_image_views= new VkImageView[this->m_present_image_count];
this->m_present_image_view_create_info= new VkImageViewCreateInfo[this->m_present_image_count];
for (int i= 0; i < this->m_present_image_count; i++) {
this->m_present_image_view_create_info[i].sType= VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
this->m_present_image_view_create_info[i].pNext= nullptr;
this->m_present_image_view_create_info[i].flags= 0;
this->m_present_image_view_create_info[i].viewType= VK_IMAGE_VIEW_TYPE_2D;
this->m_present_image_view_create_info[i].format= VK_FORMAT_B8G8R8A8_SRGB; //need to correlate this to the available formats above?
//this->m_present_image_view_create_info[i].format= this->GetImageFormat(); //There, now its linked to the available formats
this->m_present_image_view_create_info[i].components.r= VK_COMPONENT_SWIZZLE_R;
this->m_present_image_view_create_info[i].components.g= VK_COMPONENT_SWIZZLE_G;
this->m_present_image_view_create_info[i].components.b= VK_COMPONENT_SWIZZLE_B;
this->m_present_image_view_create_info[i].components.a= VK_COMPONENT_SWIZZLE_A;
this->m_present_image_view_create_info[i].subresourceRange.aspectMask= VK_IMAGE_ASPECT_COLOR_BIT;
this->m_present_image_view_create_info[i].subresourceRange.baseMipLevel= 0;
this->m_present_image_view_create_info[i].subresourceRange.levelCount= 1;
this->m_present_image_view_create_info[i].subresourceRange.baseArrayLayer= 0;
this->m_present_image_view_create_info[i].subresourceRange.layerCount= 1;
this->m_present_image_view_create_info[i].image= this->m_present_images[i];
result= vkCreateImageView(*this->m_device->get_logical_device(), &this->m_present_image_view_create_info[i], nullptr, &this->m_present_image_views[i]);
if (result != VK_SUCCESS) {
#ifdef DEBUG
std::cout << "Vulkan encountered an error creating image view " << i << ": " << result << std::endl;
#endif
throw std::exception("Could not create image view");
}
}
//Set up the depth stencil
this->m_extent_3D= { this->m_extent_2D.width, this->m_extent_2D.height, 1 };
this->m_image_create_info.sType= VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
this->m_image_create_info.pNext= nullptr;
this->m_image_create_info.flags= 0;
this->m_image_create_info.imageType= VK_IMAGE_TYPE_2D;
this->m_image_create_info.format= VK_FORMAT_D32_SFLOAT_S8_UINT;
this->m_image_create_info.extent= this->m_extent_3D;
this->m_image_create_info.mipLevels= 1;
this->m_image_create_info.arrayLayers= 1;
this->m_image_create_info.samples= VK_SAMPLE_COUNT_1_BIT;
this->m_image_create_info.tiling= VK_IMAGE_TILING_OPTIMAL;
this->m_image_create_info.usage= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
this->m_image_create_info.sharingMode= VK_SHARING_MODE_EXCLUSIVE;
this->m_image_create_info.queueFamilyIndexCount= 0;
this->m_image_create_info.pQueueFamilyIndices= nullptr;
this->m_image_create_info.initialLayout= VK_IMAGE_LAYOUT_UNDEFINED;
this->m_depth_stencil_image= {};
result= vkCreateImage(*this->m_device->get_logical_device(), &this->m_image_create_info, nullptr, &this->m_depth_stencil_image);
if (result != VK_SUCCESS) {
#ifdef DEBUG
std::cout << "Vulkan encountered an error creating the depth stencil: " << result << std::endl;
#endif
throw std::exception("Could not create depth stencil image");
}
//Get information about what memory requirements the depth stencil needs
vkGetImageMemoryRequirements(*this->m_device->get_logical_device(), this->m_depth_stencil_image, &this->m_stencil_requirements);
VkPhysicalDeviceMemoryProperties memProperties= {}; ///TODO: Do this in the Device class earlier and save for later use
vkGetPhysicalDeviceMemoryProperties(*this->m_device->get_physical_device(), &memProperties);
//Find memory that is device local
uint32_t memoryIndex= -1;
for (unsigned int i= 0; i < memProperties.memoryTypeCount; i++) {
VkMemoryType memType= memProperties.memoryTypes[i];
VkMemoryPropertyFlags memFlags= memType.propertyFlags;
if ((this->m_stencil_requirements.memoryTypeBits & (1 << i)) != 0) {
if ((memFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) != 0) {
memoryIndex= i;
break;
}
}
}
if (memoryIndex < 0) {
throw std::exception("No device memory??!!");
}
//Set up the memory allocation info struct
this->m_stencil_memory_alloc_info.sType= VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
this->m_stencil_memory_alloc_info.pNext= nullptr;
this->m_stencil_memory_alloc_info.allocationSize= this->m_stencil_requirements.size;
this->m_stencil_memory_alloc_info.memoryTypeIndex= memoryIndex;
//Then allocate the memory
this->m_stencil_memory= new VkDeviceMemory();
result= vkAllocateMemory(*this->m_device->get_logical_device(), &this->m_stencil_memory_alloc_info, nullptr, this->m_stencil_memory);
if (result != VK_SUCCESS) {
#ifdef DEBUG
std::cout << "Vulkan encountered an error allocating memory for the depth stencil: " << result << std::endl;
#endif
throw std::exception("Could not allocate memory for depth stencil");
}
//And bind the memory
result= vkBindImageMemory(*this->m_device->get_logical_device(), this->m_depth_stencil_image, *this->m_stencil_memory, 0);
if (result != VK_SUCCESS) {
#ifdef DEBUG
std::cout << "Vulkan encountered an error binding the depth stencil image memory: " << result << std::endl;
#endif
throw std::exception("Could not bind stnecil image memory");
}
//
//Then set up the image view
this->m_image_view_create_info.sType= VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
this->m_image_view_create_info.pNext= nullptr;
this->m_image_view_create_info.flags= 0;
this->m_image_view_create_info.image= this->m_depth_stencil_image;
this->m_image_view_create_info.viewType= VK_IMAGE_VIEW_TYPE_2D;
this->m_image_view_create_info.format= this->m_image_create_info.format;
this->m_image_view_create_info.components.r= VK_COMPONENT_SWIZZLE_IDENTITY;
this->m_image_view_create_info.components.g= VK_COMPONENT_SWIZZLE_IDENTITY;
this->m_image_view_create_info.components.b= VK_COMPONENT_SWIZZLE_IDENTITY;
this->m_image_view_create_info.components.a= VK_COMPONENT_SWIZZLE_IDENTITY;
this->m_image_view_create_info.subresourceRange.aspectMask= VK_IMAGE_ASPECT_DEPTH_BIT;
this->m_image_view_create_info.subresourceRange.baseMipLevel= 0;
this->m_image_view_create_info.subresourceRange.levelCount= 1;
this->m_image_view_create_info.subresourceRange.baseArrayLayer= 0;
this->m_image_view_create_info.subresourceRange.layerCount= 1;
this->m_image_view= new VkImageView();
result= vkCreateImageView(*this->m_device->get_logical_device(), &this->m_image_view_create_info, nullptr, this->m_image_view);
if (result != VK_SUCCESS) {
#ifdef DEBUG
std::cout << "Vulkan encountered an error creating the image view: " << result << std::endl;
#endif
throw std::exception("Could not create image view");
}
//
//Then set up render passes
//copied this from sample code developed by Dr. Mike Bailey at Oregon State University
//Doesn't really need to be changed yet so I'm attributing the original author because reasons
// need 2 - one for the color and one for the depth/stencil
VkAttachmentDescription vad[2];
//vad[0].format= VK_FORMAT_B8G8R8A8_UNORM;
vad[0].format= VK_FORMAT_B8G8R8A8_SRGB;
//vad[0].format= this->GetImageFormat();
vad[0].samples= VK_SAMPLE_COUNT_1_BIT;
vad[0].loadOp= VK_ATTACHMENT_LOAD_OP_CLEAR;
vad[0].storeOp= VK_ATTACHMENT_STORE_OP_STORE;
vad[0].stencilLoadOp= VK_ATTACHMENT_LOAD_OP_DONT_CARE;
vad[0].stencilStoreOp= VK_ATTACHMENT_STORE_OP_DONT_CARE;
vad[0].initialLayout= VK_IMAGE_LAYOUT_UNDEFINED;
vad[0].finalLayout= VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
vad[0].flags= 0;
//vad[0].flags= VK_ATTACHMENT_DESCRIPTION_MAT_ALIAS_BIT;
vad[1].format= VK_FORMAT_D32_SFLOAT_S8_UINT; //Note this is not using GetImageFormat because the depth format is different
vad[1].samples= VK_SAMPLE_COUNT_1_BIT;
vad[1].loadOp= VK_ATTACHMENT_LOAD_OP_CLEAR;
vad[1].storeOp= VK_ATTACHMENT_STORE_OP_DONT_CARE;
vad[1].stencilLoadOp= VK_ATTACHMENT_LOAD_OP_DONT_CARE;
vad[1].stencilStoreOp= VK_ATTACHMENT_STORE_OP_DONT_CARE;
vad[1].initialLayout= VK_IMAGE_LAYOUT_UNDEFINED;
vad[1].finalLayout= VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
vad[1].flags= 0;
VkAttachmentReference colorReference;
colorReference.attachment= 0;
colorReference.layout= VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
VkAttachmentReference depthReference;
depthReference.attachment= 1;
depthReference.layout= VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
VkSubpassDescription vsd;
vsd.flags= 0;
vsd.pipelineBindPoint= VK_PIPELINE_BIND_POINT_GRAPHICS;
vsd.inputAttachmentCount= 0;
vsd.pInputAttachments= (VkAttachmentReference*)nullptr;
vsd.colorAttachmentCount= 1;
vsd.pColorAttachments= &colorReference;
vsd.pResolveAttachments= (VkAttachmentReference*)nullptr;
vsd.pDepthStencilAttachment= &depthReference;
vsd.preserveAttachmentCount= 0;
vsd.pPreserveAttachments= (uint32_t*)nullptr;
this->m_render_pass_create_info.sType= VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
this->m_render_pass_create_info.pNext= nullptr;
this->m_render_pass_create_info.flags= 0;
this->m_render_pass_create_info.attachmentCount= 2;
this->m_render_pass_create_info.pAttachments= vad;
this->m_render_pass_create_info.subpassCount= 1;
this->m_render_pass_create_info.pSubpasses= &vsd;
this->m_render_pass_create_info.dependencyCount= 0;
this->m_render_pass_create_info.pDependencies= nullptr;
this->m_render_passes= new VkRenderPass();
result= vkCreateRenderPass(*this->m_device->get_logical_device(), &this->m_render_pass_create_info, nullptr, this->m_render_passes);
if (result != VK_SUCCESS) {
#ifdef DEBUG
std::cout << "Vulkan encountered an error creating the render pass: " << result << std::endl;
#endif
throw std::exception("Could not create render passes");
}
//
//Finally set up the frame buffer
this->m_framebuffers= new VkFramebuffer[this->m_framebuffer_count];
this->m_framebuffer_create_info.sType= VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
this->m_framebuffer_create_info.pNext= nullptr;
this->m_framebuffer_create_info.flags= 0;
this->m_framebuffer_create_info.renderPass= *this->m_render_passes;
this->m_framebuffer_create_info.attachmentCount= 2;
this->m_framebuffer_create_info.pAttachments= this->m_framebuffer_attachments;
this->m_framebuffer_create_info.width= this->m_extent_2D.width;
this->m_framebuffer_create_info.height= this->m_extent_2D.height;
this->m_framebuffer_create_info.layers= 1;
this->m_framebuffer_attachments[0]= this->m_present_image_views[0];
this->m_framebuffer_attachments[1]= *this->m_image_view;
result= vkCreateFramebuffer(*this->m_device->get_logical_device(), &this->m_framebuffer_create_info, nullptr, &this->m_framebuffers[0]);
if (result != VK_SUCCESS) {
#ifdef DEBUG
std::cout << "Vulkan encountered an error creating the first frame buffer: " << result << std::endl;
#endif
throw std::exception("Could not create first frame buffer");
}
this->m_framebuffer_attachments[0]= this->m_present_image_views[1];
this->m_framebuffer_attachments[1]= *this->m_image_view;
result= vkCreateFramebuffer(*this->m_device->get_logical_device(), &this->m_framebuffer_create_info, nullptr, &this->m_framebuffers[1]);
if (result != VK_SUCCESS) {
#ifdef DEBUG
std::cout << "Vulkan encountered an error creating the second frame buffer: " << result << std::endl;
#endif
throw std::exception("Could not create second frame buffer");
}
}
VkSwapchainKHR *c_view::get_swapchain() {
return &this->m_swapchain;
}
VkExtent2D c_view::get_extent_2D() {
return this->m_extent_2D;
}
VkRenderPass *c_view::get_render_pass() {
return this->m_render_passes;
}
VkFramebuffer *c_view::get_frame_buffers(int *out_count) {
if (out_count != nullptr) {
*out_count= this->m_framebuffer_count;
}
return this->m_framebuffers;
}
void c_view::set_closing_callback(std::function<void()> new_callback) {
this->m_closing_callback= new_callback;
}
void c_view::set_resize_callback(std::function<void(int, int)> new_callback) {
this->m_resize_callback= new_callback;
}
void c_view::resize(int x, int y) {
///TODO: implement this
} | 43.222222 | 181 | 0.783454 |
fd40420eed3530e8d6555fb6d2d9a3aea4dc90af | 4,550 | cc | C++ | content/browser/devtools/shared_worker_devtools_agent_host.cc | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | content/browser/devtools/shared_worker_devtools_agent_host.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | content/browser/devtools/shared_worker_devtools_agent_host.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/devtools/shared_worker_devtools_agent_host.h"
#include "content/browser/devtools/devtools_session.h"
#include "content/browser/devtools/protocol/inspector_handler.h"
#include "content/browser/devtools/protocol/network_handler.h"
#include "content/browser/devtools/protocol/protocol.h"
#include "content/browser/devtools/protocol/schema_handler.h"
#include "content/browser/devtools/shared_worker_devtools_manager.h"
#include "content/browser/shared_worker/shared_worker_host.h"
#include "content/browser/shared_worker/shared_worker_instance.h"
#include "content/browser/shared_worker/shared_worker_service_impl.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_process_host.h"
namespace content {
SharedWorkerDevToolsAgentHost::SharedWorkerDevToolsAgentHost(
SharedWorkerHost* worker_host,
const base::UnguessableToken& devtools_worker_token)
: DevToolsAgentHostImpl(devtools_worker_token.ToString()),
state_(WORKER_NOT_READY),
worker_host_(worker_host),
devtools_worker_token_(devtools_worker_token),
instance_(new SharedWorkerInstance(*worker_host->instance())) {
NotifyCreated();
}
SharedWorkerDevToolsAgentHost::~SharedWorkerDevToolsAgentHost() {
SharedWorkerDevToolsManager::GetInstance()->AgentHostDestroyed(this);
}
BrowserContext* SharedWorkerDevToolsAgentHost::GetBrowserContext() {
if (!worker_host_)
return nullptr;
RenderProcessHost* rph =
RenderProcessHost::FromID(worker_host_->process_id());
return rph ? rph->GetBrowserContext() : nullptr;
}
std::string SharedWorkerDevToolsAgentHost::GetType() {
return kTypeSharedWorker;
}
std::string SharedWorkerDevToolsAgentHost::GetTitle() {
return instance_->name();
}
GURL SharedWorkerDevToolsAgentHost::GetURL() {
return instance_->url();
}
bool SharedWorkerDevToolsAgentHost::Activate() {
return false;
}
void SharedWorkerDevToolsAgentHost::Reload() {
}
bool SharedWorkerDevToolsAgentHost::Close() {
if (worker_host_)
worker_host_->TerminateWorker();
return true;
}
bool SharedWorkerDevToolsAgentHost::AttachSession(DevToolsSession* session) {
session->AddHandler(std::make_unique<protocol::InspectorHandler>());
session->AddHandler(
std::make_unique<protocol::NetworkHandler>(GetId(), GetIOContext()));
session->AddHandler(std::make_unique<protocol::SchemaHandler>());
session->SetRenderer(worker_host_ ? worker_host_->process_id() : -1, nullptr);
if (state_ == WORKER_READY)
session->AttachToAgent(EnsureAgent());
return true;
}
void SharedWorkerDevToolsAgentHost::DetachSession(DevToolsSession* session) {
// Destroying session automatically detaches in renderer.
}
void SharedWorkerDevToolsAgentHost::DispatchProtocolMessage(
DevToolsSession* session,
const std::string& message) {
session->DispatchProtocolMessage(message);
}
bool SharedWorkerDevToolsAgentHost::Matches(SharedWorkerHost* worker_host) {
return instance_->Matches(*worker_host->instance());
}
void SharedWorkerDevToolsAgentHost::WorkerReadyForInspection() {
DCHECK_EQ(WORKER_NOT_READY, state_);
DCHECK(worker_host_);
state_ = WORKER_READY;
for (DevToolsSession* session : sessions())
session->AttachToAgent(EnsureAgent());
}
void SharedWorkerDevToolsAgentHost::WorkerRestarted(
SharedWorkerHost* worker_host) {
DCHECK_EQ(WORKER_TERMINATED, state_);
DCHECK(!worker_host_);
state_ = WORKER_NOT_READY;
worker_host_ = worker_host;
for (auto* inspector : protocol::InspectorHandler::ForAgentHost(this))
inspector->TargetReloadedAfterCrash();
for (DevToolsSession* session : sessions())
session->SetRenderer(worker_host_->process_id(), nullptr);
}
void SharedWorkerDevToolsAgentHost::WorkerDestroyed() {
DCHECK_NE(WORKER_TERMINATED, state_);
DCHECK(worker_host_);
state_ = WORKER_TERMINATED;
for (auto* inspector : protocol::InspectorHandler::ForAgentHost(this))
inspector->TargetCrashed();
for (DevToolsSession* session : sessions())
session->SetRenderer(-1, nullptr);
worker_host_ = nullptr;
agent_ptr_.reset();
}
const blink::mojom::DevToolsAgentAssociatedPtr&
SharedWorkerDevToolsAgentHost::EnsureAgent() {
DCHECK_EQ(WORKER_READY, state_);
DCHECK(worker_host_);
if (!agent_ptr_)
worker_host_->BindDevToolsAgent(mojo::MakeRequest(&agent_ptr_));
return agent_ptr_;
}
} // namespace content
| 33.455882 | 80 | 0.781099 |
fd4388dfd1ea017870625c4dc6aeff347a5b6371 | 4,640 | cpp | C++ | ProjectTimeConeLib/src/ProjectTimeCone/Initialisation/Initialiser.cpp | HellicarAndLewis/ProjectTimeCone | 8074c202d943c156168b0e550f8615cd350a6d98 | [
"MIT"
] | 3 | 2015-01-17T11:57:10.000Z | 2019-10-25T08:01:28.000Z | ProjectTimeConeLib/src/ProjectTimeCone/Initialisation/Initialiser.cpp | HellicarAndLewis/ProjectTimeCone | 8074c202d943c156168b0e550f8615cd350a6d98 | [
"MIT"
] | null | null | null | ProjectTimeConeLib/src/ProjectTimeCone/Initialisation/Initialiser.cpp | HellicarAndLewis/ProjectTimeCone | 8074c202d943c156168b0e550f8615cd350a6d98 | [
"MIT"
] | 1 | 2018-10-19T04:57:29.000Z | 2018-10-19T04:57:29.000Z | #include "Initialiser.h"
using namespace ofxMachineVision;
namespace ProjectTimeCone {
namespace Initialisation {
#pragma mark CameraController
//--------------------------------------------------------------
CameraController::CameraController(int index, ofPtr<ofxMachineVision::Grabber::Simple> grabber) {
this->index = index;
this->grabber = grabber;
this->setAllFromThis = false;
this->load();
}
//--------------------------------------------------------------
void CameraController::onControlChange(ofxUIEventArgs & args) {
if(args.widget->getName() == "Exposure") {
this->setExposure(this->exposure, true);
} else if (args.widget->getName() == "Gain") {
this->setGain(this->gain, true);
} else if (args.widget->getName() == "Focus") {
this->setFocus(this->focus, true);
}
}
//--------------------------------------------------------------
void CameraController::setExposure(float exposure, bool setOthers) {
this->exposure = exposure;
this->grabber->setExposure(exposure);
if (setOthers && this->setAllFromThis) {
this->onExposureChangeAll(exposure);
}
this->save();
}
//--------------------------------------------------------------
void CameraController::setGain(float gain, bool setOthers) {
this->gain = gain;
this->grabber->setGain(gain);
if (setOthers && this->setAllFromThis) {
this->onGainChangeAll(gain);
}
this->save();
}
//--------------------------------------------------------------
void CameraController::setFocus(float focus, bool setOthers) {
this->focus = focus;
this->grabber->setFocus(focus);
if (setOthers && this->setAllFromThis) {
this->onFocusChangeAll(focus);
}
this->save();
}
//--------------------------------------------------------------
string CameraController::getFilename() const {
return "../../../Data/camera" + ofToString(this->index) + ".xml";
}
//--------------------------------------------------------------
void CameraController::load() {
if (this->xml.load(this->getFilename())) {
;
this->setExposure(this->xml.getValue<float>("//Exposure"), false);
this->setGain(this->xml.getValue<float>("//Gain"), false);
this->setFocus(this->xml.getValue<float>("//Focus"), false);
xml.setTo("//CameraSettings");
} else {
this->xml.clear();
this->xml.addChild("CameraSettings");
this->xml.setTo("//CameraSettings");
this->xml.addValue("Exposure", ofToString(this->exposure));
this->xml.addValue("Gain", ofToString(this->gain));
this->xml.addValue("Focus", ofToString(this->focus));
this->exposure = 500;
this->focus = 0;
this->gain = 0;
}
}
//--------------------------------------------------------------
void CameraController::save() {
this->xml.setTo("//CameraSettings");
this->xml.setValue("Exposure", ofToString(this->exposure));
this->xml.setValue("Gain", ofToString(this->gain));
this->xml.setValue("Focus", ofToString(this->focus));
this->xml.save(this->getFilename());
}
#pragma mark Initialiser
//---------
void Initialiser::LoadCameras(std::vector<ofPtr<CameraController>> & controllers, std::function<void (ofPtr<CameraController>)> functor,
int width, int height) {
//order is a vector where
// - order of vector is order of devices
// - content of vector is index of devices
vector<int> order;
try {
ofFile load(ORDER_FILENAME, ofFile::ReadOnly, true);
int count = load.getPocoFile().getSize() / sizeof(int);
order.resize(count);
load.read((char*) &order[0], sizeof(int) * count);
load.close();
} catch(...) {
ofSystemAlertDialog("Couldn't load camera order, please place save.bin into data folder.");
std::exit(1);
}
videoInput deviceEnumerator;
auto deviceCount = deviceEnumerator.listDevices();
if (deviceCount != order.size()) {
ofSystemAlertDialog("We've saved the order for a different number of cameras");
std::exit(1);
}
controllers.resize(deviceCount);
int index = 0;
for(auto deviceIndex : order) {
auto device = DevicePtr(new Device::VideoInputDevice(1280, 720));
auto grabber = ofPtr<Grabber::Simple>(new Grabber::Simple(device));
grabber->open(deviceIndex);
grabber->startCapture();
auto controller = ofPtr<CameraController>(new CameraController(index, grabber));
functor(controller);
controllers[index] = controller;
index++;
}
}
//---------
void Initialiser::FillDevelopmentScreens() {
ofSetWindowPosition(1920,0);
ofSetWindowShape(1080 * 2, 1920);
}
}
} | 32.907801 | 139 | 0.578664 |
fd4408ee86a9d054d4044866ece60bfb2d85b646 | 2,937 | cc | C++ | webserver/libwebserv/request_utils.cc | emersion/chromiumos-platform2 | ba71ad06f7ba52e922c647a8915ff852b2d4ebbd | [
"BSD-3-Clause"
] | 5 | 2019-01-19T15:38:48.000Z | 2021-10-06T03:59:46.000Z | webserver/libwebserv/request_utils.cc | emersion/chromiumos-platform2 | ba71ad06f7ba52e922c647a8915ff852b2d4ebbd | [
"BSD-3-Clause"
] | null | null | null | webserver/libwebserv/request_utils.cc | emersion/chromiumos-platform2 | ba71ad06f7ba52e922c647a8915ff852b2d4ebbd | [
"BSD-3-Clause"
] | 1 | 2019-02-15T23:05:30.000Z | 2019-02-15T23:05:30.000Z | // Copyright 2015 The Android Open Source Project
//
// 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 <libwebserv/request_utils.h>
#include <utility>
#include <base/bind.h>
#include <brillo/streams/memory_stream.h>
#include <brillo/streams/stream_utils.h>
#include <libwebserv/request.h>
#include <libwebserv/response.h>
namespace libwebserv {
namespace {
struct RequestDataContainer {
std::unique_ptr<Request> request;
std::unique_ptr<Response> response;
GetRequestDataSuccessCallback success_callback;
GetRequestDataErrorCallback error_callback;
std::vector<uint8_t> data;
};
void OnCopySuccess(std::shared_ptr<RequestDataContainer> container,
brillo::StreamPtr /* in_stream */,
brillo::StreamPtr out_stream,
uint64_t /* size_copied */) {
// Close/release the memory stream so we can work with underlying data buffer.
out_stream->CloseBlocking(nullptr);
out_stream.reset();
container->success_callback.Run(std::move(container->request),
std::move(container->response),
std::move(container->data));
}
void OnCopyError(std::shared_ptr<RequestDataContainer> container,
brillo::StreamPtr /* in_stream */,
brillo::StreamPtr /* out_stream */,
const brillo::Error* error) {
container->error_callback.Run(std::move(container->request),
std::move(container->response), error);
}
} // anonymous namespace
void GetRequestData(std::unique_ptr<Request> request,
std::unique_ptr<Response> response,
const GetRequestDataSuccessCallback& success_callback,
const GetRequestDataErrorCallback& error_callback) {
auto container = std::make_shared<RequestDataContainer>();
auto in_stream = request->GetDataStream();
auto out_stream =
brillo::MemoryStream::CreateRef(&container->data, nullptr);
container->request = std::move(request);
container->response = std::move(response);
container->success_callback = success_callback;
container->error_callback = error_callback;
brillo::stream_utils::CopyData(std::move(in_stream), std::move(out_stream),
base::Bind(&OnCopySuccess, container),
base::Bind(&OnCopyError, container));
}
} // namespace libwebserv
| 38.142857 | 80 | 0.677562 |
fd475727ae2c507e53318e34ee7a5ba5fe66d3e7 | 4,400 | cpp | C++ | dwarf/SB/Game/zCamMarker.cpp | stravant/bfbbdecomp | 2126be355a6bb8171b850f829c1f2731c8b5de08 | [
"OLDAP-2.7"
] | 1 | 2021-01-05T11:28:55.000Z | 2021-01-05T11:28:55.000Z | dwarf/SB/Game/zCamMarker.cpp | sonich2401/bfbbdecomp | 5f58b62505f8929a72ccf2aa118a1539eb3a5bd6 | [
"OLDAP-2.7"
] | null | null | null | dwarf/SB/Game/zCamMarker.cpp | sonich2401/bfbbdecomp | 5f58b62505f8929a72ccf2aa118a1539eb3a5bd6 | [
"OLDAP-2.7"
] | 1 | 2022-03-30T15:15:08.000Z | 2022-03-30T15:15:08.000Z | typedef struct xCamAsset;
typedef struct zCamMarker;
typedef struct xSerial;
typedef struct _tagxCamFollowAsset;
typedef struct xBase;
typedef struct xVec3;
typedef struct _tagxCamShoulderAsset;
typedef struct xLinkAsset;
typedef struct xBaseAsset;
typedef struct _tagp2CamStaticAsset;
typedef struct _tagp2CamStaticFollowAsset;
typedef enum _tagTransType;
typedef struct _tagxCamPathAsset;
typedef int32(*type_1)(xBase*, xBase*, uint32, float32*, xBase*);
typedef int32(*type_4)(xBase*, xBase*, uint32, float32*, xBase*);
typedef float32 type_0[4];
typedef uint32 type_2[2];
typedef uint8 type_3[3];
struct xCamAsset : xBaseAsset
{
xVec3 pos;
xVec3 at;
xVec3 up;
xVec3 right;
xVec3 view_offset;
int16 offset_start_frames;
int16 offset_end_frames;
float32 fov;
float32 trans_time;
_tagTransType trans_type;
uint32 flags;
float32 fade_up;
float32 fade_down;
union
{
_tagxCamFollowAsset cam_follow;
_tagxCamShoulderAsset cam_shoulder;
_tagp2CamStaticAsset cam_static;
_tagxCamPathAsset cam_path;
_tagp2CamStaticFollowAsset cam_staticFollow;
};
uint32 valid_flags;
uint32 markerid[2];
uint8 cam_type;
uint8 pad[3];
};
struct zCamMarker : xBase
{
xCamAsset* asset;
};
struct xSerial
{
};
struct _tagxCamFollowAsset
{
float32 rotation;
float32 distance;
float32 height;
float32 rubber_band;
float32 start_speed;
float32 end_speed;
};
struct xBase
{
uint32 id;
uint8 baseType;
uint8 linkCount;
uint16 baseFlags;
xLinkAsset* link;
int32(*eventFunc)(xBase*, xBase*, uint32, float32*, xBase*);
};
struct xVec3
{
float32 x;
float32 y;
float32 z;
};
struct _tagxCamShoulderAsset
{
float32 distance;
float32 height;
float32 realign_speed;
float32 realign_delay;
};
struct xLinkAsset
{
uint16 srcEvent;
uint16 dstEvent;
uint32 dstAssetID;
float32 param[4];
uint32 paramWidgetAssetID;
uint32 chkAssetID;
};
struct xBaseAsset
{
uint32 id;
uint8 baseType;
uint8 linkCount;
uint16 baseFlags;
};
struct _tagp2CamStaticAsset
{
uint32 unused;
};
struct _tagp2CamStaticFollowAsset
{
float32 rubber_band;
};
enum _tagTransType
{
eTransType_None,
eTransType_Interp1,
eTransType_Interp2,
eTransType_Interp3,
eTransType_Interp4,
eTransType_Linear,
eTransType_Interp1Rev,
eTransType_Interp2Rev,
eTransType_Interp3Rev,
eTransType_Interp4Rev,
eTransType_Total
};
struct _tagxCamPathAsset
{
uint32 assetID;
float32 time_end;
float32 time_delay;
};
int32(*zCamMarkerEventCB)(xBase*, xBase*, uint32, float32*, xBase*);
int32 zCamMarkerEventCB(xBase* to, uint32 toEvent, float32* toParam);
void zCamMarkerLoad(zCamMarker* m, xSerial* s);
void zCamMarkerSave(zCamMarker* m, xSerial* s);
void zCamMarkerInit(xBase* b, xCamAsset* asset);
// zCamMarkerEventCB__FP5xBaseP5xBaseUiPCfP5xBase
// Start address: 0x310910
int32 zCamMarkerEventCB(xBase* to, uint32 toEvent, float32* toParam)
{
// Line 47, Address: 0x310910, Func Offset: 0
// Line 51, Address: 0x310914, Func Offset: 0x4
// Line 59, Address: 0x310948, Func Offset: 0x38
// Line 60, Address: 0x310954, Func Offset: 0x44
// Line 62, Address: 0x31095c, Func Offset: 0x4c
// Line 63, Address: 0x310960, Func Offset: 0x50
// Line 64, Address: 0x310968, Func Offset: 0x58
// Line 67, Address: 0x310970, Func Offset: 0x60
// Line 72, Address: 0x310978, Func Offset: 0x68
// Line 71, Address: 0x31097c, Func Offset: 0x6c
// Line 72, Address: 0x310980, Func Offset: 0x70
// Func End, Address: 0x310988, Func Offset: 0x78
}
// zCamMarkerLoad__FP10zCamMarkerP7xSerial
// Start address: 0x310990
void zCamMarkerLoad(zCamMarker* m, xSerial* s)
{
// Line 38, Address: 0x310990, Func Offset: 0
// Func End, Address: 0x310998, Func Offset: 0x8
}
// zCamMarkerSave__FP10zCamMarkerP7xSerial
// Start address: 0x3109a0
void zCamMarkerSave(zCamMarker* m, xSerial* s)
{
// Line 29, Address: 0x3109a0, Func Offset: 0
// Func End, Address: 0x3109a8, Func Offset: 0x8
}
// zCamMarkerInit__FP5xBaseP9xCamAsset
// Start address: 0x3109b0
void zCamMarkerInit(xBase* b, xCamAsset* asset)
{
// Line 10, Address: 0x3109b0, Func Offset: 0
// Line 12, Address: 0x3109c4, Func Offset: 0x14
// Line 17, Address: 0x3109cc, Func Offset: 0x1c
// Line 18, Address: 0x3109d8, Func Offset: 0x28
// Line 21, Address: 0x3109e0, Func Offset: 0x30
// Line 23, Address: 0x3109ec, Func Offset: 0x3c
// Line 24, Address: 0x3109f0, Func Offset: 0x40
// Func End, Address: 0x310a04, Func Offset: 0x54
}
| 22 | 69 | 0.76 |
fd47afe859506578fb0db6362b231e20b435202e | 2,634 | cpp | C++ | src/services/pcn-k8sfilter/src/serializer/K8sfilterJsonObject.cpp | francescomessina/polycube | 38f2fb4ffa13cf51313b3cab9994be738ba367be | [
"ECL-2.0",
"Apache-2.0"
] | 337 | 2018-12-12T11:50:15.000Z | 2022-03-15T00:24:35.000Z | src/services/pcn-k8sfilter/src/serializer/K8sfilterJsonObject.cpp | l1b0k/polycube | 7af919245c131fa9fe24c5d39d10039cbb81e825 | [
"ECL-2.0",
"Apache-2.0"
] | 253 | 2018-12-17T21:36:15.000Z | 2022-01-17T09:30:42.000Z | src/services/pcn-k8sfilter/src/serializer/K8sfilterJsonObject.cpp | l1b0k/polycube | 7af919245c131fa9fe24c5d39d10039cbb81e825 | [
"ECL-2.0",
"Apache-2.0"
] | 90 | 2018-12-19T15:49:38.000Z | 2022-03-27T03:56:07.000Z | /**
* k8sfilter API
* k8sfilter API generated from k8sfilter.yang
*
* OpenAPI spec version: 1.0.0
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/polycube-network/swagger-codegen.git
* branch polycube
*/
/* Do not edit this file manually */
#include "K8sfilterJsonObject.h"
#include <regex>
namespace io {
namespace swagger {
namespace server {
namespace model {
K8sfilterJsonObject::K8sfilterJsonObject() {
m_nameIsSet = false;
m_portsIsSet = false;
m_nodeportRange = "30000-32767";
m_nodeportRangeIsSet = true;
}
K8sfilterJsonObject::K8sfilterJsonObject(const nlohmann::json &val) :
JsonObjectBase(val) {
m_nameIsSet = false;
m_portsIsSet = false;
m_nodeportRangeIsSet = false;
if (val.count("name")) {
setName(val.at("name").get<std::string>());
}
if (val.count("ports")) {
for (auto& item : val["ports"]) {
PortsJsonObject newItem{ item };
m_ports.push_back(newItem);
}
m_portsIsSet = true;
}
if (val.count("nodeport-range")) {
setNodeportRange(val.at("nodeport-range").get<std::string>());
}
}
nlohmann::json K8sfilterJsonObject::toJson() const {
nlohmann::json val = nlohmann::json::object();
if (!getBase().is_null()) {
val.update(getBase());
}
if (m_nameIsSet) {
val["name"] = m_name;
}
{
nlohmann::json jsonArray;
for (auto& item : m_ports) {
jsonArray.push_back(JsonObjectBase::toJson(item));
}
if (jsonArray.size() > 0) {
val["ports"] = jsonArray;
}
}
if (m_nodeportRangeIsSet) {
val["nodeport-range"] = m_nodeportRange;
}
return val;
}
std::string K8sfilterJsonObject::getName() const {
return m_name;
}
void K8sfilterJsonObject::setName(std::string value) {
m_name = value;
m_nameIsSet = true;
}
bool K8sfilterJsonObject::nameIsSet() const {
return m_nameIsSet;
}
const std::vector<PortsJsonObject>& K8sfilterJsonObject::getPorts() const{
return m_ports;
}
void K8sfilterJsonObject::addPorts(PortsJsonObject value) {
m_ports.push_back(value);
m_portsIsSet = true;
}
bool K8sfilterJsonObject::portsIsSet() const {
return m_portsIsSet;
}
void K8sfilterJsonObject::unsetPorts() {
m_portsIsSet = false;
}
std::string K8sfilterJsonObject::getNodeportRange() const {
return m_nodeportRange;
}
void K8sfilterJsonObject::setNodeportRange(std::string value) {
m_nodeportRange = value;
m_nodeportRangeIsSet = true;
}
bool K8sfilterJsonObject::nodeportRangeIsSet() const {
return m_nodeportRangeIsSet;
}
void K8sfilterJsonObject::unsetNodeportRange() {
m_nodeportRangeIsSet = false;
}
}
}
}
}
| 18.680851 | 75 | 0.69552 |
fd4c453e0c95352b913e3bcaa07432714103ca73 | 606 | cpp | C++ | sprint05/t04/app/src/Soldier.cpp | arni30/marathon-cpp | b8716599a891e2c534f2d63dd662931fe098e36a | [
"MIT"
] | null | null | null | sprint05/t04/app/src/Soldier.cpp | arni30/marathon-cpp | b8716599a891e2c534f2d63dd662931fe098e36a | [
"MIT"
] | null | null | null | sprint05/t04/app/src/Soldier.cpp | arni30/marathon-cpp | b8716599a891e2c534f2d63dd662931fe098e36a | [
"MIT"
] | null | null | null | #include "Soldier.h"
Soldier::Soldier(std::string&& name, int health) :m_health(health), m_name(name){
std::cout << "Soldier " << m_name << " was created" << std::endl;
}
Soldier::~Soldier() {
std::cout << "Soldier " << m_name << " was deleted" << std::endl;
}
void Soldier::setWeapon(Weapon* weapon) {
m_weapon = weapon;
}
int Soldier::getHealth() const {
return m_health;
}
void Soldier::attack(Soldier& other) {
other.m_health -= m_weapon->getDamage();
std::cout << m_name << " attacks " << other.m_name << " and deals " << m_weapon->getDamage() << " damage" << std::endl;
}
| 30.3 | 125 | 0.618812 |
fd4f885e8e2a92839403ee05655e3fa61ab11c12 | 1,952 | cpp | C++ | staff/samples/optional/component/src/TasksImpl.cpp | gale320/staff | c90e65a984e9931d803fc88243971639fe3876b7 | [
"Apache-2.0"
] | 14 | 2015-04-04T17:42:53.000Z | 2021-03-09T11:09:51.000Z | staff/samples/optional/component/src/TasksImpl.cpp | gale320/staff | c90e65a984e9931d803fc88243971639fe3876b7 | [
"Apache-2.0"
] | 3 | 2015-07-30T13:22:42.000Z | 2017-06-06T15:13:28.000Z | staff/samples/optional/component/src/TasksImpl.cpp | gale320/staff | c90e65a984e9931d803fc88243971639fe3876b7 | [
"Apache-2.0"
] | 13 | 2015-04-25T20:43:45.000Z | 2021-12-29T07:55:47.000Z | // This file generated by staff_codegen
// For more information please visit: http://code.google.com/p/staff/
// Service Implementation
#include "TasksImpl.h"
namespace samples
{
namespace optional
{
TasksImpl::TasksImpl()
{
}
TasksImpl::~TasksImpl()
{
}
void TasksImpl::OnCreate()
{
// this function is called when service instance is created and registered
}
void TasksImpl::OnDestroy()
{
// this function is called immediately before service instance destruction
}
int TasksImpl::Add(const Task& rstTask)
{
Task& rstAddedTask = *m_lsTasks.insert(m_lsTasks.end(), rstTask);
rstAddedTask.nId = m_lsTasks.size();
return *rstAddedTask.nId;
}
void TasksImpl::UpdateOwner(int nTaskId, const staff::Optional< int >& rtnOwnerId)
{
for (TasksList::iterator itTask = m_lsTasks.begin();
itTask != m_lsTasks.end(); ++itTask)
{
if (itTask->nId == nTaskId)
{
itTask->tnOwnerId = rtnOwnerId;
break;
}
}
}
void TasksImpl::UpdateAttachInfo(int nTaskId, const staff::Optional< AttachInfo >& rtnAttachInfo)
{
for (TasksList::iterator itTask = m_lsTasks.begin();
itTask != m_lsTasks.end(); ++itTask)
{
if (itTask->nId == nTaskId)
{
itTask->tstAttachInfo = rtnAttachInfo;
break;
}
}
}
staff::Optional< AttachInfo > samples::optional::TasksImpl::GetAttachInfo(int nTaskId)
{
for (TasksList::iterator itTask = m_lsTasks.begin();
itTask != m_lsTasks.end(); ++itTask)
{
if (itTask->nId == nTaskId)
{
return itTask->tstAttachInfo;
}
}
return staff::Optional< AttachInfo >();
}
::samples::optional::TasksList TasksImpl::GetAllTasks() const
{
return m_lsTasks;
}
staff::Optional< std::list<std::string> > TasksImpl::EchoOpt(
const staff::Optional< std::list<std::string> >& opt)
{
return opt;
}
std::list< staff::Optional<std::string> > TasksImpl::EchoOpt2(
const std::list< staff::Optional<std::string> >& opt)
{
return opt;
}
}
}
| 19.717172 | 97 | 0.674693 |
fd5134bdb38c6445f558d74504981cf0649ff898 | 45,308 | cc | C++ | src/main/cpp/controller/controller.cc | rdfostrich/cobra | b65ec1aa7b10e990a3b40d86636050377ff2d2d6 | [
"MIT"
] | 4 | 2020-07-02T12:11:41.000Z | 2021-11-03T13:44:57.000Z | src/main/cpp/controller/controller.cc | rdfostrich/cobra | b65ec1aa7b10e990a3b40d86636050377ff2d2d6 | [
"MIT"
] | 6 | 2021-06-14T11:34:39.000Z | 2021-06-29T15:10:16.000Z | src/main/cpp/controller/controller.cc | rdfostrich/cobra | b65ec1aa7b10e990a3b40d86636050377ff2d2d6 | [
"MIT"
] | 1 | 2021-05-20T14:16:24.000Z | 2021-05-20T14:16:24.000Z | #include <util/StopWatch.hpp>
#include "controller.h"
#include "snapshot_patch_iterator_triple_id.h"
#include "patch_builder_streaming.h"
#include "../snapshot/combined_triple_iterator.h"
#include "../simpleprogresslistener.h"
#include <sys/stat.h>
#include <boost/filesystem.hpp>
Controller::Controller(string basePath, int8_t kc_opts, bool readonly) : patchTreeManager(new PatchTreeManager(basePath, kc_opts, readonly)), snapshotManager(new SnapshotManager(basePath, readonly)) {
struct stat sb;
if (!(stat(basePath.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode))) {
throw std::invalid_argument("The provided path '" + basePath + "' is not a valid directory.");
}
}
Controller::~Controller() {
delete patchTreeManager;
delete snapshotManager;
}
size_t Controller::get_version_materialized_count_estimated(const Triple& triple_pattern, int patch_id) const {
return get_version_materialized_count(triple_pattern, patch_id, true).first;
}
std::pair<size_t, ResultEstimationType> Controller::get_version_materialized_count(const Triple& triple_pattern, int patch_id, bool allowEstimates) const {
int snapshot_id = get_corresponding_snapshot_id(patch_id);
if(snapshot_id < 0) {
return std::make_pair(0, EXACT);
}
HDT* snapshot = get_snapshot_manager()->get_snapshot(snapshot_id);
IteratorTripleID* snapshot_it = SnapshotManager::search_with_offset(snapshot, triple_pattern, 0);
size_t snapshot_count = snapshot_it->estimatedNumResults();
if (!allowEstimates && snapshot_it->numResultEstimation() != EXACT) {
snapshot_count = 0;
while (snapshot_it->hasNext()) {
snapshot_it->next();
snapshot_count++;
}
}
if(snapshot_id == patch_id) {
return std::make_pair(snapshot_count, snapshot_it->numResultEstimation());
}
DictionaryManager *dict = get_snapshot_manager()->get_dictionary_manager(snapshot_id);
int patch_tree_id = get_patch_tree_id(patch_id);
PatchTree* patchTree = get_patch_tree_manager()->get_patch_tree(patch_tree_id, dict);
if(patchTree == NULL) {
return std::make_pair(snapshot_count, snapshot_it->numResultEstimation());
}
std::pair<PatchPosition, Triple> deletion_count_data = patchTree->deletion_count(triple_pattern, patch_id);
size_t addition_count = patchTree->addition_count(patch_id, triple_pattern);
return std::make_pair(snapshot_count - deletion_count_data.first + addition_count, snapshot_it->numResultEstimation());
}
TripleIterator* Controller::get_version_materialized(const Triple &triple_pattern, int offset, int patch_id) const {
// Find the snapshot
int snapshot_id = get_corresponding_snapshot_id(patch_id);
if(snapshot_id < 0) {
//throw std::invalid_argument("No snapshot was found for version " + std::to_string(patch_id));
return new EmptyTripleIterator();
}
HDT* snapshot = get_snapshot_manager()->get_snapshot(snapshot_id);
// Simple case: We are requesting a snapshot, delegate lookup to that snapshot.
IteratorTripleID* snapshot_it = SnapshotManager::search_with_offset(snapshot, triple_pattern, offset);
if(snapshot_id == patch_id) {
return new SnapshotTripleIterator(snapshot_it);
}
DictionaryManager *dict = get_snapshot_manager()->get_dictionary_manager(snapshot_id);
// Otherwise, we have to prepare an iterator for a certain patch
int patch_tree_id = get_patch_tree_id(patch_id);
PatchTree* patchTree = get_patch_tree_manager()->get_patch_tree(patch_tree_id, dict);
if(patchTree == NULL) {
return new SnapshotTripleIterator(snapshot_it);
}
PositionedTripleIterator* deletion_it = NULL;
long added_offset = 0;
bool check_offseted_deletions = true;
// Limit the patch id to the latest available patch id
// int max_patch_id = patchTree->get_max_patch_id();
// if (patch_id > max_patch_id) {
// patch_id = max_patch_id;
// }
std::pair<PatchPosition, Triple> deletion_count_data = patchTree->deletion_count(triple_pattern, patch_id);
// This loop continuously determines new snapshot iterators until it finds one that contains
// no new deletions with respect to the snapshot iterator from last iteration.
// This loop is required to handle special cases like the one in the ControllerTest::EdgeCase1.
// As worst-case, this loop will take O(n) (n:dataset size), as an optimization we can look
// into storing long consecutive chains of deletions more efficiently.
while(check_offseted_deletions) {
if (snapshot_it->hasNext()) { // We have elements left in the snapshot we should apply deletions to
// Determine the first triple in the original snapshot and use it as offset for the deletion iterator
TripleID *tripleId = snapshot_it->next();
Triple firstTriple(tripleId->getSubject(), tripleId->getPredicate(), tripleId->getObject());
deletion_it = patchTree->deletion_iterator_from(firstTriple, patch_id, triple_pattern);
deletion_it->getPatchTreeIterator()->set_early_break(true);
// Calculate a new offset, taking into account deletions.
PositionedTriple first_deletion_triple;
long snapshot_offset = 0;
if (deletion_it->next(&first_deletion_triple, true)) {
snapshot_offset = first_deletion_triple.position;
} else {
// The exact snapshot triple could not be found as a deletion
if (patchTree->get_spo_comparator()->compare(firstTriple, deletion_count_data.second) < 0) {
// If the snapshot triple is smaller than the largest deletion,
// set the offset to zero, as all deletions will come *after* this triple.
// Note that it should impossible that there would exist a deletion *before* this snapshot triple,
// otherwise we would already have found this triple as a snapshot triple before.
// If we would run into issues because of this after all, we could do a backwards step with
// deletion_it and see if we find a triple matching the pattern, and use its position.
snapshot_offset = 0;
} else {
// If the snapshot triple is larger than the largest deletion,
// set the offset to the total number of deletions.
snapshot_offset = deletion_count_data.first;
}
}
long previous_added_offset = added_offset;
added_offset = snapshot_offset;
// Make a new snapshot iterator for the new offset
// TODO: look into reusing the snapshot iterator and applying a relative offset (NOTE: I tried it before, it's trickier than it seems...)
delete snapshot_it;
snapshot_it = SnapshotManager::search_with_offset(snapshot, triple_pattern, offset + added_offset);
// Check if we need to loop again
check_offseted_deletions = previous_added_offset < added_offset;
if(check_offseted_deletions) {
delete deletion_it;
deletion_it = NULL;
}
} else {
check_offseted_deletions = false;
}
}
return new SnapshotPatchIteratorTripleID(snapshot_it, deletion_it, patchTree->get_spo_comparator(), snapshot, triple_pattern, patchTree, patch_id, offset, deletion_count_data.first);
}
std::pair<size_t, ResultEstimationType> Controller::get_delta_materialized_count(const Triple &triple_pattern, int patch_id_start, int patch_id_end, bool allowEstimates) const {
int snapshot_id_start = get_corresponding_snapshot_id(patch_id_start);
int snapshot_id_end = get_corresponding_snapshot_id(patch_id_end);
int patch_tree_id_end = get_patch_tree_id(patch_id_end);
int patch_tree_id_start = get_patch_tree_id(patch_id_start);
// S_start <- P <- P_end
if(snapshot_id_start == patch_id_start){
DictionaryManager *dict = get_snapshot_manager()->get_dictionary_manager(snapshot_id_start);
PatchTree* patchTree = get_patch_tree_manager()->get_patch_tree(patch_tree_id_end, dict);
size_t count = patchTree->deletion_count(triple_pattern, patch_id_end).first + patchTree->addition_count(patch_id_end, triple_pattern);
return std::make_pair(count, EXACT);
}
//P_start -> P -> S_end
else if(snapshot_id_end == patch_id_end){
DictionaryManager *dict = get_snapshot_manager()->get_dictionary_manager(snapshot_id_end);
PatchTree* patchTree = get_patch_tree_manager()->get_patch_tree(patch_tree_id_start, dict);
size_t count = patchTree->deletion_count(triple_pattern, patch_id_start).first + patchTree->addition_count(patch_id_start, triple_pattern);
return std::make_pair(count, EXACT);
}
// reverse tree and forward tree case P_start -> S <- P_end
else if(snapshot_id_start > patch_id_start && snapshot_id_end < patch_id_end) {
DictionaryManager *dict = get_snapshot_manager()->get_dictionary_manager(snapshot_id_end);
PatchTree* patchTreeForward = get_patch_tree_manager()->get_patch_tree(patch_tree_id_end, dict);
PatchTree* patchTreeReverse = get_patch_tree_manager()->get_patch_tree(patch_tree_id_start, dict);
size_t count = patchTreeForward->deletion_count(triple_pattern, patch_id_end).first + patchTreeForward->addition_count(patch_id_end, triple_pattern) + patchTreeReverse->deletion_count(triple_pattern, patch_id_start).first + patchTreeReverse->addition_count(patch_id_start, triple_pattern);
return std::make_pair(count, UP_TO);
}
else{
if (allowEstimates) {
DictionaryManager *dict = get_snapshot_manager()->get_dictionary_manager(snapshot_id_start);
PatchTree* patchTree = get_patch_tree_manager()->get_patch_tree(patch_tree_id_start, dict);
size_t count_start = patchTree->deletion_count(triple_pattern, patch_id_start).first + patchTree->addition_count(patch_id_start, triple_pattern);
size_t count_end = patchTree->deletion_count(triple_pattern, patch_id_end).first + patchTree->addition_count(patch_id_end, triple_pattern);
// There may be an overlap between the delta-triples from start and end.
// This overlap is not easy to determine, so we ignore it when possible.
// The real count will never be higher this value, because we should subtract the overlap count.
return std::make_pair(count_start + count_end, UP_TO);
} else {
return std::make_pair(get_delta_materialized(triple_pattern, 0, patch_id_start, patch_id_end)->get_count(), EXACT);
}
}
}
size_t Controller::get_delta_materialized_count_estimated(const Triple &triple_pattern, int patch_id_start, int patch_id_end) const {
return get_delta_materialized_count(triple_pattern, patch_id_start, patch_id_end, true).second;
}
TripleDeltaIterator* Controller::get_delta_materialized(const Triple &triple_pattern, int offset, int patch_id_start,
int patch_id_end) const {
if (patch_id_end <= patch_id_start) {
return new EmptyTripleDeltaIterator();
}
// Find the snapshot
int snapshot_id_start = get_corresponding_snapshot_id(patch_id_start);
int snapshot_id_end = get_corresponding_snapshot_id(patch_id_end);
if (snapshot_id_start < 0 || snapshot_id_end < 0) {
return new EmptyTripleDeltaIterator();
}
// start = snapshot, end = snapshot
if(snapshot_id_start == patch_id_start && snapshot_id_end == patch_id_end) {
// TODO: implement this when multiple snapshots are supported
throw std::invalid_argument("Multiple snapshots are not supported.");
}
// start = snapshot, end = patch
if(snapshot_id_start == patch_id_start && snapshot_id_end != patch_id_end) {
DictionaryManager *dict = get_snapshot_manager()->get_dictionary_manager(snapshot_id_end);
if (snapshot_id_start == snapshot_id_end) {
// Return iterator for the end patch relative to the start snapshot
int patch_tree_id = get_patch_tree_id(patch_id_end);
PatchTree* patchTree = get_patch_tree_manager()->get_patch_tree(patch_tree_id, dict);
if(patchTree == NULL) {
throw std::invalid_argument("Could not find the given end patch id");
}
if (TripleStore::is_default_tree(triple_pattern)) {
return (new ForwardPatchTripleDeltaIterator<PatchTreeDeletionValue>(patchTree, triple_pattern, patch_id_end))->offset(offset);
} else {
return (new ForwardPatchTripleDeltaIterator<PatchTreeDeletionValueReduced>(patchTree, triple_pattern, patch_id_end))->offset(offset);
}
} else {
// TODO: implement this when multiple snapshots are supported
throw std::invalid_argument("Multiple snapshots are not supported.");
}
}
// start = patch, end = snapshot
if(snapshot_id_start != patch_id_start && snapshot_id_end == patch_id_end) {
DictionaryManager *dict = get_snapshot_manager()->get_dictionary_manager(snapshot_id_end);
if (snapshot_id_start == snapshot_id_end) {
// Return iterator for the end patch relative to the start snapshot
int patch_tree_id = get_patch_tree_id(patch_id_start);
PatchTree* patchTree = get_patch_tree_manager()->get_patch_tree(patch_tree_id, dict);
if(patchTree == NULL) {
throw std::invalid_argument("Could not find the given end patch id");
}
if (TripleStore::is_default_tree(triple_pattern)) {
return (new ForwardPatchTripleDeltaIterator<PatchTreeDeletionValue>(patchTree, triple_pattern, patch_id_start))->offset(offset);
} else {
return (new ForwardPatchTripleDeltaIterator<PatchTreeDeletionValueReduced>(patchTree, triple_pattern, patch_id_start))->offset(offset);
}
} else {
// TODO: implement this when multiple snapshots are supported
throw std::invalid_argument("Multiple snapshots are not supported.");
}
// // TODO: implement this when multiple snapshots are supported
// throw std::invalid_argument("Multiple snapshots are not supported.");
}
// start = patch, end = patch
if(snapshot_id_start != patch_id_start && snapshot_id_end != patch_id_end) {
DictionaryManager *dict = get_snapshot_manager()->get_dictionary_manager(snapshot_id_end);
if (snapshot_id_start == snapshot_id_end) {
// Return diff between two patches relative to the same snapshot
int patch_tree_id_end = get_patch_tree_id(patch_id_end);
int patch_tree_id_start = get_patch_tree_id(patch_id_start);
// forward patch tree (same tree) S <- P_start <- P_end
if(snapshot_id_start < patch_tree_id_start && patch_tree_id_end == patch_tree_id_start){
PatchTree* patchTree = get_patch_tree_manager()->get_patch_tree(patch_tree_id_end, dict);
if(patchTree == NULL) {
throw std::invalid_argument("Could not find the given end patch id");
}
if (TripleStore::is_default_tree(triple_pattern)) {
return (new ForwardDiffPatchTripleDeltaIterator<PatchTreeDeletionValue>(patchTree, triple_pattern, patch_id_start, patch_id_end))->offset(offset);
} else {
return (new ForwardDiffPatchTripleDeltaIterator<PatchTreeDeletionValueReduced>(patchTree, triple_pattern, patch_id_start, patch_id_end))->offset(offset);
}
}
//reverse patch tree (same tree) P_start -> P_end -> S
else if(snapshot_id_start > patch_tree_id_start && patch_tree_id_end == patch_tree_id_start){
PatchTree* patchTree = get_patch_tree_manager()->get_patch_tree(patch_tree_id_end, dict);
if(patchTree == NULL) {
throw std::invalid_argument("Could not find the given end patch id");
}
if (TripleStore::is_default_tree(triple_pattern)) {
return (new ForwardDiffPatchTripleDeltaIterator<PatchTreeDeletionValue>(patchTree, triple_pattern, patch_id_start, patch_id_end, true))->offset(offset);
} else {
return (new ForwardDiffPatchTripleDeltaIterator<PatchTreeDeletionValueReduced>(patchTree, triple_pattern, patch_id_start, patch_id_end, true))->offset(offset);
}
}
// reverse tree and forward tree case P_start -> S <- P_end
else{
// int patch_tree_id = get_patch_tree_id(patch_id_start);
// PatchTree* patchTree = get_patch_tree_manager()->get_patch_tree(patch_tree_id, dict);
// if(patchTree == NULL) {
// throw std::invalid_argument("Could not find the given end patch id");
// }
// if (TripleStore::is_default_tree(triple_pattern)) {
// return (new ForwardPatchTripleDeltaIterator<PatchTreeDeletionValue>(patchTree, triple_pattern, patch_id_start))->offset(offset);
// } else {
// return (new ForwardPatchTripleDeltaIterator<PatchTreeDeletionValueReduced>(patchTree, triple_pattern, patch_id_start))->offset(offset);
// }
//
// int patch_tree_id = get_patch_tree_id(patch_id_end);
// PatchTree* patchTree = get_patch_tree_manager()->get_patch_tree(patch_tree_id, dict);
// if(patchTree == NULL) {
// throw std::invalid_argument("Could not find the given end patch id");
// }
// if (TripleStore::is_default_tree(triple_pattern)) {
// return (new ForwardPatchTripleDeltaIterator<PatchTreeDeletionValue>(patchTree, triple_pattern, patch_id_end))->offset(offset);
// } else {
// return (new ForwardPatchTripleDeltaIterator<PatchTreeDeletionValueReduced>(patchTree, triple_pattern, patch_id_end))->offset(offset);
// }
PatchTree* patchTreeReverse = get_patch_tree_manager()->get_patch_tree(patch_tree_id_start, dict);
PatchTree* patchTreeForward = get_patch_tree_manager()->get_patch_tree(patch_tree_id_end, dict);
if(patchTreeReverse == NULL || patchTreeForward == NULL) {
throw std::invalid_argument("Could not find the given patch id");
}
if (TripleStore::is_default_tree(triple_pattern)) {
return (new BiDiffPatchTripleDeltaIterator<PatchTreeDeletionValue>(
new ForwardPatchTripleDeltaIterator<PatchTreeDeletionValue>(patchTreeReverse,
triple_pattern,
patch_id_start
),
new ForwardPatchTripleDeltaIterator<PatchTreeDeletionValue>(patchTreeForward,
triple_pattern,
patch_id_end),
patchTreeForward->get_spo_comparator()))->offset(offset);
} else {
return (new BiDiffPatchTripleDeltaIterator<PatchTreeDeletionValueReduced>(
new ForwardPatchTripleDeltaIterator<PatchTreeDeletionValueReduced>(patchTreeReverse,
triple_pattern,
patch_id_start),
new ForwardPatchTripleDeltaIterator<PatchTreeDeletionValueReduced>(patchTreeForward,
triple_pattern,
patch_id_end),
patchTreeForward->get_spo_comparator()))->offset(offset);
}
}
} else {
// TODO: implement this when multiple snapshots are supported
throw std::invalid_argument("Multiple snapshots are not supported.");
}
}
return nullptr;
}
std::pair<size_t, ResultEstimationType> Controller::get_version_count(const Triple &triple_pattern, bool allowEstimates) const {
// TODO: this will require some changes when we support multiple snapshots.
// Find the snapshot an count its elements
HDT* snapshot = get_snapshot_manager()->get_snapshot(0);
IteratorTripleID* snapshot_it = SnapshotManager::search_with_offset(snapshot, triple_pattern, 0);
size_t count = snapshot_it->estimatedNumResults();
if (!allowEstimates && snapshot_it->numResultEstimation() != EXACT) {
count = 0;
while (snapshot_it->hasNext()) {
snapshot_it->next();
count++;
}
}
// Count the additions for all versions
DictionaryManager *dict = get_snapshot_manager()->get_dictionary_manager(0);
PatchTree* patchTree = get_patch_tree_manager()->get_patch_tree(0, dict);
if (patchTree != NULL) {
count += patchTree->addition_count(0, triple_pattern);
}
return std::make_pair(count, allowEstimates ? snapshot_it->numResultEstimation() : EXACT);
}
std::pair<size_t, ResultEstimationType> Controller::get_partial_version_count(const Triple &triple_pattern, bool allowEstimates) const {
// TODO: this will require some changes when we support multiple snapshots.
int snapshot_id = snapshotManager->get_snapshots().begin()->first;
int reverse_patch_tree_id = snapshot_id - 1;
int forward_patch_tree_id = snapshot_id + 1;
// Find the snapshot an count its elements
HDT* snapshot = get_snapshot_manager()->get_snapshot(snapshot_id);
DictionaryManager *dict = get_snapshot_manager()->get_dictionary_manager(snapshot_id);
IteratorTripleID* snapshot_it = SnapshotManager::search_with_offset(snapshot, triple_pattern, 0);
PatchTree* reverse_patch_tree = get_patch_tree_manager()->get_patch_tree(reverse_patch_tree_id, dict); // Can be null
PatchTree* forward_patch_tree = get_patch_tree_manager()->get_patch_tree(forward_patch_tree_id, dict); // Can be null
size_t count = snapshot_it->estimatedNumResults();
if (!allowEstimates && snapshot_it->numResultEstimation() != EXACT) {
count = 0;
while (snapshot_it->hasNext()) {
snapshot_it->next();
count++;
}
}
// Count the additions for all versions
if (reverse_patch_tree != NULL) {
count += reverse_patch_tree->addition_count(-1, triple_pattern);
}
if (forward_patch_tree != NULL) {
count += forward_patch_tree->addition_count(-1, triple_pattern);
}
return std::make_pair(count, UP_TO);
}
size_t Controller::get_version_count_estimated(const Triple &triple_pattern) const {
return get_version_count(triple_pattern, true).first;
}
TripleVersionsIterator* Controller::get_partial_version(const Triple &triple_pattern, int offset) const {
int snapshot_id = snapshotManager->get_snapshots().begin()->first;
int reverse_patch_tree_id = snapshot_id - 1;
int forward_patch_tree_id = snapshot_id + 1;
HDT* snapshot = get_snapshot_manager()->get_snapshot(snapshot_id);
IteratorTripleID* snapshot_it = SnapshotManager::search_with_offset(snapshot, triple_pattern, offset);
DictionaryManager *dict = get_snapshot_manager()->get_dictionary_manager(snapshot_id);
PatchTree* reverse_patch_tree = get_patch_tree_manager()->get_patch_tree(reverse_patch_tree_id, dict); // Can be null
PatchTree* forward_patch_tree = get_patch_tree_manager()->get_patch_tree(forward_patch_tree_id, dict); // Can be null
// Snapshots have already been offsetted, calculate the remaining offset.
// After this, offset will only be >0 if we are past the snapshot elements and at the additions.
if (snapshot_it->numResultEstimation() == EXACT) {
offset -= snapshot_it->estimatedNumResults();
if (offset <= 0) {
offset = 0;
} else {
delete snapshot_it;
snapshot_it = NULL;
}
} else {
IteratorTripleID *tmp_it = SnapshotManager::search_with_offset(snapshot, triple_pattern, 0);
while (tmp_it->hasNext() && offset > 0) {
tmp_it->next();
offset--;
}
delete tmp_it;
}
return (new TripleVersionsIterator(triple_pattern, snapshot_it, reverse_patch_tree, forward_patch_tree, snapshot_id))->offset(offset);
}
TripleVersionsIterator* Controller::get_version(const Triple &triple_pattern, int offset) const {
// // TODO: this will require some changes when we support multiple snapshots. (probably just a simple merge for all snapshots with what is already here)
// // Find the snapshot
// int snapshot_id = 0;
// HDT* snapshot = get_snapshot_manager()->get_snapshot(snapshot_id);
// IteratorTripleID* snapshot_it = SnapshotManager::search_with_offset(snapshot, triple_pattern, offset);
// DictionaryManager *dict = get_snapshot_manager()->get_dictionary_manager(snapshot_id);
// PatchTree* patchTree = get_patch_tree_manager()->get_patch_tree(snapshot_id, dict); // Can be null, if only snapshot is available
//
// // Snapshots have already been offsetted, calculate the remaining offset.
// // After this, offset will only be >0 if we are past the snapshot elements and at the additions.
// if (snapshot_it->numResultEstimation() == EXACT) {
// offset -= snapshot_it->estimatedNumResults();
// if (offset <= 0) {
// offset = 0;
// } else {
// delete snapshot_it;
// snapshot_it = NULL;
// }
// } else {
// IteratorTripleID *tmp_it = SnapshotManager::search_with_offset(snapshot, triple_pattern, 0);
// while (tmp_it->hasNext() && offset > 0) {
// tmp_it->next();
// offset--;
// }
// delete tmp_it;
// }
//
// return (new TripleVersionsIterator(triple_pattern, snapshot_it, patchTree, 0))->offset(offset);
return NULL;
}
bool Controller::append(PatchElementIterator* patch_it, int patch_id, DictionaryManager* dict, bool check_uniqueness, ProgressListener* progressListener) {
//find largest key smaller or equal to patch_id, this is the patch_tree_id
auto it = patchTreeManager->get_patch_trees().lower_bound(patch_id); //gives elements equal to or greater than patch_id
if(it == patchTreeManager->get_patch_trees().end() || it->first > patch_id) {
if(it == patchTreeManager->get_patch_trees().begin()) {
// todo error no smaller element found
return -1;
}
it--;
}
int patch_tree_id = it->first;
return get_patch_tree_manager()->append(patch_it, patch_id, patch_tree_id, check_uniqueness, progressListener, dict);
}
bool Controller::reverse_append(PatchElementIterator* patch_it, int patch_id, DictionaryManager* dict, bool check_uniqueness, ProgressListener* progressListener) {
//find smallest element larger than or equal to patch_id, this is the patch_tree_id
int patch_tree_id;
if(patchTreeManager->get_patch_trees().find(patch_id) == patchTreeManager->get_patch_trees().end()){
auto iterator = patchTreeManager->get_patch_trees().upper_bound(patch_id); //returns first element bigger than patch_id
patch_tree_id = iterator->first;
}
else{
patch_tree_id = patch_id;
}
return get_patch_tree_manager()->reverse_append(patch_it, patch_id, patch_tree_id, dict, check_uniqueness, progressListener);
}
PatchTreeManager* Controller::get_patch_tree_manager() const {
return patchTreeManager;
}
SnapshotManager* Controller::get_snapshot_manager() const {
return snapshotManager;
}
DictionaryManager *Controller::get_dictionary_manager(int patch_id) const {
int snapshot_id = get_corresponding_snapshot_id(patch_id);
if(snapshot_id < 0) {
throw std::invalid_argument("No snapshot has been created yet.");
}
get_snapshot_manager()->get_snapshot(snapshot_id); // Force a snapshot load
return get_snapshot_manager()->get_dictionary_manager(snapshot_id);
}
int Controller::get_max_patch_id() {
get_snapshot_manager()->get_snapshot(0); // Make sure our first snapshot is loaded, otherwise KC might get intro trouble while reorganising since it needs the dict for that.
int max_patch_id = get_patch_tree_manager()->get_max_patch_id(get_snapshot_manager()->get_dictionary_manager(0));
if (max_patch_id < 0) {
return get_corresponding_snapshot_id(0);
}
return max_patch_id;
}
void Controller::cleanup(string basePath, Controller* controller) {
// Delete patch files
std::map<int, PatchTree*> patches = controller->get_patch_tree_manager()->get_patch_trees();
std::map<int, PatchTree*>::iterator itP = patches.begin();
std::list<int> patchMetadataToDelete;
while(itP != patches.end()) {
int id = itP->first;
std::remove((basePath + PATCHTREE_FILENAME(id, "spo_deletions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(id, "pos_deletions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(id, "pso_deletions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(id, "sop_deletions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(id, "osp_deletions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(id, "spo_additions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(id, "pos_additions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(id, "pso_additions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(id, "sop_additions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(id, "osp_additions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(id, "count_additions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(id, "count_additions.tmp")).c_str());
patchMetadataToDelete.push_back(id);
itP++;
}
// Delete snapshot files
std::map<int, HDT*> snapshots = controller->get_snapshot_manager()->get_snapshots();
std::map<int, HDT*>::iterator itS = snapshots.begin();
std::list<int> patchDictsToDelete;
while(itS != snapshots.end()) {
int id = itS->first;
std::remove((basePath + SNAPSHOT_FILENAME_BASE(id)).c_str());
std::remove((basePath + SNAPSHOT_FILENAME_BASE(id) + ".index").c_str());
patchDictsToDelete.push_back(id);
itS++;
}
delete controller;
// Delete dictionaries
std::list<int>::iterator it1;
for(it1=patchDictsToDelete.begin(); it1!=patchDictsToDelete.end(); ++it1) {
DictionaryManager::cleanup(basePath, *it1);
}
// Delete metadata files
std::list<int>::iterator it2;
for(it2=patchMetadataToDelete.begin(); it2!=patchMetadataToDelete.end(); ++it2) {
std::remove((basePath + METADATA_FILENAME_BASE(*it2)).c_str());
}
}
PatchBuilder* Controller::new_patch_bulk() {
return new PatchBuilder(this);
}
PatchBuilderStreaming *Controller::new_patch_stream() {
return new PatchBuilderStreaming(this);
}
bool Controller::replace_patch_tree(string basePath, int patch_tree_id) {
// remove old files
std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "spo_deletions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "pos_deletions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "pso_deletions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "sop_deletions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "osp_deletions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "spo_additions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "pos_additions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "pso_additions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "sop_additions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "osp_additions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "count_additions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "count_additions.tmp")).c_str());
std::remove((basePath + METADATA_FILENAME_BASE(patch_tree_id)).c_str());
//rename temp files
std::rename((basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "spo_deletions")).c_str(), (basePath + PATCHTREE_FILENAME(patch_tree_id, "spo_deletions")).c_str());
std::rename((basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "pos_deletions")).c_str(), (basePath + PATCHTREE_FILENAME(patch_tree_id, "pos_deletions")).c_str());
std::rename((basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "pso_deletions")).c_str(), (basePath + PATCHTREE_FILENAME(patch_tree_id, "pso_deletions")).c_str());
std::rename((basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "sop_deletions")).c_str(), (basePath + PATCHTREE_FILENAME(patch_tree_id, "sop_deletions")).c_str());
std::rename((basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "osp_deletions")).c_str(), (basePath + PATCHTREE_FILENAME(patch_tree_id, "osp_deletions")).c_str());
std::rename((basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "spo_additions")).c_str(), (basePath + PATCHTREE_FILENAME(patch_tree_id, "spo_additions")).c_str());
std::rename((basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "pos_additions")).c_str(), (basePath + PATCHTREE_FILENAME(patch_tree_id, "pos_additions")).c_str());
std::rename((basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "pso_additions")).c_str(), (basePath + PATCHTREE_FILENAME(patch_tree_id, "pso_additions")).c_str());
std::rename((basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "sop_additions")).c_str(), (basePath + PATCHTREE_FILENAME(patch_tree_id, "sop_additions")).c_str());
std::rename((basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "osp_additions")).c_str(), (basePath + PATCHTREE_FILENAME(patch_tree_id, "osp_additions")).c_str());
std::rename((basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "count_additions")).c_str(), (basePath + PATCHTREE_FILENAME(patch_tree_id, "count_additions")).c_str());
std::rename((basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "count_additions.tmp")).c_str(), (basePath + PATCHTREE_FILENAME(patch_tree_id, "count_additions.tmp")).c_str());
std::rename((basePath + TEMP_METADATA_FILENAME_BASE(patch_tree_id)).c_str(), (basePath + METADATA_FILENAME_BASE(patch_tree_id)).c_str());
return true;
}
int Controller::get_patch_tree_id(int patch_id)const {
// case 1: S <- P <- P
// case 2: S <- P <- P S <- P
// case 3: S <- P <- P P -> P -> S <- P
// case 4: P -> P -> S <- P <- P
// return lower tree if reverse tree does not exists
// return upper tree if reverse tree does exists
std::map<int, HDT*> loaded_snapshots = get_snapshot_manager()->get_snapshots();
std::map<int, HDT*>::iterator low, prev;
low = loaded_snapshots.lower_bound(patch_id);
int low_snapshot_id = -1;
int high_snapshot_id = -1;
if(low == loaded_snapshots.begin() && low == loaded_snapshots.end()) {
// empty map
return -1;
}
if (low == loaded_snapshots.end()) {
low--;
low_snapshot_id = low->first;
} else if (low == loaded_snapshots.begin()) {
low_snapshot_id = low->first;
} else {
prev = std::prev(low);
high_snapshot_id = low->first;
low_snapshot_id = prev->first;
}
// case 4
if(low_snapshot_id > patch_id){
return low_snapshot_id - 1;
}
std::map<int, PatchTree*> patches = get_patch_tree_manager()->get_patch_trees();
int low_patch_tree_id = low_snapshot_id + 1 ; // todo make function of forward patch_tree_id
if(high_snapshot_id >= 0){ // if high snapshot exists
auto it = patches.find(high_snapshot_id - 1); // todo make function of reverse patch_tree_id
if(it != patches.end()){ // if reverse patch tree exists
int dist_to_low = patch_id - low_snapshot_id;
int dist_to_high = high_snapshot_id - patch_id;
if(dist_to_high < dist_to_low){ // closer to reverse patch tree
return high_snapshot_id - 1; // todo make function of reverse patch_tree_id
}
}
}
// check if forward chain exists
auto it = patches.find(low_patch_tree_id); // todo make function of reverse patch_tree_id
if(it == patches.end()){
return -1;
}
return low_patch_tree_id;
}
int Controller::get_corresponding_snapshot_id(int patch_id) const {
// get snapshot before patch_id
// get snapshot after patch_id
// if snapshot after patch_id does not exist or snapshot_after does not have reverse tree, return snapshot before patch_id
// if reverse does exist, return snapshot id closest to patch_id (in case of tie, return lowest snapshot_id
std::map<int, HDT*> loaded_snapshots = get_snapshot_manager()->get_snapshots();
std::map<int, HDT*>::iterator low, prev;
low = loaded_snapshots.lower_bound(patch_id);
int low_snapshot_id = -1;
int high_snapshot_id = -1;
if(low == loaded_snapshots.begin() && low == loaded_snapshots.end()) {
// empty map
return -1;
}
if (low == loaded_snapshots.end()) {
low--;
low_snapshot_id = low->first;
} else if (low == loaded_snapshots.begin()) {
low_snapshot_id = low->first;
} else {
prev = std::prev(low);
high_snapshot_id = low->first;
low_snapshot_id = prev->first;
}
if(high_snapshot_id == patch_id)
return high_snapshot_id;
else if(low_snapshot_id == patch_id)
return low_snapshot_id;
else{
std::map<int, PatchTree*> loaded_patches = get_patch_tree_manager()->get_patch_trees();
int low_patch_tree_id = low_snapshot_id + 1 ; // todo make function of forward patch_tree_id
if(high_snapshot_id >= 0){ // if high snapshot exists
auto it = loaded_patches.find(high_snapshot_id - 1); // todo make function of reverse patch_tree_id
if(it != loaded_patches.end()){ // if reverse patch tree exists
int dist_to_low = patch_id - low_snapshot_id;
int dist_to_high = high_snapshot_id - patch_id;
if(dist_to_high < dist_to_low){ // closer to reverse patch tree
return high_snapshot_id;
}
}
}
return low_snapshot_id;}
}
bool Controller::copy_patch_tree_files(string basePath, int patch_tree_id) {
try {
boost::filesystem::path source, target;
source = basePath + PATCHTREE_FILENAME(patch_tree_id, "spo_deletions");
target = basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "spo_deletions");
if (boost::filesystem::exists(source))
boost::filesystem::copy_file(source, target);
source = basePath + PATCHTREE_FILENAME(patch_tree_id, "pos_deletions");
target = basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "pos_deletions");
if (boost::filesystem::exists(source))
boost::filesystem::copy_file(source, target);
source = basePath + PATCHTREE_FILENAME(patch_tree_id, "pso_deletions");
target = basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "pso_deletions");
if (boost::filesystem::exists(source))
boost::filesystem::copy_file(source, target);
source = basePath + PATCHTREE_FILENAME(patch_tree_id, "sop_deletions");
target = basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "sop_deletions");
if (boost::filesystem::exists(source))
boost::filesystem::copy_file(source, target);
source = basePath + PATCHTREE_FILENAME(patch_tree_id, "osp_deletions");
target = basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "osp_deletions");
if (boost::filesystem::exists(source))
boost::filesystem::copy_file(source, target);
source = basePath + PATCHTREE_FILENAME(patch_tree_id, "spo_additions");
target = basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "spo_additions");
if (boost::filesystem::exists(source))
boost::filesystem::copy_file(source, target);
source = basePath + PATCHTREE_FILENAME(patch_tree_id, "pos_additions");
target = basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "pos_additions");
if (boost::filesystem::exists(source))
boost::filesystem::copy_file(source, target);
source = basePath + PATCHTREE_FILENAME(patch_tree_id, "pso_additions");
target = basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "pso_additions");
if (boost::filesystem::exists(source))
boost::filesystem::copy_file(source, target);
source = basePath + PATCHTREE_FILENAME(patch_tree_id, "sop_additions");
target = basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "sop_additions");
if (boost::filesystem::exists(source))
boost::filesystem::copy_file(source, target);
source = basePath + PATCHTREE_FILENAME(patch_tree_id, "osp_additions");
target = basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "osp_additions");
if (boost::filesystem::exists(source))
boost::filesystem::copy_file(source, target);
source = basePath + PATCHTREE_FILENAME(patch_tree_id, "count_additions");
target = basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "count_additions");
if (boost::filesystem::exists(source))
boost::filesystem::copy_file(source, target);
// source = basePath + PATCHTREE_FILENAME(patch_tree_id, "count_additions.tmp");
// target = basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "count_additions.tmp");
// if (boost::filesystem::exists(source))
// boost::filesystem::copy_file(source, target);
source = basePath + METADATA_FILENAME_BASE(patch_tree_id);
target = basePath + TEMP_METADATA_FILENAME_BASE(patch_tree_id);
if (boost::filesystem::exists(source))
boost::filesystem::copy_file(source, target);
} catch (const boost::filesystem::filesystem_error& e){
return false;
}
return true;
}
void Controller::remove_forward_chain(std::string basePath, int temp_snapshot_id){
int patch_tree_id = temp_snapshot_id + 1;
get_patch_tree_manager()->remove_patch_tree(patch_tree_id);
get_snapshot_manager()->remove_snapshot(temp_snapshot_id);
std::remove((basePath + PATCHDICT_FILENAME_BASE(temp_snapshot_id)).c_str());
std::remove((basePath + METADATA_FILENAME_BASE(patch_tree_id)).c_str());
std::remove((basePath + SNAPSHOT_FILENAME_BASE(temp_snapshot_id)).c_str());
std::remove((basePath + SNAPSHOT_FILENAME_BASE(temp_snapshot_id) + ".index").c_str());
std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "spo_deletions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "pos_deletions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "pso_deletions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "sop_deletions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "osp_deletions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "spo_additions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "pos_additions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "pso_additions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "sop_additions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "osp_additions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "count_additions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "count_additions.tmp")).c_str());
}
void Controller::extract_changeset(int patch_tree_id, std::string path_to_files) {
patchTreeManager->get_patch_tree(patch_tree_id, get_dictionary_manager(patch_tree_id))->getTripleStore()->extract_additions(get_dictionary_manager(patch_tree_id), path_to_files);
patchTreeManager->get_patch_tree(patch_tree_id, get_dictionary_manager(patch_tree_id))->getTripleStore()->extract_deletions(get_dictionary_manager(patch_tree_id), path_to_files);
}
| 55.119221 | 297 | 0.677916 |
fd513c0e3af24e2511e6d4b399996a53d7b9bcd9 | 7,120 | cc | C++ | DPPIR/shuffle/shuffle_test.cc | multiparty/drivacy | bb215831a9114e837ff7b1b75dc2195396a5fffa | [
"MIT"
] | 3 | 2019-09-23T19:01:23.000Z | 2020-09-07T22:23:11.000Z | DPPIR/shuffle/shuffle_test.cc | multiparty/drivacy | bb215831a9114e837ff7b1b75dc2195396a5fffa | [
"MIT"
] | 4 | 2020-10-09T14:13:13.000Z | 2020-10-09T14:14:25.000Z | DPPIR/shuffle/shuffle_test.cc | multiparty/drivacy | bb215831a9114e837ff7b1b75dc2195396a5fffa | [
"MIT"
] | null | null | null | #include <cassert>
// NOLINTNEXTLINE
#include <chrono>
#include <iostream>
#include <string>
#include <vector>
#include "DPPIR/shuffle/local_shuffle.h"
#include "DPPIR/shuffle/parallel_shuffle.h"
#include "DPPIR/types/types.h"
#define SERVER_COUNT 8
#define TOTAL_COUNT 10000006
// Whether to print intermediate batches.
#define PRINT false
namespace DPPIR {
namespace shuffle {
index_t InputCountForServer(server_id_t server) {
index_t uniform = TOTAL_COUNT / SERVER_COUNT;
if (server == SERVER_COUNT - 1) {
uniform = TOTAL_COUNT - (uniform * server);
}
// Introduce ~1% variance in input size.
index_t offset = (TOTAL_COUNT / SERVER_COUNT) / 20;
assert(offset < uniform && offset > 0);
if (server % 2 == 0) {
return uniform + offset;
} else {
return uniform - offset;
}
}
// Printing utils.
template <typename T>
void Print(server_id_t sid, const std::string& label, const std::vector<T>& v) {
if (PRINT) {
std::cout << "(server " << int(sid) << ") " << label << ": [";
for (const auto& q : v) {
std::cout << q << ", ";
}
std::cout << "] @ " << v.size();
std::cout << std::endl;
}
}
template <typename T>
void Print2D(server_id_t sid, const std::string& label,
const std::vector<std::vector<T>>& v) {
if (PRINT) {
for (size_t i = 0; i < v.size(); i++) {
std::cout << "(server " << int(sid) << ") " << label << " from " << i
<< ": [";
for (const auto& q : v.at(i)) {
std::cout << q << ", ";
}
std::cout << "] @ " << v.at(i).size();
std::cout << std::endl;
}
}
}
// Server struct.
struct Server {
server_id_t id;
// Shufflers.
ParallelShuffler pshuffler;
LocalShuffler lshuffler;
std::vector<key_t> inputs;
// Going forward.
std::vector<std::vector<key_t>> forward_from_servers;
std::vector<key_t> outbox;
// Output of shuffling.
// Going backward.
std::vector<key_t> inbox;
std::vector<std::vector<key_t>> backward_from_servers;
// Should be == inputs.
std::vector<key_t> outputs;
// Constructor.
Server(server_id_t sid, index_t* server_counts)
: id(sid),
pshuffler(sid, SERVER_COUNT, SERVER_COUNT),
lshuffler(sid),
forward_from_servers(SERVER_COUNT, std::vector<key_t>()),
backward_from_servers(SERVER_COUNT, std::vector<key_t>()) {
// Initialize parallel shuffler.
pshuffler.Initialize(server_counts, 0);
index_t in_slice = server_counts[sid];
index_t out_slice = pshuffler.GetServerSliceSize();
// Initialize local shuffler.
lshuffler.Initialize(out_slice);
// Initialize vectors.
inputs.reserve(in_slice);
outbox = std::vector<key_t>(out_slice, -1);
inbox = std::vector<key_t>(out_slice, -1);
outputs = std::vector<key_t>(in_slice, -1);
for (index_t i = 0; i < in_slice; i++) {
inputs.push_back(sid * TOTAL_COUNT + i);
}
}
};
// Measure time for a single preshuffle.
void SingleOffline() {
// Give every server an input size.
std::vector<index_t> input_counts;
for (server_id_t sid = 0; sid < SERVER_COUNT; sid++) {
input_counts.push_back(InputCountForServer(sid));
}
// Create shuffler.
ParallelShuffler _pshuffler(SERVER_COUNT - 1, SERVER_COUNT, SERVER_COUNT);
LocalShuffler _lshuffler(0);
// Time initialization.
auto s = std::chrono::steady_clock::now();
_pshuffler.Initialize(&input_counts.at(0), 0);
_lshuffler.Initialize(_pshuffler.GetServerSliceSize());
auto e = std::chrono::steady_clock::now();
auto d = std::chrono::duration_cast<std::chrono::milliseconds>(e - s).count();
// Done.
std::cout << "Preprocessing: " << d << "ms" << std::endl;
std::cout << std::endl;
}
bool SimpleProtocol() {
// Give every server an input size.
std::vector<index_t> input_counts;
for (server_id_t sid = 0; sid < SERVER_COUNT; sid++) {
input_counts.push_back(InputCountForServer(sid));
}
// Create server structs.
std::vector<Server> servers;
servers.reserve(SERVER_COUNT);
for (server_id_t sid = 0; sid < SERVER_COUNT; sid++) {
servers.emplace_back(sid, &input_counts.at(0));
}
// First stage.
std::cout << "First stage" << std::endl;
for (auto& server : servers) {
Print(server.id, "inputs", server.inputs);
for (auto& q : server.inputs) {
server_id_t tserver = server.pshuffler.ShuffleOne();
servers.at(tserver).forward_from_servers.at(server.id).push_back(q);
}
server.pshuffler.FinishForward();
}
// Print state.
for (auto& server : servers) {
Print2D(server.id, "forward", server.forward_from_servers);
}
std::cout << std::endl;
// Second stage.
std::cout << "Second stage" << std::endl;
for (auto& server : servers) {
std::vector<key_t> before_shuffle;
for (auto& v : server.forward_from_servers) {
for (auto& q : v) {
index_t target_idx = server.lshuffler.Shuffle(before_shuffle.size());
server.outbox.at(target_idx) = q;
before_shuffle.push_back(q);
}
}
server.lshuffler.FinishForward();
Print(server.id, "outbox (no shuffle)", before_shuffle);
Print(server.id, "outbox: ", server.outbox);
}
std::cout << std::endl;
// Reverse second stage.
std::cout << "Reverse second stage" << std::endl;
for (auto& server : servers) {
for (index_t idx = 0; idx < server.outbox.size(); idx++) {
index_t target_idx = server.lshuffler.Deshuffle(idx);
server.inbox.at(target_idx) = server.outbox.at(idx);
}
server.lshuffler.FinishBackward();
Print(server.id, "inbox (deshuffled)", server.inbox);
// Send to servers.
index_t acc = 0;
for (server_id_t tserver = 0; tserver < SERVER_COUNT; tserver++) {
index_t count = server.forward_from_servers.at(tserver).size();
for (index_t i = 0; i < count; i++) {
auto& q = server.inbox.at(i + acc);
servers.at(tserver).backward_from_servers.at(server.id).push_back(q);
}
acc += count;
}
}
// Print state.
for (auto& server : servers) {
Print2D(server.id, "backward", server.backward_from_servers);
}
std::cout << std::endl;
// Reverse first stage.
std::cout << "Reverse first stage" << std::endl;
for (auto& server : servers) {
for (server_id_t tserver = 0; tserver < SERVER_COUNT; tserver++) {
auto& v = server.backward_from_servers.at(tserver);
for (auto& q : v) {
index_t target_idx = server.pshuffler.DeshuffleOne(tserver);
server.outputs.at(target_idx) = q;
}
}
server.pshuffler.FinishBackward();
Print(server.id, "output", server.outputs);
if (server.outputs != server.inputs) {
return false;
}
}
std::cout << std::endl;
return true;
}
} // namespace shuffle
} // namespace DPPIR
// Main function.
int main(int argc, char** argv) {
// Start.
std::cout << "starting... " << std::endl;
// Preprocessing.
DPPIR::shuffle::SingleOffline();
// Protocol.
if (!DPPIR::shuffle::SimpleProtocol()) {
std::cout << "error!" << std::endl;
return 1;
}
// Done.
std::cout << "Success!" << std::endl;
return 0;
}
| 28.253968 | 80 | 0.630478 |
fd51bebb0df2e5fe0b10e900258aebabdf1d932f | 384 | cpp | C++ | src/Scene.cpp | jomoho/SDL_Framework | 903b6baff5f18bbf18b9c90861478fb005525527 | [
"BSD-2-Clause"
] | null | null | null | src/Scene.cpp | jomoho/SDL_Framework | 903b6baff5f18bbf18b9c90861478fb005525527 | [
"BSD-2-Clause"
] | null | null | null | src/Scene.cpp | jomoho/SDL_Framework | 903b6baff5f18bbf18b9c90861478fb005525527 | [
"BSD-2-Clause"
] | null | null | null | //
// Created by moritz on 20.08.15.
//
#include "Scene.h"
#include <Box2D/Box2D.h>
Scene::Scene(){
b2Vec2 gravity(0.0f, -10.0f);
// world = new b2World(gravity);
// world->SetDebugDraw(&debugDraw);
// debugDraw.SetFlags( b2Draw::e_shapeBit |b2Draw::e_jointBit);
}
Scene::~Scene() {
// delete world;
}
void Scene::update(float dt) {
// world->Step(dt, 6, 2);
}
| 17.454545 | 66 | 0.617188 |
fd52725e24f6782dfda7cf00f21ae25e22aabc8f | 3,345 | hpp | C++ | src/route/TopicRouteManager.hpp | ifplusor/rocketmq-client-cpp | fd301f4b064d5035fc72261023a396e2c9126c53 | [
"Apache-2.0"
] | 5 | 2019-04-24T13:37:05.000Z | 2021-01-29T16:37:55.000Z | src/route/TopicRouteManager.hpp | ifplusor/rocketmq-client-cpp | fd301f4b064d5035fc72261023a396e2c9126c53 | [
"Apache-2.0"
] | null | null | null | src/route/TopicRouteManager.hpp | ifplusor/rocketmq-client-cpp | fd301f4b064d5035fc72261023a396e2c9126c53 | [
"Apache-2.0"
] | 1 | 2021-02-03T03:11:03.000Z | 2021-02-03T03:11:03.000Z | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ROCKETMQ_ROUTE_TOPICROUTEMANAGER_HPP_
#define ROCKETMQ_ROUTE_TOPICROUTEMANAGER_HPP_
#include <map> // std::map
#include <memory> // std::shared_ptr
#include <mutex> // std::mutex
#include <set> // std::set
#include <string> // std::string
#include "utility/MapAccessor.hpp"
namespace rocketmq {
struct TopicRouteData;
class TopicPublishInfo;
class TopicSubscribeInfo;
class TopicRouteManager {
public:
std::shared_ptr<TopicRouteData> GetTopicRouteData(const std::string& topic) {
return MapAccessor::GetOrDefault(topic_route_table_, topic, nullptr, topic_route_table_mutex_);
}
void PutTopicRouteData(const std::string& topic, std::shared_ptr<TopicRouteData> topic_route) {
MapAccessor::InsertOrAssign(topic_route_table_, topic, topic_route, topic_route_table_mutex_);
}
bool ContainsBrokerAddress(const std::string& address);
std::shared_ptr<TopicPublishInfo> GetTopicPublishInfo(const std::string& topic) {
return MapAccessor::GetOrDefault(topic_publish_info_table_, topic, nullptr, topic_publish_info_table_mutex_);
}
void PutTopicPublishInfo(const std::string& topic, std::shared_ptr<TopicPublishInfo> publish_info) {
MapAccessor::InsertOrAssign(topic_publish_info_table_, topic, std::move(publish_info),
topic_publish_info_table_mutex_);
}
std::set<std::string> TopicInPublish() {
return MapAccessor::KeySet(topic_publish_info_table_, topic_publish_info_table_mutex_);
}
std::shared_ptr<TopicSubscribeInfo> GetTopicSubscribeInfo(const std::string& topic) {
return MapAccessor::GetOrDefault(topic_subscribe_info_table_, topic, nullptr, topic_subescribe_info_table_mutex_);
}
void PutTopicSubscribeInfo(const std::string& topic, std::shared_ptr<TopicSubscribeInfo> subscribe_info) {
MapAccessor::InsertOrAssign(topic_subscribe_info_table_, topic, std::move(subscribe_info),
topic_subescribe_info_table_mutex_);
}
private:
// topic -> TopicRouteData
std::map<std::string, std::shared_ptr<TopicRouteData>> topic_route_table_;
std::mutex topic_route_table_mutex_;
// topic -> TopicPublishInfo
std::map<std::string, std::shared_ptr<TopicPublishInfo>> topic_publish_info_table_;
std::mutex topic_publish_info_table_mutex_;
// topic -> TopicSubscribeInfo
std::map<std::string, std::shared_ptr<TopicSubscribeInfo>> topic_subscribe_info_table_;
std::mutex topic_subescribe_info_table_mutex_;
};
} // namespace rocketmq
#endif // ROCKETMQ_ROUTE_TOPICROUTEMANAGER_HPP_
| 39.352941 | 118 | 0.76562 |
fd541295ab267af73a7a4def844271f4430b93ad | 6,306 | cpp | C++ | src/cpp/constraints.cpp | laudv/veritas | ba1761cc333b08b4381afa720b24ace065a9f106 | [
"Apache-2.0"
] | 6 | 2020-10-29T10:20:48.000Z | 2022-03-31T13:39:47.000Z | src/cpp/constraints.cpp | laudv/veritas | ba1761cc333b08b4381afa720b24ace065a9f106 | [
"Apache-2.0"
] | 1 | 2021-11-25T13:15:11.000Z | 2021-12-08T09:23:24.000Z | src/cpp/constraints.cpp | laudv/veritas | ba1761cc333b08b4381afa720b24ace065a9f106 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2020 DTAI Research Group - KU Leuven.
* License: Apache License 2.0
* Author: Laurens Devos
*/
#include "constraints.hpp"
namespace veritas {
UpdateResult
Add::update(Domain& self, Domain& ldom, Domain& rdom)
{
std::cout << "ADD0 "
<< "self: " << self
<< ", l: " << ldom
<< ", r: " << rdom
<< std::endl;
// self = ldom + rdom
FloatT new_self_lo, new_self_hi;
FloatT new_ldom_lo, new_ldom_hi;
FloatT new_rdom_lo, new_rdom_hi;
new_self_lo = std::max(self.lo, ldom.lo+rdom.lo);
new_self_hi = std::min(self.hi, ldom.hi+rdom.hi);
new_ldom_lo = std::max(ldom.lo, self.lo-rdom.hi);
new_ldom_hi = std::min(ldom.hi, self.hi-rdom.lo);
new_rdom_lo = std::max(rdom.lo, self.lo-ldom.hi),
new_rdom_hi = std::min(rdom.hi, self.hi-ldom.lo);
if (new_self_lo > new_self_hi
|| new_ldom_lo > new_ldom_hi
|| new_rdom_lo > new_rdom_hi)
return INVALID;
UpdateResult res = static_cast<UpdateResult>(
!(self.lo == new_self_lo && self.hi == new_self_hi
&& ldom.lo == new_ldom_lo && ldom.hi == new_ldom_hi
&& rdom.lo == new_rdom_lo && rdom.hi == new_rdom_hi));
self = {new_self_lo, new_self_hi};
ldom = {new_ldom_lo, new_ldom_hi};
rdom = {new_rdom_lo, new_rdom_hi};
std::cout << "ADD1 "
<< "self: " << self
<< ", l: " << ldom
<< ", r: " << rdom
<< " res=" << res
<< std::endl;
return res;
}
UpdateResult
Eq::update(Domain& ldom, Domain& rdom)
{
// L == R -> share the same domain
FloatT new_lo = std::max(ldom.lo, rdom.lo);
FloatT new_hi = std::min(ldom.hi, rdom.hi);
//std::cout << "EQ ldom " << ldom << ", rdom " << rdom << std::endl;
if (new_lo > new_hi)
return INVALID;
UpdateResult res = static_cast<UpdateResult>(
(ldom.lo != new_lo || ldom.hi != new_hi)
|| (rdom.lo != new_lo || rdom.hi != new_hi));
ldom.lo = new_lo;
rdom.lo = new_lo;
ldom.hi = new_hi;
rdom.hi = new_hi;
//std::cout << "-- ldom " << ldom << ", rdom " << rdom << std::endl;
return res;
}
UpdateResult
LtEq::update(Domain& ldom, Domain& rdom)
{
// LEFT <= RIGHT
FloatT new_lo = std::max(ldom.lo, rdom.lo);
FloatT new_hi = std::min(ldom.hi, rdom.hi);
//std::cout << "LTEQ ldom " << ldom << ", rdom " << rdom << std::endl;
if (ldom.lo > new_hi || new_lo > rdom.hi)
return INVALID;
UpdateResult res = static_cast<UpdateResult>(
(ldom.lo != new_lo || ldom.hi != new_hi)
|| (rdom.lo != new_lo || rdom.hi != new_hi));
ldom = {ldom.lo, new_hi};
rdom = {new_lo, rdom.hi};
//std::cout << "---- ldom " << ldom << ", rdom " << rdom << std::endl;
return res;
}
ConstraintPropagator::ConstraintPropagator(int num_features)
: num_features_(num_features)
{
for (int i = 0; i < num_features_; ++i)
{
AnyExpr e;
e.tag = AnyExpr::VAR;
e.parent = -1;
exprs_.push_back(e);
}
}
void
ConstraintPropagator::copy_from_box(const Box& box)
{
size_t j = 0;
for (int i = 0; i < num_features_; ++i) // box is sorted by item.feat_id
{
AnyExpr& e = exprs_[i];
e.tag = AnyExpr::VAR;
e.dom = {};
if (j < box.size() && box[j].feat_id == i)
{
e.dom = box[j].domain;
++j;
}
}
for (size_t i = num_features_; i < exprs_.size(); ++i)
{
AnyExpr& expr = exprs_[i];
if (expr.tag == AnyExpr::CONST)
expr.dom = {expr.constant.value, expr.constant.value};
else
expr.dom = {}; // reset domain of non-consts
}
}
void
ConstraintPropagator::copy_to_box(Box& box) const
{
size_t j = 0;
size_t sz = box.size();
for (int i = 0; i < num_features_; ++i)
{
if (j < sz && box[j].feat_id == i)
{
box[j].domain = exprs_[i].dom;
++j;
}
else if (!exprs_[i].dom.is_everything())
{
box.push_back({i, exprs_[i].dom}); // add new domain to box
}
}
// sort newly added domain ids, if any
if (sz < box.size())
{
std::sort(box.begin(), box.end(),
[](const DomainPair& a, const DomainPair& b) {
return a.feat_id < b.feat_id;
});
}
}
UpdateResult
ConstraintPropagator::aggregate_update_result(std::initializer_list<UpdateResult> l)
{
UpdateResult res = UNCHANGED;
for (auto r : l)
{
if (r == INVALID)
return INVALID;
if (r == UPDATED)
res = UPDATED;
};
return res;
}
void
ConstraintPropagator::eq(int left, int right)
{
AnyComp c;
c.left = left;
c.right = right;
c.comp.eq = {};
c.tag = AnyComp::EQ;
comps_.push_back(c);
}
void
ConstraintPropagator::lteq(int left, int right)
{
AnyComp c;
c.left = left;
c.right = right;
c.comp.lteq = {};
c.tag = AnyComp::LTEQ;
comps_.push_back(c);
}
int
ConstraintPropagator::constant(FloatT value)
{
AnyExpr e;
e.tag = AnyExpr::CONST;
e.constant = {value};
e.parent = -1;
exprs_.push_back(e);
return exprs_.size() - 1;
}
int
ConstraintPropagator::add(int left, int right)
{
AnyExpr e;
e.tag = AnyExpr::ADD;
e.add = {left, right};
e.parent = -1;
int id = exprs_.size();
exprs_.push_back(e);
exprs_.at(left).parent = id;
exprs_.at(right).parent = id;
return id;
}
} // namespace veritas
| 27.417391 | 88 | 0.479385 |
fd54eedc8a24099c00852574b67811e86b32aabf | 54,516 | cpp | C++ | airavata-api/airavata-client-sdks/airavata-cpp-sdk/src/main/resources/lib/airavata/group_resource_profile_model_types.cpp | docquantum/airavata | 4ec5fa0aab1b75ca1e98a16648c57cd8abdb4b9c | [
"ECL-2.0",
"Apache-2.0"
] | 74 | 2015-04-10T02:57:26.000Z | 2022-02-28T16:10:03.000Z | airavata-api/airavata-client-sdks/airavata-cpp-sdk/src/main/resources/lib/airavata/group_resource_profile_model_types.cpp | docquantum/airavata | 4ec5fa0aab1b75ca1e98a16648c57cd8abdb4b9c | [
"ECL-2.0",
"Apache-2.0"
] | 126 | 2015-04-26T02:55:26.000Z | 2022-02-16T22:43:28.000Z | airavata-api/airavata-client-sdks/airavata-cpp-sdk/src/main/resources/lib/airavata/group_resource_profile_model_types.cpp | docquantum/airavata | 4ec5fa0aab1b75ca1e98a16648c57cd8abdb4b9c | [
"ECL-2.0",
"Apache-2.0"
] | 163 | 2015-01-22T14:05:24.000Z | 2022-03-17T12:24:34.000Z | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Autogenerated by Thrift Compiler (0.10.0)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
#include "group_resource_profile_model_types.h"
#include <algorithm>
#include <ostream>
#include <thrift/TToString.h>
namespace apache { namespace airavata { namespace model { namespace appcatalog { namespace groupresourceprofile {
GroupAccountSSHProvisionerConfig::~GroupAccountSSHProvisionerConfig() throw() {
}
void GroupAccountSSHProvisionerConfig::__set_resourceId(const std::string& val) {
this->resourceId = val;
}
void GroupAccountSSHProvisionerConfig::__set_groupResourceProfileId(const std::string& val) {
this->groupResourceProfileId = val;
}
void GroupAccountSSHProvisionerConfig::__set_configName(const std::string& val) {
this->configName = val;
}
void GroupAccountSSHProvisionerConfig::__set_configValue(const std::string& val) {
this->configValue = val;
__isset.configValue = true;
}
uint32_t GroupAccountSSHProvisionerConfig::read(::apache::thrift::protocol::TProtocol* iprot) {
apache::thrift::protocol::TInputRecursionTracker tracker(*iprot);
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
bool isset_resourceId = false;
bool isset_groupResourceProfileId = false;
bool isset_configName = false;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
switch (fid)
{
case 1:
if (ftype == ::apache::thrift::protocol::T_STRING) {
xfer += iprot->readString(this->resourceId);
isset_resourceId = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 2:
if (ftype == ::apache::thrift::protocol::T_STRING) {
xfer += iprot->readString(this->groupResourceProfileId);
isset_groupResourceProfileId = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 3:
if (ftype == ::apache::thrift::protocol::T_STRING) {
xfer += iprot->readString(this->configName);
isset_configName = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 4:
if (ftype == ::apache::thrift::protocol::T_STRING) {
xfer += iprot->readString(this->configValue);
this->__isset.configValue = true;
} else {
xfer += iprot->skip(ftype);
}
break;
default:
xfer += iprot->skip(ftype);
break;
}
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
if (!isset_resourceId)
throw TProtocolException(TProtocolException::INVALID_DATA);
if (!isset_groupResourceProfileId)
throw TProtocolException(TProtocolException::INVALID_DATA);
if (!isset_configName)
throw TProtocolException(TProtocolException::INVALID_DATA);
return xfer;
}
uint32_t GroupAccountSSHProvisionerConfig::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
apache::thrift::protocol::TOutputRecursionTracker tracker(*oprot);
xfer += oprot->writeStructBegin("GroupAccountSSHProvisionerConfig");
xfer += oprot->writeFieldBegin("resourceId", ::apache::thrift::protocol::T_STRING, 1);
xfer += oprot->writeString(this->resourceId);
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldBegin("groupResourceProfileId", ::apache::thrift::protocol::T_STRING, 2);
xfer += oprot->writeString(this->groupResourceProfileId);
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldBegin("configName", ::apache::thrift::protocol::T_STRING, 3);
xfer += oprot->writeString(this->configName);
xfer += oprot->writeFieldEnd();
if (this->__isset.configValue) {
xfer += oprot->writeFieldBegin("configValue", ::apache::thrift::protocol::T_STRING, 4);
xfer += oprot->writeString(this->configValue);
xfer += oprot->writeFieldEnd();
}
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
return xfer;
}
void swap(GroupAccountSSHProvisionerConfig &a, GroupAccountSSHProvisionerConfig &b) {
using ::std::swap;
swap(a.resourceId, b.resourceId);
swap(a.groupResourceProfileId, b.groupResourceProfileId);
swap(a.configName, b.configName);
swap(a.configValue, b.configValue);
swap(a.__isset, b.__isset);
}
GroupAccountSSHProvisionerConfig::GroupAccountSSHProvisionerConfig(const GroupAccountSSHProvisionerConfig& other0) {
resourceId = other0.resourceId;
groupResourceProfileId = other0.groupResourceProfileId;
configName = other0.configName;
configValue = other0.configValue;
__isset = other0.__isset;
}
GroupAccountSSHProvisionerConfig& GroupAccountSSHProvisionerConfig::operator=(const GroupAccountSSHProvisionerConfig& other1) {
resourceId = other1.resourceId;
groupResourceProfileId = other1.groupResourceProfileId;
configName = other1.configName;
configValue = other1.configValue;
__isset = other1.__isset;
return *this;
}
void GroupAccountSSHProvisionerConfig::printTo(std::ostream& out) const {
using ::apache::thrift::to_string;
out << "GroupAccountSSHProvisionerConfig(";
out << "resourceId=" << to_string(resourceId);
out << ", " << "groupResourceProfileId=" << to_string(groupResourceProfileId);
out << ", " << "configName=" << to_string(configName);
out << ", " << "configValue="; (__isset.configValue ? (out << to_string(configValue)) : (out << "<null>"));
out << ")";
}
GroupComputeResourcePreference::~GroupComputeResourcePreference() throw() {
}
void GroupComputeResourcePreference::__set_computeResourceId(const std::string& val) {
this->computeResourceId = val;
}
void GroupComputeResourcePreference::__set_groupResourceProfileId(const std::string& val) {
this->groupResourceProfileId = val;
}
void GroupComputeResourcePreference::__set_overridebyAiravata(const bool val) {
this->overridebyAiravata = val;
}
void GroupComputeResourcePreference::__set_loginUserName(const std::string& val) {
this->loginUserName = val;
__isset.loginUserName = true;
}
void GroupComputeResourcePreference::__set_preferredJobSubmissionProtocol(const ::apache::airavata::model::appcatalog::computeresource::JobSubmissionProtocol::type val) {
this->preferredJobSubmissionProtocol = val;
__isset.preferredJobSubmissionProtocol = true;
}
void GroupComputeResourcePreference::__set_preferredDataMovementProtocol(const ::apache::airavata::model::data::movement::DataMovementProtocol::type val) {
this->preferredDataMovementProtocol = val;
__isset.preferredDataMovementProtocol = true;
}
void GroupComputeResourcePreference::__set_preferredBatchQueue(const std::string& val) {
this->preferredBatchQueue = val;
__isset.preferredBatchQueue = true;
}
void GroupComputeResourcePreference::__set_scratchLocation(const std::string& val) {
this->scratchLocation = val;
__isset.scratchLocation = true;
}
void GroupComputeResourcePreference::__set_allocationProjectNumber(const std::string& val) {
this->allocationProjectNumber = val;
__isset.allocationProjectNumber = true;
}
void GroupComputeResourcePreference::__set_resourceSpecificCredentialStoreToken(const std::string& val) {
this->resourceSpecificCredentialStoreToken = val;
__isset.resourceSpecificCredentialStoreToken = true;
}
void GroupComputeResourcePreference::__set_usageReportingGatewayId(const std::string& val) {
this->usageReportingGatewayId = val;
__isset.usageReportingGatewayId = true;
}
void GroupComputeResourcePreference::__set_qualityOfService(const std::string& val) {
this->qualityOfService = val;
__isset.qualityOfService = true;
}
void GroupComputeResourcePreference::__set_reservation(const std::string& val) {
this->reservation = val;
__isset.reservation = true;
}
void GroupComputeResourcePreference::__set_reservationStartTime(const int64_t val) {
this->reservationStartTime = val;
__isset.reservationStartTime = true;
}
void GroupComputeResourcePreference::__set_reservationEndTime(const int64_t val) {
this->reservationEndTime = val;
__isset.reservationEndTime = true;
}
void GroupComputeResourcePreference::__set_sshAccountProvisioner(const std::string& val) {
this->sshAccountProvisioner = val;
__isset.sshAccountProvisioner = true;
}
void GroupComputeResourcePreference::__set_groupSSHAccountProvisionerConfigs(const std::vector<GroupAccountSSHProvisionerConfig> & val) {
this->groupSSHAccountProvisionerConfigs = val;
__isset.groupSSHAccountProvisionerConfigs = true;
}
void GroupComputeResourcePreference::__set_sshAccountProvisionerAdditionalInfo(const std::string& val) {
this->sshAccountProvisionerAdditionalInfo = val;
__isset.sshAccountProvisionerAdditionalInfo = true;
}
uint32_t GroupComputeResourcePreference::read(::apache::thrift::protocol::TProtocol* iprot) {
apache::thrift::protocol::TInputRecursionTracker tracker(*iprot);
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
bool isset_computeResourceId = false;
bool isset_groupResourceProfileId = false;
bool isset_overridebyAiravata = false;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
switch (fid)
{
case 1:
if (ftype == ::apache::thrift::protocol::T_STRING) {
xfer += iprot->readString(this->computeResourceId);
isset_computeResourceId = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 2:
if (ftype == ::apache::thrift::protocol::T_STRING) {
xfer += iprot->readString(this->groupResourceProfileId);
isset_groupResourceProfileId = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 3:
if (ftype == ::apache::thrift::protocol::T_BOOL) {
xfer += iprot->readBool(this->overridebyAiravata);
isset_overridebyAiravata = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 4:
if (ftype == ::apache::thrift::protocol::T_STRING) {
xfer += iprot->readString(this->loginUserName);
this->__isset.loginUserName = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 5:
if (ftype == ::apache::thrift::protocol::T_I32) {
int32_t ecast2;
xfer += iprot->readI32(ecast2);
this->preferredJobSubmissionProtocol = ( ::apache::airavata::model::appcatalog::computeresource::JobSubmissionProtocol::type)ecast2;
this->__isset.preferredJobSubmissionProtocol = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 6:
if (ftype == ::apache::thrift::protocol::T_I32) {
int32_t ecast3;
xfer += iprot->readI32(ecast3);
this->preferredDataMovementProtocol = ( ::apache::airavata::model::data::movement::DataMovementProtocol::type)ecast3;
this->__isset.preferredDataMovementProtocol = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 7:
if (ftype == ::apache::thrift::protocol::T_STRING) {
xfer += iprot->readString(this->preferredBatchQueue);
this->__isset.preferredBatchQueue = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 8:
if (ftype == ::apache::thrift::protocol::T_STRING) {
xfer += iprot->readString(this->scratchLocation);
this->__isset.scratchLocation = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 9:
if (ftype == ::apache::thrift::protocol::T_STRING) {
xfer += iprot->readString(this->allocationProjectNumber);
this->__isset.allocationProjectNumber = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 10:
if (ftype == ::apache::thrift::protocol::T_STRING) {
xfer += iprot->readString(this->resourceSpecificCredentialStoreToken);
this->__isset.resourceSpecificCredentialStoreToken = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 11:
if (ftype == ::apache::thrift::protocol::T_STRING) {
xfer += iprot->readString(this->usageReportingGatewayId);
this->__isset.usageReportingGatewayId = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 12:
if (ftype == ::apache::thrift::protocol::T_STRING) {
xfer += iprot->readString(this->qualityOfService);
this->__isset.qualityOfService = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 13:
if (ftype == ::apache::thrift::protocol::T_STRING) {
xfer += iprot->readString(this->reservation);
this->__isset.reservation = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 14:
if (ftype == ::apache::thrift::protocol::T_I64) {
xfer += iprot->readI64(this->reservationStartTime);
this->__isset.reservationStartTime = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 15:
if (ftype == ::apache::thrift::protocol::T_I64) {
xfer += iprot->readI64(this->reservationEndTime);
this->__isset.reservationEndTime = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 16:
if (ftype == ::apache::thrift::protocol::T_STRING) {
xfer += iprot->readString(this->sshAccountProvisioner);
this->__isset.sshAccountProvisioner = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 17:
if (ftype == ::apache::thrift::protocol::T_LIST) {
{
this->groupSSHAccountProvisionerConfigs.clear();
uint32_t _size4;
::apache::thrift::protocol::TType _etype7;
xfer += iprot->readListBegin(_etype7, _size4);
this->groupSSHAccountProvisionerConfigs.resize(_size4);
uint32_t _i8;
for (_i8 = 0; _i8 < _size4; ++_i8)
{
xfer += this->groupSSHAccountProvisionerConfigs[_i8].read(iprot);
}
xfer += iprot->readListEnd();
}
this->__isset.groupSSHAccountProvisionerConfigs = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 18:
if (ftype == ::apache::thrift::protocol::T_STRING) {
xfer += iprot->readString(this->sshAccountProvisionerAdditionalInfo);
this->__isset.sshAccountProvisionerAdditionalInfo = true;
} else {
xfer += iprot->skip(ftype);
}
break;
default:
xfer += iprot->skip(ftype);
break;
}
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
if (!isset_computeResourceId)
throw TProtocolException(TProtocolException::INVALID_DATA);
if (!isset_groupResourceProfileId)
throw TProtocolException(TProtocolException::INVALID_DATA);
if (!isset_overridebyAiravata)
throw TProtocolException(TProtocolException::INVALID_DATA);
return xfer;
}
uint32_t GroupComputeResourcePreference::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
apache::thrift::protocol::TOutputRecursionTracker tracker(*oprot);
xfer += oprot->writeStructBegin("GroupComputeResourcePreference");
xfer += oprot->writeFieldBegin("computeResourceId", ::apache::thrift::protocol::T_STRING, 1);
xfer += oprot->writeString(this->computeResourceId);
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldBegin("groupResourceProfileId", ::apache::thrift::protocol::T_STRING, 2);
xfer += oprot->writeString(this->groupResourceProfileId);
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldBegin("overridebyAiravata", ::apache::thrift::protocol::T_BOOL, 3);
xfer += oprot->writeBool(this->overridebyAiravata);
xfer += oprot->writeFieldEnd();
if (this->__isset.loginUserName) {
xfer += oprot->writeFieldBegin("loginUserName", ::apache::thrift::protocol::T_STRING, 4);
xfer += oprot->writeString(this->loginUserName);
xfer += oprot->writeFieldEnd();
}
if (this->__isset.preferredJobSubmissionProtocol) {
xfer += oprot->writeFieldBegin("preferredJobSubmissionProtocol", ::apache::thrift::protocol::T_I32, 5);
xfer += oprot->writeI32((int32_t)this->preferredJobSubmissionProtocol);
xfer += oprot->writeFieldEnd();
}
if (this->__isset.preferredDataMovementProtocol) {
xfer += oprot->writeFieldBegin("preferredDataMovementProtocol", ::apache::thrift::protocol::T_I32, 6);
xfer += oprot->writeI32((int32_t)this->preferredDataMovementProtocol);
xfer += oprot->writeFieldEnd();
}
if (this->__isset.preferredBatchQueue) {
xfer += oprot->writeFieldBegin("preferredBatchQueue", ::apache::thrift::protocol::T_STRING, 7);
xfer += oprot->writeString(this->preferredBatchQueue);
xfer += oprot->writeFieldEnd();
}
if (this->__isset.scratchLocation) {
xfer += oprot->writeFieldBegin("scratchLocation", ::apache::thrift::protocol::T_STRING, 8);
xfer += oprot->writeString(this->scratchLocation);
xfer += oprot->writeFieldEnd();
}
if (this->__isset.allocationProjectNumber) {
xfer += oprot->writeFieldBegin("allocationProjectNumber", ::apache::thrift::protocol::T_STRING, 9);
xfer += oprot->writeString(this->allocationProjectNumber);
xfer += oprot->writeFieldEnd();
}
if (this->__isset.resourceSpecificCredentialStoreToken) {
xfer += oprot->writeFieldBegin("resourceSpecificCredentialStoreToken", ::apache::thrift::protocol::T_STRING, 10);
xfer += oprot->writeString(this->resourceSpecificCredentialStoreToken);
xfer += oprot->writeFieldEnd();
}
if (this->__isset.usageReportingGatewayId) {
xfer += oprot->writeFieldBegin("usageReportingGatewayId", ::apache::thrift::protocol::T_STRING, 11);
xfer += oprot->writeString(this->usageReportingGatewayId);
xfer += oprot->writeFieldEnd();
}
if (this->__isset.qualityOfService) {
xfer += oprot->writeFieldBegin("qualityOfService", ::apache::thrift::protocol::T_STRING, 12);
xfer += oprot->writeString(this->qualityOfService);
xfer += oprot->writeFieldEnd();
}
if (this->__isset.reservation) {
xfer += oprot->writeFieldBegin("reservation", ::apache::thrift::protocol::T_STRING, 13);
xfer += oprot->writeString(this->reservation);
xfer += oprot->writeFieldEnd();
}
if (this->__isset.reservationStartTime) {
xfer += oprot->writeFieldBegin("reservationStartTime", ::apache::thrift::protocol::T_I64, 14);
xfer += oprot->writeI64(this->reservationStartTime);
xfer += oprot->writeFieldEnd();
}
if (this->__isset.reservationEndTime) {
xfer += oprot->writeFieldBegin("reservationEndTime", ::apache::thrift::protocol::T_I64, 15);
xfer += oprot->writeI64(this->reservationEndTime);
xfer += oprot->writeFieldEnd();
}
if (this->__isset.sshAccountProvisioner) {
xfer += oprot->writeFieldBegin("sshAccountProvisioner", ::apache::thrift::protocol::T_STRING, 16);
xfer += oprot->writeString(this->sshAccountProvisioner);
xfer += oprot->writeFieldEnd();
}
if (this->__isset.groupSSHAccountProvisionerConfigs) {
xfer += oprot->writeFieldBegin("groupSSHAccountProvisionerConfigs", ::apache::thrift::protocol::T_LIST, 17);
{
xfer += oprot->writeListBegin(::apache::thrift::protocol::T_STRUCT, static_cast<uint32_t>(this->groupSSHAccountProvisionerConfigs.size()));
std::vector<GroupAccountSSHProvisionerConfig> ::const_iterator _iter9;
for (_iter9 = this->groupSSHAccountProvisionerConfigs.begin(); _iter9 != this->groupSSHAccountProvisionerConfigs.end(); ++_iter9)
{
xfer += (*_iter9).write(oprot);
}
xfer += oprot->writeListEnd();
}
xfer += oprot->writeFieldEnd();
}
if (this->__isset.sshAccountProvisionerAdditionalInfo) {
xfer += oprot->writeFieldBegin("sshAccountProvisionerAdditionalInfo", ::apache::thrift::protocol::T_STRING, 18);
xfer += oprot->writeString(this->sshAccountProvisionerAdditionalInfo);
xfer += oprot->writeFieldEnd();
}
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
return xfer;
}
void swap(GroupComputeResourcePreference &a, GroupComputeResourcePreference &b) {
using ::std::swap;
swap(a.computeResourceId, b.computeResourceId);
swap(a.groupResourceProfileId, b.groupResourceProfileId);
swap(a.overridebyAiravata, b.overridebyAiravata);
swap(a.loginUserName, b.loginUserName);
swap(a.preferredJobSubmissionProtocol, b.preferredJobSubmissionProtocol);
swap(a.preferredDataMovementProtocol, b.preferredDataMovementProtocol);
swap(a.preferredBatchQueue, b.preferredBatchQueue);
swap(a.scratchLocation, b.scratchLocation);
swap(a.allocationProjectNumber, b.allocationProjectNumber);
swap(a.resourceSpecificCredentialStoreToken, b.resourceSpecificCredentialStoreToken);
swap(a.usageReportingGatewayId, b.usageReportingGatewayId);
swap(a.qualityOfService, b.qualityOfService);
swap(a.reservation, b.reservation);
swap(a.reservationStartTime, b.reservationStartTime);
swap(a.reservationEndTime, b.reservationEndTime);
swap(a.sshAccountProvisioner, b.sshAccountProvisioner);
swap(a.groupSSHAccountProvisionerConfigs, b.groupSSHAccountProvisionerConfigs);
swap(a.sshAccountProvisionerAdditionalInfo, b.sshAccountProvisionerAdditionalInfo);
swap(a.__isset, b.__isset);
}
GroupComputeResourcePreference::GroupComputeResourcePreference(const GroupComputeResourcePreference& other10) {
computeResourceId = other10.computeResourceId;
groupResourceProfileId = other10.groupResourceProfileId;
overridebyAiravata = other10.overridebyAiravata;
loginUserName = other10.loginUserName;
preferredJobSubmissionProtocol = other10.preferredJobSubmissionProtocol;
preferredDataMovementProtocol = other10.preferredDataMovementProtocol;
preferredBatchQueue = other10.preferredBatchQueue;
scratchLocation = other10.scratchLocation;
allocationProjectNumber = other10.allocationProjectNumber;
resourceSpecificCredentialStoreToken = other10.resourceSpecificCredentialStoreToken;
usageReportingGatewayId = other10.usageReportingGatewayId;
qualityOfService = other10.qualityOfService;
reservation = other10.reservation;
reservationStartTime = other10.reservationStartTime;
reservationEndTime = other10.reservationEndTime;
sshAccountProvisioner = other10.sshAccountProvisioner;
groupSSHAccountProvisionerConfigs = other10.groupSSHAccountProvisionerConfigs;
sshAccountProvisionerAdditionalInfo = other10.sshAccountProvisionerAdditionalInfo;
__isset = other10.__isset;
}
GroupComputeResourcePreference& GroupComputeResourcePreference::operator=(const GroupComputeResourcePreference& other11) {
computeResourceId = other11.computeResourceId;
groupResourceProfileId = other11.groupResourceProfileId;
overridebyAiravata = other11.overridebyAiravata;
loginUserName = other11.loginUserName;
preferredJobSubmissionProtocol = other11.preferredJobSubmissionProtocol;
preferredDataMovementProtocol = other11.preferredDataMovementProtocol;
preferredBatchQueue = other11.preferredBatchQueue;
scratchLocation = other11.scratchLocation;
allocationProjectNumber = other11.allocationProjectNumber;
resourceSpecificCredentialStoreToken = other11.resourceSpecificCredentialStoreToken;
usageReportingGatewayId = other11.usageReportingGatewayId;
qualityOfService = other11.qualityOfService;
reservation = other11.reservation;
reservationStartTime = other11.reservationStartTime;
reservationEndTime = other11.reservationEndTime;
sshAccountProvisioner = other11.sshAccountProvisioner;
groupSSHAccountProvisionerConfigs = other11.groupSSHAccountProvisionerConfigs;
sshAccountProvisionerAdditionalInfo = other11.sshAccountProvisionerAdditionalInfo;
__isset = other11.__isset;
return *this;
}
void GroupComputeResourcePreference::printTo(std::ostream& out) const {
using ::apache::thrift::to_string;
out << "GroupComputeResourcePreference(";
out << "computeResourceId=" << to_string(computeResourceId);
out << ", " << "groupResourceProfileId=" << to_string(groupResourceProfileId);
out << ", " << "overridebyAiravata=" << to_string(overridebyAiravata);
out << ", " << "loginUserName="; (__isset.loginUserName ? (out << to_string(loginUserName)) : (out << "<null>"));
out << ", " << "preferredJobSubmissionProtocol="; (__isset.preferredJobSubmissionProtocol ? (out << to_string(preferredJobSubmissionProtocol)) : (out << "<null>"));
out << ", " << "preferredDataMovementProtocol="; (__isset.preferredDataMovementProtocol ? (out << to_string(preferredDataMovementProtocol)) : (out << "<null>"));
out << ", " << "preferredBatchQueue="; (__isset.preferredBatchQueue ? (out << to_string(preferredBatchQueue)) : (out << "<null>"));
out << ", " << "scratchLocation="; (__isset.scratchLocation ? (out << to_string(scratchLocation)) : (out << "<null>"));
out << ", " << "allocationProjectNumber="; (__isset.allocationProjectNumber ? (out << to_string(allocationProjectNumber)) : (out << "<null>"));
out << ", " << "resourceSpecificCredentialStoreToken="; (__isset.resourceSpecificCredentialStoreToken ? (out << to_string(resourceSpecificCredentialStoreToken)) : (out << "<null>"));
out << ", " << "usageReportingGatewayId="; (__isset.usageReportingGatewayId ? (out << to_string(usageReportingGatewayId)) : (out << "<null>"));
out << ", " << "qualityOfService="; (__isset.qualityOfService ? (out << to_string(qualityOfService)) : (out << "<null>"));
out << ", " << "reservation="; (__isset.reservation ? (out << to_string(reservation)) : (out << "<null>"));
out << ", " << "reservationStartTime="; (__isset.reservationStartTime ? (out << to_string(reservationStartTime)) : (out << "<null>"));
out << ", " << "reservationEndTime="; (__isset.reservationEndTime ? (out << to_string(reservationEndTime)) : (out << "<null>"));
out << ", " << "sshAccountProvisioner="; (__isset.sshAccountProvisioner ? (out << to_string(sshAccountProvisioner)) : (out << "<null>"));
out << ", " << "groupSSHAccountProvisionerConfigs="; (__isset.groupSSHAccountProvisionerConfigs ? (out << to_string(groupSSHAccountProvisionerConfigs)) : (out << "<null>"));
out << ", " << "sshAccountProvisionerAdditionalInfo="; (__isset.sshAccountProvisionerAdditionalInfo ? (out << to_string(sshAccountProvisionerAdditionalInfo)) : (out << "<null>"));
out << ")";
}
ComputeResourcePolicy::~ComputeResourcePolicy() throw() {
}
void ComputeResourcePolicy::__set_resourcePolicyId(const std::string& val) {
this->resourcePolicyId = val;
}
void ComputeResourcePolicy::__set_computeResourceId(const std::string& val) {
this->computeResourceId = val;
}
void ComputeResourcePolicy::__set_groupResourceProfileId(const std::string& val) {
this->groupResourceProfileId = val;
}
void ComputeResourcePolicy::__set_allowedBatchQueues(const std::vector<std::string> & val) {
this->allowedBatchQueues = val;
__isset.allowedBatchQueues = true;
}
uint32_t ComputeResourcePolicy::read(::apache::thrift::protocol::TProtocol* iprot) {
apache::thrift::protocol::TInputRecursionTracker tracker(*iprot);
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
bool isset_resourcePolicyId = false;
bool isset_computeResourceId = false;
bool isset_groupResourceProfileId = false;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
switch (fid)
{
case 1:
if (ftype == ::apache::thrift::protocol::T_STRING) {
xfer += iprot->readString(this->resourcePolicyId);
isset_resourcePolicyId = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 2:
if (ftype == ::apache::thrift::protocol::T_STRING) {
xfer += iprot->readString(this->computeResourceId);
isset_computeResourceId = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 3:
if (ftype == ::apache::thrift::protocol::T_STRING) {
xfer += iprot->readString(this->groupResourceProfileId);
isset_groupResourceProfileId = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 4:
if (ftype == ::apache::thrift::protocol::T_LIST) {
{
this->allowedBatchQueues.clear();
uint32_t _size12;
::apache::thrift::protocol::TType _etype15;
xfer += iprot->readListBegin(_etype15, _size12);
this->allowedBatchQueues.resize(_size12);
uint32_t _i16;
for (_i16 = 0; _i16 < _size12; ++_i16)
{
xfer += iprot->readString(this->allowedBatchQueues[_i16]);
}
xfer += iprot->readListEnd();
}
this->__isset.allowedBatchQueues = true;
} else {
xfer += iprot->skip(ftype);
}
break;
default:
xfer += iprot->skip(ftype);
break;
}
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
if (!isset_resourcePolicyId)
throw TProtocolException(TProtocolException::INVALID_DATA);
if (!isset_computeResourceId)
throw TProtocolException(TProtocolException::INVALID_DATA);
if (!isset_groupResourceProfileId)
throw TProtocolException(TProtocolException::INVALID_DATA);
return xfer;
}
uint32_t ComputeResourcePolicy::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
apache::thrift::protocol::TOutputRecursionTracker tracker(*oprot);
xfer += oprot->writeStructBegin("ComputeResourcePolicy");
xfer += oprot->writeFieldBegin("resourcePolicyId", ::apache::thrift::protocol::T_STRING, 1);
xfer += oprot->writeString(this->resourcePolicyId);
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldBegin("computeResourceId", ::apache::thrift::protocol::T_STRING, 2);
xfer += oprot->writeString(this->computeResourceId);
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldBegin("groupResourceProfileId", ::apache::thrift::protocol::T_STRING, 3);
xfer += oprot->writeString(this->groupResourceProfileId);
xfer += oprot->writeFieldEnd();
if (this->__isset.allowedBatchQueues) {
xfer += oprot->writeFieldBegin("allowedBatchQueues", ::apache::thrift::protocol::T_LIST, 4);
{
xfer += oprot->writeListBegin(::apache::thrift::protocol::T_STRING, static_cast<uint32_t>(this->allowedBatchQueues.size()));
std::vector<std::string> ::const_iterator _iter17;
for (_iter17 = this->allowedBatchQueues.begin(); _iter17 != this->allowedBatchQueues.end(); ++_iter17)
{
xfer += oprot->writeString((*_iter17));
}
xfer += oprot->writeListEnd();
}
xfer += oprot->writeFieldEnd();
}
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
return xfer;
}
void swap(ComputeResourcePolicy &a, ComputeResourcePolicy &b) {
using ::std::swap;
swap(a.resourcePolicyId, b.resourcePolicyId);
swap(a.computeResourceId, b.computeResourceId);
swap(a.groupResourceProfileId, b.groupResourceProfileId);
swap(a.allowedBatchQueues, b.allowedBatchQueues);
swap(a.__isset, b.__isset);
}
ComputeResourcePolicy::ComputeResourcePolicy(const ComputeResourcePolicy& other18) {
resourcePolicyId = other18.resourcePolicyId;
computeResourceId = other18.computeResourceId;
groupResourceProfileId = other18.groupResourceProfileId;
allowedBatchQueues = other18.allowedBatchQueues;
__isset = other18.__isset;
}
ComputeResourcePolicy& ComputeResourcePolicy::operator=(const ComputeResourcePolicy& other19) {
resourcePolicyId = other19.resourcePolicyId;
computeResourceId = other19.computeResourceId;
groupResourceProfileId = other19.groupResourceProfileId;
allowedBatchQueues = other19.allowedBatchQueues;
__isset = other19.__isset;
return *this;
}
void ComputeResourcePolicy::printTo(std::ostream& out) const {
using ::apache::thrift::to_string;
out << "ComputeResourcePolicy(";
out << "resourcePolicyId=" << to_string(resourcePolicyId);
out << ", " << "computeResourceId=" << to_string(computeResourceId);
out << ", " << "groupResourceProfileId=" << to_string(groupResourceProfileId);
out << ", " << "allowedBatchQueues="; (__isset.allowedBatchQueues ? (out << to_string(allowedBatchQueues)) : (out << "<null>"));
out << ")";
}
BatchQueueResourcePolicy::~BatchQueueResourcePolicy() throw() {
}
void BatchQueueResourcePolicy::__set_resourcePolicyId(const std::string& val) {
this->resourcePolicyId = val;
}
void BatchQueueResourcePolicy::__set_computeResourceId(const std::string& val) {
this->computeResourceId = val;
}
void BatchQueueResourcePolicy::__set_groupResourceProfileId(const std::string& val) {
this->groupResourceProfileId = val;
}
void BatchQueueResourcePolicy::__set_queuename(const std::string& val) {
this->queuename = val;
__isset.queuename = true;
}
void BatchQueueResourcePolicy::__set_maxAllowedNodes(const int32_t val) {
this->maxAllowedNodes = val;
__isset.maxAllowedNodes = true;
}
void BatchQueueResourcePolicy::__set_maxAllowedCores(const int32_t val) {
this->maxAllowedCores = val;
__isset.maxAllowedCores = true;
}
void BatchQueueResourcePolicy::__set_maxAllowedWalltime(const int32_t val) {
this->maxAllowedWalltime = val;
__isset.maxAllowedWalltime = true;
}
uint32_t BatchQueueResourcePolicy::read(::apache::thrift::protocol::TProtocol* iprot) {
apache::thrift::protocol::TInputRecursionTracker tracker(*iprot);
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
bool isset_resourcePolicyId = false;
bool isset_computeResourceId = false;
bool isset_groupResourceProfileId = false;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
switch (fid)
{
case 1:
if (ftype == ::apache::thrift::protocol::T_STRING) {
xfer += iprot->readString(this->resourcePolicyId);
isset_resourcePolicyId = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 2:
if (ftype == ::apache::thrift::protocol::T_STRING) {
xfer += iprot->readString(this->computeResourceId);
isset_computeResourceId = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 3:
if (ftype == ::apache::thrift::protocol::T_STRING) {
xfer += iprot->readString(this->groupResourceProfileId);
isset_groupResourceProfileId = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 4:
if (ftype == ::apache::thrift::protocol::T_STRING) {
xfer += iprot->readString(this->queuename);
this->__isset.queuename = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 5:
if (ftype == ::apache::thrift::protocol::T_I32) {
xfer += iprot->readI32(this->maxAllowedNodes);
this->__isset.maxAllowedNodes = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 6:
if (ftype == ::apache::thrift::protocol::T_I32) {
xfer += iprot->readI32(this->maxAllowedCores);
this->__isset.maxAllowedCores = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 7:
if (ftype == ::apache::thrift::protocol::T_I32) {
xfer += iprot->readI32(this->maxAllowedWalltime);
this->__isset.maxAllowedWalltime = true;
} else {
xfer += iprot->skip(ftype);
}
break;
default:
xfer += iprot->skip(ftype);
break;
}
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
if (!isset_resourcePolicyId)
throw TProtocolException(TProtocolException::INVALID_DATA);
if (!isset_computeResourceId)
throw TProtocolException(TProtocolException::INVALID_DATA);
if (!isset_groupResourceProfileId)
throw TProtocolException(TProtocolException::INVALID_DATA);
return xfer;
}
uint32_t BatchQueueResourcePolicy::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
apache::thrift::protocol::TOutputRecursionTracker tracker(*oprot);
xfer += oprot->writeStructBegin("BatchQueueResourcePolicy");
xfer += oprot->writeFieldBegin("resourcePolicyId", ::apache::thrift::protocol::T_STRING, 1);
xfer += oprot->writeString(this->resourcePolicyId);
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldBegin("computeResourceId", ::apache::thrift::protocol::T_STRING, 2);
xfer += oprot->writeString(this->computeResourceId);
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldBegin("groupResourceProfileId", ::apache::thrift::protocol::T_STRING, 3);
xfer += oprot->writeString(this->groupResourceProfileId);
xfer += oprot->writeFieldEnd();
if (this->__isset.queuename) {
xfer += oprot->writeFieldBegin("queuename", ::apache::thrift::protocol::T_STRING, 4);
xfer += oprot->writeString(this->queuename);
xfer += oprot->writeFieldEnd();
}
if (this->__isset.maxAllowedNodes) {
xfer += oprot->writeFieldBegin("maxAllowedNodes", ::apache::thrift::protocol::T_I32, 5);
xfer += oprot->writeI32(this->maxAllowedNodes);
xfer += oprot->writeFieldEnd();
}
if (this->__isset.maxAllowedCores) {
xfer += oprot->writeFieldBegin("maxAllowedCores", ::apache::thrift::protocol::T_I32, 6);
xfer += oprot->writeI32(this->maxAllowedCores);
xfer += oprot->writeFieldEnd();
}
if (this->__isset.maxAllowedWalltime) {
xfer += oprot->writeFieldBegin("maxAllowedWalltime", ::apache::thrift::protocol::T_I32, 7);
xfer += oprot->writeI32(this->maxAllowedWalltime);
xfer += oprot->writeFieldEnd();
}
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
return xfer;
}
void swap(BatchQueueResourcePolicy &a, BatchQueueResourcePolicy &b) {
using ::std::swap;
swap(a.resourcePolicyId, b.resourcePolicyId);
swap(a.computeResourceId, b.computeResourceId);
swap(a.groupResourceProfileId, b.groupResourceProfileId);
swap(a.queuename, b.queuename);
swap(a.maxAllowedNodes, b.maxAllowedNodes);
swap(a.maxAllowedCores, b.maxAllowedCores);
swap(a.maxAllowedWalltime, b.maxAllowedWalltime);
swap(a.__isset, b.__isset);
}
BatchQueueResourcePolicy::BatchQueueResourcePolicy(const BatchQueueResourcePolicy& other20) {
resourcePolicyId = other20.resourcePolicyId;
computeResourceId = other20.computeResourceId;
groupResourceProfileId = other20.groupResourceProfileId;
queuename = other20.queuename;
maxAllowedNodes = other20.maxAllowedNodes;
maxAllowedCores = other20.maxAllowedCores;
maxAllowedWalltime = other20.maxAllowedWalltime;
__isset = other20.__isset;
}
BatchQueueResourcePolicy& BatchQueueResourcePolicy::operator=(const BatchQueueResourcePolicy& other21) {
resourcePolicyId = other21.resourcePolicyId;
computeResourceId = other21.computeResourceId;
groupResourceProfileId = other21.groupResourceProfileId;
queuename = other21.queuename;
maxAllowedNodes = other21.maxAllowedNodes;
maxAllowedCores = other21.maxAllowedCores;
maxAllowedWalltime = other21.maxAllowedWalltime;
__isset = other21.__isset;
return *this;
}
void BatchQueueResourcePolicy::printTo(std::ostream& out) const {
using ::apache::thrift::to_string;
out << "BatchQueueResourcePolicy(";
out << "resourcePolicyId=" << to_string(resourcePolicyId);
out << ", " << "computeResourceId=" << to_string(computeResourceId);
out << ", " << "groupResourceProfileId=" << to_string(groupResourceProfileId);
out << ", " << "queuename="; (__isset.queuename ? (out << to_string(queuename)) : (out << "<null>"));
out << ", " << "maxAllowedNodes="; (__isset.maxAllowedNodes ? (out << to_string(maxAllowedNodes)) : (out << "<null>"));
out << ", " << "maxAllowedCores="; (__isset.maxAllowedCores ? (out << to_string(maxAllowedCores)) : (out << "<null>"));
out << ", " << "maxAllowedWalltime="; (__isset.maxAllowedWalltime ? (out << to_string(maxAllowedWalltime)) : (out << "<null>"));
out << ")";
}
GroupResourceProfile::~GroupResourceProfile() throw() {
}
void GroupResourceProfile::__set_gatewayId(const std::string& val) {
this->gatewayId = val;
}
void GroupResourceProfile::__set_groupResourceProfileId(const std::string& val) {
this->groupResourceProfileId = val;
}
void GroupResourceProfile::__set_groupResourceProfileName(const std::string& val) {
this->groupResourceProfileName = val;
__isset.groupResourceProfileName = true;
}
void GroupResourceProfile::__set_computePreferences(const std::vector<GroupComputeResourcePreference> & val) {
this->computePreferences = val;
__isset.computePreferences = true;
}
void GroupResourceProfile::__set_computeResourcePolicies(const std::vector<ComputeResourcePolicy> & val) {
this->computeResourcePolicies = val;
__isset.computeResourcePolicies = true;
}
void GroupResourceProfile::__set_batchQueueResourcePolicies(const std::vector<BatchQueueResourcePolicy> & val) {
this->batchQueueResourcePolicies = val;
__isset.batchQueueResourcePolicies = true;
}
void GroupResourceProfile::__set_creationTime(const int64_t val) {
this->creationTime = val;
__isset.creationTime = true;
}
void GroupResourceProfile::__set_updatedTime(const int64_t val) {
this->updatedTime = val;
__isset.updatedTime = true;
}
void GroupResourceProfile::__set_defaultCredentialStoreToken(const std::string& val) {
this->defaultCredentialStoreToken = val;
__isset.defaultCredentialStoreToken = true;
}
uint32_t GroupResourceProfile::read(::apache::thrift::protocol::TProtocol* iprot) {
apache::thrift::protocol::TInputRecursionTracker tracker(*iprot);
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
bool isset_gatewayId = false;
bool isset_groupResourceProfileId = false;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
switch (fid)
{
case 1:
if (ftype == ::apache::thrift::protocol::T_STRING) {
xfer += iprot->readString(this->gatewayId);
isset_gatewayId = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 2:
if (ftype == ::apache::thrift::protocol::T_STRING) {
xfer += iprot->readString(this->groupResourceProfileId);
isset_groupResourceProfileId = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 3:
if (ftype == ::apache::thrift::protocol::T_STRING) {
xfer += iprot->readString(this->groupResourceProfileName);
this->__isset.groupResourceProfileName = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 4:
if (ftype == ::apache::thrift::protocol::T_LIST) {
{
this->computePreferences.clear();
uint32_t _size22;
::apache::thrift::protocol::TType _etype25;
xfer += iprot->readListBegin(_etype25, _size22);
this->computePreferences.resize(_size22);
uint32_t _i26;
for (_i26 = 0; _i26 < _size22; ++_i26)
{
xfer += this->computePreferences[_i26].read(iprot);
}
xfer += iprot->readListEnd();
}
this->__isset.computePreferences = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 5:
if (ftype == ::apache::thrift::protocol::T_LIST) {
{
this->computeResourcePolicies.clear();
uint32_t _size27;
::apache::thrift::protocol::TType _etype30;
xfer += iprot->readListBegin(_etype30, _size27);
this->computeResourcePolicies.resize(_size27);
uint32_t _i31;
for (_i31 = 0; _i31 < _size27; ++_i31)
{
xfer += this->computeResourcePolicies[_i31].read(iprot);
}
xfer += iprot->readListEnd();
}
this->__isset.computeResourcePolicies = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 6:
if (ftype == ::apache::thrift::protocol::T_LIST) {
{
this->batchQueueResourcePolicies.clear();
uint32_t _size32;
::apache::thrift::protocol::TType _etype35;
xfer += iprot->readListBegin(_etype35, _size32);
this->batchQueueResourcePolicies.resize(_size32);
uint32_t _i36;
for (_i36 = 0; _i36 < _size32; ++_i36)
{
xfer += this->batchQueueResourcePolicies[_i36].read(iprot);
}
xfer += iprot->readListEnd();
}
this->__isset.batchQueueResourcePolicies = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 7:
if (ftype == ::apache::thrift::protocol::T_I64) {
xfer += iprot->readI64(this->creationTime);
this->__isset.creationTime = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 8:
if (ftype == ::apache::thrift::protocol::T_I64) {
xfer += iprot->readI64(this->updatedTime);
this->__isset.updatedTime = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 9:
if (ftype == ::apache::thrift::protocol::T_STRING) {
xfer += iprot->readString(this->defaultCredentialStoreToken);
this->__isset.defaultCredentialStoreToken = true;
} else {
xfer += iprot->skip(ftype);
}
break;
default:
xfer += iprot->skip(ftype);
break;
}
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
if (!isset_gatewayId)
throw TProtocolException(TProtocolException::INVALID_DATA);
if (!isset_groupResourceProfileId)
throw TProtocolException(TProtocolException::INVALID_DATA);
return xfer;
}
uint32_t GroupResourceProfile::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
apache::thrift::protocol::TOutputRecursionTracker tracker(*oprot);
xfer += oprot->writeStructBegin("GroupResourceProfile");
xfer += oprot->writeFieldBegin("gatewayId", ::apache::thrift::protocol::T_STRING, 1);
xfer += oprot->writeString(this->gatewayId);
xfer += oprot->writeFieldEnd();
xfer += oprot->writeFieldBegin("groupResourceProfileId", ::apache::thrift::protocol::T_STRING, 2);
xfer += oprot->writeString(this->groupResourceProfileId);
xfer += oprot->writeFieldEnd();
if (this->__isset.groupResourceProfileName) {
xfer += oprot->writeFieldBegin("groupResourceProfileName", ::apache::thrift::protocol::T_STRING, 3);
xfer += oprot->writeString(this->groupResourceProfileName);
xfer += oprot->writeFieldEnd();
}
if (this->__isset.computePreferences) {
xfer += oprot->writeFieldBegin("computePreferences", ::apache::thrift::protocol::T_LIST, 4);
{
xfer += oprot->writeListBegin(::apache::thrift::protocol::T_STRUCT, static_cast<uint32_t>(this->computePreferences.size()));
std::vector<GroupComputeResourcePreference> ::const_iterator _iter37;
for (_iter37 = this->computePreferences.begin(); _iter37 != this->computePreferences.end(); ++_iter37)
{
xfer += (*_iter37).write(oprot);
}
xfer += oprot->writeListEnd();
}
xfer += oprot->writeFieldEnd();
}
if (this->__isset.computeResourcePolicies) {
xfer += oprot->writeFieldBegin("computeResourcePolicies", ::apache::thrift::protocol::T_LIST, 5);
{
xfer += oprot->writeListBegin(::apache::thrift::protocol::T_STRUCT, static_cast<uint32_t>(this->computeResourcePolicies.size()));
std::vector<ComputeResourcePolicy> ::const_iterator _iter38;
for (_iter38 = this->computeResourcePolicies.begin(); _iter38 != this->computeResourcePolicies.end(); ++_iter38)
{
xfer += (*_iter38).write(oprot);
}
xfer += oprot->writeListEnd();
}
xfer += oprot->writeFieldEnd();
}
if (this->__isset.batchQueueResourcePolicies) {
xfer += oprot->writeFieldBegin("batchQueueResourcePolicies", ::apache::thrift::protocol::T_LIST, 6);
{
xfer += oprot->writeListBegin(::apache::thrift::protocol::T_STRUCT, static_cast<uint32_t>(this->batchQueueResourcePolicies.size()));
std::vector<BatchQueueResourcePolicy> ::const_iterator _iter39;
for (_iter39 = this->batchQueueResourcePolicies.begin(); _iter39 != this->batchQueueResourcePolicies.end(); ++_iter39)
{
xfer += (*_iter39).write(oprot);
}
xfer += oprot->writeListEnd();
}
xfer += oprot->writeFieldEnd();
}
if (this->__isset.creationTime) {
xfer += oprot->writeFieldBegin("creationTime", ::apache::thrift::protocol::T_I64, 7);
xfer += oprot->writeI64(this->creationTime);
xfer += oprot->writeFieldEnd();
}
if (this->__isset.updatedTime) {
xfer += oprot->writeFieldBegin("updatedTime", ::apache::thrift::protocol::T_I64, 8);
xfer += oprot->writeI64(this->updatedTime);
xfer += oprot->writeFieldEnd();
}
if (this->__isset.defaultCredentialStoreToken) {
xfer += oprot->writeFieldBegin("defaultCredentialStoreToken", ::apache::thrift::protocol::T_STRING, 9);
xfer += oprot->writeString(this->defaultCredentialStoreToken);
xfer += oprot->writeFieldEnd();
}
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
return xfer;
}
void swap(GroupResourceProfile &a, GroupResourceProfile &b) {
using ::std::swap;
swap(a.gatewayId, b.gatewayId);
swap(a.groupResourceProfileId, b.groupResourceProfileId);
swap(a.groupResourceProfileName, b.groupResourceProfileName);
swap(a.computePreferences, b.computePreferences);
swap(a.computeResourcePolicies, b.computeResourcePolicies);
swap(a.batchQueueResourcePolicies, b.batchQueueResourcePolicies);
swap(a.creationTime, b.creationTime);
swap(a.updatedTime, b.updatedTime);
swap(a.defaultCredentialStoreToken, b.defaultCredentialStoreToken);
swap(a.__isset, b.__isset);
}
GroupResourceProfile::GroupResourceProfile(const GroupResourceProfile& other40) {
gatewayId = other40.gatewayId;
groupResourceProfileId = other40.groupResourceProfileId;
groupResourceProfileName = other40.groupResourceProfileName;
computePreferences = other40.computePreferences;
computeResourcePolicies = other40.computeResourcePolicies;
batchQueueResourcePolicies = other40.batchQueueResourcePolicies;
creationTime = other40.creationTime;
updatedTime = other40.updatedTime;
defaultCredentialStoreToken = other40.defaultCredentialStoreToken;
__isset = other40.__isset;
}
GroupResourceProfile& GroupResourceProfile::operator=(const GroupResourceProfile& other41) {
gatewayId = other41.gatewayId;
groupResourceProfileId = other41.groupResourceProfileId;
groupResourceProfileName = other41.groupResourceProfileName;
computePreferences = other41.computePreferences;
computeResourcePolicies = other41.computeResourcePolicies;
batchQueueResourcePolicies = other41.batchQueueResourcePolicies;
creationTime = other41.creationTime;
updatedTime = other41.updatedTime;
defaultCredentialStoreToken = other41.defaultCredentialStoreToken;
__isset = other41.__isset;
return *this;
}
void GroupResourceProfile::printTo(std::ostream& out) const {
using ::apache::thrift::to_string;
out << "GroupResourceProfile(";
out << "gatewayId=" << to_string(gatewayId);
out << ", " << "groupResourceProfileId=" << to_string(groupResourceProfileId);
out << ", " << "groupResourceProfileName="; (__isset.groupResourceProfileName ? (out << to_string(groupResourceProfileName)) : (out << "<null>"));
out << ", " << "computePreferences="; (__isset.computePreferences ? (out << to_string(computePreferences)) : (out << "<null>"));
out << ", " << "computeResourcePolicies="; (__isset.computeResourcePolicies ? (out << to_string(computeResourcePolicies)) : (out << "<null>"));
out << ", " << "batchQueueResourcePolicies="; (__isset.batchQueueResourcePolicies ? (out << to_string(batchQueueResourcePolicies)) : (out << "<null>"));
out << ", " << "creationTime="; (__isset.creationTime ? (out << to_string(creationTime)) : (out << "<null>"));
out << ", " << "updatedTime="; (__isset.updatedTime ? (out << to_string(updatedTime)) : (out << "<null>"));
out << ", " << "defaultCredentialStoreToken="; (__isset.defaultCredentialStoreToken ? (out << to_string(defaultCredentialStoreToken)) : (out << "<null>"));
out << ")";
}
}}}}} // namespace
| 38.773826 | 184 | 0.686551 |
fd5600d4de12c6ffe705171681fb34b5fab1cf0e | 764 | cpp | C++ | dynamic-programming/C++/0063-unique-paths-ii/main.cpp | ljyljy/LeetCode-Solution-in-Good-Style | 0998211d21796868061eb22e2cbb9bcd112cedce | [
"Apache-2.0"
] | 1 | 2020-03-09T00:45:32.000Z | 2020-03-09T00:45:32.000Z | dynamic-programming/C++/0063-unique-paths-ii/main.cpp | Eddiehugh/LeetCode-Solution-Well-Formed | bdc1e7153de737b84890153434bf8df5838d0be5 | [
"Apache-2.0"
] | null | null | null | dynamic-programming/C++/0063-unique-paths-ii/main.cpp | Eddiehugh/LeetCode-Solution-Well-Formed | bdc1e7153de737b84890153434bf8df5838d0be5 | [
"Apache-2.0"
] | 1 | 2021-06-17T09:21:54.000Z | 2021-06-17T09:21:54.000Z | #include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>> &obstacleGrid) {
int m = obstacleGrid.size();
if (m == 0) {
return 0;
}
int n = obstacleGrid[0].size();
vector<long> dp(n + 1, 0);
if (obstacleGrid[0][0] == 1) {
return 0;
}
// 注意:这里是索引为 1 的位置
dp[1] = 1;
// 下面这两行赋值比较关键
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (obstacleGrid[i][j] == 1) {
dp[j + 1] = 0;
} else {
dp[j + 1] += dp[j];
}
}
}
return dp[n];
}
}; | 21.828571 | 69 | 0.39267 |
fd56b6f69cb56a982b035873e8b501012f623a25 | 29,721 | cpp | C++ | Common/src/song.cpp | danfrz/PLEBTracker | f6aa7078c3f39e9c8b025e70e7dbeab19119e213 | [
"MIT"
] | 86 | 2016-04-13T16:39:02.000Z | 2022-03-20T17:35:09.000Z | Common/src/song.cpp | danfrz/PLEBTracker | f6aa7078c3f39e9c8b025e70e7dbeab19119e213 | [
"MIT"
] | 19 | 2016-04-14T07:38:19.000Z | 2021-04-12T21:58:08.000Z | Common/src/song.cpp | danfrz/PLEBTracker | f6aa7078c3f39e9c8b025e70e7dbeab19119e213 | [
"MIT"
] | 8 | 2018-06-04T22:02:06.000Z | 2022-01-19T05:34:19.000Z | #include "song.h"
#include <iostream>
Song::Song(bool fill_defaults)
{
bytes_per_row = 0x1CB0;
interrow_resolution = 0x18;
for(int i = 9; i < SONGNAME_LENGTH+1; i++)
songname[i] = 0;
songname[0]='s';
songname[1]='o';
songname[2]='n';
songname[3]='g';
songname[4]=' ';
songname[5]='n';
songname[6]='a';
songname[7]='m';
songname[8]='e';
instruments = new Instrument*[256];
num_instruments = 0;
tracks = 4;
patterns = new Pattern*[256];
num_patterns = 0;
//Either 1 or 0; will be same as num_instruments. either work.
for(int i = num_patterns; i < 256; i++)
{
instruments[i] = NULL;
patterns[i] = NULL;
}
orders = new unsigned char[256];
num_orders=0;
waveEntries = 0;
waveTable = new unsigned short[512];
for(int i = 0; i < 512; i++)
waveTable[i] = 0;
pulseEntries = 0;
pulseTable = new unsigned short[512];
for(int i = 0; i < 512; i++)
pulseTable[i] = 0;
filterEntries = 0;
filterTable = new unsigned short[512];
for(int i = 0; i < 512; i++)
filterTable[i] = 0;
if(fill_defaults)
{
num_instruments = 1;
Instrument *defaultInst = new Instrument();
instruments[0] = defaultInst;
Pattern *defaultPat = new Pattern(tracks, 64);
patterns[0] = defaultPat;
num_patterns = 1;
num_orders = 1;
orders[0] = 0;
waveEntries = 1;
waveTable[0] = 0x0100;
pulseEntries = 2;
pulseTable[0] = 0x0000;
pulseTable[1] = 0xFF00;
filterEntries = 3;
filterTable[0] = 0xF000;
filterTable[1] = 0x0000;
filterTable[2] = 0xFF01;
}
}
Song::Song(std::istream &in)
{
patterns = NULL;
instruments = NULL;
orders = new unsigned char[256];
waveTable = new unsigned short[512];
pulseTable = new unsigned short[512];
filterTable = new unsigned short[512];
input(in);
}
Song::~Song()
{
for(int i = 0; i < num_instruments; i++)
delete instruments[i];
for(int i = 0; i < num_patterns; i++)
delete patterns[i];
delete [] instruments;
delete [] patterns;
delete [] orders;
delete [] waveTable;
delete [] pulseTable;
delete [] filterTable;
}
std::ostream &Song::output(std::ostream &out) const
{
out.write(songname, SONGNAME_LENGTH+1);
out.write((char*)&bytes_per_row, sizeof(short));
out.write((char*)&interrow_resolution, sizeof(char));
out.write((char*)&tracks, sizeof(char));
out.write((char*)&num_orders, sizeof(char));
out.write((char*)orders, num_orders);
out.write((char*)&waveEntries, sizeof(short));
out.write((char*)waveTable, waveEntries*sizeof(short));
out.write((char*)&pulseEntries, sizeof(short));
out.write((char*)pulseTable, pulseEntries*sizeof(short));
out.write((char*)&filterEntries, sizeof(short));
out.write((char*)filterTable, filterEntries*sizeof(short));
out.write((char*)&num_instruments, sizeof(char));
for(int i = 0; i < num_instruments; i++)
(instruments[i])->output(out);
out.write((char*)&num_patterns, sizeof(char));
for(int i = 0; i < num_patterns; i++)
(patterns[i])->output(out);
return out;
}
std::istream &Song::input(std::istream &in)
{
if(instruments)
delete [] instruments;
if(patterns)
delete [] patterns;
in.read(songname, SONGNAME_LENGTH+1);
in.read((char*)&bytes_per_row, sizeof(short));
in.read((char*)&interrow_resolution, sizeof(char));
in.read((char*)&tracks, sizeof(char));
in.read((char*)&num_orders, sizeof(char));
in.read((char*)orders, num_orders);
in.read((char*)&waveEntries, sizeof(short));
in.read((char*)waveTable, waveEntries*sizeof(short));
for(int i = waveEntries; i < 512; i++)
waveTable[i] = 0;
in.read((char*)&pulseEntries, sizeof(short));
in.read((char*)pulseTable, pulseEntries*sizeof(short));
for(int i = pulseEntries; i < 512; i++)
pulseTable[i] = 0;
in.read((char*)&filterEntries, sizeof(short));
in.read((char*)filterTable, filterEntries*sizeof(short));
for(int i = filterEntries; i < 512; i++)
filterTable[i] = 0;
instruments = new Instrument*[256];
in.read((char*)&num_instruments, sizeof(char));
for(int i = 0; i < num_instruments; i++)
instruments[i] = new Instrument(in);
for(int i = num_instruments; i < 256; i++)
instruments[i] = NULL;
patterns = new Pattern*[256];
in.read((char*)&num_patterns, sizeof(char));
for(int i = 0; i < num_patterns; i++)
patterns[i] = new Pattern(in);
for(int i = num_patterns; i < 256; i++)
patterns[i] = NULL;
return in;
}
void Song::copyCommutable(Song *other)
{
//Copy things that are necessary for any of the objects of the song to operate
//Instruments, Wavetable, Pulsetable, metadata
//Copy the wave table from this song into the other song
unsigned short *otrwavebl = other->getWaveTable();
for(int i = 0; i < waveEntries; i++)
other->setWaveEntry(i,waveTable[i]);
other->waveEntries = waveEntries;
//Copy the pulse table from this song into the other song
unsigned short *otrpulsebl = other->getPulseTable();
for(int i = 0; i < pulseEntries; i++)
other->setPulseEntry(i,pulseTable[i]);
other->pulseEntries = pulseEntries;
unsigned short *otrfilterbl = other->getFilterTable();
for(int i = 0; i < filterEntries; i++)
other->setFilterEntry(i,filterTable[i]);
other->filterEntries = filterEntries;
//Copy important song data to the other song
other->setInterRowResolution(interrow_resolution);
other->setBytesPerRow(bytes_per_row);
other->setTrackNum(tracks);
//Copy instruments
for(int i = 0; i < num_instruments; i++)
other->addInstrument(new Instrument(*instruments[i]));
}
Song *Song::makeExcerpt(unsigned char orderstart, unsigned char orderend, unsigned char rowstart, unsigned char rowend)
{
unsigned int len = 0;
for(int orderi = orderstart; orderi <= orderend; orderi++)
len += getPatternByOrder(orderi)->numRows();
len -= rowstart;
len -= getPatternByOrder(orderend)->numRows() - orderend+1;
Song *out = new Song(false);
copyCommutable(out);
Pattern *first, *last;
if(orderstart == orderend) //play only one order
{
first = new Pattern(*getPatternByOrder(orderstart));
first->chop(rowstart, rowend);
out->addPattern(first);
out->insertOrder(0,0);
}
else //play multiple orders
{
//Copy over the first and last patterns
first = new Pattern(*getPatternByOrder(orderstart));
last = new Pattern(*getPatternByOrder(orderend));
//Chop them to specification
first->chop(rowstart, first->numRows()-1);
last->chop(0,rowend);
//Add the first pattern
out->addPattern(first);
out->insertOrder(0,0);
//Add the final pattern at the end
out->addPattern(last);
out->insertOrder(1,1);
//The last order will continue to be pushed back by the insertion of other orders on it's location
for(int orderi = orderstart+1, i = 1; orderi < orderend; orderi++, i++)
{
//Have to create new patterns because Song will
//run destructor: the patters would be double-freed
out->addPattern(new Pattern(*getPatternByOrder(orderi)));
out->insertOrder(i,i+1);
}
}
return out;
}
Song *Song::makeExcerpt(unsigned int length, unsigned char orderstart, unsigned char rowstart)
{
//Acc is used to accumulate how many rows have been added already until length has been reached
unsigned char rowend, orderend;
unsigned int acc = getPatternByOrder(orderstart)->numRows() - rowstart;
unsigned char orderi = orderstart;
//Loop through following orders until acc >= length
while (acc < length && ++orderi < num_orders)
{
acc += getPatternByOrder(orderi)->numRows();
}
//Make the ending order the last order that filled acc to length
if(orderi >= num_orders)
orderend = num_orders-1;
else
orderend = orderi;
if(orderstart == orderend) //If there is only one order in this excerpt
{
//cut off rowend at wherever makes the length
rowend = rowstart + length;
if(rowend >= getPatternByOrder(orderstart)->numRows())
rowend = getPatternByOrder(orderstart)->numRows()-1;
}
else
{
//cut off rowend at the max row of the last order's pattern plus (length - acc)
rowend = length - (acc - getPatternByOrder(orderend)->numRows());
}
return makeExcerpt(orderstart, orderend, rowstart, rowend);
}
void Song::setName(const char *name, int length)
{
if(length > SONGNAME_LENGTH)
length = SONGNAME_LENGTH;
for(int i = 0; i < length; i++)
songname[i] = name[i];
}
bool Song::insertOrder(unsigned char dest, unsigned char pattern)
{
if(pattern >= num_patterns)
return false;
if(dest >num_orders)
return false;
for(int i=(num_orders++)-1; i >= dest; i--)
orders[i+1] = orders[i];
orders[dest] = pattern;
return true;
}
bool Song::removeOrder(unsigned char ordr)
{
if(ordr >= num_orders || num_orders == 1)
return false;
num_orders--;
for(int i=ordr; i < num_orders; i++)
orders[i] = orders[i+1];
return true;
}
void Song::setTrackNum(const unsigned newtracks)
{
tracks = newtracks;
//loop through every pattern and change tracks
for(int i = 0; i < num_patterns; i++)
patterns[i]->setTrackNum(newtracks);
}
bool Song::newPattern(unsigned int tracks, unsigned int rows)
{
if(num_patterns == 255)
return false;
Pattern *newPat = new Pattern(tracks,rows);
patterns[num_patterns++] = newPat;
return true;
}
bool Song::clonePattern(unsigned char src)
{
if(num_patterns == 255)
return false;
Pattern *source = patterns[src];
Pattern *newPat = new Pattern(*source);
patterns[num_patterns++] = newPat;
return true;
}
bool Song::clearPattern(unsigned char ptrn)
{
patterns[ptrn]->clear();
}
bool Song::removePattern(unsigned char ptrn)
{
if(ptrn >= num_patterns || num_patterns == 1)
return false;
delete patterns[ptrn];
for(int i = ptrn+1; i < num_patterns; i++)
patterns[i-1] = patterns[i];
num_patterns--;
patterns[num_patterns] = NULL;
//then update orders to the new pattern indicies!
//Set to the first pattern
//so that it stands out and it would stand out looking through order list
for(int i = 0; i < num_orders; i++)
if(orders[i] > ptrn)
orders[i]--;
return true;
}
void Song::addPattern(Pattern *ptrn)
{
if(num_patterns == 0xFF)
return;
patterns[num_patterns] = ptrn;
num_patterns++;
}
bool Song::newInstrument()
{
if(num_instruments == 255)
return false;
Instrument *defaultInst = new Instrument();
instruments[num_instruments++] = defaultInst;
return true;
}
bool Song::cloneInstrument(unsigned char inst)
{
if(num_instruments == 255)
return false;
Instrument *srcInst = instruments[inst];
Instrument *newInst = new Instrument(*srcInst);
instruments[num_instruments++] = newInst;
return true;
}
bool Song::removeInstrument(unsigned char inst)
{
if(inst >= num_instruments || num_instruments == 1)
return false;
delete instruments[inst];
inst+=1;
while(inst < num_instruments)
instruments[inst-1] = instruments[inst++];
num_instruments--;
//then update patterns with new instrument indicies
for(int i = 0; i < num_patterns; i++)
patterns[i]->purgeInstrument(inst);
return true;
}
void Song::addInstrument(Instrument *inst)
{
instruments[num_instruments++]=inst;
}
bool Song::insertWaveEntry(unsigned short index, unsigned short entry)
{
if(waveEntries == 0xFFFF)
return false;
for(unsigned short last = ++waveEntries; last > index; last--)
waveTable[last] = waveTable[last-1];
fixWaveJumps(index, 1);
waveTable[index] = entry;
return true;
}
//The entry is a jump function whose value might be changed
//by the insertion or deletion of other entries.
bool isJumpFunc_Volatile(const unsigned short &wave)
{
unsigned char func = (wave & 0xFF00) >> 8;
switch(func)
{
case 0xFF:
case 0xFC:
case 0xFD:
return true;
}
return false;
}
void Song::fixWaveJumps(const unsigned short &index, short difference)
{
if(difference == 0) return;
//FIX WAVE INDEXES FOR INSTRUMENTS
unsigned char instwav;
if(difference > 0)
{
for(unsigned char i = 0; i < num_instruments; i++)
{
instwav = instruments[i]->getWaveIndex();
// > 0 because the first instrument's wave pointer shouldn't
// realistically change due to insertions at index 0
if(instwav > 0 && instwav > index && instwav < 0xFFFF-difference)
{
instruments[i]->setWaveIndex(instwav+difference);
}
}
}
else
{
for(unsigned char i = 0; i < num_instruments; i++)
{
instwav = instruments[i]->getWaveIndex();
if(instwav > index)
{
if(instwav >= -difference)
instruments[i]->setWaveIndex(instwav +difference);
else
instruments[i]->setWaveIndex(0);
}
}
}
//FIX WAVE JUMPS IN WAVE TABLE
unsigned short jumptype;
unsigned short dest;
if(difference > 0)
{
for(unsigned short i = 0; i < waveEntries; i++)
{
if( isJumpFunc_Volatile(waveTable[i]))//is jump, correct it
{
jumptype = waveTable[i] & 0xFF00;
if( (i < waveEntries-1) && ((waveTable[i+1]&0xFF00) == jumptype))//Long jump
{
dest = ((waveTable[i] & 0xFF) << 8) | (waveTable[i+1] & 0xFF);
if(dest > index && dest < 0xFFFF-difference)
{
dest += difference;
waveTable[i] = jumptype | ((dest & 0xFF00) >> 8);
waveTable[i+1] = jumptype | (dest & 0xFF);
}
i++;
}
else
{
dest = waveTable[i] & 0xFF;
if(dest > index)
{
if(dest >= 0xFF - difference)
{
if(waveEntries < 0xFFFF)
{
dest += difference;
waveTable[i] &= 0xFF00;
waveTable[i] |= ((dest & 0xFF00) >> 8);
insertWaveEntry(i+1,jumptype | (dest & 0xFF));
}
}
else
waveTable[i]+=difference;
}
}
}
}
}
else //difference negative
{
for(unsigned short i = 0; i < waveEntries; i++)
{
if( isJumpFunc_Volatile(waveTable[i]))//is jump, correct it
{
jumptype = waveTable[i] & 0xFF00;
if( (i < waveEntries-1) && ((waveTable[i+1] & 0xFF00) == jumptype) )//Long jump
{
dest = ((waveTable[i] & 0xFF) << 8) | (waveTable[i+1] & 0xFF);
if(dest > index && dest >= -difference)
{
dest += difference;
waveTable[i] = jumptype | ((dest & 0xFF00) >> 8);
waveTable[i+1] = jumptype | (dest & 0xFF);
}
i++;
}
else
{
dest = waveTable[i] & 0xFF;
if(dest > index)
{
if(dest >= -difference)
waveTable[i]+= difference;
else
waveTable[i] &= 0xFF00;
}
}
}
}
}
//FIX WAVE JUMPS IN PATTERNS: 7XX
Pattern *p;
for(int i = 0; i < num_patterns; i++)
{
p = patterns[i];
for(int trk = 0; trk < p->numTracks(); trk++)
{
for(int row = 0; row < p->numRows(); row++)
{
unsigned int entry = p->at(trk,row);
if((entry & 0xF00) == 0x700)
{
unsigned char wavejump = entry & 0xFF;
if(difference > 0)
{
if(wavejump > 0 &&wavejump >= index && wavejump < 0xFF-difference)
{
wavejump +=difference;
}
}
else
{
if(wavejump > index)
{
if(wavejump >= -difference)
wavejump +=difference;
else
wavejump = 0;
}
}
entry &= ~0xFF;
entry |= wavejump;
p->setAt(trk,row,entry);
}
}
}
}
}
bool Song::removeWaveEntry(unsigned short index)
{
if(waveEntries == 0)
return false;
for(unsigned short i = index+1; i < waveEntries; i++)
waveTable[i-1] = waveTable[i];
waveTable[--waveEntries] = 0;
fixWaveJumps(index, -1);
return true;
}
bool Song::insertPulseEntry(unsigned short index, unsigned short entry)
{
if(pulseEntries == 0xFFFF)
return false;
for(unsigned short last = ++pulseEntries; last > index; last--)
pulseTable[last] = pulseTable[last-1];
fixPulseJumps(index, 1);
pulseTable[index] = entry;
return true;
}
void Song::fixPulseJumps(const unsigned short &index, short difference)
{
if(difference == 0) return;
//Fix instrument pulse index references
unsigned short instpls;
if(difference > 0)
{
for(unsigned char i = 0; i < num_instruments; i++)
{
instpls = instruments[i]->getPulseIndex();
// > 0 because the first instrument's wave pointer shouldn't
// realistically change due to insertions at index 0
if(instpls > 0 && instpls > index && instpls < 0xFFFF-difference && instpls != 0xFFFF)
{
instruments[i]->setPulseIndex(instpls+difference);
}
}
}
else
{
for(unsigned char i = 0; i < num_instruments; i++)
{
instpls = instruments[i]->getPulseIndex();
if(instpls > index && instpls != 0xFFFF)
{
if(instpls >= -difference)
instruments[i]->setPulseIndex(instpls +difference);
else
instruments[i]->setPulseIndex(0);
}
}
}
//Fix Pulse jumps
unsigned short jumptype;
unsigned short dest;
if(difference > 0)
{
for(unsigned short i = 0; i < pulseEntries; i++)
{
if( isJumpFunc_Volatile(pulseTable[i]))//is jump, correct it
{
jumptype = pulseTable[i] & 0xFF00;
if( (i < pulseEntries-1) && ((pulseTable[i+1]&0xFF00) == jumptype))//Long jump
{
dest = ((pulseTable[i] & 0xFF) << 8) | (pulseTable[i+1] & 0xFF);
if(dest > index && dest < 0xFFFF-difference)
{
dest += difference;
pulseTable[i] = jumptype | ((dest & 0xFF00) >> 8);
pulseTable[i+1] = jumptype | (dest & 0xFF);
}
i++;
}
else
{
dest = pulseTable[i] & 0xFF;
if(dest > index)
{
if(dest >= 0xFF - difference)
{
if(waveEntries < 0xFFFF)
{
dest += difference;
pulseTable[i] &= 0xFF00;
pulseTable[i] |= ((dest & 0xFF00) >> 8);
insertPulseEntry(i+1,jumptype | (dest & 0xFF));
}
}
else
pulseTable[i]+=difference;
}
}
}
}
}
else //difference negative
{
for(unsigned short i = 0; i < pulseEntries; i++)
{
if( isJumpFunc_Volatile(pulseTable[i]))//is jump, correct it
{
jumptype = pulseTable[i] & 0xFF00;
if( (i < pulseEntries-1) && ((pulseTable[i+1] & 0xFF00) == jumptype) )//Long jump
{
dest = ((pulseTable[i] & 0xFF) << 8) | (pulseTable[i+1] & 0xFF);
if(dest > index && dest >= -difference)
{
dest += difference;
pulseTable[i] = jumptype | ((dest & 0xFF00) >> 8);
pulseTable[i+1] = jumptype | (dest & 0xFF);
}
i++;
}
else
{
dest = pulseTable[i] & 0xFF;
if(dest > index)
{
if(dest >= -difference)
pulseTable[i]+= difference;
else
pulseTable[i] &= 0xFF00;
}
}
}
}
}
Pattern *p;
for(int i = 0; i < num_patterns; i++)
{
p = patterns[i];
for(int trk = 0; trk < p->numTracks(); trk++)
{
for(int row = 0; row < p->numRows(); row++)
{
unsigned int entry = p->at(trk,row);
if((entry & 0xF00) == 0x900)
{
unsigned char plsjump = entry & 0xFF;
if(difference > 0)
{
if(plsjump > 0 && plsjump > index && plsjump < 0xFF-difference)
{
plsjump +=difference;
}
}
else
{
if(plsjump > index)
{
if(plsjump >= -difference)
plsjump +=difference;
else
plsjump = 0;
}
}
entry &= ~0xFF;
entry |= plsjump;
p->setAt(trk,row,entry);
}
}
}
}
}
bool Song::removePulseEntry(unsigned short index)
{
if(pulseEntries == 0)
return false;
for(unsigned short i = index+1; i < pulseEntries; i++)
pulseTable[i-1] = pulseTable[i];
pulseTable[--pulseEntries] = 0;
fixPulseJumps(index, -1);
return true;
}
bool Song::insertFilterEntry(unsigned short index, unsigned short entry)
{
if(filterEntries == 0xFFFF)
return false;
for(unsigned short last = ++filterEntries; last > index; last--)
filterTable[last] = filterTable[last-1];
fixFilterJumps(index, 1);
filterTable[index] = entry;
return true;
}
void Song::fixFilterJumps(const unsigned short &index, short difference)
{
if(difference == 0) return;
//Fix instrument pulse index references
unsigned short instflt;
if(difference > 0)
{
for(unsigned char i = 0; i < num_instruments; i++)
{
instflt = instruments[i]->getFilterIndex();
// > 0 because the first instrument's wave pointer shouldn't
// realistically change due to insertions at index 0
if(instflt > 0 && instflt > index && instflt < 0xFFFF-difference && instflt != 0xFFFF)
{
instruments[i]->setFilterIndex(instflt+difference);
}
}
}
else
{
for(unsigned char i = 0; i < num_instruments; i++)
{
instflt = instruments[i]->getFilterIndex();
if(instflt > index && instflt != 0xFFFF)
{
if(instflt >= -difference)
instruments[i]->setFilterIndex(instflt +difference);
else
instruments[i]->setFilterIndex(0);
}
}
}
//Fix Pulse jumps
unsigned short jumptype;
unsigned short dest;
if(difference > 0)
{
for(unsigned short i = 0; i < filterEntries; i++)
{
if( isJumpFunc_Volatile(filterTable[i]))//is jump, correct it
{
jumptype = filterTable[i] & 0xFF00;
if( (i < filterEntries-1) && ((filterTable[i+1]&0xFF00) == jumptype))//Long jump
{
dest = ((filterTable[i] & 0xFF) << 8) | (filterTable[i+1] & 0xFF);
if(dest > index && dest < 0xFFFF-difference)
{
dest += difference;
filterTable[i] = jumptype | ((dest & 0xFF00) >> 8);
filterTable[i+1] = jumptype | (dest & 0xFF);
}
i++;
}
else
{
dest = filterTable[i] & 0xFF;
if(dest > index)
{
if(dest >= 0xFF - difference)
{
if(waveEntries < 0xFFFF)
{
dest += difference;
filterTable[i] &= 0xFF00;
filterTable[i] |= ((dest & 0xFF00) >> 8);
insertFilterEntry(i+1,jumptype | (dest & 0xFF));
}
}
else
filterTable[i]+=difference;
}
}
}
}
}
else //difference negative
{
for(unsigned short i = 0; i < filterEntries; i++)
{
if( isJumpFunc_Volatile(filterTable[i]))//is jump, correct it
{
jumptype = filterTable[i] & 0xFF00;
if( (i < filterEntries-1) && ((filterTable[i+1] & 0xFF00) == jumptype) )//Long jump
{
dest = ((filterTable[i] & 0xFF) << 8) | (filterTable[i+1] & 0xFF);
if(dest > index && dest >= -difference)
{
dest += difference;
filterTable[i] = jumptype | ((dest & 0xFF00) >> 8);
filterTable[i+1] = jumptype | (dest & 0xFF);
}
i++;
}
else
{
dest = filterTable[i] & 0xFF;
if(dest > index)
{
if(dest >= -difference)
filterTable[i]+= difference;
else
filterTable[i] &= 0xFF00;
}
}
}
}
}
Pattern *p;
for(int i = 0; i < num_patterns; i++)
{
p = patterns[i];
for(int trk = 0; trk < p->numTracks(); trk++)
{
for(int row = 0; row < p->numRows(); row++)
{
unsigned int entry = p->at(trk,row);
if((entry & 0xF00) == 0xC00)
{
unsigned char fltjump = entry & 0xFF;
if(difference > 0)
{
if(fltjump > 0 &&fltjump > index && fltjump < 0xFF-difference)
{
fltjump +=difference;
}
}
else
{
if(fltjump > index)
{
if(fltjump >= -difference)
fltjump +=difference;
else
fltjump = 0;
}
}
entry &= ~0xFF;
entry |= fltjump;
p->setAt(trk,row,entry);
}
}
}
}
}
bool Song::removeFilterEntry(unsigned short index)
{
if(filterEntries == 0)
return false;
for(unsigned short i = index+1; i < filterEntries; i++)
filterTable[i-1] = filterTable[i];
filterTable[--filterEntries] = 0;
fixFilterJumps(index, -1);
return true;
}
| 28.359733 | 119 | 0.488611 |
fd56c266e67f9a9621272d0355c7a7fc5be6d34b | 1,588 | cpp | C++ | client.cpp | tklam/licensing-server | a583ea02fcd290dd3b0665df4b163c94302f3f0b | [
"MIT"
] | null | null | null | client.cpp | tklam/licensing-server | a583ea02fcd290dd3b0665df4b163c94302f3f0b | [
"MIT"
] | null | null | null | client.cpp | tklam/licensing-server | a583ea02fcd290dd3b0665df4b163c94302f3f0b | [
"MIT"
] | null | null | null | #include "config.h"
#include "client.h"
#include "zeromq/zhelpers.hpp"
#include "crypto.h"
LoginRequest::LoginRequest(const std::string & clientIdentity_,
const std::string & clientID_,
const std::string & ip_):
clientIdentity(clientIdentity_),
clientID(clientID_),
ip(ip_)
{
}
Client::Client():
_id(CLIENT_ID)
{
}
Client::~Client() {
}
bool Client::connectAndGetAuthToken() {
Crypto crypto;
crypto.initKeyExchangeParams();
zmq::context_t context(1);
zmq::socket_t client(context, ZMQ_DEALER);
client.connect(LICENSING_SERVER_ADDRESS);
s_sendmore (client, GREETING);
//key exchange
//1. send public keys to another party
s_sendmore(client, crypto.spubHexStr()); //signing public key
s_send(client, crypto.epubHexStr()); //ephemeral(temp) public key
//2. receive publics keys from another party
const std::string spub = s_recv(client);
const std::string epub = s_recv(client);
//3. generate XPORT (encrypted CEK + digest)
crypto.genXport(spub, epub);
//4. receiv XPORT from another party
const std::string xport = s_recv(client);
crypto.decryptXport(xport);
//5. send client ID
s_send(client, _id);
// The communication channel can now be encrypted with CEK
std::string ack = s_recv(client);
client.disconnect(LICENSING_SERVER_ADDRESS);
ack = crypto.decrypt(ack);
if (ack == SUCCESSFUL_LOGIN_REPLY) {
return true;
}
else if (ack == FAILED_LOGIN_REPLY) {
return false;
}
return false;
}
| 25.206349 | 69 | 0.65806 |
fd57609a87c44fed9c4340ddf05369168e5621cc | 15,285 | cpp | C++ | cppVersion/map.cpp | maxgoren/codealong2020 | b8ef380900544c3daabd549f89f196e133622b10 | [
"MIT"
] | 5 | 2020-06-17T06:27:45.000Z | 2021-01-17T19:59:41.000Z | cppVersion/map.cpp | maxgoren/codealong2020 | b8ef380900544c3daabd549f89f196e133622b10 | [
"MIT"
] | null | null | null | cppVersion/map.cpp | maxgoren/codealong2020 | b8ef380900544c3daabd549f89f196e133622b10 | [
"MIT"
] | 1 | 2022-03-07T15:22:17.000Z | 2022-03-07T15:22:17.000Z |
/****************************************************************
* MIT License
*
* Copyright (c) 2020 Max Goren
*
* 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.
***************************************************/
Rect::Rect(int x, int y, int w, int h)
{
this->uL.x = x;
this->uL.y = y;
this->lR.x = x + w;
this->lR.y = y + h;
}
Rect::Rect()
{
}
Map::Map(int w, int h)
{
int x, y;
this->width = w;
this->height = h;
//initialize tile grid
for (x = 1; x < w - 1; x++)
{
for (y = 1; y < h - 1; y++)
{
layout[x][y].blocks = true;
layout[x][y].pos.x = x;
layout[x][y].pos.y = y;
}
}
}
bool Rect::collision(Rect other)
{
if ((uL.x < other.lR.x) && (lR.x > other.uL.x) &&
(uL.y < other.lR.y) && (lR.y > other.uL.y)) {
return true; //collision
} else {
return false;
}
}
double Map::isInFov(int x, int y, int px, int py)
{
double alpha = (px - x) * (px - x);
double beta = (py - y) * (py - y);
return sqrt((alpha+beta)*1.0);
}
void Map::digRect(Rect room)
{
int x, y;
for (x = room.uL.x; x < room.lR.x; x++)
{
for (y = room.uL.y; y < room.lR.y; y++)
{
this->layout[x][y].blocks = false;
this->layout[x][y].isinRoom = room.idNum;
this->layout[x][y].value = 10;
}
}
std::cout<<"Dug room "<<room.idNum<<"from x"<<room.uL.x<<" to x "<<room.lR.x<<" and y"<<room.uL.y<<" to "<<room.lR.y<<".\n";
}
void Map::genRect(int numRoom, int maxSize)
{
int i;
int posx, posy, possize;
int roomsMade = 0;
int collisions = 0;
Rect* posroom;
//screensections;
Rect scrSec1(1,1,width/2, height/2 - 1);
scrSec1.numItems = 0;
scrSec1.numEnts = 0;
scrSect.push_back(scrSec1);
Rect scrSec2(width/2, 1, width/2 - 1, height/2 - 1);
scrSec2.numItems = 0;
scrSec2.numEnts = 0;
scrSect.push_back(scrSec2);
Rect scrSec3(1, height/2, width/2, height/2);
scrSec3.numItems = 0;
scrSec3.numEnts = 0;
scrSect.push_back(scrSec3);
Rect scrSec4(width/2, height/2, width/2 - 1, height/2 - 1);
scrSec4.numItems = 0;
scrSec4.numEnts = 0;
scrSect.push_back(scrSec4);
std::cout<<"Screen partition complete.\n";
while (roomsMade < numRoom)
{
possize = getrand(5, maxSize);
switch (getrand(1,4))
{
case 1:
posx = getrand(scrSect[0].uL.x + 1, scrSect[0].lR.x - (possize + 1));
posy = getrand(scrSect[0].uL.y + 1, scrSect[0].lR.y - (possize + 1));
std::cout<<"Room: "<<roomsMade<<" section one selected\n";
break;
case 2:
posx = getrand(scrSect[1].uL.x + 1, scrSect[1].lR.x - (possize + 1));
posy = getrand(scrSect[1].uL.y + 1, scrSect[1].lR.y - (possize + 1));
std::cout<<"Room: "<<roomsMade<<" section two selected\n";
break;
case 3:
posx = getrand(scrSect[2].uL.x + 1, scrSect[2].lR.x - (possize + 1));
posy = getrand(scrSect[2].uL.y + 1, scrSect[2].lR.y - (possize + 1));
std::cout<<"Room: "<<roomsMade<<" section three selected\n";
break;
case 4:
posx = getrand(scrSect[3].uL.x + 1, scrSect[3].lR.x - (possize + 1));
posy = getrand(scrSect[3].uL.y + 1, scrSect[3].lR.y - (possize + 1));
std::cout<<"Room: "<<roomsMade<<" section four selected\n";
break;
}
std::cout<<"Room: "<<roomsMade<<" posx/posy: "<<posx<<"/"<<posy<<"\n";
posroom = new Rect(posx, posy, possize + (possize/2) , possize);
posroom->idNum = roomsMade;
std::cout<<"Room: "<<roomsMade<<" object created\n";
posroom->cent.x = (posroom->uL.x + posroom->lR.x) / 2;
posroom->cent.y = (posroom->uL.y + posroom->lR.y) / 2;
std::cout<<"Room: "<<roomsMade<<" centx/y set: "<<posroom->cent.x<<"/"<<posroom->cent.y<<"\n";
if (roomsMade > 0)
{
for (auto R = rooms.begin() ; R != rooms.end(); R++)
{ if (posroom->collision(*R)) { collisions++; } }
if (collisions == 0)
{
digRect(*posroom);
rooms.push_back(*posroom);
roomsMade++;
collisions = 0;
std::cout<<"Room "<<posroom->idNum<<"made. x/y: "<<posroom->uL.x<<"/"<<posroom->uL.y<<" x2/y2:"<<posroom->lR.x<<"/"<<posroom->lR.y<<std::endl;
} else {
std::cout<<collisions<<"Collisions Detected.\n";
collisions = 0;
}
} else {
digRect(*posroom);
rooms.push_back(*posroom);
roomsMade++;
}
if (roomsMade == 2)
{
spy = rooms.at(0).cent.y;
spx = rooms.at(0).cent.x;
}
}
if (getrand(1,100) > 50)
{
connectRooms(rooms);
} else {
connectRooms2(rooms);
}
//placePortal();
outline();
}
void Map::connectRooms(std::vector<Rect> rooms)
{
int ax,bx;
int ay,by;
Rect* start;
Rect* fin;
int i = 0;
int r;
for ( r = 0; r < rooms.size() - 1; r++)
{
start = &rooms[i];
fin = &rooms[i+1];
std::cout<<"Connecting: "<<start->idNum<<" to "<<fin->idNum<<"\n";
if (start->cent.x <= fin->cent.x)
{
std::cout<<"if one, condition A\n";
for (ax = start->cent.x; ax <= (fin->cent.x + start->cent.x) / 2; ax++)
{
layout[ax][start->cent.y].blocks = false;
layout[ax][start->cent.y].isinRoom = 77;
}
for (bx = fin->cent.x; bx >= (fin->cent.x + start->cent.x) / 2; bx--)
{
layout[bx][fin->cent.y].blocks = false;
layout[bx][fin->cent.y].isinRoom = 77;
}
std::cout<<"From: X"<<start->cent.x<<" and "<<fin->cent.x<<" to "<<(start->cent.x + fin->cent.x)/2<<"\n";
} else {
std::cout<<"If one condition B\n";
for (ax = start->cent.x; ax >= (fin->cent.x + start->cent.x) / 2; ax--)
{
layout[ax][start->cent.y].blocks = false;
layout[ax][start->cent.y].isinRoom = 77;
}
for (bx = fin->cent.x; bx <= (fin->cent.x + start->cent.x) / 2; bx++)
{
layout[bx][fin->cent.y].blocks = false;
layout[bx][fin->cent.y].isinRoom = 77;
}
std::cout<<"From: X"<<start->cent.x<<" and "<<fin->cent.x<<" to "<<(start->cent.x + fin->cent.x)/2<<"\n";
}
if (start->cent.y <= fin->cent.y)
{
std::cout<<"if two condition A\n";
for (ay = start->cent.y; ay < fin->cent.y; ay++)
{
layout[ax][ay].blocks = false;
layout[ax+1][ay].blocks = false;
layout[ax][ay].isinRoom = 77; //77 =pathway
}
std::cout<<"From: Y"<<start->cent.y<<" to "<<fin->cent.y<<"\n";
} else {
std::cout<<"if two, codition B\n";
for (by = fin->cent.y; by <= start->cent.y; by++)
{
layout[bx][by].blocks = false;
layout[bx-1][by].blocks = false;
layout[bx][by].isinRoom = 77;
}
std::cout<<"From: Y"<<fin->cent.y<<" to "<<start->cent.y<<"\n";
}
std::cout<<"Connected.\n";
i++;
}
}
void Map::connectRooms2(std::vector<Rect> rooms)
{
int ax, ay;
int bx, by;
Rect* start;
Rect* fin;
int r, i=0;
for (r = 0; r < rooms.size() - 1; r++)
{
start = &rooms[i];
fin = &rooms[i] + 1;
std::cout<<"Connecting: "<<start->idNum<<" to "<<fin->idNum<<"\n";
if (start->cent.y <= fin->cent.y)
{
std::cout<<"If one, condition A\n";
for (ay = start->cent.y; ay <= (start->cent.y + fin->cent.y) / 2; ay++)
{
layout[start->cent.x][ay].blocks = false;
layout[start->cent.x][ay].isinRoom = 77;
/***********************************/
layout[start->cent.x+1][ay].blocks=false;
}
for (by = fin->cent.y; by >= (start->cent.y + fin->cent.y) / 2; by--)
{
layout[fin->cent.x][by].blocks = false;
layout[fin->cent.x][by].isinRoom = 77;
/**************************************/
layout[fin->cent.x-1][by].blocks=false;
}
} else {
std::cout<<"If one, condition B\n";
for (ay = start->cent.y; ay >= (start->cent.y + fin->cent.y) / 2; ay--)
{
layout[start->cent.x][ay].blocks = false;
layout[start->cent.x][ay].isinRoom = 77;
/***************************************/
layout[start->cent.x-1][ay].blocks = false;
}
for (by = fin->cent.y; by <= (start->cent.y + fin->cent.y) / 2; by++)
{
layout[fin->cent.x][by].blocks = false;
layout[fin->cent.x][by].isinRoom = 77;
/***************************************/
layout[fin->cent.x+1][by].blocks=false;
}
}
if (start->cent.x <= fin->cent.x)
{
std::cout<<"If two, condition A\n";
for (ax = start->cent.x; ax <= fin->cent.x; ax++)
{
layout[ax][ay].blocks = false;
layout[ax][ay].isinRoom = 77;
}
} else {
std::cout<<"If two, condition B\n";
for (bx = fin->cent.x; bx <= start->cent.x; bx++)
{
layout[bx][by].blocks = false;
layout[bx][by].isinRoom = 77;
}
}
std::cout<<"Connection complete.\n";
i++;
}
}
void Map::connectR2R(Rect st, Rect fi)
{
int ax, ay;
int bx, by;
Rect* start = &st;
Rect* fin = &fi;
int r, i=0;
std::cout<<"Connecting: "<<start->idNum<<" to "<<fin->idNum<<"\n";
if (start->cent.y <= fin->cent.y)
{
std::cout<<"If one, condition A\n";
for (ay = start->cent.y; ay <= (start->cent.y + fin->cent.y) / 2; ay++)
{
layout[start->cent.x][ay].blocks = false;
layout[start->cent.x][ay].isinRoom = 77;
/***********************************/
layout[start->cent.x+1][ay].blocks=false;
}
for (by = fin->cent.y; by >= (start->cent.y + fin->cent.y) / 2; by--)
{
layout[fin->cent.x][by].blocks = false;
layout[fin->cent.x][by].isinRoom = 77;
/**************************************/
layout[fin->cent.x-1][by].blocks=false;
}
} else {
std::cout<<"If one, condition B\n";
for (ay = start->cent.y; ay >= (start->cent.y + fin->cent.y) / 2; ay--)
{
layout[start->cent.x][ay].blocks = false;
layout[start->cent.x][ay].isinRoom = 77;
/***************************************/
layout[start->cent.x-1][ay].blocks = false;
}
for (by = fin->cent.y; by <= (start->cent.y + fin->cent.y) / 2; by++)
{
layout[fin->cent.x][by].blocks = false;
layout[fin->cent.x][by].isinRoom = 77;
/***************************************/
layout[fin->cent.x+1][by].blocks=false;
}
}
if (start->cent.x <= fin->cent.x)
{
std::cout<<"If two, condition A\n";
for (ax = start->cent.x; ax <= fin->cent.x; ax++)
{
layout[ax][ay].blocks = false;
layout[ax][ay].isinRoom = 77;
}
} else {
std::cout<<"If two, condition B\n";
for (bx = fin->cent.x; bx <= start->cent.x; bx++)
{
layout[bx][by].blocks = false;
layout[bx][by].isinRoom = 77;
}
}
std::cout<<"Connection complete.\n";
}
void Map::outline()
{
int x, y;
for (x = 0; x < width; x++)
{
for (y = 0; y < height; y++)
{
if (layout[x][y].blocks == false && layout[x+1][y].blocks == true)
{
layout[x+1][y].border = true;
}
if (layout[x][y].blocks == false && layout[x][y+1].blocks == true)
{
layout[x][y+1].border = true;
}
if (layout[x][y].blocks == false && layout[x-1][y].blocks == true)
{
layout[x-1][y].border = true;
}
if (layout[x][y].blocks == false && layout[x][y-1].blocks == true)
{
layout[x][y-1].border = true;
}
if (layout[x][y].blocks == false && layout[x-1][y].border == true && layout[x][y+1].border==true)
{
layout[x-1][y+1].border=true;
}
if (layout[x][y].blocks == false && layout[x-1][y].border == true && layout[x][y-1].border==true)
{
layout[x-1][y-1].border=true;
}
if (layout[x][y].blocks == false && layout[x+1][y].border == true && layout[x][y-1].border==true)
{
layout[x+1][y-1].border=true;
}
if (layout[x][y].blocks == false && layout[x+1][y].border == true && layout[x][y+1].border==true)
{
layout[x+1][y+1].border=true;
}
}
}
}
void Map::spawnMonsters(int numBads)
{
ent *badGuy;
int numMonst = 0;
int i, randRm, x, y;
while (numMonst < 13)
{
randRm = getrand(0, rooms.size() - 1);
if (rooms.at(randRm).numEnts <= 2)
{
x = getrand(rooms[randRm].uL.x+1, rooms[randRm].lR.x-1);
y = getrand(rooms[randRm].uL.y+1, rooms[randRm].lR.y-1);
if (layout[x][y].populated == false && layout[x][y].blocks==false)
{
if (getrand(0,50) < 35)
{
badGuy = new ent(x, y, "Goblin", 'G', color_from_name("green"));
} else {
badGuy = new ent(x, y, "Vampire", 'V', color_from_name("flame"));
}
badGuys.push_back(badGuy);
rooms[randRm].numEnts++;
layout[x][y].populated = true;
layout[x][y].blocks = true;
numMonst++;
}
}
}
}
void Map::placeItems(int numItems)
{
int sect;
int rit;
float rp, rh;
int itemsMade = 0;
Point randPos;
Items* item;
struct stuff things;
while (itemsMade < numItems)
{
rp = getrandfloat(0.10, 2.25);
rh = getrandfloat(4.35, 9.33);
rit = getrand(0,22);
sect = getrand(0, 3);
if (scrSect[sect].numItems < numItems)
{
randPos.x = getrand(this->scrSect.at(sect).uL.x, this->scrSect.at(sect).lR.x);
randPos.y = getrand(this->scrSect.at(sect).uL.y, this->scrSect.at(sect).lR.y);
if (this->layout[randPos.x][randPos.y].blocks == false && this->layout[randPos.x][randPos.y].populated == false)
{
item = new Items(randPos.x,randPos.y, things.things[rit], rh, rp);
this->itemList.push_back(item);
this->layout[randPos.x][randPos.y].populated = true;
itemsMade++;
scrSect[sect].numItems++;
}
}
}
}
void Map::placePortal()
{
int dx, dy;
int dx2, dy2;
int distance;
int distance2;
float dist;
std::pair<Rect*,Rect*> closest;
Rect far = rooms.back();
Rect* start = &rooms.front();
Rect* next;
for (auto r = rooms.begin() + 1; r != rooms.end(); r++)
{
dx = r->cent.x - start->cent.x;
dy = r->cent.y - start->cent.y;
dx2 = r->cent.x - far.cent.x;
dy2 = r->cent.y - far.cent.y;
dist = sqrtf(dx*dx+dy*dy);
distance = (int)round(dist);
dist = sqrtf(dx2*dx2+dy2*dy2);
distance2 = (int)round(dist);
std::cout<<r->idNum<<" & "<<start->idNum<<"\n";
std::cout<<"r -> start "<<distance<<"\n";
std::cout<<r->idNum<<" & "<<far.idNum<<"\n";
std::cout<<"r -> finnish "<<distance2<<"\n";
if (distance < distance2)
{
next = start;
} else {
next = &far;
far = *r;
}
std::cout<<"winner: "<<r->idNum<<" & "<<next->idNum<<"\n";
}
connectR2R(*start,*next);
start = next;
}
| 28.948864 | 149 | 0.53366 |
fd5b5642bd20ebde3431ec8c7689553cadf9ad85 | 4,483 | cpp | C++ | eiam/src/v20210420/model/UserGroupInformation.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 43 | 2019-08-14T08:14:12.000Z | 2022-03-30T12:35:09.000Z | eiam/src/v20210420/model/UserGroupInformation.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 12 | 2019-07-15T10:44:59.000Z | 2021-11-02T12:35:00.000Z | eiam/src/v20210420/model/UserGroupInformation.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 28 | 2019-07-12T09:06:22.000Z | 2022-03-30T08:04:18.000Z | /*
* 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/eiam/v20210420/model/UserGroupInformation.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Eiam::V20210420::Model;
using namespace std;
UserGroupInformation::UserGroupInformation() :
m_userGroupIdHasBeenSet(false),
m_userGroupNameHasBeenSet(false),
m_lastModifiedDateHasBeenSet(false)
{
}
CoreInternalOutcome UserGroupInformation::Deserialize(const rapidjson::Value &value)
{
string requestId = "";
if (value.HasMember("UserGroupId") && !value["UserGroupId"].IsNull())
{
if (!value["UserGroupId"].IsString())
{
return CoreInternalOutcome(Core::Error("response `UserGroupInformation.UserGroupId` IsString=false incorrectly").SetRequestId(requestId));
}
m_userGroupId = string(value["UserGroupId"].GetString());
m_userGroupIdHasBeenSet = true;
}
if (value.HasMember("UserGroupName") && !value["UserGroupName"].IsNull())
{
if (!value["UserGroupName"].IsString())
{
return CoreInternalOutcome(Core::Error("response `UserGroupInformation.UserGroupName` IsString=false incorrectly").SetRequestId(requestId));
}
m_userGroupName = string(value["UserGroupName"].GetString());
m_userGroupNameHasBeenSet = true;
}
if (value.HasMember("LastModifiedDate") && !value["LastModifiedDate"].IsNull())
{
if (!value["LastModifiedDate"].IsString())
{
return CoreInternalOutcome(Core::Error("response `UserGroupInformation.LastModifiedDate` IsString=false incorrectly").SetRequestId(requestId));
}
m_lastModifiedDate = string(value["LastModifiedDate"].GetString());
m_lastModifiedDateHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
void UserGroupInformation::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const
{
if (m_userGroupIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "UserGroupId";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_userGroupId.c_str(), allocator).Move(), allocator);
}
if (m_userGroupNameHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "UserGroupName";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_userGroupName.c_str(), allocator).Move(), allocator);
}
if (m_lastModifiedDateHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "LastModifiedDate";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_lastModifiedDate.c_str(), allocator).Move(), allocator);
}
}
string UserGroupInformation::GetUserGroupId() const
{
return m_userGroupId;
}
void UserGroupInformation::SetUserGroupId(const string& _userGroupId)
{
m_userGroupId = _userGroupId;
m_userGroupIdHasBeenSet = true;
}
bool UserGroupInformation::UserGroupIdHasBeenSet() const
{
return m_userGroupIdHasBeenSet;
}
string UserGroupInformation::GetUserGroupName() const
{
return m_userGroupName;
}
void UserGroupInformation::SetUserGroupName(const string& _userGroupName)
{
m_userGroupName = _userGroupName;
m_userGroupNameHasBeenSet = true;
}
bool UserGroupInformation::UserGroupNameHasBeenSet() const
{
return m_userGroupNameHasBeenSet;
}
string UserGroupInformation::GetLastModifiedDate() const
{
return m_lastModifiedDate;
}
void UserGroupInformation::SetLastModifiedDate(const string& _lastModifiedDate)
{
m_lastModifiedDate = _lastModifiedDate;
m_lastModifiedDateHasBeenSet = true;
}
bool UserGroupInformation::LastModifiedDateHasBeenSet() const
{
return m_lastModifiedDateHasBeenSet;
}
| 30.496599 | 155 | 0.7205 |
fd5c167fe2de69e059d08716f61869c19ccce090 | 2,360 | cc | C++ | src/mnn/kernel/cpu/fully_connected_op_cpu.cc | horance-liu/mnn | d53216e5f3fb60ea1da6f44e72fc0d949974931d | [
"Apache-2.0"
] | 4 | 2021-05-17T02:49:36.000Z | 2021-05-18T13:31:33.000Z | src/mnn/kernel/cpu/fully_connected_op_cpu.cc | horance-liu/mnn | d53216e5f3fb60ea1da6f44e72fc0d949974931d | [
"Apache-2.0"
] | 1 | 2021-06-02T03:01:05.000Z | 2021-06-02T03:01:05.000Z | src/mnn/kernel/cpu/fully_connected_op_cpu.cc | horance-liu/mnn | d53216e5f3fb60ea1da6f44e72fc0d949974931d | [
"Apache-2.0"
] | 4 | 2021-05-19T01:43:07.000Z | 2021-12-09T07:29:34.000Z | /*
* Copyright (c) 2021, Horance Liu and the respective contributors
* All rights reserved.
*
* Use of this source code is governed by a Apache 2.0 license that can be found
* in the LICENSE file.
*/
#include "mnn/kernel/cpu/fully_connected_op_cpu.h"
namespace mnn {
namespace kernels {
void fully_connected_op_internal(const Matrix &in_data, const Vector &W,
const Vector &bias, Matrix &out_data, const FullyParams ¶ms,
const bool layer_parallelize)
{
for_i(layer_parallelize, in_data.size(), [&](size_t sample) {
const Vector &in = in_data[sample];
Vector &out = out_data[sample];
for (size_t i = 0; i < params.out_size_; i++) {
out[i] = Float {0};
for (size_t c = 0; c < params.in_size_; c++) {
out[i] += W[c * params.out_size_ + i] * in[c];
}
if (params.has_bias_) {
out[i] += bias[i];
}
}
});
}
void fully_connected_op_internal(const Matrix &prev_out, const Vector &W,
Matrix &dW, Matrix &db, Matrix &curr_delta, Matrix &prev_delta,
const FullyParams ¶ms, const bool layer_parallelize)
{
for (size_t sample = 0; sample < prev_out.size(); sample++) {
for (size_t c = 0; c < params.in_size_; c++) {
// propagate delta to previous layer
// prev_delta[c] += current_delta[r] * W_[c * out_size_ + r]
prev_delta[sample][c] += vectorize::dot(&curr_delta[sample][0],
&W[c * params.out_size_], params.out_size_);
}
for_(layer_parallelize, 0, params.out_size_, [&](const BlockedRange &r) {
// accumulate weight-step using delta
// dW[c * out_size + i] += current_delta[i] * prev_out[c]
for (size_t c = 0; c < params.in_size_; c++) {
vectorize::muladd(&curr_delta[sample][r.begin()], prev_out[sample][c],
r.end() - r.begin(),
&dW[sample][c * params.out_size_ + r.begin()]);
}
if (params.has_bias_) {
// Vector& db = *in_grad[2];
for (size_t i = r.begin(); i < r.end(); i++) {
db[sample][i] += curr_delta[sample][i];
}
}
});
}
}
} // namespace kernels
} // namespace mnn
| 35.223881 | 86 | 0.54322 |
fd5d55923e68b941e8e033abfac025a43107741c | 1,881 | cpp | C++ | source/computation-derivatives-gt2s_ga1s.cpp | p-maybank/bayesian-uq | 5e3b34aaf33512d94fd417238df5582b3a89170b | [
"BSD-3-Clause"
] | 1 | 2021-07-03T22:53:53.000Z | 2021-07-03T22:53:53.000Z | source/computation-derivatives-gt2s_ga1s.cpp | p-maybank/bayesian-uq | 5e3b34aaf33512d94fd417238df5582b3a89170b | [
"BSD-3-Clause"
] | null | null | null | source/computation-derivatives-gt2s_ga1s.cpp | p-maybank/bayesian-uq | 5e3b34aaf33512d94fd417238df5582b3a89170b | [
"BSD-3-Clause"
] | 2 | 2021-07-03T22:57:22.000Z | 2021-10-10T13:29:54.000Z | #include <vector>
#include "Eigen/Dense"
#include "scalar-typedef.hpp"
#include "stable-sde.hpp"
#include "data-vector.hpp"
#include "vector-io.hpp"
#include "computation.hpp"
using namespace std;
using namespace Eigen;
#ifdef USE_DCO_TYPES
template<>
void Computation<gt2s_ga1s_scalar>::derivatives(Matrix<gt2s_ga1s_scalar, Dynamic, 1>& theta,
const Eigen::Matrix<gt2s_ga1s_scalar, Eigen::Dynamic, 1>& x_star,
Matrix<double,Dynamic,1> & grad,
Matrix<double,Dynamic,Dynamic> & hess,
unsigned int & ifail){
const int theta_size = theta.size();
grad.resize(theta_size);
hess.resize(theta_size,theta_size);
// Create tape
if( DCO_GA1S_MODE::global_tape==nullptr) {
DCO_GT2S_GA1S_MODE::global_tape = DCO_GT2S_GA1S_MODE::tape_t::create();
}
auto pos = DCO_GT2S_GA1S_MODE::global_tape->get_position();
for(int i=0; i<theta_size; i++) {
// Register inputs
for(int j=0; j<theta_size; j++) {
DCO_GT2S_GA1S_MODE::global_tape->register_variable(theta(j));
}
dco::derivative(dco::value(theta(i))) = 1.0;
// Actual computation to be differentiated
gt2s_ga1s_scalar ll = eval(theta, x_star, ifail);
DCO_GT2S_GA1S_MODE::global_tape->register_output_variable(ll);
dco::derivative(ll) = 1.0;
DCO_GT2S_GA1S_MODE::global_tape->interpret_adjoint();
// Fill Jacobian
grad(i) = dco::value(dco::derivative(theta(i)));
// Fill Hessian
for(int j=0; j<theta_size; j++) hess(j, i) = dco::derivative(dco::derivative(theta(j)));
dco::derivative(dco::value(theta(i))) = 0.0;
DCO_GT2S_GA1S_MODE::global_tape->reset();
}
DCO_GT2S_GA1S_MODE::global_tape->reset_to( pos );
DCO_GT2S_GA1S_MODE::tape_t::remove(DCO_GT2S_GA1S_MODE::global_tape);
return;
}
#endif
| 32.431034 | 103 | 0.653907 |
5b746ac7d9bb646e6168d6c081e3f442cb2d1b9f | 366 | cpp | C++ | src/en/WorldManager.cpp | kochol/ari2 | ca185191531acc1954cd4acfec2137e32fdb5c2d | [
"MIT"
] | 81 | 2018-12-11T20:48:41.000Z | 2022-03-18T22:24:11.000Z | src/en/WorldManager.cpp | kochol/ari2 | ca185191531acc1954cd4acfec2137e32fdb5c2d | [
"MIT"
] | 7 | 2020-04-19T11:50:39.000Z | 2021-11-12T16:08:53.000Z | src/en/WorldManager.cpp | kochol/ari2 | ca185191531acc1954cd4acfec2137e32fdb5c2d | [
"MIT"
] | 4 | 2019-04-24T11:51:29.000Z | 2021-03-10T05:26:33.000Z | #include "WorldManager.hpp"
#include "World.hpp"
#include <core/memory/Memory.hpp>
namespace ari
{
namespace en
{
//! Create a new World
World* WorldManager::CreateWorld()
{
return core::Memory::New<World>();
}
//! Destroy a world
void WorldManager::DestroyWorld(World* _world)
{
core::Memory::Delete<World>(_world);
}
} // en
} // ari
| 15.25 | 48 | 0.647541 |
5b74ba1b03cad0dd05bb7a7897ff8267b20e34cc | 22,705 | cc | C++ | src/CGContext.cc | hailongz/kk-canvas | f53c994bce49ca4375a27d69c0d08c121ac538ad | [
"MIT"
] | null | null | null | src/CGContext.cc | hailongz/kk-canvas | f53c994bce49ca4375a27d69c0d08c121ac538ad | [
"MIT"
] | null | null | null | src/CGContext.cc | hailongz/kk-canvas | f53c994bce49ca4375a27d69c0d08c121ac538ad | [
"MIT"
] | null | null | null | //
// CGContext.cc
// KKCanvas
//
// Created by zhanghailong on 2018/8/17.
// Copyright © 2018年 kkmofang.cn. All rights reserved.
//
#include "kk-config.h"
#include "CGContext.h"
namespace kk {
namespace CG {
Palette::Palette(kk::CString name, ...) {
va_list va;
va_start(va, name);
kk::CString key = name;
kk::CString value = nullptr;
while(1) {
if(key == nullptr) {
key = va_arg(va, kk::CString);
if(key == nullptr) {
break;
}
}
if(value == nullptr) {
value = va_arg(va, kk::CString);
if(value == nullptr) {
break;
}
}
_values[key] = ColorFromString(value);
key = nullptr;
value = nullptr;
}
va_end(va);
}
void Palette::set(kk::CString name,Color v) {
_values[name] = v;
}
Color Palette::get(kk::CString name) {
Color v = {0,0,0,0};
std::map<kk::String,Color>::iterator i = _values.find(name);
if(i != _values.end()) {
return i->second;
}
return v;
}
Palette Palette::Default("black","#000000",
"red","#ff0000",
"white","#ffffff",
"green","#00ff00",
"blue","#0000ff",
"magenta","#ff00ff",
"yellow","#ffff00",
nullptr);
Color ColorFromString(kk::CString string) {
Color v = {0,0,0,0};
if(string != nullptr) {
if(CStringHasPrefix(string, "rgba(")) {
#ifdef KK_CG_FLOAT64
sscanf(string, "rgba(%lf,%lf,%lf,%lf)",&v.r,&v.g,&v.b,&v.a);
#else
sscanf(string, "rgba(%f,%f,%f,%f)",&v.r,&v.g,&v.b,&v.a);
#endif
v.r = v.r / 255.0f;
v.g = v.g / 255.0f;
v.b = v.b / 255.0f;
} else if(CStringHasPrefix(string, "rgb(")) {
#ifdef KK_CG_FLOAT64
sscanf(string, "rgba(%lf,%lf,%lf)",&v.r,&v.g,&v.b);
#else
sscanf(string, "rgba(%f,%f,%f)",&v.r,&v.g,&v.b);
#endif
v.r = v.r / 255.0f;
v.g = v.g / 255.0f;
v.b = v.b / 255.0f;
v.a = 1.0f;
} else if(CStringHasPrefix(string, "#")) {
size_t n = CStringLength(string);
if(n == 4) {
Uint r = 0,g = 0,b = 0;
sscanf(string, "#%1x%1x%1x",&r,&g,&b);
v.r = (Float)(r << 8 | r) / 255.0f;
v.g = (Float)(g << 8 | r) / 255.0f;
v.b = (Float)(b << 8 | r) / 255.0f;
v.a = 1.0f;
} else if(n == 7) {
Uint r = 0,g = 0,b = 0;
sscanf(string, "#%2x%2x%2x",&r,&g,&b);
v.r = (Float)(r) / 255.0f;
v.g = (Float)(g) / 255.0f;
v.b = (Float)(b) / 255.0f;
v.a = 1.0f;
}
} else {
return Palette::Default.get(string);
}
}
return v;
}
kk::String StringFromColor(Color v) {
char fmt[16] = "";
Uint r = v.r * 255.0;
Uint g = v.g * 255.0;
Uint b = v.b * 255.0;
if(v.a == 1.0f) {
snprintf(fmt, sizeof(fmt), "#%2x%2x%2x",r,g,b);
} else {
snprintf(fmt, sizeof(fmt), "rgba(%u,%u,%u,%g)",r,g,b,v.a);
}
return fmt;
}
PatternType PatternTypeFromString(kk::CString string) {
if(CStringEqual(string, "repeat-x")){
return PatternTypeRepeatX;
}
if(CStringEqual(string, "repeat-y")){
return PatternTypeRepeatY;
}
if(CStringEqual(string, "no-repeat")){
return PatternTypeNoRepeat;
}
return PatternTypeRepeat;
}
kk::String StringFromPatternType(PatternType v) {
switch (v) {
case PatternTypeRepeatX:
return "repeat-x";
case PatternTypeRepeatY:
return "repeat-y";
case PatternTypeNoRepeat:
return "no-repeat";
default:
return "repeat";
}
}
LineCapType LineCapTypeFromString(kk::CString string) {
if(CStringEqual(string, "round")) {
return LineCapTypeRound;
}
if(CStringEqual(string, "square")) {
return LineCapTypeSquare;
}
return LineCapTypeButt;
}
kk::String StringFromLineCapType(LineCapType v) {
switch (v) {
case LineCapTypeRound:
return "round";
case LineCapTypeSquare:
return "square";
default:
return "butt";
}
}
LineJoinType LineJoinTypeFromString(kk::CString string) {
if(CStringEqual(string, "round")) {
return LineJoinTypeRound;
}
if(CStringEqual(string, "bevel")) {
return LineJoinTypeBevel;
}
return LineJoinTypeMiter;
}
kk::String StringFromLineJoinType(LineJoinType v) {
switch (v) {
case LineJoinTypeRound:
return "round";
case LineJoinTypeBevel:
return "bevel";
default:
return "miter";
}
}
Font FontFromString(kk::CString string) {
Font v = {"",14,FontStyleNormal,FontWeightNormal};
std::vector<kk::String> items;
CStringSplit(string, " ", items);
std::vector<kk::String>::iterator i = items.begin();
while(i != items.end()) {
kk::String & s = * i;
if(s == "bold") {
v.weight = FontWeightBold;
} else if(s == "italic") {
v.style = FontStyleItalic;
} else if(CStringHasSuffix(s.c_str(), "px")) {
v.size = atof(s.c_str());
} else {
v.family = s;
}
i ++;
}
return v;
}
kk::String StringFromFont(Font v) {
std::vector<kk::String> items;
if(v.family != "") {
items.push_back(v.family);
}
if(v.weight == FontWeightBold) {
items.push_back("bold");
}
if(v.style == FontStyleItalic) {
items.push_back("italic");
}
char fmt[32];
snprintf(fmt, sizeof(fmt), "%gpx",v.size);
items.push_back(fmt);
return CStringJoin(items, " ");
}
TextAlign TextAlignFromString(kk::CString string) {
if(CStringEqual(string, "end")) {
return TextAlignEnd;
}
if(CStringEqual(string, "center")) {
return TextAlignCenter;
}
if(CStringEqual(string, "left")) {
return TextAlignLeft;
}
if(CStringEqual(string, "right")) {
return TextAlignRight;
}
return TextAlignStart;
}
kk::String StringFromTextAlign(TextAlign v) {
switch (v) {
case TextAlignEnd:
return "end";
case TextAlignCenter:
return "center";
case TextAlignLeft:
return "left";
case TextAlignRight:
return "right";
default:
return "start";
}
}
TextBaseline TextBaselineFromString(kk::CString string) {
if(CStringEqual(string, "top")) {
return TextBaselineTop;
}
if(CStringEqual(string, "hanging")) {
return TextBaselineHanging;
}
if(CStringEqual(string, "middle")) {
return TextBaselineMiddle;
}
if(CStringEqual(string, "ideographic")) {
return TextBaselineIdeographic;
}
if(CStringEqual(string, "bottom")) {
return TextBaselineBottom;
}
return TextBaselineAlphabetic;
}
kk::String StringFromTextBaseline(TextBaseline v) {
switch (v) {
case TextBaselineTop:
return "top";
case TextBaselineHanging:
return "hanging";
case TextBaselineMiddle:
return "middle";
case TextBaselineIdeographic:
return "ideographic";
case TextBaselineBottom:
return "bottom";
default:
return "alphabetic";
}
}
GlobalCompositeOperation GlobalCompositeOperationFromString(kk::CString string) {
if(CStringEqual(string, "source-atop")) {
return GlobalCompositeOperationSourceAtop;
}
if(CStringEqual(string, "source-in")) {
return GlobalCompositeOperationSourceIn;
}
if(CStringEqual(string, "source-out")) {
return GlobalCompositeOperationSourceOut;
}
if(CStringEqual(string, "destination-over")) {
return GlobalCompositeOperationDestinationOver;
}
if(CStringEqual(string, "destination-atop")) {
return GlobalCompositeOperationDestinationAtop;
}
if(CStringEqual(string, "destination-in")) {
return GlobalCompositeOperationDestinationIn;
}
if(CStringEqual(string, "destination-out")) {
return GlobalCompositeOperationDestinationOut;
}
if(CStringEqual(string, "destination-lighter")) {
return GlobalCompositeOperationDestinationLighter;
}
if(CStringEqual(string, "destination-copy")) {
return GlobalCompositeOperationDestinationCopy;
}
if(CStringEqual(string, "destination-xor")) {
return GlobalCompositeOperationDestinationXOR;
}
return GlobalCompositeOperationSourceOver;
}
kk::String StringFromGlobalCompositeOperation(GlobalCompositeOperation v) {
switch (v) {
case GlobalCompositeOperationSourceAtop:
return "source-atop";
case GlobalCompositeOperationSourceIn:
return "source-in";
case GlobalCompositeOperationSourceOut:
return "source-out";
case GlobalCompositeOperationDestinationOver:
return "destination-over";
case GlobalCompositeOperationDestinationAtop:
return "destination-atop";
case GlobalCompositeOperationDestinationIn:
return "destination-in";
case GlobalCompositeOperationDestinationOut:
return "destination-out";
case GlobalCompositeOperationDestinationLighter:
return "destination-lighter";
case GlobalCompositeOperationDestinationCopy:
return "destination-copy";
case GlobalCompositeOperationDestinationXOR:
return "destination-xor";
default:
break;
}
return "source-over";
}
Context::Context(Uint width,Uint height):_width(width),_height(height) {
_fillColor = {0,0,0,1};
_strokeColor = {0,0,0,1};
_shadowColor = {0,0,0,1};
_shadowBlur = 0;
_shadowOffsetX = 0;
_shadowOffsetY = 0;
_lineCap = LineCapTypeButt;
_lineJoin = LineJoinTypeBevel;
_lineWidth = 1;
_miterLimit = 0;
_font = {"",14,FontStyleNormal,FontWeightNormal};
_textAlign = TextAlignStart;
_textBaseline = TextBaselineAlphabetic;
_globalAlpha = 1.0f;
_globalCompositeOperation = GlobalCompositeOperationSourceOver;
}
kk::Strong Context::getImageData(Uint x,Uint y,Uint width,Uint height) {
if(width == 0 || height == 0) {
return (kk::Object *) nullptr;
}
kk::Strong v = createImageData(width, height);
ImageData * image = v.as<ImageData>();
if(image != nullptr) {
Ubyte * p = image->data();
Ubyte * s = getContextData();
for(Uint r = 0; r < height; r ++) {
for(Uint c = 0; c < width; c ++) {
if(r + y < _height && c + x < _width) {
for(Uint n = 0; n < 4; n ++) {
*p = s[((r + y) * _width + (c + x)) * 4 + n];
p ++;
}
} else {
p += 4;
}
}
}
}
return image;
}
void Context::putImageData(ImageData * image,Uint x,Uint y,Uint dirtyX,Uint dirtyY,Uint dirtyWidth,Uint dirtyHeight) {
if(image == nullptr) {
return;
}
if(dirtyWidth == 0) {
dirtyWidth = _width - dirtyX;
}
if(dirtyHeight == 0) {
dirtyHeight = _height - dirtyY;
}
Uint mWidth = image->width();
Uint width = MIN(mWidth - x,dirtyWidth);
Uint height = MIN(image->height() - y,dirtyHeight);
Ubyte * p = image->data();
Ubyte * s = getContextData();
for(Uint r = 0; r < height; r ++) {
for(Uint c = 0; c < width; c ++) {
Uint i_p = ((r + y) * mWidth + (c + x)) * 4;
Uint i_s = ((r + dirtyY) * _width + (c + dirtyX)) * 4;
for(Uint n = 0; n < 4; n ++) {
s[i_s + n] = p[i_p + n];
}
}
}
}
void Context::setFillStyle(Style * style) {
_fillStyle = style;
}
Style * Context::fillStyle() {
return _fillStyle.as<Style>();
}
void Context::setFillColor(Color color) {
_fillColor = color;
}
Color Context::fillColor() {
return _fillColor;
}
void Context::setStrokeStyle(Style * style) {
_strokeStyle = style;
}
Style * Context::strokeStyle() {
return _strokeStyle.as<Style>();
}
void Context::setStrokeColor(Color color) {
_strokeColor = color;
}
Color Context::strokeColor() {
return _strokeColor;
}
void Context::setShadowColor(Color v) {
_shadowColor = v;
}
Color Context::shadowColor() {
return _shadowColor;
}
void Context::setShadowBlur(Float v) {
_shadowBlur = v;
}
Float Context::shadowBlur() {
return _shadowBlur;
}
void Context::setShadowOffsetX(Float v) {
_shadowOffsetX = v;
}
Float Context::shadowOffsetX() {
return _shadowOffsetX;
}
void Context::setShadowOffsetY(Float v) {
_shadowOffsetY = v;
}
Float Context::shadowOffsetY() {
return _shadowOffsetY;
}
void Context::setLineCap(LineCapType v) {
_lineCap = v;
}
LineCapType Context::lineCap() {
return _lineCap;
}
void Context::setLineJoin(LineJoinType v) {
_lineJoin = v;
}
LineJoinType Context::lineJoin() {
return _lineJoin;
}
void Context::setLineWidth(Float v) {
_lineWidth = v;
}
Float Context::lineWidth() {
return _lineWidth;
}
void Context::setMiterLimit(Float v) {
_miterLimit = v;
}
Float Context::miterLimit() {
return _miterLimit;
}
void Context::setFont(Font v) {
_font = v;
}
Font Context::font() {
return _font;
}
void Context::setTextAlign(TextAlign v) {
_textAlign = v;
}
TextAlign Context::textAlign() {
return _textAlign;
}
void Context::setTextBaseline(TextBaseline v) {
_textBaseline = v;
}
TextBaseline Context::textBaseline() {
return _textBaseline;
}
void Context::setGlobalAlpha(Float v) {
_globalAlpha = v;
}
Float Context::globalAlpha() {
return _globalAlpha;
}
void Context::setGlobalCompositeOperation(GlobalCompositeOperation v) {
_globalCompositeOperation = v;
}
GlobalCompositeOperation Context::globalCompositeOperation() {
return _globalCompositeOperation;
}
Uint Context::width() {
return _width;
}
Uint Context::height() {
return _height;
}
kk::Strong Context::createLinearGradient(Float x0,Float y0, Float x1, Float y1) {
return new LinearGradient(x0,y0,x1,y1);
}
kk::Strong Context::createRadialGradient(Float x0,Float y0,Float r0, Float x1, Float y1, Float r1) {
return new RadialGradient(x0,y0,r0,x1,y1,r1);
}
kk::Strong Context::createPattern(Image * image,PatternType type) {
return new Pattern(image,type);
}
void Context::fillRect(Float x, Float y,Float width,Float height) {
rect(x, y, width, height);
fill();
}
void Context::strokeRect(Float x, Float y,Float width,Float height) {
rect(x, y, width, height);
stroke();
}
kk::Strong Context::createImageData(Uint width,Uint height) {
if(width == 0 || height == 0) {
return (kk::Object *) nullptr;
}
return new ImageData(width,height);
}
Pattern::Pattern(Image * image,PatternType type):_image((kk::Object *) image),_type(type) {
}
Image * Pattern::image() {
return _image.as<Image>();
}
PatternType Pattern::type() {
return _type;
}
void Gradient::addColorStop(Float loc,Color color) {
_locations.push_back(loc);
_colors.push_back(color);
}
RadialGradient::RadialGradient(Float x0,Float y0,Float r0, Float x1, Float y1, Float r1)
:Gradient(),
_x0(x0),_y0(y0),_r0(r0),
_x1(x1),_y1(y1),_r1(r1) {
}
LinearGradient::LinearGradient(Float x0,Float y0, Float x1, Float y1)
:Gradient(),
_x0(x0),_y0(y0),
_x1(x1),_y1(y1){
}
void ImageData::copyPixels(void * data) {
memcpy(data, _data, _width * _height * 4);
}
Boolean ImageData::isCopyPixels() {
return true;
}
Uint ImageData::width() {
return _width;
}
Uint ImageData::height() {
return _height;
}
Ubyte * ImageData::data() {
return _data;
}
Uint ImageData::size() {
return _width * _height * 4;
}
kk::CString OSImage::src() {
return _src.c_str();
}
kk::CString OSImage::basePath() {
return _basePath.c_str();
}
}
}
| 30.192819 | 126 | 0.418586 |
5b74f18990a179a8d50db65116d404a890d70e13 | 480 | cpp | C++ | tools/cross_pp.cpp | mcarlen/libbiarc | d016a1be643ddcded53411b4f242ac6004b65173 | [
"Apache-2.0"
] | null | null | null | tools/cross_pp.cpp | mcarlen/libbiarc | d016a1be643ddcded53411b4f242ac6004b65173 | [
"Apache-2.0"
] | 1 | 2019-08-23T09:36:29.000Z | 2019-08-26T09:56:38.000Z | tools/cross_pp.cpp | mcarlen/libbiarc | d016a1be643ddcded53411b4f242ac6004b65173 | [
"Apache-2.0"
] | 1 | 2019-08-11T21:12:02.000Z | 2019-08-11T21:12:02.000Z | #include "../include/Curve.h"
int main(int argc, char** argv) {
int N;
float s, t0, t1;
if (argc!=6) {
cout << "Usage : " << argv[0] << " s t0 t1 N pkf\n";
exit(0);
}
s = atof(argv[1]);
t0 = atof(argv[2]);
t1 = atof(argv[3]);
N = atoi(argv[4]);
Curve<Vector3> c(argv[5]);
c.make_default();
c.normalize();
c.make_default();
for (int i=0;i<N;++i) {
float t = t0 + (t1-t0)*(float)i/(float)N;
cout << t << " " << c.pp(s, t) << endl;
}
return 0;
}
| 17.142857 | 56 | 0.508333 |
5b786104818f2dded7183adeed4c73af5a677cb4 | 2,561 | cpp | C++ | 648-replace-words/648-replace-words.cpp | shreydevep/DSA | 688af414c1fada1b82a4b4e9506747352007c894 | [
"MIT"
] | null | null | null | 648-replace-words/648-replace-words.cpp | shreydevep/DSA | 688af414c1fada1b82a4b4e9506747352007c894 | [
"MIT"
] | null | null | null | 648-replace-words/648-replace-words.cpp | shreydevep/DSA | 688af414c1fada1b82a4b4e9506747352007c894 | [
"MIT"
] | null | null | null | class Solution {
public:
class Trie{
public:
class Node{
public:
Node* links[26] = {NULL};
string str = "";
bool containsKey(char ch){
return (links[ch-'a'] != NULL);
}
void put(char ch, Node* node){
links[ch-'a'] = node;
}
Node* get(char ch){
return links[ch-'a'];
}
void setEnd(string word){
str = word;
}
};
Node* root;
Trie(){
root = new Node();
}
void insert(string word){
Node* node = root;
for(auto ch : word){
if(!node->containsKey(ch)){
node->put(ch,new Node);
}
node = node->get(ch);
}
node->setEnd(word);
}
string replaceWithPrefix(string word){
Node* node = root;
for(auto ch : word){
if(!node->containsKey(ch)){
return word;
}
node = node->get(ch);
//cout << ch <<" "<< node->str <<" "<< word <<"\n";
if(node->str != ""){
return node->str;
}
}
if(node->str != "") return node->str;
return word;
}
};
vector<string> removeDupWord(string str)
{
// Used to split string around spaces.
vector <string> fin;
istringstream ss(str);
string word; // for storing each word
// Traverse through all words
// while loop till we get
// strings to store in string word
while (ss >> word)
{
// print the read word
fin.push_back(word);
}
return fin;
}
string replaceWords(vector<string>& dictionary, string sentence) {
Trie obj;
vector <string> fin = removeDupWord(sentence);
for(auto word : dictionary){
obj.insert(word);
}
for(int i=0;i<fin.size();++i){
fin[i] = obj.replaceWithPrefix(fin[i]);
}
sentence = "";
for(int i=0;i<fin.size();++i){
sentence += (fin[i] + " ");
}
sentence.pop_back();
return sentence;
}
}; | 25.868687 | 70 | 0.385396 |
5b7a233f651cf3fd113d95f0df596b982066c3b6 | 4,813 | hpp | C++ | hpx/util/detail/empty_vtable.hpp | andreasbuhr/hpx | 4366a90aacbd3e95428a94ab24a1646a67459cc2 | [
"BSL-1.0"
] | null | null | null | hpx/util/detail/empty_vtable.hpp | andreasbuhr/hpx | 4366a90aacbd3e95428a94ab24a1646a67459cc2 | [
"BSL-1.0"
] | null | null | null | hpx/util/detail/empty_vtable.hpp | andreasbuhr/hpx | 4366a90aacbd3e95428a94ab24a1646a67459cc2 | [
"BSL-1.0"
] | null | null | null | // Copyright (c) 2011 Thomas Heller
// Copyright (c) 2013 Hartmut Kaiser
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#if !BOOST_PP_IS_ITERATING
#ifndef HPX_FUNCTION_DETAIL_EMPTY_VTABLE_HPP
#define HPX_FUNCTION_DETAIL_EMPTY_VTABLE_HPP
#include <hpx/config/forceinline.hpp>
#include <hpx/util/add_rvalue_reference.hpp>
#include <boost/ref.hpp>
#include <boost/preprocessor/iteration/iterate.hpp>
#include <boost/preprocessor/repetition/enum_params.hpp>
#include <boost/preprocessor/repetition/enum_trailing_params.hpp>
#include <typeinfo>
namespace hpx { namespace util { namespace detail
{
struct empty_vtable_base
{
enum { empty = true };
static std::type_info const& get_type()
{
return typeid(void);
}
static void static_delete(void ** f) {}
static void destruct(void ** f) {}
static void clone(void *const* f, void ** dest) {}
static void copy(void *const* f, void ** dest) {}
// we can safely return an int here as those function will never
// be called.
static int& construct(void ** f)
{
hpx::throw_exception(bad_function_call,
"empty function object should not be used",
"empty_vtable_base::construct", __FILE__, __LINE__);
static int t = 0;
return t;
}
static int& get(void **f)
{
hpx::throw_exception(bad_function_call,
"empty function object should not be used",
"empty_vtable_base::get", __FILE__, __LINE__);
static int t = 0;
return t;
}
static int& get(void *const*f)
{
hpx::throw_exception(bad_function_call,
"empty function object should not be used",
"empty_vtable_base::get", __FILE__, __LINE__);
static int t = 0;
return t;
}
};
template <typename Sig, typename IArchive, typename OArchive>
struct empty_vtable;
}}}
#define BOOST_UTIL_DETAIL_EMPTY_VTABLE_ADD_RVALUE_REF(Z, N, D) \
typename util::add_rvalue_reference<BOOST_PP_CAT(D, N)>::type \
BOOST_PP_CAT(a, N) \
/**/
#if !defined(HPX_USE_PREPROCESSOR_LIMIT_EXPANSION)
# include <hpx/util/detail/preprocessed/empty_vtable.hpp>
#else
#if defined(__WAVE__) && defined(HPX_CREATE_PREPROCESSED_FILES)
# pragma wave option(preserve: 1, line: 0, output: "preprocessed/empty_vtable_" HPX_LIMIT_STR ".hpp")
#endif
#define BOOST_PP_ITERATION_PARAMS_1 \
( \
3 \
, ( \
0 \
, HPX_FUNCTION_ARGUMENT_LIMIT \
, <hpx/util/detail/empty_vtable.hpp> \
) \
) \
/**/
#include BOOST_PP_ITERATE()
#if defined(__WAVE__) && defined (HPX_CREATE_PREPROCESSED_FILES)
# pragma wave option(output: null)
#endif
#endif // !defined(HPX_USE_PREPROCESSOR_LIMIT_EXPANSION)
#undef BOOST_UTIL_DETAIL_EMPTY_VTABLE_ADD_RVALUE_REF
#endif
#else
#define N BOOST_PP_ITERATION()
namespace hpx { namespace util { namespace detail
{
template <
typename R
BOOST_PP_ENUM_TRAILING_PARAMS(N, typename A)
, typename IArchive
, typename OArchive
>
struct empty_vtable<
R(BOOST_PP_ENUM_PARAMS(N, A))
, IArchive
, OArchive
>
: empty_vtable_base
{
typedef R (*functor_type)(BOOST_PP_ENUM_PARAMS(N, A));
static vtable_ptr_base<
R(BOOST_PP_ENUM_PARAMS(N, A))
, IArchive
, OArchive
> *get_ptr()
{
return
get_empty_table<
R(BOOST_PP_ENUM_PARAMS(N, A))
>::template get<IArchive, OArchive>();
}
BOOST_ATTRIBUTE_NORETURN static R
invoke(void ** f
BOOST_PP_ENUM_TRAILING(N, BOOST_UTIL_DETAIL_EMPTY_VTABLE_ADD_RVALUE_REF, A))
{
hpx::throw_exception(bad_function_call,
"empty function object should not be used",
"empty_vtable::operator()");
}
};
}}}
#undef N
#endif
| 31.051613 | 102 | 0.540204 |
5b7babe6958aa7327c1581dc0a7afa00fc9aab33 | 1,960 | cpp | C++ | khr2/controllers/khr2/KHR2_Data.cpp | llessieux/KHR2Webot | f1d7207c12b2a666b023c4a16082601b29ae54bb | [
"MIT"
] | null | null | null | khr2/controllers/khr2/KHR2_Data.cpp | llessieux/KHR2Webot | f1d7207c12b2a666b023c4a16082601b29ae54bb | [
"MIT"
] | null | null | null | khr2/controllers/khr2/KHR2_Data.cpp | llessieux/KHR2Webot | f1d7207c12b2a666b023c4a16082601b29ae54bb | [
"MIT"
] | null | null | null | #include "KHR2_Data.h"
bool RCBMotion::SaveToFile(RCBMotion *m,char *filename)
{
FILE *f = fopen(filename,"wt");
if ( f == NULL )
return false;
fprintf(f,"[GraphicalEdit]\n");
fprintf(f,"Type=%d\n",m->m_type);
fprintf(f,"Width=500\n");
fprintf(f,"Height=%d\n",30*((m->m_item_count/8) + 1));
fprintf(f,"Items=%d\n",m->m_item_count);
fprintf(f,"Links=%d\n",m->m_link_count);
fprintf(f,"Start=%d\n",m->m_start);
fprintf(f,"Name=%s\n",m->m_name);
fprintf(f,"Port=0\n");
fprintf(f,"Ctrl=%d\n",m->m_control);
fprintf(f,"\n");
for(int i=0;i<m->m_item_count;i++)
{
const RCBMotionItem &item = m->m_items[i];
fprintf(f,"[Item%d]\n",i);
fprintf(f,"Name=%s\n",item.m_name);
fprintf(f,"Width=%d\n",item.m_width);
fprintf(f,"Height=%d\n",item.m_height);
fprintf(f,"Left=%d\n",item.m_left);
fprintf(f,"Top=%d\n",item.m_top);
fprintf(f,"Color=%d\n",item.m_color);
fprintf(f,"Type=%d\n",item.m_type);
fprintf(f,"Prm=");
std::list<int>::const_iterator it = item.m_params.begin();
for(int j=0;j<24;j++,it++)
{
fprintf(f,"%d",*it);
if ( j != 23 )
fprintf(f,",");
else
fprintf(f,"\n");
}
fprintf(f,"\n");
}
for(int i=0;i<m->m_link_count;i++)
{
const RCBMotionLink &item = m->m_links[i];
fprintf(f,"[Link%d]\n",i);
fprintf(f,"Main=%d\n",item.m_main);
fprintf(f,"Origin=%d\n",item.m_origin);
fprintf(f,"Final=%d\n",item.m_final);
fprintf(f,"Point=");
for(unsigned int j=0;j<item.m_points.size();j++)
{
fprintf(f,"%d",item.m_points[j]);
if ( j != item.m_points.size()-1 )
fprintf(f,",");
}
fprintf(f,"\n");
fprintf(f,"\n");
}
fclose(f);
return true;
}
| 28.823529 | 66 | 0.497959 |
5b829bdb1b036b5ea700ffa3692ecbcf1da3b1ca | 674 | hpp | C++ | ILogger.hpp | kit-cpp-course/yushkov-ia | f08795754beec39a5b0801a0e4bad8f87c9838b4 | [
"MIT"
] | null | null | null | ILogger.hpp | kit-cpp-course/yushkov-ia | f08795754beec39a5b0801a0e4bad8f87c9838b4 | [
"MIT"
] | null | null | null | ILogger.hpp | kit-cpp-course/yushkov-ia | f08795754beec39a5b0801a0e4bad8f87c9838b4 | [
"MIT"
] | null | null | null | #pragma once
#include <string>
namespace wv
{
class OperationLogger;
/*
* Интерфейс для логирования действий
*/
class ILogger
{
public:
virtual ~ILogger() = default;
/*
* Записывает строку в лог
*/
virtual void Log(const std::string& message) const = 0;
/*
* Записывает строку в лог, добавляя в конец символ конца строки
*/
virtual void LogLine(const std::string& message) const = 0;
/*
* Записывает целое число в лог
*/
virtual void Log(int value) const = 0;
/*
* Логирует длительность операции
*/
virtual OperationLogger LogOperation(const std::string& message) const = 0;
};
}
| 18.216216 | 78 | 0.626113 |
5b852d0c70db57495ec62ec252293d274e3741f1 | 475 | cpp | C++ | Data Structures/Stack/Stock and Span/Stock and Span.cpp | bodhisatwa-mandal/CompetitiveCoding | bb3c6cad8581880561dfb3e7d5c3e66197ab656f | [
"MIT"
] | 25 | 2017-08-07T13:47:55.000Z | 2021-07-23T02:44:19.000Z | Data Structures/Stack/Stock and Span/Stock and Span.cpp | bodhisatwa-mandal/CompetitiveCoding | bb3c6cad8581880561dfb3e7d5c3e66197ab656f | [
"MIT"
] | 1 | 2017-07-28T17:53:24.000Z | 2017-07-28T17:53:24.000Z | Data Structures/Stack/Stock and Span/Solutions/Stock and Span.cpp | CodeClub-JU/CompetitiveCoding | 0162c869d14ff5357b05a209424f3616aed90478 | [
"MIT"
] | 20 | 2017-07-02T06:05:28.000Z | 2020-08-06T14:23:58.000Z | #include <bits/stdc++.h>
using namespace std;
void print(vector<int> v)
{
for(int i=0; i<v.size(); i++)
{
cout << v[i] << " ";
}
cout << endl;
}
int main()
{
int i, n, count;
stack<int> s;
cin >> n;
vector<int> arr(n), ans(n);
for(i=0; i<n; i++)
{
cin >> arr[i];
}
ans[0] = 1;
s.push(0);
for(i=1; i<n; i++)
{
while(!s.empty() && arr[i] > arr[s.top()])
s.pop();
ans[i] = s.empty() ? i+1: i-s.top();
s.push(i);
}
print(ans);
}
| 12.179487 | 44 | 0.461053 |
5b876d3da54dbd8e01a2d50acf5895694f48e76a | 489 | hpp | C++ | include/boost/hana/group/minus_mcd.hpp | rbock/hana | 2b76377f91a5ebe037dea444e4eaabba6498d3a8 | [
"BSL-1.0"
] | 2 | 2015-05-07T14:29:13.000Z | 2015-07-04T10:59:46.000Z | include/boost/hana/group/minus_mcd.hpp | rbock/hana | 2b76377f91a5ebe037dea444e4eaabba6498d3a8 | [
"BSL-1.0"
] | null | null | null | include/boost/hana/group/minus_mcd.hpp | rbock/hana | 2b76377f91a5ebe037dea444e4eaabba6498d3a8 | [
"BSL-1.0"
] | null | null | null | /*!
@file
Defines `boost::hana::Group::minus_mcd`.
@copyright Louis Dionne 2014
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
#ifndef BOOST_HANA_GROUP_MINUS_MCD_HPP
#define BOOST_HANA_GROUP_MINUS_MCD_HPP
// minus_mcd is in the forward declaration header because it is required by
// the instance for builtins
#include <boost/hana/group/group.hpp>
#endif // !BOOST_HANA_GROUP_MINUS_MCD_HPP
| 27.166667 | 78 | 0.791411 |
5b88b9108869ce09833464ed746880ef99723f20 | 1,039 | cpp | C++ | 20.Valid_Parentheses/solution_1.cpp | bngit/leetcode-practices | 5324aceac708d9b214a7d98d489b8d5dc55c89e9 | [
"MIT"
] | null | null | null | 20.Valid_Parentheses/solution_1.cpp | bngit/leetcode-practices | 5324aceac708d9b214a7d98d489b8d5dc55c89e9 | [
"MIT"
] | null | null | null | 20.Valid_Parentheses/solution_1.cpp | bngit/leetcode-practices | 5324aceac708d9b214a7d98d489b8d5dc55c89e9 | [
"MIT"
] | null | null | null | #include <cstdlib>
#include <vector>
#include <string>
#include <cassert>
#include <algorithm>
#include <sstream>
#include <map>
#include <typeinfo>
#include <iostream>
#include <stack>
using namespace std;
class Solution {
public:
bool isValid(string s) {
stack<char> bracket;
for (auto &c : s) {
if (!bracket.empty()) {
if ((bracket.top() == '(' && c == ')') // 这里写成and也是可以的
|| (bracket.top() == '[' && c == ']')
|| (bracket.top() == '{' && c == '}')) {
bracket.pop();
}
else {
if (c == ')' || c == ']' || c == '}') {
return false;
}
else {
bracket.push(c);
}
}
}
else {
bracket.push(c);
}
}
if (!bracket.empty()) {
return false;
}
return true;
}
};
| 23.613636 | 71 | 0.358999 |
5b8935a5a4c773a5f9f74342fae8a901c867b383 | 5,673 | cpp | C++ | DiffSamp/src/code/Main/Nearest2D.cpp | 1iyiwei/noise | 0d1be2030518517199dff5c7e7514ee072037d59 | [
"MIT"
] | 24 | 2016-12-13T09:48:17.000Z | 2022-01-13T03:24:45.000Z | DiffSamp/src/code/Main/Nearest2D.cpp | 1iyiwei/noise | 0d1be2030518517199dff5c7e7514ee072037d59 | [
"MIT"
] | 2 | 2019-03-29T06:44:41.000Z | 2019-11-12T03:14:25.000Z | DiffSamp/src/code/Main/Nearest2D.cpp | 1iyiwei/noise | 0d1be2030518517199dff5c7e7514ee072037d59 | [
"MIT"
] | 8 | 2016-11-09T15:54:19.000Z | 2021-04-08T14:04:17.000Z | /*
Nearest2D.cpp
Li-Yi Wei
2/7/2013
*/
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
#include <stdlib.h>
#include "Utility.hpp"
#include "Exception.hpp"
#include "FrameBuffer.hpp"
#include "LloydRelaxation.hpp"
#include "DelaunayProximity2D.hpp"
#include "Random.hpp"
int Main(int argc, char **argv)
{
int min_argc = 8;
if(argc < min_argc)
{
cerr << "Usage: " << argv[0] << " samples-file-name output-file-name dimension domain_size boundary_condition (0 none, 1 toroidal) dot_radius [color_palette_file]" << endl;
return 1;
}
int arg_ctr = 0;
const string input_file_name = argv[++arg_ctr];
const string output_file_name = argv[++arg_ctr];
const int dimension = atoi(argv[++arg_ctr]);
const float domain_size_y = atof(argv[++arg_ctr]);
const float domain_size_x = atof(argv[++arg_ctr]);
const DelaunayProximity2D::BoundaryCondition boundary_condition = static_cast<DelaunayProximity2D::BoundaryCondition>(atoi(argv[++arg_ctr]));
const float radius = atof(argv[++arg_ctr]);
const double very_small = 0;
const int tile_boundary = 1;
const int region_boundary = 1;
const int color_scheme = 0;
const string color_palette_file_name = (arg_ctr+1 < argc ? argv[++arg_ctr] : "");
if(dimension != 2)
{
cerr << "dimension != 2" << endl;
return 1;
}
// samples
vector<Sample> samples;
if(! Utility::ReadSamples(dimension, input_file_name, samples))
{
cerr << "cannot read samples from " << input_file_name << endl;
return 1;
}
// color palette
int num_colors = 0;
for(unsigned int i = 0; i < samples.size(); i++)
{
if((samples[i].id+1) > num_colors)
{
num_colors = (samples[i].id+1);
}
}
num_colors += 2; // query and answer points
Random::InitRandomNumberGenerator();
vector<FrameBuffer::P3> palette;
{
string message = Utility::BuildPalette(num_colors, color_palette_file_name, palette);
if(message != "")
{
cerr << message << endl;
return 1;
}
}
// proximity class
vector<DelaunayProximity2D::Point2D> points(samples.size());
for(unsigned int i = 0; i < points.size(); i++)
{
points[i].id = samples[i].id;
points[i].x = samples[i].coordinate[1];
points[i].y = samples[i].coordinate[0];
}
vector<const DelaunayProximity2D::Point2D *> p_points(points.size());
for(unsigned int i = 0; i < p_points.size(); i++)
{
p_points[i] = &points[i];
}
const DelaunayProximity2D::Box box(0, domain_size_x, 0, domain_size_y);
DelaunayProximity2D proximity2D(box, very_small, boundary_condition, p_points);
// query point
DelaunayProximity2D::Point2D query, result;
query.x = Random::UniformRandom()*domain_size_x;
query.y = Random::UniformRandom()*domain_size_y;
if(! proximity2D.Nearest(query, result))
{
cerr << "cannot query (" << query.x << ", " << query.y << ")" << endl;
return 1;
}
// draw
{
vector<FrameBuffer::L2F> locations(samples.size());
for(unsigned int i = 0; i < locations.size(); i++)
{
locations[i].color_index = samples[i].id;
locations[i].x = samples[i].coordinate[1];
locations[i].y = samples[i].coordinate[0];
if((locations[i].x == result.x) && (locations[i].y == result.y))
{
locations[i].color_index = num_colors - 1;
}
}
FrameBuffer::L2F query_f, result_f;
query_f.color_index = num_colors - 2;
query_f.x = query.x;
query_f.y = query.y;
result_f.color_index = num_colors - 1;
result_f.x = result.x;
result_f.y = result.y;
locations.push_back(query_f);
locations.push_back(result_f);
// generate Voronoi
vector<LloydRelaxation::VoronoiRegion> regions;
const string message = LloydRelaxation::Voronoi(box.x_min, box.x_max, box.y_min, box.y_max, boundary_condition, p_points, regions);
if(message != "")
{
cerr << "error in generating Voronoi " << message << endl;
return 1;
}
vector<FrameBuffer::Tile> tiles(regions.size());
if(tiles.size() != regions.size())
{
throw Exception("weird size mismatch");
}
for(unsigned int i = 0; i < tiles.size(); i++)
{
tiles[i].color_index = regions[i].center.id;
tiles[i].vertices = vector<FrameBuffer::L2F>(regions[i].ring.size());
for(unsigned int j = 0; j < tiles[i].vertices.size(); j++)
{
tiles[i].vertices[j].x = regions[i].ring[j].x;
tiles[i].vertices[j].y = regions[i].ring[j].y;
}
}
vector<float> region(4);
region[2] = 0;
region[3] = fabs(domain_size_y);
region[0] = 0;
region[1] = fabs(domain_size_x);
vector<FrameBuffer::Circle> circles;
// draw Voronoi
if(!FrameBuffer::WriteFIG(locations, tiles, circles, palette, region, radius, tile_boundary, region_boundary, color_scheme, output_file_name))
{
cerr << "error in writing " << output_file_name << endl;
return 1;
}
}
// done
return 0;
}
int main(int argc, char **argv)
{
try
{
return Main(argc, argv);
}
catch(Exception e)
{
cerr << "Error : " << e.Message() << endl;
return 1;
}
}
| 26.759434 | 180 | 0.575886 |
5b89baef9f25a6bd3f1dc680290ea321cd6196dd | 1,427 | cpp | C++ | problemes/probleme303.cpp | ZongoForSpeed/ProjectEuler | 2e2d45f984d48a1da8275886c976f909a0de94ce | [
"MIT"
] | 6 | 2015-10-13T17:07:21.000Z | 2018-05-08T11:50:22.000Z | problemes/probleme303.cpp | ZongoForSpeed/ProjectEuler | 2e2d45f984d48a1da8275886c976f909a0de94ce | [
"MIT"
] | null | null | null | problemes/probleme303.cpp | ZongoForSpeed/ProjectEuler | 2e2d45f984d48a1da8275886c976f909a0de94ce | [
"MIT"
] | null | null | null | #include "problemes.h"
#include "utilitaires.h"
typedef unsigned long long nombre;
typedef std::vector<nombre> vecteur;
namespace {
bool trinary(nombre n) {
while (n % 10 < 3 && n > 10) {
n /= 10;
}
return n % 10 < 3;
}
nombre f(size_t n) {
nombre base = 1;
vecteur v;
v.emplace_back(0);
while (true) {
vecteur tmp;
for (size_t i = 1; i < 11; ++i) {
for (const nombre &f : v) {
nombre m = i * base + f;
nombre mn = m * n;
if (trinary(mn))
return m;
else if (trinary(mn % base))
tmp.push_back(m);
}
}
base *= 10;
std::sort(tmp.begin(), tmp.end());
std::swap(tmp, v);
}
}
}
ENREGISTRER_PROBLEME(303, "Multiples with small digits") {
// For a positive integer n, define f(n) as the least positive multiple of n that, written in base 10, uses only
// digits ≤ 2.
//
// Thus f(2)=2, f(3)=12, f(7)=21, f(42)=210, f(89)=1121222.
// ∑
// Also, ∑ n=1..100 f(n)/n = 11363107
//
// Find ∑ n=1..10000 f(n)/n.
size_t limite = 10000;
nombre resultat = 0;
for (size_t n = 1; n < limite + 1; ++n) {
resultat += f(n);
}
return std::to_string(resultat);
}
| 26.425926 | 116 | 0.451997 |
5b8accce8f4a6d09fa5094ea799582fe333cadd5 | 1,120 | cpp | C++ | Codeforces/20C - Dijkstra.cpp | Joon7891/Competitive-Programming | d860b7ad932cd5a6fb91fdc8c53101da57f4a408 | [
"MIT"
] | 2 | 2021-04-13T00:19:56.000Z | 2021-04-13T01:19:45.000Z | Codeforces/20C - Dijkstra.cpp | Joon7891/Competitive-Programming | d860b7ad932cd5a6fb91fdc8c53101da57f4a408 | [
"MIT"
] | null | null | null | Codeforces/20C - Dijkstra.cpp | Joon7891/Competitive-Programming | d860b7ad932cd5a6fb91fdc8c53101da57f4a408 | [
"MIT"
] | 1 | 2020-08-26T12:36:08.000Z | 2020-08-26T12:36:08.000Z | #include<bits/stdc++.h>
#define INF 0x3f3f3f3f
#define i64 long long
#define pii pair<i64, i64>
using namespace std;
struct Edge{
i64 next, weight;
};
const int MAXN = 100005;
vector<Edge> adj[MAXN];
int back[MAXN];
i64 weight[MAXN];
int N, M;
int main(){
cin >> N >> M;
for (int i = 1, a, b, w; i <= M; i++){
cin >> a >> b >> w;
adj[a].push_back({b, w});
adj[b].push_back({a, w});
}
fill(weight, weight + MAXN, LLONG_MAX);
weight[1] = 0;
back[1] = 1;
priority_queue<pii, vector<pii>, greater<pii>> q;
q.push({0, 1});
while (!q.empty()){
pii cur = q.top(); q.pop();
if (cur.second == N) break;
for (Edge e : adj[cur.second]){
if (cur.first + e.weight < weight[e.next]){
weight[e.next] = cur.first + e.weight;
q.push({weight[e.next], e.next});
back[e.next] = cur.second;
}
}
}
if (weight[N] == LLONG_MAX){
cout << -1 << endl;
return 0;
}
int cur = N;
vector<int> path;
while (cur != back[cur]){
path.push_back(cur);
cur = back[cur];
}
cout << "1 ";
for (int i = path.size() - 1; i >= 0; i--) cout << path[i] << " ";
cout << endl;
} | 17.777778 | 67 | 0.549107 |
5b8baff0ff81c8aab079816830a61a3f5713b118 | 159 | cpp | C++ | test/com/facebook/buck/android/testdata/android_project/native/cxx/symbols.cpp | Unknoob/buck | 2dfc734354b326f2f66896dde7746a11965d5a13 | [
"Apache-2.0"
] | 8,027 | 2015-01-02T05:31:44.000Z | 2022-03-31T07:08:09.000Z | test/com/facebook/buck/android/testdata/android_project/native/cxx/symbols.cpp | Unknoob/buck | 2dfc734354b326f2f66896dde7746a11965d5a13 | [
"Apache-2.0"
] | 2,355 | 2015-01-01T15:30:53.000Z | 2022-03-30T20:21:16.000Z | test/com/facebook/buck/android/testdata/android_project/native/cxx/symbols.cpp | Unknoob/buck | 2dfc734354b326f2f66896dde7746a11965d5a13 | [
"Apache-2.0"
] | 1,280 | 2015-01-09T03:29:04.000Z | 2022-03-30T15:14:14.000Z | extern "C" {
int __attribute__ ((noinline, visibility ("hidden"))) supply_value() {
return 42;
}
int get_value() {
return supply_value();
}
}
| 15.9 | 72 | 0.610063 |
5b8e0ad8c2a72e7b0c96728367d7311d9dd0297c | 325 | cpp | C++ | test/StaircaseSimulator_main.cpp | leiz86/staircase_code_simulator | bba297c1c1fbb4921855b0e4f43afb505c1235fa | [
"Apache-2.0"
] | null | null | null | test/StaircaseSimulator_main.cpp | leiz86/staircase_code_simulator | bba297c1c1fbb4921855b0e4f43afb505c1235fa | [
"Apache-2.0"
] | null | null | null | test/StaircaseSimulator_main.cpp | leiz86/staircase_code_simulator | bba297c1c1fbb4921855b0e4f43afb505c1235fa | [
"Apache-2.0"
] | null | null | null | /*
* StaircaseSimulator_main.cpp
*
* Created on: Dec 10, 2017
* Author: leizhang
*/
#include "StaircaseSimulator.h"
int main(int argc, char **argv) {
StaircaseSimulator & scs = StaircaseSimulator::GetInstance();
const char testOpts[] = "test";
scs.init(testOpts);
scs.run(0);
scs.report(1);
return 0;
}
| 15.47619 | 62 | 0.664615 |
5b901cc7a7352094517dae80b4131606c50d23d6 | 674 | hpp | C++ | src/ResolvedResource.hpp | abelsensors/esp32_https_server | e568d8321764cce26ab76976f6489065b3744c7a | [
"MIT"
] | 221 | 2018-06-11T07:47:54.000Z | 2022-03-28T17:56:06.000Z | src/ResolvedResource.hpp | abelsensors/esp32_https_server | e568d8321764cce26ab76976f6489065b3744c7a | [
"MIT"
] | 128 | 2017-12-19T18:18:58.000Z | 2022-03-22T01:15:26.000Z | src/ResolvedResource.hpp | abelsensors/esp32_https_server | e568d8321764cce26ab76976f6489065b3744c7a | [
"MIT"
] | 82 | 2018-04-29T01:14:47.000Z | 2022-03-21T11:32:02.000Z | #ifndef SRC_RESOLVEDRESOURCE_HPP_
#define SRC_RESOLVEDRESOURCE_HPP_
#include "ResourceNode.hpp"
#include "ResourceParameters.hpp"
namespace httpsserver {
/**
* \brief This class represents a resolved resource, meaning the result of mapping a string URL to an HTTPNode
*/
class ResolvedResource {
public:
ResolvedResource();
~ResolvedResource();
void setMatchingNode(HTTPNode * node);
HTTPNode * getMatchingNode();
bool didMatch();
ResourceParameters * getParams();
void setParams(ResourceParameters * params);
private:
HTTPNode * _matchingNode;
ResourceParameters * _params;
};
} /* namespace httpsserver */
#endif /* SRC_RESOLVEDRESOURCE_HPP_ */
| 21.741935 | 110 | 0.759644 |
5b91ec74d866de7ea3bd980efbbfe012b81f128a | 1,153 | cpp | C++ | cpp/leetcode/PermutationInString.cpp | danyfang/SourceCode | 8168f6058648f2a330a7354daf3a73a4d8a4e730 | [
"MIT"
] | null | null | null | cpp/leetcode/PermutationInString.cpp | danyfang/SourceCode | 8168f6058648f2a330a7354daf3a73a4d8a4e730 | [
"MIT"
] | null | null | null | cpp/leetcode/PermutationInString.cpp | danyfang/SourceCode | 8168f6058648f2a330a7354daf3a73a4d8a4e730 | [
"MIT"
] | null | null | null | //Leetcode Problem No 567 Permutation in String
//Solution written by Xuqiang Fang on 24 Oct, 2018
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <unordered_map>
#include <unordered_set>
#include <stack>
#include <queue>
using namespace std;
class Solution{
public:
bool checkInclusion(string s1, string s2) {
const int n = s1.length();
const int m = s2.length();
int a[26] = {0};
int b[26] = {0};
for(int i=0; i<n; ++i){
a[s1[i]-'a']++;
b[s2[i]-'a']++;
}
if(compare(a,b)) return true;
for(int i=n; i<m; ++i){
b[s2[i-n]-'a']--;
b[s2[i]-'a']++;
if(compare(a,b)) return true;
}
return false;
}
private:
bool compare(int* a, int* b){
for(int i=0; i<26; ++i){
if(a[i] != b[i]) return false;
}
return true;
}
};
int main(){
Solution s;
string s1 = "ab";
string s2 = "eidbaooo";
cout << s.checkInclusion(s1, s2) << endl;
s2 = "eidboaoo";
cout << s.checkInclusion(s1, s2) << endl;
return 0;
}
| 22.607843 | 50 | 0.512576 |
5b9206299cc2c3b46c4b7e669684fcc0a484121e | 1,684 | hpp | C++ | src/modules/tvlp/controller_stack.hpp | DerangedMonkeyNinja/openperf | cde4dc6bf3687f0663c11e9e856e26a0dc2b1d16 | [
"Apache-2.0"
] | 20 | 2019-12-04T01:28:52.000Z | 2022-03-17T14:09:34.000Z | src/modules/tvlp/controller_stack.hpp | DerangedMonkeyNinja/openperf | cde4dc6bf3687f0663c11e9e856e26a0dc2b1d16 | [
"Apache-2.0"
] | 115 | 2020-02-04T21:29:54.000Z | 2022-02-17T13:33:51.000Z | src/modules/tvlp/controller_stack.hpp | DerangedMonkeyNinja/openperf | cde4dc6bf3687f0663c11e9e856e26a0dc2b1d16 | [
"Apache-2.0"
] | 16 | 2019-12-03T16:41:18.000Z | 2021-11-06T04:44:11.000Z | #ifndef _OP_TVLP_CONTROLLER_STACK_HPP_
#define _OP_TVLP_CONTROLLER_STACK_HPP_
#include <string>
#include <memory>
#include <unordered_map>
#include <vector>
#include <variant>
#include "tl/expected.hpp"
namespace openperf::tvlp {
namespace model {
class tvlp_configuration_t;
class tvlp_result_t;
struct tvlp_start_t;
} // namespace model
namespace internal {
class controller_t;
class controller_stack
{
using tvlp_controller_ptr = std::shared_ptr<controller_t>;
using tvlp_controller_map =
std::unordered_map<std::string, tvlp_controller_ptr>;
using tvlp_result_ptr = std::shared_ptr<model::tvlp_result_t>;
using tvlp_result_map = std::unordered_map<std::string, tvlp_result_ptr>;
private:
tvlp_controller_map m_controllers;
tvlp_result_map m_results;
void* m_context;
public:
controller_stack() = delete;
controller_stack(void* context);
std::vector<tvlp_controller_ptr> list() const;
tl::expected<tvlp_controller_ptr, std::string>
create(const model::tvlp_configuration_t&);
tl::expected<tvlp_controller_ptr, std::string>
get(const std::string& id) const;
tl::expected<void, std::string> erase(const std::string& id);
tl::expected<tvlp_result_ptr, std::string>
start(const std::string&, const model::tvlp_start_t&);
tl::expected<void, std::string> stop(const std::string&);
std::vector<tvlp_result_ptr> results() const;
tl::expected<tvlp_result_ptr, std::string>
result(const std::string& id) const;
tl::expected<void, std::string> erase_result(const std::string& id);
};
} // namespace internal
} // namespace openperf::tvlp
#endif /* _OP_TVLP_CONTROLLER_STACK_HPP_ */
| 27.16129 | 77 | 0.738124 |
5b9966bc6bc25a5787931306782e1eb5f09e8f9f | 12,190 | cc | C++ | source/extensions/transport_sockets/tls/ssl_handshaker.cc | dcillera/envoy | cb54ba8eec26f768f8c1ae412113b07bacde7321 | [
"Apache-2.0"
] | null | null | null | source/extensions/transport_sockets/tls/ssl_handshaker.cc | dcillera/envoy | cb54ba8eec26f768f8c1ae412113b07bacde7321 | [
"Apache-2.0"
] | 11 | 2019-10-15T23:03:57.000Z | 2020-06-14T16:10:12.000Z | source/extensions/transport_sockets/tls/ssl_handshaker.cc | dcillera/envoy | cb54ba8eec26f768f8c1ae412113b07bacde7321 | [
"Apache-2.0"
] | 7 | 2019-07-04T14:23:54.000Z | 2020-04-27T08:52:51.000Z | #include "source/extensions/transport_sockets/tls/ssl_handshaker.h"
#include "envoy/stats/scope.h"
#include "source/common/common/assert.h"
#include "source/common/common/empty_string.h"
#include "source/common/common/hex.h"
#include "source/common/http/headers.h"
#include "source/extensions/transport_sockets/tls/utility.h"
#include "absl/strings/str_replace.h"
#include "openssl/err.h"
#include "openssl/x509v3.h"
using Envoy::Network::PostIoAction;
namespace Envoy {
namespace Extensions {
namespace TransportSockets {
namespace Tls {
void SslExtendedSocketInfoImpl::setCertificateValidationStatus(
Envoy::Ssl::ClientValidationStatus validated) {
certificate_validation_status_ = validated;
}
Envoy::Ssl::ClientValidationStatus SslExtendedSocketInfoImpl::certificateValidationStatus() const {
return certificate_validation_status_;
}
SslHandshakerImpl::SslHandshakerImpl(bssl::UniquePtr<SSL> ssl, int ssl_extended_socket_info_index,
Ssl::HandshakeCallbacks* handshake_callbacks)
: ssl_(std::move(ssl)), handshake_callbacks_(handshake_callbacks),
state_(Ssl::SocketState::PreHandshake) {
SSL_set_ex_data(ssl_.get(), ssl_extended_socket_info_index, &(this->extended_socket_info_));
}
bool SslHandshakerImpl::peerCertificatePresented() const {
bssl::UniquePtr<X509> cert(SSL_get_peer_certificate(ssl()));
return cert != nullptr;
}
bool SslHandshakerImpl::peerCertificateValidated() const {
return extended_socket_info_.certificateValidationStatus() ==
Envoy::Ssl::ClientValidationStatus::Validated;
}
absl::Span<const std::string> SslHandshakerImpl::uriSanLocalCertificate() const {
if (!cached_uri_san_local_certificate_.empty()) {
return cached_uri_san_local_certificate_;
}
// The cert object is not owned.
X509* cert = SSL_get_certificate(ssl());
if (!cert) {
ASSERT(cached_uri_san_local_certificate_.empty());
return cached_uri_san_local_certificate_;
}
cached_uri_san_local_certificate_ = Utility::getSubjectAltNames(*cert, GEN_URI);
return cached_uri_san_local_certificate_;
}
absl::Span<const std::string> SslHandshakerImpl::dnsSansLocalCertificate() const {
if (!cached_dns_san_local_certificate_.empty()) {
return cached_dns_san_local_certificate_;
}
X509* cert = SSL_get_certificate(ssl());
if (!cert) {
ASSERT(cached_dns_san_local_certificate_.empty());
return cached_dns_san_local_certificate_;
}
cached_dns_san_local_certificate_ = Utility::getSubjectAltNames(*cert, GEN_DNS);
return cached_dns_san_local_certificate_;
}
const std::string& SslHandshakerImpl::sha256PeerCertificateDigest() const {
if (!cached_sha_256_peer_certificate_digest_.empty()) {
return cached_sha_256_peer_certificate_digest_;
}
bssl::UniquePtr<X509> cert(SSL_get_peer_certificate(ssl()));
if (!cert) {
ASSERT(cached_sha_256_peer_certificate_digest_.empty());
return cached_sha_256_peer_certificate_digest_;
}
std::vector<uint8_t> computed_hash(SHA256_DIGEST_LENGTH);
unsigned int n;
X509_digest(cert.get(), EVP_sha256(), computed_hash.data(), &n);
RELEASE_ASSERT(n == computed_hash.size(), "");
cached_sha_256_peer_certificate_digest_ = Hex::encode(computed_hash);
return cached_sha_256_peer_certificate_digest_;
}
const std::string& SslHandshakerImpl::sha1PeerCertificateDigest() const {
if (!cached_sha_1_peer_certificate_digest_.empty()) {
return cached_sha_1_peer_certificate_digest_;
}
bssl::UniquePtr<X509> cert(SSL_get_peer_certificate(ssl()));
if (!cert) {
ASSERT(cached_sha_1_peer_certificate_digest_.empty());
return cached_sha_1_peer_certificate_digest_;
}
std::vector<uint8_t> computed_hash(SHA_DIGEST_LENGTH);
unsigned int n;
X509_digest(cert.get(), EVP_sha1(), computed_hash.data(), &n);
RELEASE_ASSERT(n == computed_hash.size(), "");
cached_sha_1_peer_certificate_digest_ = Hex::encode(computed_hash);
return cached_sha_1_peer_certificate_digest_;
}
const std::string& SslHandshakerImpl::urlEncodedPemEncodedPeerCertificate() const {
if (!cached_url_encoded_pem_encoded_peer_certificate_.empty()) {
return cached_url_encoded_pem_encoded_peer_certificate_;
}
bssl::UniquePtr<X509> cert(SSL_get_peer_certificate(ssl()));
if (!cert) {
ASSERT(cached_url_encoded_pem_encoded_peer_certificate_.empty());
return cached_url_encoded_pem_encoded_peer_certificate_;
}
bssl::UniquePtr<BIO> buf(BIO_new(BIO_s_mem()));
RELEASE_ASSERT(buf != nullptr, "");
RELEASE_ASSERT(PEM_write_bio_X509(buf.get(), cert.get()) == 1, "");
const uint8_t* output;
size_t length;
RELEASE_ASSERT(BIO_mem_contents(buf.get(), &output, &length) == 1, "");
absl::string_view pem(reinterpret_cast<const char*>(output), length);
cached_url_encoded_pem_encoded_peer_certificate_ = absl::StrReplaceAll(
pem, {{"\n", "%0A"}, {" ", "%20"}, {"+", "%2B"}, {"/", "%2F"}, {"=", "%3D"}});
return cached_url_encoded_pem_encoded_peer_certificate_;
}
const std::string& SslHandshakerImpl::urlEncodedPemEncodedPeerCertificateChain() const {
if (!cached_url_encoded_pem_encoded_peer_cert_chain_.empty()) {
return cached_url_encoded_pem_encoded_peer_cert_chain_;
}
STACK_OF(X509)* cert_chain = SSL_get_peer_full_cert_chain(ssl());
if (cert_chain == nullptr) {
ASSERT(cached_url_encoded_pem_encoded_peer_cert_chain_.empty());
return cached_url_encoded_pem_encoded_peer_cert_chain_;
}
for (int i = 0; i < sk_X509_num(cert_chain); i++) {
X509* cert = sk_X509_value(cert_chain, i);
bssl::UniquePtr<BIO> buf(BIO_new(BIO_s_mem()));
RELEASE_ASSERT(buf != nullptr, "");
RELEASE_ASSERT(PEM_write_bio_X509(buf.get(), cert) == 1, "");
const uint8_t* output;
size_t length;
RELEASE_ASSERT(BIO_mem_contents(buf.get(), &output, &length) == 1, "");
absl::string_view pem(reinterpret_cast<const char*>(output), length);
cached_url_encoded_pem_encoded_peer_cert_chain_ = absl::StrCat(
cached_url_encoded_pem_encoded_peer_cert_chain_,
absl::StrReplaceAll(
pem, {{"\n", "%0A"}, {" ", "%20"}, {"+", "%2B"}, {"/", "%2F"}, {"=", "%3D"}}));
}
sk_X509_pop_free(cert_chain, X509_free);
return cached_url_encoded_pem_encoded_peer_cert_chain_;
}
absl::Span<const std::string> SslHandshakerImpl::uriSanPeerCertificate() const {
if (!cached_uri_san_peer_certificate_.empty()) {
return cached_uri_san_peer_certificate_;
}
bssl::UniquePtr<X509> cert(SSL_get_peer_certificate(ssl()));
if (!cert) {
ASSERT(cached_uri_san_peer_certificate_.empty());
return cached_uri_san_peer_certificate_;
}
cached_uri_san_peer_certificate_ = Utility::getSubjectAltNames(*cert, GEN_URI);
return cached_uri_san_peer_certificate_;
}
absl::Span<const std::string> SslHandshakerImpl::dnsSansPeerCertificate() const {
if (!cached_dns_san_peer_certificate_.empty()) {
return cached_dns_san_peer_certificate_;
}
bssl::UniquePtr<X509> cert(SSL_get_peer_certificate(ssl()));
if (!cert) {
ASSERT(cached_dns_san_peer_certificate_.empty());
return cached_dns_san_peer_certificate_;
}
cached_dns_san_peer_certificate_ = Utility::getSubjectAltNames(*cert, GEN_DNS);
return cached_dns_san_peer_certificate_;
}
uint16_t SslHandshakerImpl::ciphersuiteId() const {
const SSL_CIPHER* cipher = SSL_get_current_cipher(ssl());
if (cipher == nullptr) {
return 0xffff;
}
// From the OpenSSL docs:
// SSL_CIPHER_get_id returns |cipher|'s id. It may be cast to a |uint16_t| to
// get the cipher suite value.
return static_cast<uint16_t>(SSL_CIPHER_get_id(cipher));
}
std::string SslHandshakerImpl::ciphersuiteString() const {
const SSL_CIPHER* cipher = SSL_get_current_cipher(ssl());
if (cipher == nullptr) {
return {};
}
return SSL_CIPHER_get_name(cipher);
}
const std::string& SslHandshakerImpl::tlsVersion() const {
if (!cached_tls_version_.empty()) {
return cached_tls_version_;
}
cached_tls_version_ = SSL_get_version(ssl());
return cached_tls_version_;
}
Network::PostIoAction SslHandshakerImpl::doHandshake() {
ASSERT(state_ != Ssl::SocketState::HandshakeComplete && state_ != Ssl::SocketState::ShutdownSent);
int rc = SSL_do_handshake(ssl());
if (rc == 1) {
state_ = Ssl::SocketState::HandshakeComplete;
handshake_callbacks_->onSuccess(ssl());
// It's possible that we closed during the handshake callback.
return handshake_callbacks_->connection().state() == Network::Connection::State::Open
? PostIoAction::KeepOpen
: PostIoAction::Close;
} else {
int err = SSL_get_error(ssl(), rc);
ENVOY_CONN_LOG(trace, "ssl error occurred while read: {}", handshake_callbacks_->connection(),
Utility::getErrorDescription(err));
switch (err) {
case SSL_ERROR_WANT_READ:
case SSL_ERROR_WANT_WRITE:
return PostIoAction::KeepOpen;
// SSL_ERROR_WANT_PRIVATE_KEY_OPERATION is undefined in OpenSSL
// case SSL_ERROR_WANT_PRIVATE_KEY_OPERATION:
// state_ = Ssl::SocketState::HandshakeInProgress;
// return PostIoAction::KeepOpen;
default:
handshake_callbacks_->onFailure();
return PostIoAction::Close;
}
}
}
const std::string& SslHandshakerImpl::serialNumberPeerCertificate() const {
if (!cached_serial_number_peer_certificate_.empty()) {
return cached_serial_number_peer_certificate_;
}
bssl::UniquePtr<X509> cert(SSL_get_peer_certificate(ssl()));
if (!cert) {
ASSERT(cached_serial_number_peer_certificate_.empty());
return cached_serial_number_peer_certificate_;
}
cached_serial_number_peer_certificate_ = Utility::getSerialNumberFromCertificate(*cert.get());
return cached_serial_number_peer_certificate_;
}
const std::string& SslHandshakerImpl::issuerPeerCertificate() const {
if (!cached_issuer_peer_certificate_.empty()) {
return cached_issuer_peer_certificate_;
}
bssl::UniquePtr<X509> cert(SSL_get_peer_certificate(ssl()));
if (!cert) {
ASSERT(cached_issuer_peer_certificate_.empty());
return cached_issuer_peer_certificate_;
}
cached_issuer_peer_certificate_ = Utility::getIssuerFromCertificate(*cert);
return cached_issuer_peer_certificate_;
}
const std::string& SslHandshakerImpl::subjectPeerCertificate() const {
if (!cached_subject_peer_certificate_.empty()) {
return cached_subject_peer_certificate_;
}
bssl::UniquePtr<X509> cert(SSL_get_peer_certificate(ssl()));
if (!cert) {
ASSERT(cached_subject_peer_certificate_.empty());
return cached_subject_peer_certificate_;
}
cached_subject_peer_certificate_ = Utility::getSubjectFromCertificate(*cert);
return cached_subject_peer_certificate_;
}
const std::string& SslHandshakerImpl::subjectLocalCertificate() const {
if (!cached_subject_local_certificate_.empty()) {
return cached_subject_local_certificate_;
}
X509* cert = SSL_get_certificate(ssl());
if (!cert) {
ASSERT(cached_subject_local_certificate_.empty());
return cached_subject_local_certificate_;
}
cached_subject_local_certificate_ = Utility::getSubjectFromCertificate(*cert);
return cached_subject_local_certificate_;
}
absl::optional<SystemTime> SslHandshakerImpl::validFromPeerCertificate() const {
bssl::UniquePtr<X509> cert(SSL_get_peer_certificate(ssl()));
if (!cert) {
return absl::nullopt;
}
return Utility::getValidFrom(*cert);
}
absl::optional<SystemTime> SslHandshakerImpl::expirationPeerCertificate() const {
bssl::UniquePtr<X509> cert(SSL_get_peer_certificate(ssl()));
if (!cert) {
return absl::nullopt;
}
return Utility::getExpirationTime(*cert);
}
const std::string& SslHandshakerImpl::sessionId() const {
if (!cached_session_id_.empty()) {
return cached_session_id_;
}
SSL_SESSION* session = SSL_get_session(ssl());
if (session == nullptr) {
ASSERT(cached_session_id_.empty());
return cached_session_id_;
}
unsigned int session_id_length = 0;
const uint8_t* session_id = SSL_SESSION_get_id(session, &session_id_length);
cached_session_id_ = Hex::encode(session_id, session_id_length);
return cached_session_id_;
}
} // namespace Tls
} // namespace TransportSockets
} // namespace Extensions
} // namespace Envoy
| 35.747801 | 100 | 0.750041 |
5b9d03e9935b8a3135870fceae961f323becc7a0 | 20,861 | hpp | C++ | main.hpp | mehmetoguzderin/cpp-2021-vulkan | 07e3eba40e9df66ddd3bce8ea266300dc735a3f0 | [
"CC0-1.0"
] | null | null | null | main.hpp | mehmetoguzderin/cpp-2021-vulkan | 07e3eba40e9df66ddd3bce8ea266300dc735a3f0 | [
"CC0-1.0"
] | null | null | null | main.hpp | mehmetoguzderin/cpp-2021-vulkan | 07e3eba40e9df66ddd3bce8ea266300dc735a3f0 | [
"CC0-1.0"
] | null | null | null | /* Inspired by
* https://github.com/KhronosGroup/Vulkan-Hpp/tree/master/RAII_Samples
* https://github.com/KhronosGroup/Vulkan-Tools/tree/master/cube
* https://github.com/KhronosGroup/Vulkan-Samples/tree/master/samples/extensions/raytracing_basic
* https://github.com/glfw/glfw/blob/master/tests/triangle-vulkan.c
* https://github.com/charles-lunarg/vk-bootstrap/tree/master/example
* https://github.com/ocornut/imgui/blob/master/examples/example_glfw_vulkan/main.cpp
* https://github.com/nvpro-samples/vk_raytracing_tutorial_KHR
*/
#include <algorithm>
#include <cassert>
#include <chrono>
#include <cinttypes>
#include <csignal>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <filesystem>
#include <fstream>
#include <functional>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <limits>
#include <memory>
#include <numeric>
#include <optional>
#include <sstream>
#include <stdexcept>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#define VK_NO_PROTOTYPES
#define VULKAN_HPP_TYPESAFE_CONVERSION
#define VULKAN_HPP_DISPATCH_LOADER_DYNAMIC 1
#include "vulkan/vulkan.hpp"
#include "vulkan/vulkan_raii.hpp"
VULKAN_HPP_DEFAULT_DISPATCH_LOADER_DYNAMIC_STORAGE
#define VMA_VULKAN_VERSION 1002000
#define VMA_STATIC_VULKAN_FUNCTIONS 0
#define VMA_DYNAMIC_VULKAN_FUNCTIONS 0
#define VMA_IMPLEMENTATION
#include "vk_mem_alloc.h"
#define GLFW_INCLUDE_NONE
#include "GLFW/glfw3.h"
#define IMGUI_IMPL_VULKAN_NO_PROTOTYPES
#include "imgui.h"
#include "imgui_impl_glfw.h"
#include "imgui_impl_vulkan.h"
#include "glm/ext.hpp"
#include "glm/glm.hpp"
using namespace glm;
#include "glslang/SPIRV/GlslangToSpv.h"
#include "CLI/App.hpp"
#include "CLI/Config.hpp"
#include "CLI/Formatter.hpp"
#include "main.h"
struct Main {
std::string applicationName{"cpp-2021-vulkan"};
double applicationDuration = 0.0;
uint64_t frameCount = 0;
double frameDuration = 0.0;
UniformConstants uniformConstants{{0, 0, 0}};
std::unique_ptr<vk::raii::Context> context;
std::unique_ptr<vk::raii::Instance> instance;
std::unique_ptr<vk::raii::PhysicalDevice> physicalDevice;
uint32_t queueFamilyIndex;
std::unique_ptr<vk::raii::Device> device;
std::unique_ptr<vk::raii::Queue> queue;
std::unique_ptr<vk::raii::CommandPool> commandPool;
void commandPoolSubmit(const std::function<void(const vk::raii::CommandBuffer& commandBuffer)> encoder,
vk::Fence waitFence = {},
const vk::ArrayProxyNoTemporaries<const vk::PipelineStageFlags>& waitStageMask = {},
const vk::ArrayProxyNoTemporaries<const vk::Semaphore>& waitSemaphores = {}) {
vk::CommandBufferAllocateInfo commandBufferAllocateInfo(**commandPool, vk::CommandBufferLevel::ePrimary, 1);
auto commandBuffer = std::move(vk::raii::CommandBuffers(*device, commandBufferAllocateInfo).front());
commandBuffer.begin(vk::CommandBufferBeginInfo(vk::CommandBufferUsageFlagBits::eOneTimeSubmit));
encoder(commandBuffer);
commandBuffer.end();
vk::SubmitInfo submitInfo(waitSemaphores, waitStageMask, *commandBuffer);
queue->submit(submitInfo, waitFence);
queue->waitIdle();
}
std::unique_ptr<vk::raii::DescriptorPool> descriptorPool;
VmaAllocator allocator;
void allocatorCreate() {
VmaVulkanFunctions allocatorVulkanFunctions{};
#define VMA_VULKAN_FUNCTIONS_RAII_INSTANCE(functionName) allocatorVulkanFunctions.functionName = instance->getDispatcher()->functionName
#define VMA_VULKAN_FUNCTIONS_RAII_DEVICE(functionName) allocatorVulkanFunctions.functionName = device->getDispatcher()->functionName;
#define VMA_VULKAN_KHR_FUNCTIONS_RAII_INSTANCE(functionName) \
if (instance->getDispatcher()->functionName##KHR == nullptr) \
allocatorVulkanFunctions.functionName##KHR = instance->getDispatcher()->functionName; \
else \
allocatorVulkanFunctions.functionName##KHR = instance->getDispatcher()->functionName##KHR;
#define VMA_VULKAN_KHR_FUNCTIONS_RAII_DEVICE(functionName) \
if (device->getDispatcher()->functionName##KHR == nullptr) \
allocatorVulkanFunctions.functionName##KHR = device->getDispatcher()->functionName; \
else \
allocatorVulkanFunctions.functionName##KHR = device->getDispatcher()->functionName##KHR;
VMA_VULKAN_FUNCTIONS_RAII_INSTANCE(vkGetPhysicalDeviceProperties);
VMA_VULKAN_FUNCTIONS_RAII_INSTANCE(vkGetPhysicalDeviceMemoryProperties);
VMA_VULKAN_FUNCTIONS_RAII_DEVICE(vkAllocateMemory);
VMA_VULKAN_FUNCTIONS_RAII_DEVICE(vkFreeMemory);
VMA_VULKAN_FUNCTIONS_RAII_DEVICE(vkMapMemory);
VMA_VULKAN_FUNCTIONS_RAII_DEVICE(vkUnmapMemory);
VMA_VULKAN_FUNCTIONS_RAII_DEVICE(vkFlushMappedMemoryRanges);
VMA_VULKAN_FUNCTIONS_RAII_DEVICE(vkInvalidateMappedMemoryRanges);
VMA_VULKAN_FUNCTIONS_RAII_DEVICE(vkBindBufferMemory);
VMA_VULKAN_FUNCTIONS_RAII_DEVICE(vkBindImageMemory);
VMA_VULKAN_FUNCTIONS_RAII_DEVICE(vkGetBufferMemoryRequirements);
VMA_VULKAN_FUNCTIONS_RAII_DEVICE(vkGetImageMemoryRequirements);
VMA_VULKAN_FUNCTIONS_RAII_DEVICE(vkCreateBuffer);
VMA_VULKAN_FUNCTIONS_RAII_DEVICE(vkDestroyBuffer);
VMA_VULKAN_FUNCTIONS_RAII_DEVICE(vkCreateImage);
VMA_VULKAN_FUNCTIONS_RAII_DEVICE(vkDestroyImage);
VMA_VULKAN_FUNCTIONS_RAII_DEVICE(vkCmdCopyBuffer);
VMA_VULKAN_KHR_FUNCTIONS_RAII_DEVICE(vkGetBufferMemoryRequirements2);
VMA_VULKAN_KHR_FUNCTIONS_RAII_DEVICE(vkGetImageMemoryRequirements2);
VMA_VULKAN_KHR_FUNCTIONS_RAII_DEVICE(vkBindBufferMemory2);
VMA_VULKAN_KHR_FUNCTIONS_RAII_DEVICE(vkBindImageMemory2);
VMA_VULKAN_KHR_FUNCTIONS_RAII_INSTANCE(vkGetPhysicalDeviceMemoryProperties2);
#undef VMA_VULKAN_KHR_FUNCTIONS_RAII_DEVICE
#undef VMA_VULKAN_KHR_FUNCTIONS_RAII_INSTANCE
#undef VMA_VULKAN_FUNCTIONS_RAII_DEVICE
#undef VMA_VULKAN_FUNCTIONS_RAII_INSTANCE
VmaAllocatorCreateInfo allocatorCreateInfo{
.flags = 0,
.physicalDevice = static_cast<VkPhysicalDevice>(**physicalDevice),
.device = static_cast<VkDevice>(**device),
.pVulkanFunctions = &allocatorVulkanFunctions,
.instance = static_cast<VkInstance>(**instance),
.vulkanApiVersion = VK_API_VERSION_1_2,
};
if (vmaCreateAllocator(&allocatorCreateInfo, &allocator) != VK_SUCCESS) {
throw std::runtime_error("vmaCreateAllocator(&allocatorCreateInfo, &allocator) != VK_SUCCESS");
};
}
void allocatorDestroy() { vmaDestroyAllocator(allocator); }
struct Buffer {
vk::Buffer buffer;
vk::DescriptorBufferInfo descriptor;
VmaAllocation allocation;
VmaAllocationInfo info;
};
Buffer bufferCreate(const vk::BufferCreateInfo bufferCreateInfo, const VmaAllocationCreateInfo allocationCreateInfo) {
VkBufferCreateInfo vkBufferCreateInfo = static_cast<VkBufferCreateInfo>(bufferCreateInfo);
VkBuffer vkBuffer;
VmaAllocation vmaAllocation;
VmaAllocationInfo vmaInfo;
if (vmaCreateBuffer(allocator, &vkBufferCreateInfo, &allocationCreateInfo, &vkBuffer, &vmaAllocation, &vmaInfo) != VK_SUCCESS) {
throw std::runtime_error(
"vmaCreateBuffer(allocator, &vkBufferCreateInfo, &allocationCreateInfo, &vkBuffer, &vmaAllocation, &vmaInfo) != VK_SUCCESS");
}
return Buffer{
.buffer = static_cast<vk::Buffer>(vkBuffer),
.descriptor = vk::DescriptorBufferInfo(vkBuffer, 0, bufferCreateInfo.size),
.allocation = vmaAllocation,
.info = vmaInfo,
};
}
template <typename T>
void bufferUse(const Buffer buffer, const std::function<void(T* data)> user) {
void* data;
if (vmaMapMemory(allocator, buffer.allocation, &data) != VK_SUCCESS)
throw std::runtime_error("vmaMapMemory(allocator, buffer.allocation, &data) != VK_SUCCESS");
vmaInvalidateAllocation(allocator, buffer.allocation, 0, buffer.descriptor.range);
user(reinterpret_cast<T*>(data));
vmaFlushAllocation(allocator, buffer.allocation, 0, buffer.descriptor.range);
vmaUnmapMemory(allocator, buffer.allocation);
}
void bufferDestroy(Buffer& buffer) { vmaDestroyBuffer(allocator, buffer.buffer, buffer.allocation); }
struct Image {
vk::Image image;
std::unique_ptr<vk::raii::ImageView> view;
VmaAllocation allocation;
VmaAllocationInfo info;
};
Image imageCreate(const vk::ImageCreateInfo imageCreateInfo,
vk::ImageViewCreateInfo viewCreateInfo,
const VmaAllocationCreateInfo allocationCreateInfo) {
auto vkImageCreateInfo = static_cast<VkImageCreateInfo>(imageCreateInfo);
VkImage vkImage;
VmaAllocation allocation;
VmaAllocationInfo allocationInfo;
if (vmaCreateImage(allocator, &vkImageCreateInfo, &allocationCreateInfo, &vkImage, &allocation, &allocationInfo) != VK_SUCCESS)
throw std::runtime_error(
"vmaCreateImage(allocator, &vkImageCreateInfo, &allocationCreateInfo, &vkImage, &allocation, &allocationInfo) != "
"VK_SUCCESS");
vk::Image image(vkImage);
viewCreateInfo.image = image;
return Image{
.image = static_cast<vk::Image>(vkImage),
.view = std::make_unique<vk::raii::ImageView>(*device, viewCreateInfo),
.allocation = allocation,
.info = allocationInfo,
};
}
void imageDestroy(Image& image) {
image.view.reset();
vmaDestroyImage(allocator, image.image, image.allocation);
}
vk::raii::ShaderModule shaderModuleCreateFromGlslFile(vk::ShaderStageFlagBits shaderStage, std::filesystem::path shaderGlsl) {
std::ifstream shaderModuleMainCompInput(shaderGlsl, std::ios::binary);
if (shaderModuleMainCompInput.fail()) {
throw std::runtime_error("shaderModuleMainCompInput.fail()");
}
std::stringstream shaderModuleMainCompStream;
shaderModuleMainCompStream << shaderModuleMainCompInput.rdbuf();
std::string shaderSource = shaderModuleMainCompStream.str();
std::vector<unsigned int> shaderSpirv;
EShLanguage stage;
switch (shaderStage) {
case vk::ShaderStageFlagBits::eVertex:
stage = EShLangVertex;
break;
case vk::ShaderStageFlagBits::eTessellationControl:
stage = EShLangTessControl;
break;
case vk::ShaderStageFlagBits::eTessellationEvaluation:
stage = EShLangTessEvaluation;
break;
case vk::ShaderStageFlagBits::eGeometry:
stage = EShLangGeometry;
break;
case vk::ShaderStageFlagBits::eFragment:
stage = EShLangFragment;
break;
case vk::ShaderStageFlagBits::eCompute:
stage = EShLangCompute;
break;
case vk::ShaderStageFlagBits::eRaygenKHR:
stage = EShLangRayGen;
break;
case vk::ShaderStageFlagBits::eAnyHitKHR:
stage = EShLangAnyHit;
break;
case vk::ShaderStageFlagBits::eClosestHitKHR:
stage = EShLangClosestHit;
break;
case vk::ShaderStageFlagBits::eMissKHR:
stage = EShLangMiss;
break;
case vk::ShaderStageFlagBits::eIntersectionKHR:
stage = EShLangIntersect;
break;
case vk::ShaderStageFlagBits::eCallableKHR:
stage = EShLangCallable;
break;
default:
throw std::runtime_error("shaderStage");
}
const char* shaderStrings[1]{shaderSource.data()};
glslang::TShader shader(stage);
shader.setStrings(shaderStrings, 1);
EShMessages messages = (EShMessages)(EShMsgSpvRules | EShMsgVulkanRules);
TBuiltInResource buildInResources{.maxLights = 32,
.maxClipPlanes = 6,
.maxTextureUnits = 32,
.maxTextureCoords = 32,
.maxVertexAttribs = 64,
.maxVertexUniformComponents = 4096,
.maxVaryingFloats = 64,
.maxVertexTextureImageUnits = 32,
.maxCombinedTextureImageUnits = 80,
.maxTextureImageUnits = 32,
.maxFragmentUniformComponents = 4096,
.maxDrawBuffers = 32,
.maxVertexUniformVectors = 128,
.maxVaryingVectors = 8,
.maxFragmentUniformVectors = 16,
.maxVertexOutputVectors = 16,
.maxFragmentInputVectors = 15,
.minProgramTexelOffset = -8,
.maxProgramTexelOffset = 7,
.maxClipDistances = 8,
.maxComputeWorkGroupCountX = 65535,
.maxComputeWorkGroupCountY = 65535,
.maxComputeWorkGroupCountZ = 65535,
.maxComputeWorkGroupSizeX = 1024,
.maxComputeWorkGroupSizeY = 1024,
.maxComputeWorkGroupSizeZ = 64,
.maxComputeUniformComponents = 1024,
.maxComputeTextureImageUnits = 16,
.maxComputeImageUniforms = 8,
.maxComputeAtomicCounters = 8,
.maxComputeAtomicCounterBuffers = 1,
.maxVaryingComponents = 60,
.maxVertexOutputComponents = 64,
.maxGeometryInputComponents = 64,
.maxGeometryOutputComponents = 128,
.maxFragmentInputComponents = 128,
.maxImageUnits = 8,
.maxCombinedImageUnitsAndFragmentOutputs = 8,
.maxCombinedShaderOutputResources = 8,
.maxImageSamples = 0,
.maxVertexImageUniforms = 0,
.maxTessControlImageUniforms = 0,
.maxTessEvaluationImageUniforms = 0,
.maxGeometryImageUniforms = 0,
.maxFragmentImageUniforms = 8,
.maxCombinedImageUniforms = 8,
.maxGeometryTextureImageUnits = 16,
.maxGeometryOutputVertices = 256,
.maxGeometryTotalOutputComponents = 1024,
.maxGeometryUniformComponents = 1024,
.maxGeometryVaryingComponents = 64,
.maxTessControlInputComponents = 128,
.maxTessControlOutputComponents = 128,
.maxTessControlTextureImageUnits = 16,
.maxTessControlUniformComponents = 1024,
.maxTessControlTotalOutputComponents = 4096,
.maxTessEvaluationInputComponents = 128,
.maxTessEvaluationOutputComponents = 128,
.maxTessEvaluationTextureImageUnits = 16,
.maxTessEvaluationUniformComponents = 1024,
.maxTessPatchComponents = 120,
.maxPatchVertices = 32,
.maxTessGenLevel = 64,
.maxViewports = 16,
.maxVertexAtomicCounters = 0,
.maxTessControlAtomicCounters = 0,
.maxTessEvaluationAtomicCounters = 0,
.maxGeometryAtomicCounters = 0,
.maxFragmentAtomicCounters = 8,
.maxCombinedAtomicCounters = 8,
.maxAtomicCounterBindings = 1,
.maxVertexAtomicCounterBuffers = 0,
.maxTessControlAtomicCounterBuffers = 0,
.maxTessEvaluationAtomicCounterBuffers = 0,
.maxGeometryAtomicCounterBuffers = 0,
.maxFragmentAtomicCounterBuffers = 1,
.maxCombinedAtomicCounterBuffers = 1,
.maxAtomicCounterBufferSize = 16384,
.maxTransformFeedbackBuffers = 4,
.maxTransformFeedbackInterleavedComponents = 64,
.maxCullDistances = 8,
.maxCombinedClipAndCullDistances = 8,
.maxSamples = 4,
.maxMeshOutputVerticesNV = 256,
.maxMeshOutputPrimitivesNV = 512,
.maxMeshWorkGroupSizeX_NV = 32,
.maxMeshWorkGroupSizeY_NV = 1,
.maxMeshWorkGroupSizeZ_NV = 1,
.maxTaskWorkGroupSizeX_NV = 32,
.maxTaskWorkGroupSizeY_NV = 1,
.maxTaskWorkGroupSizeZ_NV = 1,
.maxMeshViewCountNV = 4,
.maxDualSourceDrawBuffersEXT = 1,
.limits = {
.nonInductiveForLoops = 1,
.whileLoops = 1,
.doWhileLoops = 1,
.generalUniformIndexing = 1,
.generalAttributeMatrixVectorIndexing = 1,
.generalVaryingIndexing = 1,
.generalSamplerIndexing = 1,
.generalVariableIndexing = 1,
.generalConstantMatrixVectorIndexing = 1,
}};
if (!shader.parse(&buildInResources, 100, false, messages)) {
throw std::runtime_error(std::string("!shader.parse(&buildInResources, 100, false, messages): getInfoLog:\n") +
std::string(shader.getInfoLog()) + std::string("\ngetInfoDebugLog:\n") + std::string(shader.getInfoDebugLog()));
}
glslang::TProgram program;
program.addShader(&shader);
if (!program.link(messages)) {
throw std::runtime_error(std::string("!program.link(messages): getInfoLog:\n") + std::string(shader.getInfoLog()) +
std::string("\ngetInfoDebugLog:\n") + std::string(shader.getInfoDebugLog()));
}
glslang::GlslangToSpv(*program.getIntermediate(stage), shaderSpirv);
return vk::raii::ShaderModule(*device, vk::ShaderModuleCreateInfo(vk::ShaderModuleCreateFlags(), shaderSpirv));
}
vk::raii::ShaderModule shaderModuleCreateFromSpirvFile(std::filesystem::path shaderSpirvFile) {
std::ifstream shaderModuleMainCompInput(shaderSpirvFile, std::ios::ate | std::ios::binary);
if (shaderModuleMainCompInput.fail()) {
throw std::runtime_error("shaderModuleMainCompInput.fail()");
}
size_t shaderModuleMainCompInputSize = (size_t)shaderModuleMainCompInput.tellg();
std::vector<char> shaderModuleMainCompSpirv(shaderModuleMainCompInputSize);
shaderModuleMainCompInput.seekg(0);
shaderModuleMainCompInput.read(shaderModuleMainCompSpirv.data(), static_cast<std::streamsize>(shaderModuleMainCompInputSize));
return vk::raii::ShaderModule(*device, vk::ShaderModuleCreateInfo({}, shaderModuleMainCompInputSize,
reinterpret_cast<const uint32_t*>(shaderModuleMainCompSpirv.data())));
}
Main() = delete;
Main(const Main&) = delete;
Main& operator=(const Main&) = delete;
Main(int argc, char** argv);
}; | 52.1525 | 143 | 0.602656 |
5b9f95a8c24e74fea5aa9c4adaa61c6ecec9b7d0 | 329 | cpp | C++ | SelectionAlgorithm.cpp | LegatAbyssWalker/SortingAlgorithms | ab902e8c7fe1489899263bd2a7f22553d3ed0ede | [
"MIT"
] | null | null | null | SelectionAlgorithm.cpp | LegatAbyssWalker/SortingAlgorithms | ab902e8c7fe1489899263bd2a7f22553d3ed0ede | [
"MIT"
] | null | null | null | SelectionAlgorithm.cpp | LegatAbyssWalker/SortingAlgorithms | ab902e8c7fe1489899263bd2a7f22553d3ed0ede | [
"MIT"
] | null | null | null | #include "SelectionAlgorithm.h"
void SelectionAlgorithm::sort() {
// Selective sorts the vector
// Sorts through every single element in the vector
for (int i = 0; i < numbers.size() - 1; i++) {
for (int j = i + 1; j < numbers.size(); j++) {
if (numbers[i] > numbers[j]) { std::swap(numbers[i], numbers[j]); }
}
}
}
| 25.307692 | 70 | 0.610942 |
5ba2f21372bc93827fa628f632175b0545dc71f5 | 2,892 | cpp | C++ | src/Platform/PlatformVideoUtilsCommon.cpp | mushware/adanaxis-core-app | 679ac3e8a122e059bb208e84c73efc19753e87dd | [
"MIT"
] | 9 | 2020-11-02T17:20:40.000Z | 2021-12-25T15:35:36.000Z | src/Platform/PlatformVideoUtilsCommon.cpp | mushware/adanaxis-core-app | 679ac3e8a122e059bb208e84c73efc19753e87dd | [
"MIT"
] | 2 | 2020-06-27T23:14:13.000Z | 2020-11-02T17:28:32.000Z | src/Platform/PlatformVideoUtilsCommon.cpp | mushware/adanaxis-core-app | 679ac3e8a122e059bb208e84c73efc19753e87dd | [
"MIT"
] | 1 | 2021-05-12T23:05:42.000Z | 2021-05-12T23:05:42.000Z | //%Header {
/*****************************************************************************
*
* File: src/Platform/PlatformVideoUtilsCommon.cpp
*
* Copyright: Andy Southgate 2002-2007, 2020
*
* 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.
*
****************************************************************************/
//%Header } 8CRf6CzmJsi8HkHmspv+DQ
/*
* $Id$
* $Log$
*/
#include "PlatformVideoUtils.h"
#include "mushGL.h"
#include "mushMedia.h"
#include "mushPlatform.h"
using namespace Mushware;
using namespace std;
const GLModeDef&
PlatformVideoUtils::DefaultModeDef(void) const
{
U32 modeNum = 0;
for (U32 i=2; i < m_modeDefs.size(); ++i)
{
if (m_modeDefs[i].Width() == 1024 &&
m_modeDefs[i].Height() == 768)
{
modeNum = i;
}
}
return m_modeDefs[modeNum];
}
Mushware::U32
PlatformVideoUtils::ModeDefFind(const GLModeDef& inModeDef) const
{
U32 retVal = 0;
for (U32 i=1; i<m_modeDefs.size(); ++i)
{
if (inModeDef == m_modeDefs[i])
{
retVal = i;
}
}
return retVal;
}
const GLModeDef&
PlatformVideoUtils::PreviousModeDef(const GLModeDef& inModeDef) const
{
U32 modeNum = ModeDefFind(inModeDef);
if (modeNum == 0)
{
modeNum = m_modeDefs.size() - 1;
}
else
{
--modeNum;
}
return m_modeDefs[modeNum];
}
const GLModeDef&
PlatformVideoUtils::NextModeDef(const GLModeDef& inModeDef) const
{
U32 modeNum = ModeDefFind(inModeDef);
++modeNum;
if (modeNum >= m_modeDefs.size())
{
modeNum = 0;
}
return m_modeDefs[modeNum];
}
U32
PlatformVideoUtils::NumModesGet(void) const
{
return m_modeDefs.size();
}
void
PlatformVideoUtils::RenderModeInfo(U32 inNum) const
{
throw MushcoreLogicFail("RenderModeInfo deprecated");
}
| 25.59292 | 78 | 0.640041 |
5ba7f3403253143e82e4771b18af8913d2ccb316 | 305 | cpp | C++ | ClipboardManager/ClipboardData.cpp | ZamanKwinten/ClipboardManager | a0b4bdca4b108cabae8df80cf802224dc0fbab78 | [
"Apache-2.0"
] | null | null | null | ClipboardManager/ClipboardData.cpp | ZamanKwinten/ClipboardManager | a0b4bdca4b108cabae8df80cf802224dc0fbab78 | [
"Apache-2.0"
] | null | null | null | ClipboardManager/ClipboardData.cpp | ZamanKwinten/ClipboardManager | a0b4bdca4b108cabae8df80cf802224dc0fbab78 | [
"Apache-2.0"
] | null | null | null | #include "ClipboardData.h"
ClipboardData::ClipboardData(std::wstring data) {
this->data = data;
}
ClipboardData::~ClipboardData() = default;
std::wstring ClipboardData::getData() {
return this->data;
}
std::wstring ClipboardData::getUIRepresentation() {
return this->data.substr(0, UI_LENGTH);
} | 16.944444 | 51 | 0.727869 |
5baa6188461759460a685d8ba329c33d962bcbe3 | 800 | hpp | C++ | include/threepp/materials/ShadowMaterial.hpp | maidamai0/threepp | 9b50e2c0f2a7bb3ebfd3ffeef61dbefcd54c7071 | [
"MIT"
] | null | null | null | include/threepp/materials/ShadowMaterial.hpp | maidamai0/threepp | 9b50e2c0f2a7bb3ebfd3ffeef61dbefcd54c7071 | [
"MIT"
] | null | null | null | include/threepp/materials/ShadowMaterial.hpp | maidamai0/threepp | 9b50e2c0f2a7bb3ebfd3ffeef61dbefcd54c7071 | [
"MIT"
] | null | null | null | // https://github.com/mrdoob/three.js/blob/r129/src/materials/ShadowMaterial.js
#ifndef THREEPP_SHADOWMATERIAL_HPP
#define THREEPP_SHADOWMATERIAL_HPP
#include "interfaces.hpp"
#include "threepp/materials/Material.hpp"
namespace threepp {
class ShadowMaterial : public virtual Material,
public MaterialWithColor {
public:
[[nodiscard]] std::string type() const override {
return "ShadowMaterial";
}
static std::shared_ptr<ShadowMaterial> create() {
return std::shared_ptr<ShadowMaterial>(new ShadowMaterial());
}
protected:
ShadowMaterial() : MaterialWithColor(0x000000) {
this->transparent = true;
};
};
}// namespace threepp
#endif//THREEPP_SHADOWMATERIAL_HPP
| 22.857143 | 79 | 0.655 |
5baae439c5d71695f8feea2e6d6b6e5df206df47 | 2,020 | cc | C++ | src/topo/Tree.cc | rkowalewski/fmpi | 39a5e9add0d0354c4a2cceeb0a91518bd9f41796 | [
"BSD-3-Clause"
] | null | null | null | src/topo/Tree.cc | rkowalewski/fmpi | 39a5e9add0d0354c4a2cceeb0a91518bd9f41796 | [
"BSD-3-Clause"
] | null | null | null | src/topo/Tree.cc | rkowalewski/fmpi | 39a5e9add0d0354c4a2cceeb0a91518bd9f41796 | [
"BSD-3-Clause"
] | null | null | null | #include <fmpi/topo/Tree.hpp>
#include <fmpi/util/Math.hpp>
#include <fmpi/util/NumericRange.hpp>
// TLX
#include <tlx/math/ffs.hpp>
#include <tlx/math/integer_log2.hpp>
#include <tlx/math/round_to_power_of_two.hpp>
namespace fmpi {
static void knomial_tree_aux(Tree* tree, mpi::Rank me, uint32_t size) {
/* Receive from parent */
auto const vr = (me - tree->root + size) % size;
auto const radix = static_cast<int>(tree->radix);
auto const nr = static_cast<int>(size);
int mask = 0x1;
while (mask < nr) {
if ((vr % (radix * mask)) != 0) {
int parent = vr / (radix * mask) * (radix * mask);
parent = (parent + tree->root) % nr;
tree->src = mpi::Rank{parent};
break;
}
mask *= radix;
}
mask /= radix;
/* Send data to all children */
while (mask > 0) {
for (int r = 1; r < radix; r++) {
int child = vr + mask * r;
if (child < nr) {
child = (child + tree->root) % nr;
tree->destinations.push_back(mpi::Rank{child});
}
}
mask /= radix;
}
}
static void binomial_tree_aux(Tree* tree, mpi::Rank me, uint32_t size) {
// cyclically shifted rank
int32_t const vr = (me - tree->root + size) % size;
auto const nr = static_cast<int>(size);
int d = 1; // distance
int r = 0; // round
if (vr > 0) {
r = tlx::ffs(vr) - 1;
d <<= r;
auto const from = ((vr ^ d) + tree->root) % nr;
tree->src = mpi::Rank{from};
} else {
d = tlx::round_up_to_power_of_two(nr);
}
for (d >>= 1; d > 0; d >>= 1, ++r) {
if (vr + d < nr) {
auto to = (vr + d + tree->root) % nr;
tree->destinations.push_back(mpi::Rank{to});
}
}
}
std::unique_ptr<Tree> knomial(
mpi::Rank me, mpi::Rank root, uint32_t size, uint32_t radix) {
std::unique_ptr<Tree> tree = std::make_unique<Tree>(root, radix);
if (radix == 2) {
binomial_tree_aux(tree.get(), me, size);
} else {
knomial_tree_aux(tree.get(), me, size);
}
return tree;
}
} // namespace fmpi
| 25.56962 | 72 | 0.567327 |
5bacbd5c8ea68a83f1c1dc754f283ab8e189ec98 | 2,429 | hpp | C++ | addons/vehicles_land/configs/vehicles/taki_malitia.hpp | SOCOMD/SOCOMD-MODS-2021 | 834cd5f99831bd456179a1f55f5a91398c29bf57 | [
"MIT"
] | null | null | null | addons/vehicles_land/configs/vehicles/taki_malitia.hpp | SOCOMD/SOCOMD-MODS-2021 | 834cd5f99831bd456179a1f55f5a91398c29bf57 | [
"MIT"
] | null | null | null | addons/vehicles_land/configs/vehicles/taki_malitia.hpp | SOCOMD/SOCOMD-MODS-2021 | 834cd5f99831bd456179a1f55f5a91398c29bf57 | [
"MIT"
] | null | null | null | // mortar man
/*
class CUP_O_2b14_82mm_TK_INS : CUP_2b14_82mm_Base {
class Turrets : Turrets {
class MainTurret : MainTurret {
magazines[] = {
"8Rnd_82mm_Mo_shells",
"8Rnd_82mm_Mo_shells",
"8Rnd_82mm_Mo_shells",
"8Rnd_82mm_Mo_shells",
"8Rnd_82mm_Mo_shells",
"8Rnd_82mm_Mo_shells",
"8Rnd_82mm_Mo_shells",
"8Rnd_82mm_Mo_shells",
"8Rnd_82mm_Mo_Flare_white",
"8Rnd_82mm_Mo_Smoke_white"
};
weapons[] = {"mortar_82mm"};
};
};
};
*/
// m2 BTR milita
class CUP_O_BTR40_MG_TKM : CUP_BTR40_MG_Base {
class Turrets : Turrets {
class MainTurret : MainTurret {
magazines[] = {
"CUP_200Rnd_TE1_Red_Tracer_127x99_M",
"CUP_200Rnd_TE1_Red_Tracer_127x99_M",
"CUP_200Rnd_TE1_Red_Tracer_127x99_M",
"CUP_200Rnd_TE1_Red_Tracer_127x99_M",
"CUP_200Rnd_TE1_Red_Tracer_127x99_M",
"CUP_200Rnd_TE1_Red_Tracer_127x99_M",
"CUP_200Rnd_TE1_Red_Tracer_127x99_M",
"CUP_200Rnd_TE1_Red_Tracer_127x99_M",
"CUP_200Rnd_TE1_Red_Tracer_127x99_M",
"CUP_200Rnd_TE1_Red_Tracer_127x99_M",
"CUP_200Rnd_TE1_Red_Tracer_127x99_M",
"CUP_200Rnd_TE1_Red_Tracer_127x99_M",
"CUP_200Rnd_TE1_Red_Tracer_127x99_M",
"CUP_200Rnd_TE1_Red_Tracer_127x99_M",
"CUP_200Rnd_TE1_Red_Tracer_127x99_M",
"CUP_200Rnd_TE1_Red_Tracer_127x99_M",
"CUP_200Rnd_TE1_Red_Tracer_127x99_M",
"CUP_200Rnd_TE1_Red_Tracer_127x99_M"
};
weapons[] = {"CUP_Vhmg_M2_veh"};
};
};
};
// APC MT-LB-LV
class CUP_O_MTLB_pk_TK_MILITIA : CUP_MTLB_Base {
class Turrets : Turrets {
class MainTurret : MainTurret {
magazines[] = {
"CUP_2000Rnd_TE1_Green_Tracer_762x54_PKT_M",
"CUP_2000Rnd_TE1_Green_Tracer_762x54_PKT_M",
"CUP_2000Rnd_TE1_Green_Tracer_762x54_PKT_M",
"CUP_2000Rnd_TE1_Green_Tracer_762x54_PKT_M"
};
// default: weapons[] = {"CUP_Vhmg_PKT_veh_Noeject"};
weapons[] = {"CUP_Vhmg_PKT_veh"}; // squirty :)
};
};
}; | 36.80303 | 65 | 0.575957 |
5bb3bbef1b8d4a974b85de8a136d083579370cf0 | 1,662 | cpp | C++ | source/Entity.cpp | thejsa/rhythm-run | ab11f97e7552c217bfa4a8392ec96aadf0f9f6b1 | [
"CC-BY-3.0"
] | 1 | 2022-02-01T19:33:21.000Z | 2022-02-01T19:33:21.000Z | source/Entity.cpp | thejsa/rhythm-run | ab11f97e7552c217bfa4a8392ec96aadf0f9f6b1 | [
"CC-BY-3.0"
] | null | null | null | source/Entity.cpp | thejsa/rhythm-run | ab11f97e7552c217bfa4a8392ec96aadf0f9f6b1 | [
"CC-BY-3.0"
] | null | null | null | /*
* Rhythm Run for Nintendo 3DS
* Lauren Kelly, 2020, 2021
*/
#include <3ds.h>
#include <citro2d.h>
#include <stdint.h>
// Most getters/setters are defined in the header file to enhance performance optimisations
#include "Entity.hpp"
Entity::Entity(float a_x, float a_y, C2D_SpriteSheet a_spriteSheet,
size_t a_spriteIndex = 0, float a_centerX = 0.5f, float a_centerY = 0.5f,
float a_scaleX = 1.0f, float a_scaleY = 1.0f, float a_rotation = 0.0f)
: spriteSheet(a_spriteSheet)
, spriteIndex(a_spriteIndex)
{
// Load specified sprite from specified spriteSheet
C2D_SpriteFromSheet(&sprite, spriteSheet, spriteIndex);
// Set position, scale
C2D_SpriteSetCenter(&sprite, a_centerX, a_centerY);
C2D_SpriteSetPos(&sprite, a_x, a_y);
C2D_SpriteSetScale(&sprite, a_scaleX, a_scaleY);
C2D_SpriteSetRotation(&sprite, a_rotation);
};
void Entity::setSprite(size_t a_index, C2D_SpriteSheet a_spriteSheet = NULL)
{
spriteIndex = a_index;
// If the caller passed a (valid) spritesheet param, use it
if (a_spriteSheet != NULL) {
spriteSheet = a_spriteSheet;
}
sprite.image = C2D_SpriteSheetGetImage(spriteSheet, spriteIndex);
}
Rectangle Entity::getRect()
{
float xOffset = getCenterXRaw();
float yOffset = getCenterYRaw();
return Rectangle(
// top left corner
{
sprite.params.pos.x - xOffset,
sprite.params.pos.y - yOffset },
// lower right corner
{
sprite.params.pos.x - xOffset + getWidth(),
sprite.params.pos.y - yOffset + getHeight() });
}
AABB Entity::getAABB()
{
return AABB(getRect());
} | 27.7 | 91 | 0.673887 |
5bb7858ca6daee4250c6e31ec816b851e9d6549e | 8,804 | hpp | C++ | source/timemory/components/skeletons.hpp | jrmadsen/TiMEmory | 8df2055e68da56e2fe57f716ca9b6d27f7eb4407 | [
"MIT"
] | 5 | 2018-01-19T06:18:00.000Z | 2019-07-19T16:08:46.000Z | source/timemory/components/skeletons.hpp | jrmadsen/TiMEmory | 8df2055e68da56e2fe57f716ca9b6d27f7eb4407 | [
"MIT"
] | 1 | 2018-02-09T21:33:08.000Z | 2018-02-11T23:39:47.000Z | source/timemory/components/skeletons.hpp | jrmadsen/TiMEmory | 8df2055e68da56e2fe57f716ca9b6d27f7eb4407 | [
"MIT"
] | 2 | 2019-06-30T00:46:54.000Z | 2019-07-09T18:35:45.000Z | // MIT License
//
// Copyright (c) 2020, The Regents of the University of California,
// through Lawrence Berkeley National Laboratory (subject to receipt of any
// required approvals from the U.S. Dept. of Energy). All rights reserved.
//
// 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.
/** \file components/skeletons.hpp
* \headerfile components/skeletons.hpp "timemory/components/skeletons.hpp"
*
* These provide fake types for heavyweight types w.r.t. templates. In general,
* if a component is templated or contains a lot of code, create a skeleton
* and in \ref timemory/components/types.hpp use an #ifdef to provide the skeleton
* instead. Also, make sure the component file is not directly included.
* If the type uses callbacks, emulate the callbacks here.
*
*/
#pragma once
#include <cstdint>
#include <functional>
#include <iostream>
#include <string>
#include <tuple>
#include <type_traits>
#include <vector>
#include "timemory/ert/types.hpp"
// clang-format off
namespace tim { namespace device { struct cpu; struct gpu; } }
// clang-format on
//======================================================================================//
//
namespace tim
{
namespace component
{
namespace skeleton
{
//--------------------------------------------------------------------------------------//
struct base
{};
//--------------------------------------------------------------------------------------//
template <typename... _Types>
struct cuda
{};
//--------------------------------------------------------------------------------------//
template <typename... _Types>
struct nvtx
{};
//--------------------------------------------------------------------------------------//
template <typename _Kind>
struct cupti_activity
{
using activity_kind_t = _Kind;
using kind_vector_type = std::vector<activity_kind_t>;
using get_initializer_t = std::function<kind_vector_type()>;
static get_initializer_t& get_initializer()
{
static auto _lambda = []() { return kind_vector_type{}; };
static get_initializer_t _instance = _lambda;
return _instance;
}
};
//--------------------------------------------------------------------------------------//
template <typename... _Types>
struct cupti_counters
{
// short-hand for vectors
using string_t = std::string;
using strvec_t = std::vector<string_t>;
/// a tuple of the <devices, events, metrics>
using tuple_type = std::tuple<int, strvec_t, strvec_t>;
/// function for setting all of device, metrics, and events
using get_initializer_t = std::function<tuple_type()>;
static get_initializer_t& get_initializer()
{
static auto _lambda = []() -> tuple_type { return tuple_type{}; };
static get_initializer_t _instance = _lambda;
return _instance;
}
};
//--------------------------------------------------------------------------------------//
template <typename... _Types>
struct gpu_roofline
{
using device_t = device::cpu;
using clock_type = wall_clock;
using ert_data_t = ert::exec_data<clock_type>;
using ert_data_ptr_t = std::shared_ptr<ert_data_t>;
// short-hand for variadic expansion
template <typename _Tp>
using ert_config_type = ert::configuration<device_t, _Tp, clock_type>;
template <typename _Tp>
using ert_counter_type = ert::counter<device_t, _Tp, clock_type>;
template <typename _Tp>
using ert_executor_type = ert::executor<device_t, _Tp, clock_type>;
template <typename _Tp>
using ert_callback_type = ert::callback<ert_executor_type<_Tp>>;
// variadic expansion for ERT types
using ert_config_t = std::tuple<ert_config_type<_Types>...>;
using ert_counter_t = std::tuple<ert_counter_type<_Types>...>;
using ert_executor_t = std::tuple<ert_executor_type<_Types>...>;
using ert_callback_t = std::tuple<ert_callback_type<_Types>...>;
static ert_config_t& get_finalizer()
{
static ert_config_t _instance;
return _instance;
}
};
//--------------------------------------------------------------------------------------//
template <size_t N>
struct papi_array
{
using event_list = std::vector<int>;
using get_initializer_t = std::function<event_list()>;
static get_initializer_t& get_initializer()
{
static get_initializer_t _instance = []() { return event_list{}; };
return _instance;
}
};
//--------------------------------------------------------------------------------------//
template <int... _Types>
struct papi_tuple
{};
//--------------------------------------------------------------------------------------//
template <typename... _Types>
struct cpu_roofline
{
using device_t = device::cpu;
using clock_type = wall_clock;
using ert_data_t = ert::exec_data<clock_type>;
using ert_data_ptr_t = std::shared_ptr<ert_data_t>;
// short-hand for variadic expansion
template <typename _Tp>
using ert_config_type = ert::configuration<device_t, _Tp, clock_type>;
template <typename _Tp>
using ert_counter_type = ert::counter<device_t, _Tp, clock_type>;
template <typename _Tp>
using ert_executor_type = ert::executor<device_t, _Tp, clock_type>;
template <typename _Tp>
using ert_callback_type = ert::callback<ert_executor_type<_Tp>>;
// variadic expansion for ERT types
using ert_config_t = std::tuple<ert_config_type<_Types>...>;
using ert_counter_t = std::tuple<ert_counter_type<_Types>...>;
using ert_executor_t = std::tuple<ert_executor_type<_Types>...>;
using ert_callback_t = std::tuple<ert_callback_type<_Types>...>;
static ert_config_t& get_finalizer()
{
static ert_config_t _instance;
return _instance;
}
};
//--------------------------------------------------------------------------------------//
template <size_t _N, typename... _Types>
struct gotcha
{
using config_t = void;
using get_initializer_t = std::function<config_t()>;
static get_initializer_t& get_initializer()
{
static get_initializer_t _instance = []() {};
return _instance;
}
};
//--------------------------------------------------------------------------------------//
template <typename... _Types>
struct caliper
{};
//--------------------------------------------------------------------------------------//
} // namespace skeleton
//--------------------------------------------------------------------------------------//
template <typename _Tp, typename _Vp>
struct base;
//--------------------------------------------------------------------------------------//
template <typename _Tp>
struct base<_Tp, skeleton::base>
{
static constexpr bool implements_storage_v = false;
using Type = _Tp;
using value_type = void;
using base_type = base<_Tp, skeleton::base>;
};
//--------------------------------------------------------------------------------------//
} // namespace component
} // namespace tim
#if !defined(TIMEMORY_USE_GOTCHA)
# if !defined(TIMEMORY_C_GOTCHA)
# define TIMEMORY_C_GOTCHA(...)
# endif
# if !defined(TIMEMORY_DERIVED_GOTCHA)
# define TIMEMORY_DERIVED_GOTCHA(...)
# endif
# if !defined(TIMEMORY_CXX_GOTCHA)
# define TIMEMORY_CXX_GOTCHA(...)
# endif
# if !defined(TIMEMORY_CXX_MEMFUN_GOTCHA)
# define TIMEMORY_CXX_MEMFUN_GOTCHA(...)
# endif
# if !defined(TIMEMORY_C_GOTCHA_TOOL)
# define TIMEMORY_C_GOTCHA_TOOL(...)
# endif
# if !defined(TIMEMORY_CXX_GOTCHA_TOOL)
# define TIMEMORY_CXX_GOTCHA_TOOL(...)
# endif
#endif
| 32.249084 | 90 | 0.57701 |
5bb8c970b64a85013e95d0db4749b351bf6490b0 | 8,033 | cc | C++ | subprojects/libbeyond-runtime_tflite/src/main.cc | nicesj/beyond | a0ccff33caeb2fda4a6c2071adb5581b5a63d0f3 | [
"Apache-2.0"
] | null | null | null | subprojects/libbeyond-runtime_tflite/src/main.cc | nicesj/beyond | a0ccff33caeb2fda4a6c2071adb5581b5a63d0f3 | [
"Apache-2.0"
] | null | null | null | subprojects/libbeyond-runtime_tflite/src/main.cc | nicesj/beyond | a0ccff33caeb2fda4a6c2071adb5581b5a63d0f3 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2021 Samsung Electronics Co., Ltd 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.
*/
#if !defined(NDEBUG)
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cerrno>
#include <getopt.h>
#include <unistd.h>
#include <beyond/private/beyond_private.h>
#include "runtime.h"
extern "C" {
extern void *_main(int argc, char *argv[]);
static void help(void)
{
fprintf(stderr,
"Help message\n"
"-----------------------------------------\n"
"-h help\n"
"-i filename input filename\n"
"-t input_tensor type input filename\n"
"-m filename model filename\n"
"\n");
}
// ApplicationContext
int main(void)
{
const option opts[] = {
{
.name = "help",
.has_arg = 0,
.flag = nullptr,
.val = 'h',
},
{
.name = "model",
.has_arg = 1,
.flag = nullptr,
.val = 'm',
},
{
.name = "input",
.has_arg = 1,
.flag = nullptr,
.val = 'i',
},
{
.name = "type",
.has_arg = 1,
.flag = nullptr,
.val = 't',
},
{
.name = "size", // Count of input tensor
.has_arg = 1,
.flag = nullptr,
.val = 's',
},
// TODO:
// Add more options
};
static const char *optstr = "-:hm:i:t:s:";
char *model = nullptr;
char *type = nullptr;
int argc = 0;
char **argv = nullptr;
beyond_tensor *input = nullptr;
beyond_tensor *output = nullptr;
FILE *fp = fopen("input.txt", "r");
if (fp != nullptr) {
if (fscanf(fp, "%d\n", &argc) == 1 && argc > 0) {
if (argc < 0 || static_cast<unsigned int>(argc) > strlen(optstr)) {
fprintf(stderr, "Too many arguments: %d\n", argc);
_exit(EINVAL);
}
argv = static_cast<char **>(calloc(argc, sizeof(char *)));
if (argv == nullptr) {
ErrPrintCode(errno, "calloc");
_exit(ENOMEM);
}
for (int i = 0; i < argc; i++) {
char buffer[1024];
if (fscanf(fp, "%1023s\n", buffer) == 1) {
argv[i] = strdup(buffer);
} else {
ErrPrint("Unable to parse the argument buffer");
argv[i] = nullptr;
}
}
}
fclose(fp);
fp = nullptr;
}
int input_size = 0;
int input_idx = 0;
if (argc > 0 && argv != nullptr) {
int c;
int idx;
while ((c = getopt_long(argc, argv, optstr, opts, &idx)) != -1) {
switch (c) {
case 'h':
help();
_exit(0);
break;
case 'm':
model = strdup(optarg);
break;
case 's':
if (sscanf(optarg, "%d", &input_size) != 1) {
fprintf(stderr, "Invalid input size parameter\n");
_exit(EINVAL);
}
//Temporary max size
if (1024 < input_size || input_size < 0) {
fprintf(stderr, "Invalid input size(%d) parameter\n", input_size);
_exit(EINVAL);
}
input = static_cast<beyond_tensor *>(calloc(input_size, sizeof(beyond_tensor)));
if (input == nullptr) {
int ret = errno;
ErrPrintCode(errno, "calloc");
_exit(ret);
}
break;
case 'i':
if (input_idx == input_size) {
fprintf(stderr, "Invalid input tensor, input_size must be given first (%d, %d)\n", input_idx, input_size);
_exit(EINVAL);
}
if (optarg != nullptr) {
FILE *fp = fopen(optarg, "r");
if (fp != nullptr) {
fseek(fp, 0L, SEEK_END);
input[input_idx].size = ftell(fp);
fseek(fp, 0L, SEEK_SET);
input[input_idx].data = malloc(input[input_idx].size);
if (input[input_idx].data == nullptr) {
ErrPrintCode(errno, "malloc");
} else {
if (fread(input[input_idx].data, input[input_idx].size, 1, fp) != 1) {
ErrPrintCode(errno, "fread");
_exit(EIO);
}
}
if (fclose(fp) < 0) {
ErrPrintCode(errno, "Unable to close the file pointer");
}
}
}
input_idx++;
break;
case 't':
if (nullptr == input) {
fprintf(stderr, "Invalid input(NULL)");
break;
}
if (strcmp(optarg, "int8") == 0) {
input[input_idx].type = BEYOND_TENSOR_TYPE_INT8;
} else if (strcmp(optarg, "int16") == 0) {
input[input_idx].type = BEYOND_TENSOR_TYPE_INT16;
} else if (strcmp(optarg, "int32") == 0) {
input[input_idx].type = BEYOND_TENSOR_TYPE_INT32;
} else if (strcmp(optarg, "uint8") == 0) {
input[input_idx].type = BEYOND_TENSOR_TYPE_UINT8;
} else if (strcmp(optarg, "uint16") == 0) {
input[input_idx].type = BEYOND_TENSOR_TYPE_UINT16;
} else if (strcmp(optarg, "uint32") == 0) {
input[input_idx].type = BEYOND_TENSOR_TYPE_UINT32;
} else if (strcmp(optarg, "float16") == 0) {
input[input_idx].type = BEYOND_TENSOR_TYPE_FLOAT16;
} else if (strcmp(optarg, "float32") == 0) {
input[input_idx].type = BEYOND_TENSOR_TYPE_FLOAT32;
}
break;
default:
break;
}
}
}
if (model == nullptr || input == nullptr || input_idx < input_size) {
fprintf(stderr, "Invalid arguments (%d,%d)\n", input_idx, input_size);
help();
_exit(1);
}
optind = 0;
opterr = 0;
Runtime *runtime = reinterpret_cast<Runtime *>(_main(argc, argv));
if (runtime == nullptr) {
_exit(EFAULT);
}
runtime->LoadModel(model);
runtime->Prepare();
runtime->Invoke(input, input_size);
int output_size;
runtime->GetOutput(output, output_size);
//
// Runtime has no main loop.
// It runs once
//
// TODO: manipulate the output tensor
//
runtime->FreeTensor(output, output_size);
runtime->Destroy();
free(type);
free(model);
for (int i = 0; i < input_size; i++) {
free(input[i].data);
}
free(input);
if (argc > 0) {
for (int i = 0; i < argc; i++) {
free(argv[i]);
argv[i] = nullptr;
}
free(argv);
argv = nullptr;
argc = 0;
}
_exit(0);
}
} // extern "C"
#endif // NDEBUG
| 30.777778 | 126 | 0.448898 |
5bbd11e7b929fb4ebc121c86d07aa92388bede86 | 1,954 | cpp | C++ | spleeter/inference_engine/inference_engine_strategy.cpp | jinay1991/spleeter | ae21059a369b8d13da7b5581fc8b7b5cb5ac9ec8 | [
"MIT"
] | 25 | 2020-05-16T16:08:30.000Z | 2022-03-09T04:58:16.000Z | spleeter/inference_engine/inference_engine_strategy.cpp | jinay1991/spleeter | ae21059a369b8d13da7b5581fc8b7b5cb5ac9ec8 | [
"MIT"
] | 2 | 2020-08-15T17:28:46.000Z | 2021-09-28T16:14:14.000Z | spleeter/inference_engine/inference_engine_strategy.cpp | jinay1991/spleeter | ae21059a369b8d13da7b5581fc8b7b5cb5ac9ec8 | [
"MIT"
] | 3 | 2021-07-29T08:05:03.000Z | 2022-03-22T14:28:05.000Z | ///
/// @file
/// @copyright Copyright (c) 2020. MIT License
///
#include "spleeter/inference_engine/inference_engine_strategy.h"
#include "spleeter/inference_engine/null_inference_engine.h"
#include "spleeter/inference_engine/tf_inference_engine.h"
#include "spleeter/inference_engine/tflite_inference_engine.h"
#include "spleeter/logging/logging.h"
namespace spleeter
{
InferenceEngineStrategy::InferenceEngineStrategy() : inference_engine_type_{InferenceEngineType::kInvalid} {}
void InferenceEngineStrategy::SelectInferenceEngine(const InferenceEngineType& inference_engine_type,
const InferenceEngineParameters& inference_engine_parameters)
{
inference_engine_type_ = inference_engine_type;
switch (inference_engine_type)
{
case InferenceEngineType::kTensorFlow:
{
inference_engine_ = std::make_unique<TFInferenceEngine>(inference_engine_parameters);
break;
}
case InferenceEngineType::kTensorFlowLite:
{
inference_engine_ = std::make_unique<TFLiteInferenceEngine>(inference_engine_parameters);
break;
}
case InferenceEngineType::kInvalid:
default:
{
inference_engine_ = std::make_unique<NullInferenceEngine>(inference_engine_parameters);
LOG(ERROR) << "Received " << inference_engine_type;
break;
}
}
}
void InferenceEngineStrategy::Init()
{
inference_engine_->Init();
}
void InferenceEngineStrategy::Execute(const Waveform& waveform)
{
inference_engine_->Execute(waveform);
}
void InferenceEngineStrategy::Shutdown()
{
inference_engine_->Shutdown();
}
Waveforms InferenceEngineStrategy::GetResults() const
{
return inference_engine_->GetResults();
}
InferenceEngineType InferenceEngineStrategy::GetInferenceEngineType() const
{
return inference_engine_type_;
}
} // namespace spleeter
| 28.735294 | 113 | 0.716991 |
5bc0536983148928798ae84baf6880e890bcda6c | 423 | hpp | C++ | include/geometry/segment.hpp | not522/Competitive-Programming | be4a7d25caf5acbb70783b12899474a56c34dedb | [
"Unlicense"
] | 7 | 2018-04-14T14:55:51.000Z | 2022-01-31T10:49:49.000Z | include/geometry/segment.hpp | not522/Competitive-Programming | be4a7d25caf5acbb70783b12899474a56c34dedb | [
"Unlicense"
] | 5 | 2018-04-14T14:28:49.000Z | 2019-05-11T02:22:10.000Z | include/geometry/segment.hpp | not522/Competitive-Programming | be4a7d25caf5acbb70783b12899474a56c34dedb | [
"Unlicense"
] | null | null | null | #pragma once
#include "geometry/line.hpp"
class Segment : public Line, public Ordered<Segment> {
public:
Segment() {}
Segment(const Point &a, const Point &b) : Line(a, b) {}
Segment(Input &in) : Line(in) {}
bool operator<(const Segment &segment) const {
return a == segment.a ? b < segment.b : a < segment.a;
}
Real area() const {
return (this->a.x * this->b.y - this->a.y * this->b.x) / 2;
}
};
| 21.15 | 63 | 0.602837 |
5bc0960b3dc3a2099c06255085cb44c962ad84b4 | 1,447 | cpp | C++ | ex02/Base.cpp | Igors78/cpp06 | d50929edcaef218d68ab04b41d4a6693032f83bb | [
"Unlicense"
] | 1 | 2021-11-28T14:16:09.000Z | 2021-11-28T14:16:09.000Z | ex02/Base.cpp | Igors78/cpp06 | d50929edcaef218d68ab04b41d4a6693032f83bb | [
"Unlicense"
] | null | null | null | ex02/Base.cpp | Igors78/cpp06 | d50929edcaef218d68ab04b41d4a6693032f83bb | [
"Unlicense"
] | null | null | null | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* Base.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ioleinik <ioleinik@student.42wolfsburg.de> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/11/28 15:47:22 by ioleinik #+# #+# */
/* Updated: 2021/11/28 15:47:43 by ioleinik ### ########.fr */
/* */
/* ************************************************************************** */
#include "Base.hpp"
/*
** ------------------------------- CONSTRUCTOR --------------------------------
*/
/*
** -------------------------------- DESTRUCTOR --------------------------------
*/
Base::~Base()
{
}
/*
** --------------------------------- OVERLOAD ---------------------------------
*/
/*
** --------------------------------- METHODS ----------------------------------
*/
/*
** --------------------------------- ACCESSOR ---------------------------------
*/
/* ************************************************************************** */ | 37.102564 | 80 | 0.12094 |
5bc41a641535e7d8eed059d8775775b59ce17c70 | 3,943 | cpp | C++ | src/xray/render/engine/sources/effect_deffer_aref.cpp | ixray-team/ixray-2.0 | 85c3a544175842323fc82f42efd96c66f0fc5abb | [
"Linux-OpenIB"
] | 3 | 2021-10-30T09:36:14.000Z | 2022-03-26T17:00:06.000Z | src/xray/render/engine/sources/effect_deffer_aref.cpp | acidicMercury8/ixray-2.0 | 85c3a544175842323fc82f42efd96c66f0fc5abb | [
"Linux-OpenIB"
] | null | null | null | src/xray/render/engine/sources/effect_deffer_aref.cpp | acidicMercury8/ixray-2.0 | 85c3a544175842323fc82f42efd96c66f0fc5abb | [
"Linux-OpenIB"
] | 1 | 2022-03-26T17:00:08.000Z | 2022-03-26T17:00:08.000Z | ////////////////////////////////////////////////////////////////////////////
// Created : 20.02.2009
// Author : Mykhailo Parfeniuk
// Copyright ( C) GSC Game World - 2009
////////////////////////////////////////////////////////////////////////////
#include "pch.h"
#include <xray/render/engine/effect_deffer_aref.h>
#include <xray/render/core/effect_compiler.h>
namespace xray {
namespace render_dx10 {
effect_deffer_aref::effect_deffer_aref( bool is_lmapped):
effect_deffer_base( false, false, false)
{
m_blend = FALSE;
m_desc.m_version = 1;
m_is_lmapped = is_lmapped;
}
void effect_deffer_aref::compile_blended( effect_compiler& compiler, const effect_compilation_options& options)
{
shader_defines_list defines;
make_defines( defines);
if ( m_is_lmapped)
{
compiler.begin_pass( "lmapE", "lmapE", defines)
//.set_depth( TRUE)
.set_alpha_blend ( true, D3D_BLEND_SRC_ALPHA, D3D_BLEND_INV_SRC_ALPHA)
.bind_constant ( "alpha_ref", &m_aref_val)
.set_texture ( "t_base", options.tex_list[0])
.def_sampler ( "s_lmap")
.set_texture ( "t_lmap", options.tex_list[1])
.def_sampler ( "s_hemi", D3D_TEXTURE_ADDRESS_CLAMP, D3D_FILTER_MIN_MAG_LINEAR_MIP_POINT)
.set_texture ( "t_hemi", options.tex_list[2])
.def_sampler ( "s_env", D3D_TEXTURE_ADDRESS_CLAMP)
.set_texture ( "t_env", r2_t_envs0)
.end_pass();
//C.r_Pass ( "lmapE","lmapE",TRUE,TRUE,FALSE,TRUE,D3D_BLEND_SRC_ALPHA, D3D_BLEND_INV_SRC_ALPHA, TRUE, oAREF.value);
//C.r_Sampler ( "s_base", C.L_textures[0] );
//C.r_Sampler ( "s_lmap", C.L_textures[1] );
//C.r_Sampler_clf ( "s_hemi", *C.L_textures[2]);
//C.r_Sampler ( "s_env", r2_T_envs0, false,D3DTADDRESS_CLAMP);
//C.r_End ();
}
else
{
compiler.begin_pass( "vert", "vert", defines)
.set_alpha_blend( true, D3D_BLEND_SRC_ALPHA, D3D_BLEND_INV_SRC_ALPHA)
.bind_constant ( "alpha_ref", &m_aref_val)
.set_texture ( "t_base", options.tex_list[0])
.end_pass();
//C.r_Pass ( "vert", "vert", TRUE,TRUE,FALSE,TRUE,D3D_BLEND_SRC_ALPHA, D3D_BLEND_INV_SRC_ALPHA, TRUE, oAREF.value);
//C.r_Sampler ( "s_base", C.L_textures[0] );
//C.r_End ();
}
}
void effect_deffer_aref::compile( effect_compiler& compiler, const effect_compilation_options& options)
{
if ( m_blend)
{
compiler.begin_technique( /*SE_R2_NORMAL_HQ*/);
compile_blended( compiler, options);
compiler.end_technique();
compiler.begin_technique( /*SE_R2_NORMAL_LQ*/);
compile_blended( compiler, options);
compiler.end_technique();
}
else
{
shader_defines_list defines;
make_defines( defines);
//C.SetParams ( 1,false); //.
// codepath is the same, only the shaders differ
// ***only pixel shaders differ***
compiler.begin_technique( /*SE_R2_NORMAL_HQ*/);
uber_deffer( compiler, "base", "base", true, true, options);
compiler.end_technique();
compiler.begin_technique( /*SE_R2_NORMAL_LQ*/);
uber_deffer( compiler, "base", "base", false, true, options);
compiler.end_technique();
compiler.begin_technique( /*SE_R2_SHADOW*/);
//if ( RImplementation.o.HW_smap)
// compiler.begin_pass( "shadow_direct_base_aref","shadow_direct_base_aref");
//else
compiler.begin_pass ( "shadow_direct_base_aref", "shadow_direct_base_aref", defines)
.set_depth ( true, true)
.set_alpha_blend( FALSE)
.bind_constant ( "alpha_ref", &m_aref_val220)
.set_texture ( "t_base", options.tex_list[0])
.end_pass()
.end_technique();
}
}
void effect_deffer_aref::load( memory::reader& mem_reader)
{
effect::load( mem_reader);
if ( 1==m_desc.m_version)
{
xrP_Integer aref_val;
xrPREAD_PROP( mem_reader, xrPID_INTEGER, aref_val);
//m_aref_val = aref_val.value;
xrP_BOOL blend;
xrPREAD_PROP( mem_reader, xrPID_BOOL, blend);
m_blend = blend.value != 0;
}
}
} // namespace render
} // namespace xray
| 32.319672 | 120 | 0.660918 |
5bc45115070be632ff4387809bd1a9b96c905e7b | 1,281 | hpp | C++ | src/third.hpp | hobby-dev/sirius | 8bfdef75f225ba50bde16b3f75c8b6ac09cebb86 | [
"MIT"
] | null | null | null | src/third.hpp | hobby-dev/sirius | 8bfdef75f225ba50bde16b3f75c8b6ac09cebb86 | [
"MIT"
] | null | null | null | src/third.hpp | hobby-dev/sirius | 8bfdef75f225ba50bde16b3f75c8b6ac09cebb86 | [
"MIT"
] | null | null | null | #pragma once
#include <string>
#include <vector>
namespace sirius {
// Problem 3:
// Implement Serialize and Deserialize methods of List class. Serialize into binary
// file. Note: all relationships between elements of the list must be preserved.
// Definitions of struct ListNode and class List are provided:
//struct ListNode {
// ListNode *prev;
// ListNode *next;
// ListNode *rand; // points to a random element of the list or is NULL
// std::string data;
//};
//
//class List {
//
// public:
// void Serialize(FILE *file);
// void Deserialize(FILE *file);
//
// private:
// ListNode *head;
// ListNode *tail;
// int count;
//};
struct ListNode {
ListNode *prev{nullptr};
ListNode *next{nullptr};
ListNode *rand{nullptr}; // points to a random element of the list or is NULL
std::string data{};
};
class List {
public:
~List();
void PushBack(std::string &&value);
ListNode *accessNode(uint64_t index);
uint64_t Size() { return count; }
/**
* @param file must be opened with fopen(path, "wb"))
*/
void Serialize(FILE *file);
/**
* @param file must be opened with fopen(path, "rb"))
*/
void Deserialize(FILE *file);
private:
void cleanup();
ListNode *head{nullptr};
ListNode *tail{nullptr};
uint64_t count{0};
};
} | 20.66129 | 83 | 0.662763 |
5bc5e1a9b900718c300882d1eed2067f504bb910 | 4,287 | cpp | C++ | vehicle/OVMS.V3/components/can/src/candump_crtd.cpp | goev/Open-Vehicle-Monitoring-System-3 | f2efd1898ec1df19eb730c1eda9a1999a00b36b4 | [
"MIT"
] | null | null | null | vehicle/OVMS.V3/components/can/src/candump_crtd.cpp | goev/Open-Vehicle-Monitoring-System-3 | f2efd1898ec1df19eb730c1eda9a1999a00b36b4 | [
"MIT"
] | null | null | null | vehicle/OVMS.V3/components/can/src/candump_crtd.cpp | goev/Open-Vehicle-Monitoring-System-3 | f2efd1898ec1df19eb730c1eda9a1999a00b36b4 | [
"MIT"
] | null | null | null | /*
; Project: Open Vehicle Monitor System
; Module: CAN dump framework
; Date: 18th January 2018
;
; (C) 2018 Mark Webb-Johnson
;
; 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 "ovms_log.h"
//static const char *TAG = "candump-crtd";
#include <errno.h>
#include "pcp.h"
#include "candump_crtd.h"
candump_crtd::candump_crtd()
{
m_bufpos = 0;
}
candump_crtd::~candump_crtd()
{
}
const char* candump_crtd::formatname()
{
return "crtd";
}
std::string candump_crtd::get(struct timeval *time, CAN_frame_t *frame)
{
m_bufpos = 0;
char busnumber[2]; busnumber[0]=0; busnumber[1]=0;
if (frame->origin)
{
const char* name = frame->origin->GetName();
if (*name != 0)
{
while (name[1] != 0) name++;
busnumber[0] = *name;
}
}
sprintf(m_buf,"%ld.%06ld %sR%s %0*X",
time->tv_sec, time->tv_usec,
busnumber,
(frame->FIR.B.FF == CAN_frame_std) ? "11":"29",
(frame->FIR.B.FF == CAN_frame_std) ? 3 : 8,
frame->MsgID);
for (int k=0; k<frame->FIR.B.DLC; k++)
sprintf(m_buf+strlen(m_buf)," %02x", frame->data.u8[k]);
strcat(m_buf,"\n");
return std::string(m_buf);
}
std::string candump_crtd::getheader(struct timeval *time)
{
m_bufpos = 0;
sprintf(m_buf,"%ld.%06ld CXX OVMS\n",
time->tv_sec, time->tv_usec);
return std::string(m_buf);
}
size_t candump_crtd::put(CAN_frame_t *frame, uint8_t *buffer, size_t len)
{
size_t k;
char *b = (char*)buffer;
memset(frame,0,sizeof(CAN_frame_t));
for (k=0;k<len;k++)
{
if ((b[k]=='\r')||(b[k]=='\n'))
{
//ESP_EARLY_LOGI(TAG,"CRTD GOT CR/LF %02x",b[k]);
if (m_bufpos == 0)
continue;
else
break;
}
m_buf[m_bufpos] = b[k];
if (m_bufpos < CANDUMP_CRTD_MAXLEN) m_bufpos++;
}
//ESP_EARLY_LOGI(TAG,"CRTD PUT bufpos=%d inlen=%d now=%d",m_bufpos,len,k);
if (k>=len) return len;
// OK. We have a buffer ready for decoding...
// buffer[Start .. k-1]
m_buf[m_bufpos] = 0;
//ESP_EARLY_LOGI(TAG,"CRTD message buffer is %d bytes",m_bufpos);
m_bufpos = 0; // Prepare for next message
b = m_buf;
// We look for something like
// 1524311386.811100 1R11 100 01 02 03
if (!isdigit(b[0])) return k+1;
for (;((*b != 0)&&(*b != ' '));b++) {}
if (*b == 0) return k+1;
b++;
char bus = '1';
if (isdigit(*b))
{
bus = *b;
b++;
}
if ((b[0]=='R')&&(b[1]=='1')&&(b[2]=='1'))
{
// R11 incoming CAN frame
frame->FIR.B.FF = CAN_frame_std;
}
else if ((b[0]=='R')&&(b[1]=='2')&&(b[2]=='9'))
{
// R29 incoming CAN frame
frame->FIR.B.FF = CAN_frame_ext;
}
else
return k+1;
if (b[3] != ' ') return k+1;
b += 4;
char *p;
errno = 0;
frame->MsgID = (uint32_t)strtol(b,&p,16);
if ((frame->MsgID == 0)&&(errno != 0)) return k+1;
b = p;
for (int k=0;k<8;k++)
{
if (*b==0) break;
b++;
errno = 0;
long d = strtol(b,&p,16);
if ((d==0)&&(errno != 0)) break;
frame->data.u8[k] = (uint8_t)d;
frame->FIR.B.DLC++;
b = p;
}
char cbus[5] = "can";
cbus[3] = bus;
cbus[4] = 0;
frame->origin = (canbus*)MyPcpApp.FindDeviceByName(cbus);
//ESP_EARLY_LOGI(TAG,"CRTD done return=%d",k+1);
return k+1;
}
| 24.924419 | 79 | 0.605318 |
5bcacfe1a4fe9b010dae211b326b9cca39bbf3d2 | 10,990 | cpp | C++ | src/demeter-win/vs/simple/work.cpp | pcdeadeasy/NetworkDirect | 4c2ee56604c3493f87313dbb7bc8b1630dceaf39 | [
"MIT"
] | 1 | 2019-06-18T23:31:10.000Z | 2019-06-18T23:31:10.000Z | src/demeter-win/vs/simple/work.cpp | pcdeadeasy/NetworkDirect | 4c2ee56604c3493f87313dbb7bc8b1630dceaf39 | [
"MIT"
] | null | null | null | src/demeter-win/vs/simple/work.cpp | pcdeadeasy/NetworkDirect | 4c2ee56604c3493f87313dbb7bc8b1630dceaf39 | [
"MIT"
] | 1 | 2019-06-18T21:43:29.000Z | 2019-06-18T21:43:29.000Z | #include <libraries/logger/Logger.h>
#include <libraries/Winshim/Winshim.h>
#include <libraries/ndutil/ndutil.h>
#include <libraries/ndutil/ndtestutil.h>
#include "params.h"
#include "ndscope.h"
#include "errors.h"
#include "work.h"
static void stage8(
params_t* const params,
work_t work,
const struct sockaddr* pAddress,
IND2Adapter* const pAdapter,
HANDLE const hOverlappedFile,
IND2MemoryRegion* const pMemoryRegion,
ND2_ADAPTER_INFO const* const pInfo,
IND2CompletionQueue* const pSendCompletionQueue,
IND2CompletionQueue* const pRecvCompletionQueue,
IND2QueuePair* const pQueuePair
)
{
LOG_ENTER();
IND2Connector* pConnector = 0;
HRESULT hr =
pAdapter->CreateConnector(IID_IND2Connector, hOverlappedFile, (void**)&pConnector);
LOG("IND2Adapter::CreateConnector -> %08X", hr);
if (ND_SUCCESS != hr)
throw EX_CREATE_CONNECTOR;
try
{
(*work)(
params,
pAddress,
pAdapter,
hOverlappedFile,
pMemoryRegion,
pInfo,
pSendCompletionQueue,
pRecvCompletionQueue,
pQueuePair,
pConnector
);
}
catch (...)
{
ULONG ul = pConnector->Release();
LOG("IND2QueuePair::Release -> %u", ul);
throw;
}
ULONG ul = pConnector->Release();
LOG("IND2Connector::Release -> %u", ul);
LOG_VOID_RETURN();
}
static void stage7(
params_t* const params,
work_t work,
const struct sockaddr* pAddress,
IND2Adapter* const pAdapter,
HANDLE const hOverlappedFile,
IND2MemoryRegion* const pMemoryRegion,
ND2_ADAPTER_INFO const* const pInfo,
IND2CompletionQueue* const pSendCompletionQueue,
IND2CompletionQueue* const pRecvCompletionQueue
)
{
LOG_ENTER();
static void* const context = (void*)"CreateQueuePair context";
ULONG const recvQueueDepth = 3;
ULONG const sendQueueDepth = 3;
ULONG const maxRecvRequestSge = 3;
ULONG const maxSendRequestSge = 3;
ULONG const inlineDataSize = pInfo->MaxInlineDataSize;
IND2QueuePair* pQueuePair = 0;
HRESULT const hr =
pAdapter->CreateQueuePair(
IID_IND2QueuePair,
pSendCompletionQueue,
pRecvCompletionQueue,
context,
recvQueueDepth,
sendQueueDepth,
maxRecvRequestSge,
maxSendRequestSge,
inlineDataSize,
(void**)&pQueuePair
);
LOG("IND2Adapter::CreateQueuePair -> %08X", hr);
if (ND_SUCCESS != hr)
throw EX_CREATE_QUEUE_PAIR;
try
{
stage8(
params,
work,
pAddress,
pAdapter,
hOverlappedFile,
pMemoryRegion,
pInfo,
pSendCompletionQueue,
pRecvCompletionQueue,
pQueuePair
);
}
catch (...)
{
ULONG ul = pQueuePair->Release();
LOG("IND2QueuePair::Release -> %u", ul);
throw;
}
ULONG ul = pQueuePair->Release();
LOG("IND2QueuePair::Release -> %u", ul);
LOG_VOID_RETURN();
}
static void stage6(
params_t* const params,
work_t work,
const struct sockaddr* pAddress,
IND2Adapter* const pAdapter,
HANDLE const hOverlappedFile,
IND2MemoryRegion* const pMemoryRegion,
ND2_ADAPTER_INFO const* const pInfo,
IND2CompletionQueue* const pSendCompletionQueue
)
{
LOG_ENTER();
IND2CompletionQueue* pRecvCompletionQueue = 0;
HRESULT hr =
pAdapter->CreateCompletionQueue(
IID_IND2CompletionQueue,
hOverlappedFile,
pInfo->MaxCompletionQueueDepth,
0,
0,
(void**)(&pRecvCompletionQueue)
);
LOG("IND2Adapter::CreateCompletionQueue -> %08X", hr);
if (ND_SUCCESS != hr)
throw EX_CREATE_COMPLETION_QUEUE;
try
{
stage7(
params,
work,
pAddress,
pAdapter,
hOverlappedFile,
pMemoryRegion,
pInfo,
pSendCompletionQueue,
pRecvCompletionQueue
);
}
catch (...)
{
ULONG ul = pRecvCompletionQueue->Release();
LOG("IND2CompletionQueue::Release -> %u", ul);
throw;
}
ULONG ul = pRecvCompletionQueue->Release();
LOG("IND2CompletionQueue::Release -> %u", ul);
LOG_VOID_RETURN();
}
static void stage5(
params_t* const params,
work_t work,
const struct sockaddr* pAddress,
IND2Adapter* const pAdapter,
HANDLE const hOverlappedFile,
IND2MemoryRegion* const pMemoryRegion,
ND2_ADAPTER_INFO const* const pInfo
)
{
LOG_ENTER();
IND2CompletionQueue* pSendCompletionQueue = 0;
HRESULT hr =
pAdapter->CreateCompletionQueue(
IID_IND2CompletionQueue,
hOverlappedFile,
pInfo->MaxCompletionQueueDepth,
0,
0,
(void**)(&pSendCompletionQueue)
);
LOG("IND2Adapter::CreateCompletionQueue -> %08X", hr);
if (ND_SUCCESS != hr)
throw EX_CREATE_COMPLETION_QUEUE;
try
{
stage6(
params,
work,
pAddress,
pAdapter,
hOverlappedFile,
pMemoryRegion,
pInfo,
pSendCompletionQueue
);
}
catch (...)
{
ULONG ul = pSendCompletionQueue->Release();
LOG("IND2CompletionQueue::Release -> %u", ul);
throw;
}
ULONG ul = pSendCompletionQueue->Release();
LOG("IND2CompletionQueue::Release -> %u", ul);
LOG_VOID_RETURN();
}
static void stage4(
params_t* const params,
work_t work,
const struct sockaddr* pAddress,
IND2Adapter* const pAdapter,
HANDLE const hOverlappedFile,
IND2MemoryRegion* const pMemoryRegion
)
{
LOG_ENTER();
LOG("pMemoryRegion: %p", pMemoryRegion);
ND2_ADAPTER_INFO info = { 0 };
info.InfoVersion = ND_VERSION_2;
ULONG cbInfo = sizeof(info);
HRESULT hr =
pAdapter->Query(
&info,
&cbInfo
);
LOG("IND2Adapter::Query -> %08X", hr);
if (ND_SUCCESS != hr)
throw EX_QUERY;
stage5(
params,
work,
pAddress,
pAdapter,
hOverlappedFile,
pMemoryRegion,
&info
);
LOG_VOID_RETURN();
}
static void stage3(
params_t* const params,
work_t work,
const struct sockaddr* pAddress,
IND2Adapter* const pAdapter,
HANDLE const hOverlappedFile
)
{
LOG_ENTER();
IND2MemoryRegion* pMemoryRegion = 0;
HRESULT hr =
pAdapter->CreateMemoryRegion(
IID_IND2MemoryRegion,
hOverlappedFile,
(void**)&pMemoryRegion
);
LOG("IND2Adapter::CreateMemoryRegion -> %08X", hr);
if (hr != ND_SUCCESS)
throw EX_CREATE_MEMORY_REGION;
try
{
stage4(
params,
work,
pAddress,
pAdapter,
hOverlappedFile,
pMemoryRegion
);
}
catch (...)
{
ULONG ul = pMemoryRegion->Release();
LOG("IND2MemoryRegion::Release -> %u", ul);
throw;
}
ULONG ul = pMemoryRegion->Release();
LOG("IND2MemoryRegion::Release -> %u", ul);
LOG_VOID_RETURN();
}
static void stage2(
params_t* const params,
work_t work,
const struct sockaddr* pAddress,
IND2Adapter* const pAdapter
)
{
LOG_ENTER();
HANDLE hOverlappedFile = 0;
HRESULT hr =
pAdapter->CreateOverlappedFile(
&hOverlappedFile
);
LOG("IND2Adapter::CreateOverlappedFile -> %08X", hr);
if (hr != ND_SUCCESS)
throw EX_CREATE_OVERLAPPED_FILE;
try
{
stage3(params, work, pAddress, pAdapter, hOverlappedFile);
}
catch (...)
{
BOOL b = CloseHandle(hOverlappedFile);
LOG("CloseHandle -> %d", b);
throw;
}
BOOL b = CloseHandle(hOverlappedFile);
LOG("CloseHandle -> %d", b);
LOG_VOID_RETURN();
}
void work(
params_t* const params,
work_t work,
get_local_address_t get_local_address
)
{
LOG_ENTER();
struct sockaddr LocalAddress = (*get_local_address)(
(LPSTR)params->ip.c_str(),
params->port
);
IND2Adapter* pAdapter = 0;
HRESULT const hr =
NdOpenAdapter(
IID_IND2Adapter,
&LocalAddress,
sizeof(LocalAddress),
(void**)&pAdapter
);
if (ND_SUCCESS != hr)
throw EX_OPEN_ADAPTER;
try
{
stage2(params, work, &LocalAddress, pAdapter);
}
catch (...)
{
ULONG const ul = pAdapter->Release();
LOG("IND2Adapter::Release -> %u", ul);
throw;
}
ULONG const ul = pAdapter->Release();
LOG("IND2Adapter::Release -> %u", ul);
LOG_VOID_RETURN();
}
SOCKADDR get_sockaddr(LPSTR AddressString, INT AddressFamily, uint16_t port)
{
LOG_ENTER();
SOCKADDR saddr;
INT AddressLength = (int)sizeof(saddr);
// raises an exception on failure therefore no need to look at the return code
Win::WSAStringToAddressA(
AddressString,
AddressFamily,
0, // lpProtocolInfo
&saddr, // lpAddress
&AddressLength // lpAddressLength
);
((struct sockaddr_in*)&saddr)->sin_port = htons(port);
LOG_STRUCT_RETURN(SOCKADDR);
return saddr;
}
void RegisterMemory(IND2MemoryRegion* pMemoryRegion, void* buffer, size_t size)
{
LOG_ENTER();
OVERLAPPED ov = { 0 };
ULONG const flags =
ND_MR_FLAG_ALLOW_LOCAL_WRITE |
ND_MR_FLAG_ALLOW_REMOTE_READ |
ND_MR_FLAG_ALLOW_REMOTE_WRITE;
HRESULT hr =
pMemoryRegion->Register(
buffer,
size,
flags,
&ov
);
LOG("IND2MemoryRegion::Register -> %08X", hr);
if (ND_SUCCESS != hr)
{
if (ND_PENDING != hr)
throw EX_REGISTER;
uint64_t count = 1;
while (ND_PENDING == (hr = pMemoryRegion->GetOverlappedResult(&ov, FALSE)))
{
count += 1;
}
LOG("IND2MemoryRegion::GetOverlappedResult -> %08X (called %zu times)", hr, count);
if (ND_SUCCESS != hr)
throw EX_REGISTER_OV;
}
LOG_VOID_RETURN();
}
void DeregisterMemory(IND2MemoryRegion* pMemoryRegion)
{
// do not throw an exception!
LOG_ENTER();
OVERLAPPED ov = { 0 };
HRESULT hr = pMemoryRegion->Deregister(&ov);
LOG("IND2MemoryRegion::Deregister -> %08X", hr);
if (ND_PENDING == hr)
{
uint64_t count = 1;
while (ND_PENDING == (hr = pMemoryRegion->GetOverlappedResult(&ov, FALSE)))
{
count += 1;
}
LOG("IND2MemoryRegion::GetOverlappedResult -> %08X (called %zu times)", hr, count);
}
LOG_VOID_RETURN();
} | 25.322581 | 91 | 0.582803 |
5bcb52b804b9b25039f580f93c65033a8f22c49c | 4,933 | cpp | C++ | chromaprint/audio_processor.cpp | pvinis/music-player | 0e7d06c2a648ca9cfaa46418e6536f63ab42d088 | [
"BSD-2-Clause"
] | 56 | 2015-04-21T05:35:38.000Z | 2021-02-16T13:42:45.000Z | chromaprint/audio_processor.cpp | pvinis/music-player | 0e7d06c2a648ca9cfaa46418e6536f63ab42d088 | [
"BSD-2-Clause"
] | 13 | 2015-05-09T17:36:27.000Z | 2020-02-13T17:44:59.000Z | chromaprint/audio_processor.cpp | pvinis/music-player | 0e7d06c2a648ca9cfaa46418e6536f63ab42d088 | [
"BSD-2-Clause"
] | 27 | 2015-06-15T14:54:58.000Z | 2021-07-22T09:59:40.000Z | /*
* Chromaprint -- Audio fingerprinting toolkit
* Copyright (C) 2010-2011 Lukas Lalinsky <lalinsky@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
* USA
*/
#include <assert.h>
#include <algorithm>
#include <stdio.h>
extern "C" {
#include "avresample/avcodec.h"
}
#include "debug.h"
#include "audio_processor.h"
using namespace std;
using namespace Chromaprint;
static const int kMinSampleRate = 1000;
static const int kMaxBufferSize = 1024 * 16;
// Resampler configuration
static const int kResampleFilterLength = 16;
static const int kResamplePhaseCount = 10;
static const int kResampleLinear = 0;
static const double kResampleCutoff = 0.8;
AudioProcessor::AudioProcessor(int sample_rate, AudioConsumer *consumer)
: m_buffer_size(kMaxBufferSize),
m_target_sample_rate(sample_rate),
m_consumer(consumer),
m_resample_ctx(0)
{
m_buffer = new short[kMaxBufferSize];
m_buffer_offset = 0;
m_resample_buffer = new short[kMaxBufferSize];
}
AudioProcessor::~AudioProcessor()
{
if (m_resample_ctx) {
av_resample_close(m_resample_ctx);
}
delete[] m_resample_buffer;
delete[] m_buffer;
}
void AudioProcessor::LoadMono(short *input, int length)
{
short *output = m_buffer + m_buffer_offset;
while (length--) {
*output++ = input[0];
input++;
}
}
void AudioProcessor::LoadStereo(short *input, int length)
{
short *output = m_buffer + m_buffer_offset;
while (length--) {
*output++ = (input[0] + input[1]) / 2;
input += 2;
}
}
void AudioProcessor::LoadMultiChannel(short *input, int length)
{
short *output = m_buffer + m_buffer_offset;
while (length--) {
long sum = 0;
for (int i = 0; i < m_num_channels; i++) {
sum += *input++;
}
*output++ = (short)(sum / m_num_channels);
}
}
int AudioProcessor::Load(short *input, int length)
{
assert(length >= 0);
assert(m_buffer_offset <= m_buffer_size);
length = min(length, m_buffer_size - m_buffer_offset);
switch (m_num_channels) {
case 1:
LoadMono(input, length);
break;
case 2:
LoadStereo(input, length);
break;
default:
LoadMultiChannel(input, length);
break;
}
m_buffer_offset += length;
return length;
}
void AudioProcessor::Resample()
{
if (!m_resample_ctx) {
m_consumer->Consume(m_buffer, m_buffer_offset);
m_buffer_offset = 0;
return;
}
int consumed = 0;
int length = av_resample(m_resample_ctx, m_resample_buffer, m_buffer, &consumed, m_buffer_offset, kMaxBufferSize, 1);
if (length > kMaxBufferSize) {
DEBUG() << "Chromaprint::AudioProcessor::Resample() -- Resampling overwrote output buffer.\n";
length = kMaxBufferSize;
}
m_consumer->Consume(m_resample_buffer, length);
int remaining = m_buffer_offset - consumed;
if (remaining > 0) {
copy(m_buffer + consumed, m_buffer + m_buffer_offset, m_buffer);
}
else if (remaining < 0) {
DEBUG() << "Chromaprint::AudioProcessor::Resample() -- Resampling overread input buffer.\n";
remaining = 0;
}
m_buffer_offset = remaining;
}
bool AudioProcessor::Reset(int sample_rate, int num_channels)
{
if (num_channels <= 0) {
DEBUG() << "Chromaprint::AudioProcessor::Reset() -- No audio channels.\n";
return false;
}
if (sample_rate <= kMinSampleRate) {
DEBUG() << "Chromaprint::AudioProcessor::Reset() -- Sample rate less "
<< "than " << kMinSampleRate << " (" << sample_rate << ").\n";
return false;
}
m_buffer_offset = 0;
if (m_resample_ctx) {
av_resample_close(m_resample_ctx);
m_resample_ctx = 0;
}
if (sample_rate != m_target_sample_rate) {
m_resample_ctx = av_resample_init(
m_target_sample_rate, sample_rate,
kResampleFilterLength,
kResamplePhaseCount,
kResampleLinear,
kResampleCutoff);
}
m_num_channels = num_channels;
return true;
}
void AudioProcessor::Consume(short *input, int length)
{
assert(length >= 0);
assert(length % m_num_channels == 0);
length /= m_num_channels;
while (length > 0) {
int consumed = Load(input, length);
input += consumed * m_num_channels;
length -= consumed;
if (m_buffer_size == m_buffer_offset) {
Resample();
if (m_buffer_size == m_buffer_offset) {
DEBUG() << "Chromaprint::AudioProcessor::Consume() -- Resampling failed?\n";
return;
}
}
}
}
void AudioProcessor::Flush()
{
if (m_buffer_offset) {
Resample();
}
}
| 25.692708 | 118 | 0.711535 |
5bcbcd2c5d0aea2ba6fe58313f617077b506f975 | 8,455 | cpp | C++ | src/chainparams.cpp | barrystyle/myce | 906e600642109fb87d43c25b56d0365618e71c7a | [
"MIT"
] | 3 | 2020-02-05T09:54:43.000Z | 2020-03-21T06:49:37.000Z | src/chainparams.cpp | barrystyle/myce | 906e600642109fb87d43c25b56d0365618e71c7a | [
"MIT"
] | null | null | null | src/chainparams.cpp | barrystyle/myce | 906e600642109fb87d43c25b56d0365618e71c7a | [
"MIT"
] | 1 | 2020-02-12T11:38:21.000Z | 2020-02-12T11:38:21.000Z | // Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <chainparams.h>
#include <consensus/merkle.h>
#include <streams.h>
#include <tinyformat.h>
#include <utilstrencodings.h>
#include <arith_uint256.h>
#include <util.h>
#include <assert.h>
#include <chainparamsseeds.h>
CBlock MyceLegacyBlock()
{
CBlock block;
CDataStream stream(ParseHex("01000000000000000000000000000000000000000000000000000000000000000000000090eafddb7b64457b5b30f51a6b4f07912281b3b5fa5ebf5dc4149efe6380a58e5885965affff001f4232030001010000005db8535a010000000000000000000000000000000000000000000000000000000000000000ffffffff1400012a104d796365206d61737465726e6f646573ffffffff0100000000000000000000000000"), SER_NETWORK, 70914);
stream >> block;
return block;
}
static CBlock CreateGenesisBlock(uint32_t nTimeTx, unsigned int nTimeBlock, uint32_t nNonce, uint32_t nBits, int32_t nVersion, const CAmount& genesisReward)
{
const char* pszTimestamp = "Myce masternodes";
CMutableTransaction txNew;
txNew.nVersion = 1;
txNew.nTime = nTimeTx;
txNew.vin.resize(1);
txNew.vout.resize(1);
txNew.vin[0].scriptSig = CScript() << 0 << CScriptNum(42) << std::vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
txNew.vout[0].SetEmpty();
CBlock genesis;
genesis.vtx.push_back(MakeTransactionRef(std::move(txNew)));
genesis.nTime = nTimeBlock;
genesis.nBits = nBits;
genesis.nNonce = nNonce;
genesis.nVersion = nVersion;
genesis.hashPrevBlock.SetNull();
genesis.hashMerkleRoot = BlockMerkleRoot(genesis);
return genesis;
}
void CChainParams::UpdateVersionBitsParameters(Consensus::DeploymentPos d, int64_t nStartTime, int64_t nTimeout)
{
consensus.vDeployments[d].nStartTime = nStartTime;
consensus.vDeployments[d].nTimeout = nTimeout;
}
/**
* Main network
*/
/**
* What makes a good checkpoint block?
* + Is surrounded by blocks with reasonable timestamps
* (no blocks before with a timestamp after, none after with
* timestamp before)
* + Contains no strange transactions
*/
class CMainParams : public CChainParams {
public:
CMainParams() {
strNetworkID = "main";
consensus.nLastPoWBlock = 100;
consensus.nInstantSendKeepLock = 24;
consensus.nBudgetPaymentsStartBlock = 0;
consensus.nBudgetPaymentsCycleBlocks = 16616;
consensus.nBudgetPaymentsWindowBlocks = 100;
consensus.nBudgetProposalEstablishingTime = 60*60*24;
consensus.nSuperblockCycle = 43200;
consensus.nSuperblockStartBlock = consensus.nSuperblockCycle;
consensus.nGovernanceMinQuorum = 10;
consensus.nGovernanceFilterElements = 20000;
consensus.BIP34Height = 10;
consensus.BIP34Hash = uint256S("0000000000000000000000000000000000000000000000000000000000000000");
consensus.BIP65Height = consensus.nLastPoWBlock;
consensus.BIP66Height = consensus.nLastPoWBlock;
consensus.powLimit = uint256S("0000ffff00000000000000000000000000000000000000000000000000000000");
consensus.posLimit = uint256S("007ffff000000000000000000000000000000000000000000000000000000000");
consensus.nPowTargetTimespan = 2 * 60;
consensus.nPowTargetSpacing = 40;
consensus.nPosTargetSpacing = consensus.nPowTargetSpacing;
consensus.nPosTargetTimespan = consensus.nPowTargetTimespan;
consensus.nMasternodeMinimumConfirmations = 15;
consensus.nStakeMinAge = 10 * 60;
consensus.nStakeMaxAge = 60 * 60 * 24 * 30;
consensus.nModifierInterval = 60 * 20;
consensus.nCoinbaseMaturity = 20;
consensus.fPowAllowMinDifficultyBlocks = false;
consensus.fPowNoRetargeting = false;
consensus.nRuleChangeActivationThreshold = 1080;
consensus.nMinerConfirmationWindow = 1440;
consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].bit = 28;
consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nStartTime = 1199145601; // January 1, 2008
consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nTimeout = 1230767999; // December 31, 2008
// Deployment of BIP68, BIP112, and BIP113.
consensus.vDeployments[Consensus::DEPLOYMENT_CSV].bit = 0;
consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nStartTime = 1462060800; // May 1st, 2016
consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nTimeout = 1493596800; // May 1st, 2017
// Deployment of SegWit (BIP141, BIP143, and BIP147)
consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].bit = 1;
consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nStartTime = 1479168000; // November 15th, 2016.
consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout = 1510704000; // November 15th, 2017.
// The best chain should have at least this much work.
consensus.nMinimumChainWork = uint256S("0000000000000000000000000000000000000000000000000000000000000000");
// By default assume that the signatures in ancestors of this block are valid.
consensus.defaultAssumeValid = uint256S("0000000000000000000000000000000000000000000000000000000000000000");
/**
* The message start string is designed to be unlikely to occur in normal data.
* The characters are rarely used upper ASCII, not valid as UTF-8, and produce
* a large 32-bit integer with any alignment.
*/
pchMessageStart[0] = 0xfa;
pchMessageStart[1] = 0x23;
pchMessageStart[2] = 0x43;
pchMessageStart[3] = 0x65;
nDefaultPort = 23511;
nPruneAfterHeight = 100000;
nMaxReorganizationDepth = 100;
genesis = MyceLegacyBlock();
consensus.hashGenesisBlock = genesis.GetHash();
LogPrintf("%s\n", consensus.hashGenesisBlock.ToString().c_str());
base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1, 50);
base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1, 85);
base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1, 153);
base58Prefixes[EXT_PUBLIC_KEY] = {0x04, 0x88, 0xB2, 0x1E};
base58Prefixes[EXT_SECRET_KEY] = {0x04, 0x88, 0xAD, 0xE4};
bech32_hrp = "vx";
vFixedSeeds = std::vector<SeedSpec6>(pnSeed6_main, pnSeed6_main + ARRAYLEN(pnSeed6_main));
fMiningRequiresPeers = true;
fDefaultConsistencyChecks = false;
fRequireStandard = true;
fMineBlocksOnDemand = false;
nCollateralLevels = { 0 };
nPoolMaxTransactions = 3;
nFulfilledRequestExpireTime = 60*60;
strSporkPubKey = "03f012092c5fe9ed406b43316fc87d8ace9e8eb7764999db00ef60009ddddfa723";
strSporkPubKeyOld = "0358d5fb8000c49d38aaab6dc5d0c0a0322eff3090eff026963eb819dc3dec8439";
checkpointData = {
};
chainTxData = ChainTxData{
};
/* disable fallback fee on mainnet */
m_fallback_fee_enabled = true;
}
};
/*
* Testnet (v3)
*/
class CTestNetParams : public CChainParams {
public:
CTestNetParams() {
strNetworkID = "test";
}
};
/*
* Regression test
*/
class CRegTestParams : public CChainParams {
public:
CRegTestParams() {
strNetworkID = "regtest";
}
};
static std::unique_ptr<CChainParams> globalChainParams;
const CChainParams &Params() {
assert(globalChainParams);
return *globalChainParams;
}
std::unique_ptr<CChainParams> CreateChainParams(const std::string& chain)
{
if (chain == CBaseChainParams::MAIN)
return std::unique_ptr<CChainParams>(new CMainParams());
else if (chain == CBaseChainParams::TESTNET)
return std::unique_ptr<CChainParams>(new CTestNetParams());
else if (chain == CBaseChainParams::REGTEST)
return std::unique_ptr<CChainParams>(new CRegTestParams());
throw std::runtime_error(strprintf("%s: Unknown chain %s.", __func__, chain));
}
void SelectParams(const std::string& network)
{
SelectBaseParams(network);
globalChainParams = CreateChainParams(network);
}
void UpdateVersionBitsParameters(Consensus::DeploymentPos d, int64_t nStartTime, int64_t nTimeout)
{
globalChainParams->UpdateVersionBitsParameters(d, nStartTime, nTimeout);
}
| 38.784404 | 387 | 0.720757 |
5bcc910a7b8c3a895285c00bf8c0fedf97aa5cc5 | 3,172 | cpp | C++ | copasi/sbml/unittests/test000101.cpp | SzVarga/COPASI | 00451b1a67eeec8272c73791ca861da754a7c4c4 | [
"Artistic-2.0"
] | 64 | 2015-03-14T14:06:18.000Z | 2022-02-04T23:19:08.000Z | copasi/sbml/unittests/test000101.cpp | SzVarga/COPASI | 00451b1a67eeec8272c73791ca861da754a7c4c4 | [
"Artistic-2.0"
] | 4 | 2017-08-16T10:26:46.000Z | 2020-01-08T12:05:54.000Z | copasi/sbml/unittests/test000101.cpp | SzVarga/COPASI | 00451b1a67eeec8272c73791ca861da754a7c4c4 | [
"Artistic-2.0"
] | 28 | 2015-04-16T14:14:59.000Z | 2022-03-28T12:04:14.000Z | // Copyright (C) 2017 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and University of
// of Connecticut School of Medicine.
// All rights reserved.
// Copyright (C) 2011 - 2016 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.
#include "test000101.h"
#include <iostream>
#ifndef WIN32
#include <signal.h>
#endif
#include <stdexcept>
#include <copasi/report/CRootContainer.h>
#include <copasi/CopasiDataModel/CDataModel.h>
// Since this bug leads to segmentation fault
// we need to make sure that the call to abort made by assert does not end the program.
// For this we change the signal handler to one that throws an exception.
// The current version is specific to linux. If these tests are to be run under windows,
// the mechanism for setting the signal handler will probably have to be modified.
void test000101::abort_handler(int)
{
throw std::runtime_error("Received SIGSEGV signal.");
}
#ifndef WIN32
struct sigaction* test000101::pOldAct = new struct sigaction();
struct sigaction* test000101::pNewAct = new struct sigaction();
#endif
void test000101::setUp()
{
#ifndef WIN32
// set a new action handler for SIGABRT that throws an exception
// instead of terminating the program. This is needed to handle failed assertions
// in debug versions.
pNewAct->sa_handler = &test000101::abort_handler;
int x = sigaction(SIGSEGV, test000101::pNewAct, test000101::pOldAct);
if (x != 0)
{
std::cerr << "Setting the signal handler failed." << std::endl;
}
#endif
// Create the root container.
CRootContainer::init(0, NULL, false);
pDataModel = CRootContainer::addDatamodel();
}
void test000101::tearDown()
{
#ifndef WIN32
CRootContainer::destroy();
// restore the old action handler
int x = sigaction(SIGSEGV, test000101::pOldAct, NULL);
if (x != 0)
{
std::cerr << "Resetting the signal handler failed." << std::endl;
}
#endif
}
void test000101::test_bug1740()
{
pDataModel->importSBMLFromString(SBML_STRING);
pDataModel->exportSBMLToString(NULL, 3, 1);
try
{
// the second export crashes without a bug fix
pDataModel->exportSBMLToString(NULL, 3, 1);
}
catch (const std::runtime_error& e)
{
CPPUNIT_ASSERT_MESSAGE("The second export to Level 3 Version 1 failed.", false);
}
}
const char* test000101::SBML_STRING = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<sbml xmlns=\"http://www.sbml.org/sbml/level3/version1/core\" level=\"3\" version=\"1\">\n"
" <model id=\"Module_1_RL2_1\" name=\"Module_1_RL2\">\n"
" <listOfReactions>\n"
" <reaction fast=\"false\" id=\"reaction_0\" name=\"reaction_0\" reversible=\"false\">\n"
" </reaction>\n"
" </listOfReactions>\n"
" </model>\n"
"</sbml>\n";
| 33.041667 | 132 | 0.634615 |
5bd03752bc7988a0f3f32e56f8b1a251641428e5 | 5,548 | cpp | C++ | tests/job_tests.cpp | jacobmcleman/JobBot | 1ef82a2f2fbf3321ba3ef4f2a006128bed1388c0 | [
"MIT"
] | null | null | null | tests/job_tests.cpp | jacobmcleman/JobBot | 1ef82a2f2fbf3321ba3ef4f2a006128bed1388c0 | [
"MIT"
] | null | null | null | tests/job_tests.cpp | jacobmcleman/JobBot | 1ef82a2f2fbf3321ba3ef4f2a006128bed1388c0 | [
"MIT"
] | null | null | null | /**************************************************************************
Some short tests to test basic job functionality
Author:
Jake McLeman
***************************************************************************/
#include <gtest/gtest.h>
#include "Job.h"
#define UNUSED(thing) (void)thing
using namespace JobBot;
bool testFunc1HasRun;
void TestJobFunc1(Job* job)
{
UNUSED(job);
testFunc1HasRun = true;
}
TinyJobFunction TestJob1(TestJobFunc1);
bool testFunc2HasRun;
void TestJobFunc2(Job* job)
{
UNUSED(job);
testFunc2HasRun = true;
}
HugeJobFunction TestJob2(TestJobFunc2);
bool testFunc3GotData;
void TestJobFunc3(Job* job) { testFunc3GotData = (job->GetData<int>() == 4); }
IOJobFunction TestJob3(TestJobFunc3);
bool testFunc4GotData;
void TestJobFunc4(Job* job)
{
testFunc4GotData = (job->GetData<float>() == 25.12f);
}
GraphicsJobFunction TestJob4(TestJobFunc4);
TEST(JobTests, SizeVerification)
{
ASSERT_EQ((size_t)Job::TARGET_JOB_SIZE, sizeof(Job))
<< "Job was incorrect size";
}
TEST(JobTests, Create)
{
Job* job = Job::Create(TestJob1);
EXPECT_FALSE(job->IsFinished()) << "Job has not been created correctly";
EXPECT_FALSE(job->InProgress()) << "Job has not been created correctly";
}
TEST(JobTests, RunJob)
{
testFunc1HasRun = false;
Job* job = Job::Create(TestJob1);
EXPECT_FALSE(testFunc1HasRun) << "Job has been prematurely executed";
EXPECT_FALSE(job->IsFinished())
<< "Job is marked as finished before it has run";
job->Run();
EXPECT_TRUE(testFunc1HasRun)
<< "Job has been run but has not executed job code";
EXPECT_TRUE(job->IsFinished())
<< "Job has been run but is not marked as finished";
EXPECT_FALSE(job->InProgress())
<< "Job is finished but still marked as in progress";
}
TEST(JobTests, Parent)
{
testFunc1HasRun = false;
testFunc2HasRun = false;
// Create 2 jobs with job2 as a child of job1
Job* job1 = Job::Create(TestJob1);
Job* job2 = Job::CreateChild(TestJob2, job1);
// Make sure that nothing has prematurely fired
EXPECT_FALSE(testFunc1HasRun) << "Job1 has been prematurely executed";
EXPECT_FALSE(job1->IsFinished())
<< "Job1 is marked as finished before it has run";
EXPECT_FALSE(testFunc2HasRun) << "Job2 has been prematurely executed";
EXPECT_FALSE(job2->IsFinished())
<< "Job2 is marked as finished before it has run";
// Run job1 (the parent)
job1->Run();
// Job 1 has now run, but should not be marked done because it has a child
// that has not finished
EXPECT_TRUE(testFunc1HasRun) << "Job1 has not run correctly";
EXPECT_FALSE(job1->IsFinished())
<< "Job1 is marked as finished before all of its children have finished";
EXPECT_FALSE(testFunc2HasRun) << "Job2 has been prematurely executed";
EXPECT_FALSE(job2->IsFinished())
<< "Job2 is marked as finished before it has run";
// Run job2 (the child)
job2->Run();
// Make sure all jobs are now correctly marked as completed
EXPECT_TRUE(testFunc1HasRun) << "Job1 has not run correctly";
EXPECT_TRUE(job1->IsFinished())
<< "Job1 is not marked as finished even though all child jobs are done";
EXPECT_TRUE(testFunc2HasRun) << "Job2 has not run correctly";
EXPECT_TRUE(job2->IsFinished())
<< "Job2 has been run but is not marked as finished";
}
TEST(JobTests, Callback)
{
testFunc1HasRun = false;
testFunc2HasRun = false;
// Create job1 with a callback function
Job* job = Job::Create(TestJob1);
job->SetCallback(TestJob2);
EXPECT_FALSE(testFunc1HasRun) << "Job has been prematurely executed";
EXPECT_FALSE(job->IsFinished())
<< "Job is marked as finished before it has run";
EXPECT_FALSE(testFunc2HasRun) << "Callback has been prematurely executed";
job->Run();
EXPECT_TRUE(testFunc1HasRun)
<< "Job has been run but has not executed job code";
EXPECT_TRUE(job->IsFinished())
<< "Job has been run but is not marked as finished";
EXPECT_TRUE(testFunc2HasRun)
<< "Job has been run but has not executed callback code";
}
TEST(JobTests, Data1)
{
testFunc3GotData = false;
Job* job = Job::Create(TestJob3, 4);
EXPECT_FALSE(testFunc3GotData)
<< "Function somehow already got the data even though it hasn't run yet";
EXPECT_FALSE(job->IsFinished())
<< "Job is marked as finished before it has run";
job->Run();
EXPECT_TRUE(testFunc3GotData)
<< "Function did not correctly recieve the data";
EXPECT_TRUE(job->IsFinished()) << "Job is not marked as finished";
}
TEST(JobTests, Data2)
{
testFunc4GotData = false;
Job* job = Job::Create(TestJob4, 25.12f);
EXPECT_FALSE(testFunc4GotData)
<< "Function somehow already got the data even though it hasn't run yet";
EXPECT_FALSE(job->IsFinished())
<< "Job is marked as finished before it has run";
job->Run();
EXPECT_TRUE(testFunc4GotData) << "Function recieved wrong data";
EXPECT_TRUE(job->IsFinished()) << "Job is not marked as finished";
}
TEST(JobTests, JobTypeChecks)
{
Job* job1 = Job::Create(TestJob1);
Job* job2 = Job::Create(TestJob2);
EXPECT_FALSE(job1->MatchesType(JobType::Huge)) << "Tiny job was huge";
EXPECT_FALSE(job1->MatchesType(JobType::Misc)) << "Tiny job was misc";
EXPECT_TRUE(job1->MatchesType(JobType::Tiny))
<< "Tiny job was not a tiny job";
EXPECT_TRUE(job2->MatchesType(JobType::Huge)) << "Huge job was not huge";
EXPECT_FALSE(job2->MatchesType(JobType::Misc)) << "Huge job was misc";
EXPECT_FALSE(job2->MatchesType(JobType::Tiny)) << "Huge job was tiny";
}
| 29.354497 | 79 | 0.683129 |