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
109
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
9
| max_issues_count
int64 1
48.5k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
957740122974a786e3020327b0f5a08edf6bb599
| 5,903
|
cpp
|
C++
|
src/graph_test.cpp
|
bonewell/libspfclient
|
a23201d020cd42db698c42661bb21e2c85a1dafe
|
[
"MIT"
] | null | null | null |
src/graph_test.cpp
|
bonewell/libspfclient
|
a23201d020cd42db698c42661bb21e2c85a1dafe
|
[
"MIT"
] | 4
|
2020-04-07T19:00:57.000Z
|
2020-05-31T16:56:33.000Z
|
src/graph_test.cpp
|
bonewell/libspfclient
|
a23201d020cd42db698c42661bb21e2c85a1dafe
|
[
"MIT"
] | null | null | null |
#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include "mock_rpc.h"
#include "spf/graph.h"
using ::testing::_;
using ::testing::Eq;
using ::testing::ContainerEq;
using ::testing::Return;
using namespace spf;
TEST(Graph, AddVertex) {
MockRpc mock;
Graph g{mock};
EXPECT_CALL(mock, invoke(R"({"action":"AddVertex"})"))
.WillOnce(Return(R"({"id":"1"})"));
EXPECT_THAT(g.addVertex(), Eq(1));
}
TEST(Graph, AddVertexWithError) {
MockRpc mock;
Graph g{mock};
EXPECT_CALL(mock, invoke(_)).WillOnce(Return(R"({"error":"Internal error"})"));
EXPECT_THROW(g.addVertex(), Error);
}
TEST(Graph, RemoveVertex) {
MockRpc mock;
Graph g{mock};
EXPECT_CALL(mock, invoke(R"({"action":"RemoveVertex","id":"1"})"))
.WillOnce(Return(R"({})"));
EXPECT_NO_THROW(g.removeVertex(1));
}
TEST(Graph, RemoveVertexWithError) {
MockRpc mock;
Graph g{mock};
EXPECT_CALL(mock, invoke(_)).WillOnce(Return(R"({"error":"Wrong ID"})"));
EXPECT_THROW(g.removeVertex(100), Error);
}
TEST(Graph, SetEdge) {
MockRpc mock;
Graph g{mock};
EXPECT_CALL(mock,
invoke(R"({"action":"AddEdge","from":"1","to":"2","weight":"7"})"))
.WillOnce(Return(R"({})"));
EXPECT_NO_THROW(g.setEdge(1, 2, 7));
}
TEST(Graph, SetEdgeWithError) {
MockRpc mock;
Graph g{mock};
EXPECT_CALL(mock, invoke(_)).WillOnce(Return(R"({"error":"Wrong vertex ID"})"));
EXPECT_THROW(g.setEdge(100, 2, 7), Error);
}
TEST(Graph, RemoveEdge) {
MockRpc mock;
Graph g{mock};
EXPECT_CALL(mock,
invoke(R"({"action":"RemoveEdge","from":"1","to":"2"})"))
.WillOnce(Return(R"({})"));
EXPECT_NO_THROW(g.removeEdge(1, 2));
}
TEST(Graph, RemoveEdgeWithError) {
MockRpc mock;
Graph g{mock};
EXPECT_CALL(mock, invoke(_)).WillOnce(Return(R"({"error":"Wrong vertex ID"})"));
EXPECT_THROW(g.removeEdge(100, 2), Error);
}
TEST(Graph, GetPath) {
MockRpc mock;
Graph g{mock};
EXPECT_CALL(mock, invoke(R"({"action":"GetPath","from":"0","to":"4"})"))
.WillOnce(Return(R"({"ids":["0","2","4"]})"));
EXPECT_THAT(g.path(0, 4), ContainerEq(std::list<Id>{0, 2, 4}));
}
TEST(Graph, GetPathWithError) {
MockRpc mock;
Graph g{mock};
EXPECT_CALL(mock, invoke(_)).WillOnce(Return(R"({"error":"Wrong ID"})"));
EXPECT_THROW(g.path(0, 4), Error);
}
TEST(Graph, AddVertexAsync) {
MockRpc mock;
Graph g{mock};
EXPECT_CALL(mock, async_invoke(R"({"action":"AddVertex"})", _))
.WillOnce([](auto, auto callback) {
callback(R"({"id":"1"})", {});
});
Id expected;
g.addVertex([&expected](Id id, auto) { expected = id; });
EXPECT_THAT(expected, Eq(1));
}
TEST(Graph, AddVertexAsyncWithError) {
MockRpc mock;
Graph g{mock};
EXPECT_CALL(mock, async_invoke(_, _))
.WillOnce([](auto, auto callback) {
callback(R"({"vertex":"1"})", {});
});
Error expected;
g.addVertex([&expected](Id, auto error) { expected = error; });
EXPECT_THAT(bool{expected}, Eq(true));
}
TEST(Graph, RemoveVertexAsync) {
MockRpc mock;
Graph g{mock};
EXPECT_CALL(mock, async_invoke(R"({"action":"RemoveVertex","id":"1"})", _))
.WillOnce([](auto, auto callback) {
callback(R"({})", {});
});
Error expected;
g.removeVertex(1, [&expected](auto error) { expected = error; });
EXPECT_THAT(bool{expected}, Eq(false));
}
TEST(Graph, RemoveVertexAsyncWithError) {
MockRpc mock;
Graph g{mock};
EXPECT_CALL(mock, async_invoke(_, _))
.WillOnce([](auto, auto callback) {
callback(R"({"error":"Internal error"})", {});
});
Error expected;
g.removeVertex(100, [&expected](auto error) { expected = error; });
EXPECT_THAT(bool{expected}, Eq(true));
}
TEST(Graph, SetEdgeAsync) {
MockRpc mock;
Graph g{mock};
EXPECT_CALL(mock,
async_invoke(R"({"action":"AddEdge","from":"0","to":"1","weight":"7"})", _))
.WillOnce([](auto, auto callback) {
callback(R"({})", {});
});
Error expected;
g.setEdge(0, 1, 7, [&expected](auto error) { expected = error; });
EXPECT_THAT(bool{expected}, Eq(false));
}
TEST(Graph, SetEdgeAsyncWithError) {
MockRpc mock;
Graph g{mock};
EXPECT_CALL(mock, async_invoke(_, _))
.WillOnce([](auto, auto callback) {
callback(R"({"error":"Internal error"})", {});
});
Error expected;
g.setEdge(0, 1, -3.4, [&expected](auto error) { expected = error; });
EXPECT_THAT(bool{expected}, Eq(true));
}
TEST(Graph, RemoveEdgeAsync) {
MockRpc mock;
Graph g{mock};
EXPECT_CALL(mock,
async_invoke(R"({"action":"RemoveEdge","from":"0","to":"1"})", _))
.WillOnce([](auto, auto callback) {
callback(R"({})", {});
});
Error expected;
g.removeEdge(0, 1, [&expected](auto error) { expected = error; });
EXPECT_THAT(bool{expected}, Eq(false));
}
TEST(Graph, RemoveEdgeAsyncWithError) {
MockRpc mock;
Graph g{mock};
EXPECT_CALL(mock, async_invoke(_, _))
.WillOnce([](auto, auto callback) {
callback(R"({"error":"Internal error"})", {});
});
Error expected;
g.removeEdge(0, 1, [&expected](auto error) { expected = error; });
EXPECT_THAT(bool{expected}, Eq(true));
}
TEST(Graph, GetPathAsync) {
MockRpc mock;
Graph g{mock};
EXPECT_CALL(mock,
async_invoke(R"({"action":"GetPath","from":"0","to":"4"})", _))
.WillOnce([](auto, auto callback) {
callback(R"({"ids":["0","2","4"]})", {});
});
std::list<Id> expected;
g.path(0, 4, [&expected](auto ids, auto) { expected = ids; });
EXPECT_THAT(expected, ContainerEq(std::list<Id>{0, 2, 4}));
}
TEST(Graph, GetPathAsyncWithError) {
MockRpc mock;
Graph g{mock};
EXPECT_CALL(mock, async_invoke(_, _))
.WillOnce([](auto, auto callback) {
callback(R"({"vertexes":["0","4"]})", {});
});
Error expected;
g.path(0, 4, [&expected](auto, auto error) { expected = error; });
EXPECT_THAT(bool{expected}, Eq(true));
}
| 23.332016
| 82
| 0.607657
|
bonewell
|
957ee648e041682af6879add232d28d27c5d166a
| 1,000
|
cpp
|
C++
|
yumemi_recruit/test.cpp
|
syohex/cpp-study
|
598c2afbe77c6d4ba88f549d3e99f97b5bf81acb
|
[
"MIT"
] | null | null | null |
yumemi_recruit/test.cpp
|
syohex/cpp-study
|
598c2afbe77c6d4ba88f549d3e99f97b5bf81acb
|
[
"MIT"
] | null | null | null |
yumemi_recruit/test.cpp
|
syohex/cpp-study
|
598c2afbe77c6d4ba88f549d3e99f97b5bf81acb
|
[
"MIT"
] | null | null | null |
#include <cassert>
#include <vector>
#include "ranking.h"
int main() {
{
std::vector<Rank> ranking;
auto ret = CalculateRanking("./data/all_first.csv", 1, ranking);
assert(ret == RankingError::kOk);
assert(ranking.size() == 13);
}
{
std::vector<Rank> ranking;
auto ret = CalculateRanking("./data/input01.csv", 1, ranking);
assert(ret == RankingError::kOk);
assert(ranking.size() == 2);
}
{
std::vector<Rank> ranking;
auto ret = CalculateRanking("./data/input02.csv", 5, ranking);
assert(ret == RankingError::kOk);
assert(ranking.size() == 5);
assert(ranking[0].id == "player0002");
assert(ranking[1].id == "player0001");
assert(ranking[1].average == 30);
assert(ranking[2].id == "player0003");
assert(ranking[3].id == "player0004");
assert(ranking[4].id == "player0005");
assert(ranking[4].average == 4);
}
return 0;
}
| 30.30303
| 72
| 0.555
|
syohex
|
95817fd09dd1a4939d782dcee7b0c22b5eadc02e
| 1,603
|
cpp
|
C++
|
RPC-2018/Fecha-2/I-Import Spaghetti.cpp
|
isanchez-aguilar/burrOS
|
69fa4a055e094259cd7bc8d3e5cbd350ab3ca223
|
[
"MIT"
] | null | null | null |
RPC-2018/Fecha-2/I-Import Spaghetti.cpp
|
isanchez-aguilar/burrOS
|
69fa4a055e094259cd7bc8d3e5cbd350ab3ca223
|
[
"MIT"
] | null | null | null |
RPC-2018/Fecha-2/I-Import Spaghetti.cpp
|
isanchez-aguilar/burrOS
|
69fa4a055e094259cd7bc8d3e5cbd350ab3ca223
|
[
"MIT"
] | 1
|
2018-03-11T03:55:46.000Z
|
2018-03-11T03:55:46.000Z
|
/*
* User: oozmas
* Problem: RPC 2nd Activity I-Import Spaghetti
*/
#include <bits/stdc++.h>
#define MAX 1e9
using namespace std;
int cnt = 0;
vector<string> p;
map<int, string> nm;
map<string, int> id;
vector< vector<int> > parent(500, vector<int>(500));
void path(int i, int j)
{
if (parent[i][j] != i)
path(i, parent[i][j]);
p.push_back(nm[parent[i][j]]);
return;
}
int main(void)
{
ios_base::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
for (int i = 0; i < n; ++i)
{
string name;
cin >> name;
nm[i] = name;
id[name] = i;
}
vector< vector<int> > dist(n, vector<int>(n, MAX));
for (int i = 0; i < n; ++i)
{
int t;
string name;
cin >> name >> t;
while (t--)
{
string import;
cin >> import;
getline(cin, import);
istringstream in(import);
while (in >> import)
{
if (import[import.length() - 1] == ',')
import.pop_back();
dist[id[name]][id[import]] = 1;
}
}
}
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < n; ++j)
parent[i][j] = i;
}
for (int k = 0; k < n; ++k)
{
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < n; ++j)
{
if (dist[i][j] > dist[i][k] + dist[k][j])
{
parent[i][j] = parent[k][j];
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}
}
int u = -1;
int minC = MAX;
for (int i = 0; i < n; ++i)
{
if (dist[i][i] < minC)
{
u = i;
minC = dist[i][i];
}
}
if (u == -1 or minC >= MAX)
cout << "SHIP IT\n";
else
{
path(u, u);
for (int i = 0; i < p.size(); ++i)
cout << p[i] << (i + 1 == p.size()?"\n":" ");
}
return 0;
}
| 14.185841
| 52
| 0.479726
|
isanchez-aguilar
|
958439b25673ee01c34ac0d6e9fe182d1f1708fd
| 252
|
cc
|
C++
|
test/test_trie.cc
|
stiger104/Joker
|
d03df6b8cabb96dddb00624c7bc93e5ea2b01f66
|
[
"MIT"
] | null | null | null |
test/test_trie.cc
|
stiger104/Joker
|
d03df6b8cabb96dddb00624c7bc93e5ea2b01f66
|
[
"MIT"
] | null | null | null |
test/test_trie.cc
|
stiger104/Joker
|
d03df6b8cabb96dddb00624c7bc93e5ea2b01f66
|
[
"MIT"
] | null | null | null |
//
// Created by zhuangxk on 5/19/16.
//
#include "../src/trie.h"
#include "gtest/gtest.h"
Trie trie;
TEST(Trie, main) {
trie.insert("hello");
trie.insert("helloworld");
trie.insert("he");
EXPECT_EQ(1, trie.startsWith("he"));
}
| 12
| 40
| 0.595238
|
stiger104
|
958723f46b2ff6c3c25a8f3c084ea49179164c91
| 389
|
hpp
|
C++
|
Include/FishEngine/Render/Graphics.hpp
|
yushroom/FishEngine_-Experiment
|
81e4c06f20f6b94dc561b358f8a11a092678aeeb
|
[
"MIT"
] | 1
|
2018-12-20T02:38:44.000Z
|
2018-12-20T02:38:44.000Z
|
Include/FishEngine/Render/Graphics.hpp
|
yushroom/FishEngine_-Experiment
|
81e4c06f20f6b94dc561b358f8a11a092678aeeb
|
[
"MIT"
] | null | null | null |
Include/FishEngine/Render/Graphics.hpp
|
yushroom/FishEngine_-Experiment
|
81e4c06f20f6b94dc561b358f8a11a092678aeeb
|
[
"MIT"
] | 1
|
2018-10-25T19:40:22.000Z
|
2018-10-25T19:40:22.000Z
|
#pragma once
namespace FishEngine
{
class Mesh;
class Material;
class Matrix4x4;
class Camera;
class Light;
class Graphics
{
public:
static void DrawMesh(Mesh* mesh, Material* material, int subMeshIndex = -1);
static void DrawMesh(Mesh* mesh, Material* material, int subMeshIndex, Camera* camera, const Matrix4x4& mat, Light* light);
private:
Graphics() = delete;
};
}
| 18.52381
| 125
| 0.719794
|
yushroom
|
9589bb6f14582789a7b4b9ee137c1dd05ba0a76f
| 35,887
|
cpp
|
C++
|
no_cache/src/internal_shard.cpp
|
cerww/cpp_discord_cuteness
|
3989b9e3fdcceb6823fb5df935ef38e3f7cb350e
|
[
"MIT"
] | 4
|
2020-05-19T10:13:11.000Z
|
2020-07-10T11:00:21.000Z
|
no_cache/src/internal_shard.cpp
|
cerww/cpp_discord_cuteness
|
3989b9e3fdcceb6823fb5df935ef38e3f7cb350e
|
[
"MIT"
] | null | null | null |
no_cache/src/internal_shard.cpp
|
cerww/cpp_discord_cuteness
|
3989b9e3fdcceb6823fb5df935ef38e3f7cb350e
|
[
"MIT"
] | null | null | null |
#include "internal_shard.h"
#include "client.h"
#include "voice_channel.h"
#include "dm_channel.h"
#include "init_shard.h"
#include "voice_connect_impl.h"
#include "../common/executor_binder.h"
#include "unavailable_guild.h"
#include "presence_update.h"
#include "events.h"
#include <concepts>
//#include <boost/beast/>
//copy paste start
#if defined(_WIN32) || defined(_WIN64)
static constexpr const char* s_os = "Windows";
#elif defined(__APPLE__) || defined(__MACH__)
static constexpr const char * s_os = "macOS";
#elif defined(__linux__) || defined(linux) || defined(__linux)
static constexpr const char * s_os = "Linux";
#elif defined __FreeBSD__
static constexpr const char * s_os = "FreeBSD";
#elif defined(unix) || defined(__unix__) || defined(__unix)
static constexpr const char * s_os = "Unix";
#else
static constexpr const char* s_os = "\\u00AF\\\\_(\\u30C4)_\\/\\u00AF"; //shrug I dunno
#endif
//copy paste end
using namespace fmt::literals;
template<typename rng, typename U>
//[[maybe_unused]]
constexpr bool erase_first_quick(rng& range, U&& val) {
const auto it = std::find(range.begin(), range.end(), std::forward<U>(val));
if (it == range.end())
return false;
std::swap(range.back(), *it);
range.pop_back();
return true;
}
namespace cacheless {
template<typename T>
T* ptr_or_null(ref_stable_map<snowflake, T>& in, snowflake key) {
if (key.val)
return &in[key];
return nullptr;
}
internal_shard::internal_shard(
int shard_number, client* t_parent, boost::asio::io_context& ioc, std::string_view gateway, intents intent
) :
shard(shard_number, t_parent, ioc, std::string(t_parent->auth_token())),
m_heartbeat_context(*this),
m_ioc(ioc),
m_resolver(ioc),
m_socket(boost::asio::any_io_executor(strand()), m_ssl_ctx),
m_intents(intent) {
init_shard(shard_number, *this, ioc, gateway);
}
nlohmann::json internal_shard::presence() const {
nlohmann::json retVal;
retVal["since"];
retVal["game"]["name"] = m_game_name;
retVal["game"]["type"] = 0;
retVal["status"] = enum_to_string(m_status);
retVal["afk"] = m_status == Status::idle;
return retVal;
}
cerwy::eager_task<voice_connection> internal_shard::connect_voice(const voice_channel& channel) {
const auto channel_id = channel.id;
const auto guild_id = channel.guild_id;
auto [endpoint, session_id_task] = m_opcode4(channel.guild_id, channel_id);
auto ep_json = co_await endpoint;
auto session_id = co_await session_id_task;
std::cout << ep_json.dump(1);
std::string gateway = "wss://"s + ep_json["endpoint"].get<std::string>() + "/?v=4"s;
std::cout << gateway << std::endl;
m_things_waiting_for_voice_endpoint2.erase(channel.guild_id);
m_things_waiting_for_voice_endpoint.erase(channel.guild_id);
co_return co_await voice_connect_impl(*this, channel, std::move(gateway), ep_json["token"].get<std::string>(), std::move(session_id));
}
cerwy::eager_task<voice_connection> internal_shard::connect_voice(snowflake guild_id, snowflake channel_id) {
auto [endpoint, session_id_task] = m_opcode4(guild_id, channel_id);
auto ep_json = co_await endpoint;
auto session_id = co_await session_id_task;
std::cout << ep_json.dump(1);
std::string gateway = "wss://"s + ep_json["endpoint"].get<std::string>() + "/?v=4"s;
std::cout << gateway << std::endl;
m_things_waiting_for_voice_endpoint2.erase(guild_id);
m_things_waiting_for_voice_endpoint.erase(guild_id);
co_return co_await voice_connect_impl(*this, guild_id, channel_id, std::move(gateway), ep_json["token"].get<std::string>(), std::move(session_id));
}
cerwy::eager_task<void> internal_shard::send_identity() const {
auto identity = fmt::format(R"(
{{
"op":2,
"d":{{
"token":"{}",
"properties":{{
"$os":"{}",
"$browser":"cerwy",
"$device":"cerwy"
}},
"compress":false,
"large_threashold":{},
"shard":[{},{}],
"presence":{},
"intents":{}
}}
}}
)", m_parent_client->token(), s_os, large_threshold, m_shard_number, m_parent_client->num_shards(), presence().dump(), m_intents.int_value());
// auto timer = std::make_unique<boost::asio::steady_timer>(m_ioc);
// timer->expires_at(m_parent_client->get_time_point_for_identifying());
// timer->async_wait([pin = std::move(timer), str = std::move(identity),this](auto ec)mutable {
// m_web_socket->send_thing(std::move(str));
// });
co_await m_web_socket->send_thing(std::move(identity));
m_parent_client->notify_identified();
}
cerwy::eager_task<boost::beast::error_code> internal_shard::connect_http_connection() {
auto ec = co_await m_http_connection.async_connect();
int tries = 1;
//TODO: do something else
while (ec && tries < 10) {
ec = co_await m_http_connection.async_connect();
++tries;
}
co_return ec;
}
void internal_shard::doStuff(nlohmann::json stuffs, int op) {
//fmt::print("{}\n", stuffs.dump(1));
switch (op) {
case 0:
m_opcode0(std::move(stuffs["d"]), to_event_name(stuffs["t"]), stuffs["s"]);
break;
case 1:
m_opcode1_send_heartbeat();
break;
case 2: break;
case 3: break;
case 4: break;
case 5: break;
case 6: break;
case 7:
m_opcode7_reconnect();
break;
case 8: break;
case 9:
m_opcode9_on_invalid_session(std::move(stuffs["d"]));
break;
case 10:
m_opcode10_on_hello(stuffs["d"]);
break;
case 11:
m_opcode11(stuffs["d"]);
break;
default: break;
}
}
// ReSharper disable CppMemberFunctionMayBeConst
void internal_shard::on_reconnect() {
// ReSharper restore CppMemberFunctionMayBeConst
send_resume();
}
void internal_shard::rate_limit(std::chrono::system_clock::time_point tp) {
m_http_connection.sleep_till(tp);
}
void internal_shard::close_connection(int code) {
m_is_disconnected = true;
m_web_socket->close(boost::beast::websocket::close_reason(code));
}
void internal_shard::request_guild_members(snowflake guild_id) const {
m_opcode8_guild_member_chunk(guild_id);
}
void internal_shard::m_opcode0(nlohmann::json data, event_name event, uint64_t s) {
m_seq_num.store(std::max(s, m_seq_num.load(std::memory_order_relaxed)), std::memory_order_relaxed);
std::cout << m_seq_num << std::endl;
//std::cout << data << std::endl;
//{
//auto lock = co_await m_events_mut.async_lock();//?
//}
try {
switch (event) {
case event_name::HELLO: procces_event<event_name::HELLO>(data);
break;
case event_name::READY: procces_event<event_name::READY>(data);
break;;
case event_name::RESUMED: procces_event<event_name::RESUMED>(data);
break;;
case event_name::INVALID_SESSION: procces_event<event_name::INVALID_SESSION>(data);
break;;
case event_name::CHANNEL_CREATE: procces_event<event_name::CHANNEL_CREATE>(data);
break;;
case event_name::CHANNEL_UPDATE: procces_event<event_name::CHANNEL_UPDATE>(data);
break;;
case event_name::CHANNEL_DELETE: procces_event<event_name::CHANNEL_DELETE>(data);
break;;
case event_name::CHANNEL_PINS_UPDATE: procces_event<event_name::CHANNEL_PINS_UPDATE>(data);
break;;
case event_name::GUILD_CREATE: procces_event<event_name::GUILD_CREATE>(data);
break;;
case event_name::GUILD_UPDATE: procces_event<event_name::GUILD_UPDATE>(data);
break;;
case event_name::GUILD_DELETE: procces_event<event_name::GUILD_DELETE>(data);
break;;
case event_name::GUILD_BAN_ADD: procces_event<event_name::GUILD_BAN_ADD>(data);
break;;
case event_name::GUILD_BAN_REMOVE: procces_event<event_name::GUILD_BAN_REMOVE>(data);
break;;
case event_name::GUILD_EMOJI_UPDATE: procces_event<event_name::GUILD_EMOJI_UPDATE>(data);
break;;
case event_name::GUILD_INTEGRATIONS_UPDATE: procces_event<event_name::GUILD_INTEGRATIONS_UPDATE>(data);
break;;
case event_name::GUILD_MEMBER_ADD: procces_event<event_name::GUILD_MEMBER_ADD>(data);
break;;
case event_name::GUILD_MEMBER_REMOVE: procces_event<event_name::GUILD_MEMBER_REMOVE>(data);
break;;
case event_name::GUILD_MEMBER_UPDATE: procces_event<event_name::GUILD_MEMBER_UPDATE>(data);
break;;
case event_name::GUILD_MEMBERS_CHUNK: procces_event<event_name::GUILD_MEMBERS_CHUNK>(data);
break;;
case event_name::GUILD_ROLE_CREATE: procces_event<event_name::GUILD_ROLE_CREATE>(data);
break;;
case event_name::GUILD_ROLE_UPDATE: procces_event<event_name::GUILD_ROLE_UPDATE>(data);
break;;
case event_name::GUILD_ROLE_DELETE: procces_event<event_name::GUILD_ROLE_DELETE>(data);
break;;
case event_name::MESSAGE_CREATE: procces_event<event_name::MESSAGE_CREATE>(data);
break;;
case event_name::MESSAGE_UPDATE: procces_event<event_name::MESSAGE_UPDATE>(data);
break;;
case event_name::MESSAGE_DELETE: procces_event<event_name::MESSAGE_DELETE>(data);
break;;
case event_name::MESSAGE_DELETE_BULK: procces_event<event_name::MESSAGE_DELETE_BULK>(data);
break;;
case event_name::MESSAGE_REACTION_ADD: procces_event<event_name::MESSAGE_REACTION_ADD>(data);
break;;
case event_name::MESSAGE_REACTION_REMOVE: procces_event<event_name::MESSAGE_REACTION_REMOVE>(data);
break;;
case event_name::MESSAGE_REACTION_REMOVE_ALL: procces_event<event_name::MESSAGE_REACTION_REMOVE_ALL>(data);
break;;
case event_name::PRESENCE_UPDATE: procces_event<event_name::PRESENCE_UPDATE>(data);
break;;
case event_name::TYPING_START: procces_event<event_name::TYPING_START>(data);
break;;
case event_name::USER_UPDATE: procces_event<event_name::USER_UPDATE>(data);
break;;
case event_name::VOICE_STATE_UPDATE: procces_event<event_name::VOICE_STATE_UPDATE>(data);
break;;
case event_name::VOICE_SERVER_UPDATE: procces_event<event_name::VOICE_SERVER_UPDATE>(data);
break;;
case event_name::WEBHOOKS_UPDATE: procces_event<event_name::WEBHOOKS_UPDATE>(data);
break;;
}
} catch (...) {
//swallow
}
}
void internal_shard::m_opcode1_send_heartbeat() const {
if (is_disconnected())
return;
std::string t =
R"({
"op": 1,
"d" : null
})";
m_web_socket->send_thing(std::move(t));
}
void internal_shard::m_opcode2_send_identity() const {
m_send_identity();
}
void internal_shard::m_opcode3_send_presence() const {
nlohmann::json val;
val["op"] = 3;
val["data"] = presence();
m_web_socket->send_thing(val.dump());
}
std::pair<cerwy::eager_task<nlohmann::json>, cerwy::eager_task<std::string>> internal_shard::m_opcode4(snowflake guild_id, snowflake channel_id) {
cerwy::promise<nlohmann::json> name_promise;
cerwy::promise<std::string> session_id_promise;
auto name = name_promise.get_task();
auto session_id_task = session_id_promise.get_task();
m_things_waiting_for_voice_endpoint.insert(std::make_pair(guild_id, std::move(name_promise)));
m_things_waiting_for_voice_endpoint2.insert(std::make_pair(guild_id, std::move(session_id_promise)));
m_web_socket->send_thing(
R"(
{{
"op": 4,
"d": {{
"guild_id": "{}",
"channel_id": "{}",
"self_mute": false,
"self_deaf": false
}}
}}
)"_format(guild_id, channel_id));
return {std::move(name), std::move(session_id_task)};
}
void internal_shard::m_opcode6_send_resume() const {
send_resume();
}
void internal_shard::m_opcode7_reconnect() {
reconnect();
}
void internal_shard::m_opcode8_guild_member_chunk(snowflake id) const {
nlohmann::json s;
s["op"] = 8;
s["d"]["guild_id"] = std::to_string(id.val);
s["d"]["query"] = "";
s["d"]["limit"] = 0;
std::cout << s << std::endl;
m_web_socket->send_thing(s.dump());
}
cerwy::eager_task<void> internal_shard::m_opcode9_on_invalid_session(nlohmann::json d) {
boost::asio::steady_timer timer(strand(), std::chrono::steady_clock::now() + 5s);
auto ec = co_await timer.async_wait(use_task_return_ec);
//co_await resume_on_strand(strand());
if (d.get<bool>())
m_opcode6_send_resume();
else
m_opcode2_send_identity();
/*
std::this_thread::sleep_for(5s);
if (d.get<bool>())
m_opcode6_send_resume();
else
m_opcode2_send_identity();
*/
}
void internal_shard::m_opcode10_on_hello(nlohmann::json& stuff) {
m_heartbeat_context.hb_interval = stuff["heartbeat_interval"].get<int>();
m_heartbeat_context.start();
//m_send_identity();
m_parent_client->queue_to_identify(*this);
}
void internal_shard::m_opcode11(nlohmann::json& data) {
//m_op11 = true;
m_heartbeat_context.recived_ack = true;
}
void internal_shard::reconnect() {
if (!is_disconnected())
close_connection(1001);
//m_parent->reconnect(this, m_shard_number);
//reconnect will happen in init_shard
}
void internal_shard::send_resume() const {
std::string temp(R"({
"op":6,
"d":{
"token":)"s + std::string(m_parent_client->token()) + R"(
"session_id:)"s + m_session_id + R"(
"seq:")" + std::to_string(m_seq_num) + R"(
}
}
)"s);
m_web_socket->send_thing(std::move(temp));
}
void internal_shard::apply_presences(const nlohmann::json& presences, Guild& guild) {
for (const auto& presence : presences) {
const auto id = presence["user"]["id"].get<snowflake>();
const auto& temp = presence["game"];
if (!temp.is_null()) {
guild.activities.insert(std::make_pair(id, std::optional<activity>(temp.get<activity>())));
}
//guild.status[id] = string_to_status(presence["status"].get_ref<const nlohmann::json::string_t&>());
}
}
void internal_shard::replay_events_for(snowflake guild_id) {
auto it = m_backed_up_events.find(guild_id);
if (it != m_backed_up_events.end()) {
auto backed_up_events = std::move(it->second);
m_backed_up_events.erase(it);
for (auto& event : backed_up_events) {
m_opcode0(event.first, event.second, 0);
}
} else {
//???????????
}
}
void internal_shard::m_send_identity() const {
auto identity = fmt::format(R"(
{{
"op":2,
"d":{{
"token":"{}",
"properties":{{
"$os":"{}",
"$browser":"cerwy",
"$device":"cerwy"
}},
"compress":false,
"large_threashold":{},
"shard":[{},{}],
"presence":{},
"intents":{}
}}
}}
)", m_parent_client->token(), std::string_view(s_os), large_threshold, m_shard_number, m_parent_client->num_shards(), presence().dump(), m_intents.int_value());
auto timer = std::make_unique<boost::asio::steady_timer>(m_ioc);
timer->expires_at(m_parent_client->get_time_point_for_identifying());
timer->async_wait([pin = std::move(timer), str = std::move(identity),this](auto ec)mutable {
m_web_socket->send_thing(std::move(str));
});
}
template<>
void internal_shard::procces_event<event_name::READY>(nlohmann::json& event) {
m_trace2 = event["_trace"];
auto me = event["user"].get<user>();
m_session_id = event["session_id"].get<std::string>();
//ignore unavailable guilds, only need size
m_guilds.reserve(event["guilds"].size());
m_id = me.id;
if (m_parent_client->on_ready.has_value()) {
m_parent_client->on_ready.value()(*this);
}
}
template<>
void internal_shard::procces_event<event_name::GUILD_CREATE>(nlohmann::json& data) {
// std::cout << data["id"] << std::endl;
// Guild& guild = m_guilds.insert(std::make_pair(data["id"].get<snowflake>(), data.get<Guild>())).first->second;
// if (m_intents.has_intents(intent::GUILD_MEMBERS) && guild.m_member_count >= large_threshold) {
// guild.m_is_ready = false;
// request_guild_members(guild);
// } else if (m_intents.has_intents(intent::GUILD_MEMBERS)) {
// for (const auto& member_json : data["members"]) {
// auto member = member_json.get<guild_member>();
// member.m_guild = &guild;
// const auto id = member.id();
// guild.m_members.insert(std::make_pair(id, std::move(member)));
// }
// }
//
// const auto channels = data["channels"].get_ref<const nlohmann::json::array_t&>();
// guild.m_text_channel_ids.reserve(channels.size());
// guild.m_voice_channel_ids.reserve(std::max(3ull, channels.size() / 10));//random numbers
//
// for (const auto& channel_json : channels) {
// if (const auto type = channel_json["type"].get<int>(); type == 0 || type == 5 || type == 6) {//text
// auto& channel = m_text_channel_map.insert(std::make_pair(channel_json["id"].get<snowflake>(), channel_json.get<text_channel>())).first->second;
// channel.m_guild_id = guild.id();
// guild.m_text_channel_ids.push_back(channel.id());
// channel.m_guild = &guild;
// if (type == 5) {
// channel.m_channel_type = text_channel_type::news;
// }
//
// if (type == 6) {
// channel.m_channel_type = text_channel_type::store;
// }
// } else if (type == 2) {//voice
// auto& channel = m_voice_channel_map.insert(std::make_pair(channel_json["id"].get<snowflake>(), channel_json.get<voice_channel>())).first->second;
// channel.m_guild_id = guild.id();
// guild.m_voice_channel_ids.push_back(channel.id());
// channel.m_guild = &guild;
// } else if (type == 4) {//guild catagory
// auto& channel = m_channel_catagory_map.insert(std::make_pair(channel_json["id"].get<snowflake>(), channel_json.get<channel_catagory>())).first->second;
// channel.m_guild_id = guild.id();
// guild.m_channel_catagory_ids.push_back(channel.id());
// channel.m_guild = &guild;
// } else {
// //unimplemented channel
// }
//
// //type == 1,3 is missing since it's DM channel, dm channels don't exist in guild channels
// }
//
// for (auto& channel : guild.m_text_channel_ids |
// ranges::views::transform(hof::map_with(m_text_channel_map)) |
// ranges::views::filter(&text_channel::has_parent)) {
// channel.m_parent = &m_channel_catagory_map[channel.m_parent_id];
// }
//
// for (const auto& channel_id : guild.m_voice_channel_ids) {
// auto& channel = m_voice_channel_map[channel_id];
// if (channel.m_parent_id.val)
// channel.m_parent = &m_channel_catagory_map[channel.m_parent_id];
// }
//
// if (m_intents.has_intents(intent::GUILD_PRESENCES)) {
// if (guild.m_is_ready) {
// apply_presences(data["presences"], guild);
// } else {
// guild.m_presences = std::move(data["presences"]);//save it for later
// }
// }
// guild.m_shard = this;
// if (guild.m_is_ready) {
// m_parent->on_guild_ready(guild, *this);
// }
auto guild = data.get<Guild>();
events::guild_create event;
event.guild = std::move(guild);
//m_parent->on_guild_ready(std::move(guild), *this);
if(m_parent_client->on_guild_ready.has_value()) {
m_parent_client->on_guild_ready.value()(std::move(event), *this);
}
}
template<>
void internal_shard::procces_event<event_name::GUILD_MEMBERS_CHUNK>(nlohmann::json& e) {
//m_parent->on_guild_member_chunk( guild_id, std::move(members), chunk_count, chunk_index, *this);
events::guild_members_chunk event;
event.members = e["members"].get<std::vector<guild_member>>();
event.chunk_count = e["chunk_count"].get<int>();
e["chunk_index"].get_to(event.chunk_index);
e["guild_id"].get_to(event.guild_id);
e["presences"].get_to(event.presences);
}
template<>
void internal_shard::procces_event<event_name::MESSAGE_CREATE>(nlohmann::json& e) {
const bool is_guild_msg = e.contains("guild_id");
if (is_guild_msg) {
events::guild_message_create event;
event.msg = create_msg<guild_text_message>(e);
if (m_parent_client->on_guild_text_msg.has_value()) {
m_parent_client->on_guild_text_msg.value()(std::move(event), *this);
}
} else {//dm msg
events::dm_message_create event;
event.msg = create_msg<dm_message>(e);
if (m_parent_client->on_dm_msg.has_value()) {
m_parent_client->on_dm_msg.value()(std::move(event), *this);
}
}
}
template<>
void internal_shard::procces_event<event_name::CHANNEL_CREATE>(nlohmann::json& channel_json) {
const auto type = channel_json["type"].get<int>();
if (type == 0 || type == 5 || type == 6) {//text
events::text_channel_create event;
auto& channel = event.channel = channel_json.get<text_channel>();// guild.text_channels.insert(std::make_pair(channel_json["id"].get<snowflake>(), )).first->second;
if (type == 5) {
channel.channel_type = text_channel_type::news;
}
if (type == 6) {
channel.channel_type = text_channel_type::store;
}
if (m_parent_client->on_guild_text_channel_create.has_value()) {
m_parent_client->on_guild_text_channel_create.value()(std::move(event), *this);
}
} else if (type == 1 || type == 3) {//DM
if (m_parent_client->on_dm_channel_create.has_value()) {
m_parent_client->on_dm_channel_create.value()({ channel_json.get<dm_channel>() }, *this);
}
} else if (type == 2) {//voice
if (m_parent_client->on_guild_voice_channel_create.has_value()) {
m_parent_client->on_guild_voice_channel_create.value()({ channel_json.get<voice_channel>() }, *this);
}
} else if (type == 4) {//guild catagory
if (m_parent_client->on_guild_channel_catagory_create.has_value()) {
m_parent_client->on_guild_channel_catagory_create.value()({ channel_json.get<channel_catagory>() }, *this);
}
} else {
//unimplemented channel
}
}
template<>
void internal_shard::procces_event<event_name::CHANNEL_DELETE>(nlohmann::json& e) {
const auto type = e["type"].get<int>();
if (type == 0 || type == 5 || type == 6) {//text
events::text_channel_delete event;
auto& channel = event.channel = e.get<text_channel>();// guild.text_channels.insert(std::make_pair(channel_json["id"].get<snowflake>(), )).first->second;
if (type == 5) {
channel.channel_type = text_channel_type::news;
}
if (type == 6) {
channel.channel_type = text_channel_type::store;
}
if (m_parent_client->on_guild_text_channel_delete.has_value()) {
m_parent_client->on_guild_text_channel_delete.value()(std::move(event), *this);
}
} else if (type == 1 || type == 3) {//DM
events::dm_channel_delete event;
event.channel = e.get<dm_channel>();
if (m_parent_client->on_dm_channel_delete.has_value()) {
m_parent_client->on_dm_channel_delete.value()(std::move(event), *this);
}
} else if (type == 2) {//voice
events::voice_channel_delete event;
event.channel = e.get<voice_channel>();
if (m_parent_client->on_guild_voice_channel_delete.has_value()) {
m_parent_client->on_guild_voice_channel_delete.value()(std::move(event), *this);
}
} else if (type == 4) {//guild catagory
events::channel_catagory_delete event;
event.channel = e.get<channel_catagory>();
if (m_parent_client->on_guild_channel_catagory_delete.has_value()) {
m_parent_client->on_guild_channel_catagory_delete.value()(std::move(event), *this);
}
} else {
//unimplemented channel
}
}
template<>
void internal_shard::procces_event<event_name::GUILD_MEMBER_ADD>(nlohmann::json& e) {
events::guild_member_add event;
event.guild_id = e["guild_id"].get<snowflake>();
event.member = e.get<guild_member>();
if (m_parent_client->on_guild_member_add.has_value()) {
m_parent_client->on_guild_member_add.value()(std::move(event), *this);
}
}
template<>
void internal_shard::procces_event<event_name::GUILD_MEMBER_REMOVE>(nlohmann::json& e) {
events::guild_member_remove event;
event.guild_id = e["guild_id"].get<snowflake>();
event.member = e["user"].get<user>();
if (m_parent_client->on_guild_member_remove.has_value()) {
m_parent_client->on_guild_member_remove.value()(std::move(event), *this);
}
}
template<>
void internal_shard::procces_event<event_name::RESUMED>(nlohmann::json& e) {
m_trace = e["_trace"].get<std::vector<std::string>>();
};
template<>
void internal_shard::procces_event<event_name::HELLO>(nlohmann::json& json) {
m_trace = json.at("_trace").get<std::vector<std::string>>();
m_heartbeat_context.hb_interval = json["heartbeat_interval"].get<int>();
};
template<>
void internal_shard::procces_event<event_name::INVALID_SESSION>(nlohmann::json&) { };
template<>
void internal_shard::procces_event<event_name::CHANNEL_UPDATE>(nlohmann::json& e) {
const auto type = e["type"].get<int>();
if (type == 0 || type == 5 || type == 6) {//text
events::text_channel_update event;
auto& channel = event.channel = e.get<text_channel>();// guild.text_channels.insert(std::make_pair(channel_json["id"].get<snowflake>(), )).first->second;
if (type == 5) {
channel.channel_type = text_channel_type::news;
}
if (type == 6) {
channel.channel_type = text_channel_type::store;
}
if (m_parent_client->on_guild_text_channel_update.has_value()) {
m_parent_client->on_guild_text_channel_update.value()(std::move(event), *this);
}
} else if (type == 1 || type == 3) {//DM
if (m_parent_client->on_dm_channel_update.has_value()) {
events::dm_channel_update event;
event.channel = e.get<dm_channel>();
m_parent_client->on_dm_channel_update.value()(std::move(event), *this);
}
} else if (type == 2) {//voice
events::voice_channel_update event;
event.channel = e.get<voice_channel>();
if (m_parent_client->on_guild_voice_channel_update.has_value()) {
m_parent_client->on_guild_voice_channel_update.value()(std::move(event), *this);
}
} else if (type == 4) {//guild catagory
events::channel_catagory_update event;
event.channel = e.get<channel_catagory>();
if (m_parent_client->on_guild_channel_catagory_update.has_value()) {
m_parent_client->on_guild_channel_catagory_update.value()(std::move(event), *this);
}
} else {
//unimplemented channel
}
}
template<>
void internal_shard::procces_event<event_name::CHANNEL_PINS_UPDATE>(nlohmann::json& e) {};
template<>
void internal_shard::procces_event<event_name::GUILD_UPDATE>(nlohmann::json& e) {
const auto guild_id = e["id"].get<snowflake>();
auto guild = e.get<partial_guild>();
//m_parent->on_guild_update(g, *this);
};
template<>
void internal_shard::procces_event<event_name::GUILD_DELETE>(nlohmann::json& e) {
try {
events::guild_delete event;
event.guild = e.get<unavailable_guild>();
if (m_parent_client->on_guild_remove.has_value()) {
m_parent_client->on_guild_remove.value()(event, *this);
}
} catch (...) {
//swallow
}
}
template<>
void internal_shard::procces_event<event_name::GUILD_BAN_ADD>(nlohmann::json& e) {
events::guild_ban_add event;
event.user = e.get<user>();
event.guild_id = e["guild_id"].get<snowflake>();
if (m_parent_client->on_ban_add.has_value()) {
m_parent_client->on_ban_add.value()(std::move(event), *this);
}
};
template<>
void internal_shard::procces_event<event_name::GUILD_BAN_REMOVE>(nlohmann::json& e) {
events::guild_ban_remove event;
event.user = e.get<user>();
event.guild_id = e["guild_id"].get<snowflake>();
if (m_parent_client->on_ban_remove.has_value()) {
m_parent_client->on_ban_remove.value()(std::move(event), *this);
}
}
template<>
void internal_shard::procces_event<event_name::GUILD_EMOJI_UPDATE>(nlohmann::json& e) {
events::guild_emoji_update event;
event.guild_id = e["guild_id"].get<snowflake>();
event.emojis = e["emojis"].get<std::vector<emoji>>();
if (m_parent_client->on_emoji_update.has_value()) {
m_parent_client->on_emoji_update.value()(std::move(event), *this);
}
};
template<>
void internal_shard::procces_event<event_name::GUILD_INTEGRATIONS_UPDATE>(nlohmann::json& e) {
//what is this ;-;
//only has 1 field: id
//wat
events::guild_integration_update event;
event.guild_id = e["id"].get<snowflake>();
};
template<>
void internal_shard::procces_event<event_name::GUILD_MEMBER_UPDATE>(nlohmann::json& e) {
events::guild_member_update event;
event.guild_id = e["guild_id"].get<snowflake>();
event.user = e["user"].get<cacheless::user>();
event.roles = e["roles"].get<std::vector<guild_role>>();
if (e.contains("nick")) {
event.nick = e["nick"].get<std::string>();
}
if (m_parent_client->on_guild_member_update.has_value()) {
m_parent_client->on_guild_member_update.value()(std::move(event), *this);
}
};
template<>
void internal_shard::procces_event<event_name::GUILD_ROLE_CREATE>(nlohmann::json& e) {
events::guild_role_create event;
event.guild_id = e["guild_id"].get<snowflake>();
event.role = e["role"].get<guild_role>();
if (m_parent_client->on_role_create.has_value()) {
m_parent_client->on_role_create.value()(std::move(event), *this);
}
//m_parent->on_role_create(guild, guild.m_roles.insert(std::make_pair(e["role"]["id"].get<snowflake>(), )).first->second, *this);
//m_parent->on_role_create(guild_id, std::move(new_role),*this);
};
template<>
void internal_shard::procces_event<event_name::GUILD_ROLE_UPDATE>(nlohmann::json& e) {
events::guild_role_update event;
event.guild_id = e["guild_id"].get<snowflake>();
event.role = e["role"].get<guild_role>();
if (m_parent_client->on_role_update.has_value())
m_parent_client->on_role_update.value()(std::move(event), *this);
};
template<>
void internal_shard::procces_event<event_name::GUILD_ROLE_DELETE>(nlohmann::json& e) {
events::guild_role_delete event;
event.guild_id = e["guild_id"].get<snowflake>();
event.role_id = e["role_id"].get<snowflake>();
if (m_parent_client->on_role_delete.has_value()) {
m_parent_client->on_role_delete.value()(event, *this);
}
};
template<>
void internal_shard::procces_event<event_name::MESSAGE_UPDATE>(nlohmann::json& e) {
const bool is_guild_msg = e.contains("guild_id");
if (is_guild_msg) {
auto msg = createMsgUpdate<guild_msg_update>(e);
//m_parent->on_guild_msg_update(e["guild_id"].get<snowflake>(),std::move(msg), *this);
} else {//dm msg
auto msg = createMsgUpdate<dm_msg_update>(e);
//m_parent->on_dm_msg_update(std::move(msg), *this);
}
}
template<>
void internal_shard::procces_event<event_name::MESSAGE_DELETE>(nlohmann::json& e) {
const auto id = e["id"].get<snowflake>();
const auto channel_id = e["channel_id"].get<snowflake>();
auto guild_id = e.value("guild_id", snowflake());
if (guild_id != snowflake()) {
events::guild_message_delete event;
event.id = id;
event.guild_id = guild_id;
event.channel_id = channel_id;
if (m_parent_client->on_guild_msg_delete.has_value()) {
m_parent_client->on_guild_msg_delete.value()(event, *this);
}
} else {
events::dm_message_delete event;
event.id = id;
event.channel_id = channel_id;
if (m_parent_client->on_dm_msg_delete.has_value()) {
m_parent_client->on_dm_msg_delete.value()(event, *this);
}
}
};
template<>
void internal_shard::procces_event<event_name::MESSAGE_DELETE_BULK>(nlohmann::json& e) {
auto msg_ids = e["ids"].get<std::vector<snowflake>>();
const auto channel_id = e["channel_id"].get<snowflake>();
const auto guild_id = e.value("guild_id", snowflake());
if (guild_id != snowflake()) {
events::guild_message_delete_bulk event;
event.ids = std::move(msg_ids);
event.channel_id = channel_id;
event.guild_id = guild_id;
if (m_parent_client->on_message_bulk_delete.has_value()) {
m_parent_client->on_message_bulk_delete.value()(std::move(event), *this);
}
} else {
events::dm_message_delete_bulk event;
event.ids = std::move(msg_ids);
event.channel_id = channel_id;
if (m_parent_client->on_dm_message_bulk_delete.has_value()) {
m_parent_client->on_dm_message_bulk_delete.value()(std::move(event), *this);
}
}
};
template<>
void internal_shard::procces_event<event_name::MESSAGE_REACTION_ADD>(nlohmann::json& e) {
const auto channel_id = e["channel_id"].get<snowflake>();
auto emoji = e["emoji"].get<partial_emoji>();
const snowflake guild_id = e.value("guild_id", snowflake());
const auto message_id = e["message_id"].get<snowflake>();
if (guild_id != snowflake()) {
events::guild_message_reaction_add event;
event.channel_id = channel_id;
event.emoji = std::move(emoji);
event.guild_id = guild_id;
event.message_id = message_id;
event.member = e["member"].get<guild_member>();
if (m_parent_client->on_guild_reaction_add.has_value()) {
m_parent_client->on_guild_reaction_add.value()(std::move(event), *this);
}
} else {
events::dm_message_reaction_add event;
event.channel_id = channel_id;
event.emoji = std::move(emoji);
event.message_id = message_id;
event.user_id = e["user_id"].get<snowflake>();
if (m_parent_client->on_dm_reaction_add.has_value()) {
m_parent_client->on_dm_reaction_add.value()(std::move(event), *this);;
}
}
};
template<>
void internal_shard::procces_event<event_name::MESSAGE_REACTION_REMOVE>(nlohmann::json& e) {
const auto channel_id = e["channel_id"].get<snowflake>();
auto emojiy = e["emoji"].get<partial_emoji>();
const bool is_guild = e.contains("guild_id");
const auto message_id = e["message_id"].get<snowflake>();
if (is_guild) {
events::guild_message_reaction_remove event;
event.channel_id = channel_id;
event.emoji = std::move(emojiy);
event.user_id = e["user_id"].get<snowflake>();
event.message_id = message_id;
event.guild_id = e["guild_id"].get<snowflake>();
if (m_parent_client->on_guild_reaction_remove.has_value()) {
m_parent_client->on_guild_reaction_remove.value()(std::move(event), *this);
}
} else {
events::dm_message_reaction_remove event;
event.channel_id = channel_id;
event.emoji = std::move(emojiy);
event.message_id = message_id;
event.user_id = e["user_id"].get<snowflake>();
if (m_parent_client->on_dm_reaction_remove.has_value()) {
m_parent_client->on_dm_reaction_remove.value()(std::move(event), *this);
}
}
};
template<>
void internal_shard::procces_event<event_name::MESSAGE_REACTION_REMOVE_ALL>(nlohmann::json& e) {
const auto channel_id = e["channel_id"].get<snowflake>();
const auto message_id = e["message_id"].get<snowflake>();
const auto guild_id = e.value("guild_id", snowflake());
if (guild_id.val != 0) {
events::guild_message_reaction_remove_all event;
event.channel_id = channel_id;
event.message_id = message_id;
event.guild_id = guild_id;
if (m_parent_client->on_guild_reaction_remove_all.has_value()) {
m_parent_client->on_guild_reaction_remove_all.value()(event, *this);
}
} else {
events::dm_message_reaction_remove_all event;
event.channel_id = channel_id;
event.message_id = message_id;
if (m_parent_client->on_dm_reaction_remove_all.has_value()) {
m_parent_client->on_dm_reaction_remove_all.value()(event, *this);
}
}
};
template<>
void internal_shard::procces_event<event_name::PRESENCE_UPDATE>(nlohmann::json& e) {
auto update_event = e.get<events::presence_update_event>();
if (m_parent_client->on_presence_update.has_value())
m_parent_client->on_presence_update.value()(std::move(update_event), *this);
};
template<>
void internal_shard::procces_event<event_name::TYPING_START>(nlohmann::json& e) {
const auto channel_id = e["channel_id"].get<snowflake>();
const auto guild_id = e.value("guild_id", snowflake());
if (guild_id != snowflake()) {
events::guild_typing_start event;
event.channel_id = channel_id;
event.guild_id = guild_id;
event.member = e["member"].get<guild_member>();
if (m_parent_client->on_guild_typing_start.has_value()) {
m_parent_client->on_guild_typing_start.value()(std::move(event), *this);
}
} else {
events::dm_typing_start event;
event.user_id = e["user_id"].get<snowflake>();
event.channel_id = channel_id;
if (m_parent_client->on_dm_typing_start.has_value()) {
m_parent_client->on_dm_typing_start.value()(event, *this);
}
}
};
template<>
void internal_shard::procces_event<event_name::USER_UPDATE>(nlohmann::json& e) {
//m_self_user = e.get<user>();
};
template<>
void internal_shard::procces_event<event_name::VOICE_STATE_UPDATE>(nlohmann::json& e) {
const auto guild_id = e.value("guild_id", snowflake());
//Guild& guild = guild_id.val ? m_guilds[guild_id] : *m_voice_channel_map[e["channel_id"].get<snowflake>()].m_guild;
const auto user_id = e.value("user_id", id());
auto voice_state = e.get<cacheless::voice_state>();
if (user_id == this->id()) {
auto it = m_things_waiting_for_voice_endpoint2.find(guild_id);
if (it != m_things_waiting_for_voice_endpoint2.end()) {
it->second.set_value(e["session_id"].get<std::string>());
}
}
};
template<>
void internal_shard::procces_event<event_name::VOICE_SERVER_UPDATE>(nlohmann::json& json) {
const auto guild_id = json["guild_id"].get<snowflake>();
m_things_waiting_for_voice_endpoint[guild_id].set_value(std::move(json));
};
template<>
void internal_shard::procces_event<event_name::WEBHOOKS_UPDATE>(nlohmann::json&) { }
// ReSharper disable once CppMemberFunctionMayBeConst
void internal_shard::update_presence(const Status s, std::string g) {// NOLINT
m_status = s;
m_game_name = std::move(g);
m_opcode3_send_presence();
}
}
| 33.2595
| 166
| 0.717446
|
cerww
|
958ad92cca60746a5b466640c465f2612f4acb48
| 1,034
|
cc
|
C++
|
src/scc/driver/standalone.cc
|
origamicomet/scc
|
2dc87e84289a1c5d1dd3f7159568c4472b4c977b
|
[
"CC0-1.0"
] | 5
|
2017-08-05T13:02:55.000Z
|
2022-02-12T03:02:44.000Z
|
src/scc/driver/standalone.cc
|
origamicomet/scc
|
2dc87e84289a1c5d1dd3f7159568c4472b4c977b
|
[
"CC0-1.0"
] | null | null | null |
src/scc/driver/standalone.cc
|
origamicomet/scc
|
2dc87e84289a1c5d1dd3f7159568c4472b4c977b
|
[
"CC0-1.0"
] | null | null | null |
//===-- scc/driver/standalone.cc ------------------------*- mode: C++11 -*-===//
//
// _____ _____ _____
// | __| | |
// |__ | --| --|
// |_____|_____|_____|
//
// Shader Cross Compiler
//
// This file is distributed under the terms described in LICENSE.
//
//===----------------------------------------------------------------------===//
#if defined(__SCC_IS_STANDALONE__)
#include <stdlib.h>
#include <stdio.h>
#include "scc.h"
SCC_BEGIN_EXTERN_C
int main(unsigned argc, const char *argv[]) {
// Parse arugments.
// Handle response files.
// Default to STDIN and STDOUT.
// Setup driver.
// Compile!
const char *path = "tests/basic_vertex_shader.ir";
scc_feed_t *feed = scc_feed_from_path(path);
scc_ir_parse_options_t parse_options;
scc_ir_parse(feed, &parse_options);
return EXIT_SUCCESS;
}
SCC_END_EXTERN_C
#endif
| 24.619048
| 80
| 0.48646
|
origamicomet
|
958fc3c093f3e34447a34a29d877f463737ee61a
| 62
|
cpp
|
C++
|
doc/figures.cpp
|
Xbeas/jitana
|
fc33976cf6f4cbb91263a06bae32e9ad07fc5551
|
[
"0BSD"
] | 31
|
2017-04-21T03:25:46.000Z
|
2022-02-20T20:59:23.000Z
|
doc/figures.cpp
|
Xbeas/jitana
|
fc33976cf6f4cbb91263a06bae32e9ad07fc5551
|
[
"0BSD"
] | 3
|
2020-12-21T09:02:06.000Z
|
2021-03-16T10:37:38.000Z
|
doc/figures.cpp
|
Xbeas/jitana
|
fc33976cf6f4cbb91263a06bae32e9ad07fc5551
|
[
"0BSD"
] | 9
|
2017-06-06T19:30:43.000Z
|
2021-05-19T19:50:03.000Z
|
/// @page figures Figures
/// @dotfile design.dot The design.
| 20.666667
| 35
| 0.693548
|
Xbeas
|
d2e62d9ef2a4df7ed8884c6a24302f6563be7d6b
| 8,088
|
hpp
|
C++
|
Neon Client/SDK/FN_BP_Hex_PARENT_parameters.hpp
|
Neon-FN/Neon-Client
|
9f6f62943db896021cc6bf48265169e710fa92d3
|
[
"BSD-3-Clause"
] | null | null | null |
Neon Client/SDK/FN_BP_Hex_PARENT_parameters.hpp
|
Neon-FN/Neon-Client
|
9f6f62943db896021cc6bf48265169e710fa92d3
|
[
"BSD-3-Clause"
] | null | null | null |
Neon Client/SDK/FN_BP_Hex_PARENT_parameters.hpp
|
Neon-FN/Neon-Client
|
9f6f62943db896021cc6bf48265169e710fa92d3
|
[
"BSD-3-Clause"
] | null | null | null |
#pragma once
// Fortnite (1.8) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "../SDK.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Parameters
//---------------------------------------------------------------------------
// Function BP_Hex_PARENT.BP_Hex_PARENT_C.HandleUpdatingBannerMesh
struct ABP_Hex_PARENT_C_HandleUpdatingBannerMesh_Params
{
class USceneComponent* Target; // (Parm, ZeroConstructor, IsPlainOldData)
class UFortQuestItemDefinition* CompletedQuest; // (ConstParm, Parm, ZeroConstructor, IsPlainOldData)
class UMaterialInstanceDynamic* Material_Instance_Dynamic; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function BP_Hex_PARENT.BP_Hex_PARENT_C.HandleMissionAlert
struct ABP_Hex_PARENT_C_HandleMissionAlert_Params
{
};
// Function BP_Hex_PARENT.BP_Hex_PARENT_C.GroundSliceSettings
struct ABP_Hex_PARENT_C_GroundSliceSettings_Params
{
class UMaterialInstanceDynamic* SourceMaterial; // (Parm, ZeroConstructor, IsPlainOldData)
class UTexture2D* TileTypeA; // (Parm, ZeroConstructor, IsPlainOldData)
class UTexture2D* TileTypeB; // (Parm, ZeroConstructor, IsPlainOldData)
float TileIsSameRegionA; // (Parm, ZeroConstructor, IsPlainOldData)
float TileIsSameRegionB; // (Parm, ZeroConstructor, IsPlainOldData)
float TileIsHiddenA; // (Parm, ZeroConstructor, IsPlainOldData)
float TileIsHiddenB; // (Parm, ZeroConstructor, IsPlainOldData)
float TileExistsA; // (Parm, ZeroConstructor, IsPlainOldData)
float TileExistsB; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function BP_Hex_PARENT.BP_Hex_PARENT_C.UserConstructionScript
struct ABP_Hex_PARENT_C_UserConstructionScript_Params
{
};
// Function BP_Hex_PARENT.BP_Hex_PARENT_C.Timeline_11__FinishedFunc
struct ABP_Hex_PARENT_C_Timeline_11__FinishedFunc_Params
{
};
// Function BP_Hex_PARENT.BP_Hex_PARENT_C.Timeline_11__UpdateFunc
struct ABP_Hex_PARENT_C_Timeline_11__UpdateFunc_Params
{
};
// Function BP_Hex_PARENT.BP_Hex_PARENT_C.Timeline_12__FinishedFunc
struct ABP_Hex_PARENT_C_Timeline_12__FinishedFunc_Params
{
};
// Function BP_Hex_PARENT.BP_Hex_PARENT_C.Timeline_12__UpdateFunc
struct ABP_Hex_PARENT_C_Timeline_12__UpdateFunc_Params
{
};
// Function BP_Hex_PARENT.BP_Hex_PARENT_C.HandleTeamPowerChanged
struct ABP_Hex_PARENT_C_HandleTeamPowerChanged_Params
{
int TeamPower; // (Parm, ZeroConstructor, IsPlainOldData)
int PersonalPower; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function BP_Hex_PARENT.BP_Hex_PARENT_C.FireLightningA
struct ABP_Hex_PARENT_C_FireLightningA_Params
{
};
// Function BP_Hex_PARENT.BP_Hex_PARENT_C.OnInitializeTile
struct ABP_Hex_PARENT_C_OnInitializeTile_Params
{
};
// Function BP_Hex_PARENT.BP_Hex_PARENT_C.HandleFrontendCameraChanged
struct ABP_Hex_PARENT_C_HandleFrontendCameraChanged_Params
{
EFrontEndCamera NewCamera; // (Parm, ZeroConstructor, IsPlainOldData)
EFrontEndCamera OldCamera; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function BP_Hex_PARENT.BP_Hex_PARENT_C.OnMarkedQuestChanged
struct ABP_Hex_PARENT_C_OnMarkedQuestChanged_Params
{
};
// Function BP_Hex_PARENT.BP_Hex_PARENT_C.CheckIfQuestShouldBePinned
struct ABP_Hex_PARENT_C_CheckIfQuestShouldBePinned_Params
{
};
// Function BP_Hex_PARENT.BP_Hex_PARENT_C.CheckFocus
struct ABP_Hex_PARENT_C_CheckFocus_Params
{
};
// Function BP_Hex_PARENT.BP_Hex_PARENT_C.ForceDefocus
struct ABP_Hex_PARENT_C_ForceDefocus_Params
{
};
// Function BP_Hex_PARENT.BP_Hex_PARENT_C.OnMissionDataUpdated
struct ABP_Hex_PARENT_C_OnMissionDataUpdated_Params
{
};
// Function BP_Hex_PARENT.BP_Hex_PARENT_C.CheckForPinnedInLevel
struct ABP_Hex_PARENT_C_CheckForPinnedInLevel_Params
{
};
// Function BP_Hex_PARENT.BP_Hex_PARENT_C.OnDefocus
struct ABP_Hex_PARENT_C_OnDefocus_Params
{
};
// Function BP_Hex_PARENT.BP_Hex_PARENT_C.RetryTileInitialized
struct ABP_Hex_PARENT_C_RetryTileInitialized_Params
{
};
// Function BP_Hex_PARENT.BP_Hex_PARENT_C.RetryUpdatesPaused
struct ABP_Hex_PARENT_C_RetryUpdatesPaused_Params
{
};
// Function BP_Hex_PARENT.BP_Hex_PARENT_C.OnFocus
struct ABP_Hex_PARENT_C_OnFocus_Params
{
};
// Function BP_Hex_PARENT.BP_Hex_PARENT_C.OnHostDeselect
struct ABP_Hex_PARENT_C_OnHostDeselect_Params
{
};
// Function BP_Hex_PARENT.BP_Hex_PARENT_C.OnHostSelect
struct ABP_Hex_PARENT_C_OnHostSelect_Params
{
};
// Function BP_Hex_PARENT.BP_Hex_PARENT_C.SetMissionPowerLevelDependencies
struct ABP_Hex_PARENT_C_SetMissionPowerLevelDependencies_Params
{
};
// Function BP_Hex_PARENT.BP_Hex_PARENT_C.OnClientDeselect
struct ABP_Hex_PARENT_C_OnClientDeselect_Params
{
};
// Function BP_Hex_PARENT.BP_Hex_PARENT_C.OnClientSelect
struct ABP_Hex_PARENT_C_OnClientSelect_Params
{
};
// Function BP_Hex_PARENT.BP_Hex_PARENT_C.ReceiveBeginPlay
struct ABP_Hex_PARENT_C_ReceiveBeginPlay_Params
{
};
// Function BP_Hex_PARENT.BP_Hex_PARENT_C.MissionLightning
struct ABP_Hex_PARENT_C_MissionLightning_Params
{
struct FName EventName; // (Parm, ZeroConstructor, IsPlainOldData)
float EmitterTime; // (Parm, ZeroConstructor, IsPlainOldData)
struct FVector Location; // (Parm, IsPlainOldData)
struct FVector Velocity; // (Parm, IsPlainOldData)
};
// Function BP_Hex_PARENT.BP_Hex_PARENT_C.MissionLightningOff
struct ABP_Hex_PARENT_C_MissionLightningOff_Params
{
struct FName EventName; // (Parm, ZeroConstructor, IsPlainOldData)
float EmitterTime; // (Parm, ZeroConstructor, IsPlainOldData)
int ParticleTime; // (Parm, ZeroConstructor, IsPlainOldData)
struct FVector Location; // (Parm, IsPlainOldData)
struct FVector Velocity; // (Parm, IsPlainOldData)
struct FVector Direction; // (Parm, IsPlainOldData)
};
// Function BP_Hex_PARENT.BP_Hex_PARENT_C.ExecuteUbergraph_BP_Hex_PARENT
struct ABP_Hex_PARENT_C_ExecuteUbergraph_BP_Hex_PARENT_Params
{
int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 39.647059
| 163
| 0.59137
|
Neon-FN
|
d2ee55761df3452540e90858569ebf7d529a0812
| 1,848
|
hpp
|
C++
|
include/Pomdog/Signals/Signal.hpp
|
ValtoForks/pomdog
|
73798ae5f4a4c3b9b1e1e96239187c4b842c93b2
|
[
"MIT"
] | null | null | null |
include/Pomdog/Signals/Signal.hpp
|
ValtoForks/pomdog
|
73798ae5f4a4c3b9b1e1e96239187c4b842c93b2
|
[
"MIT"
] | null | null | null |
include/Pomdog/Signals/Signal.hpp
|
ValtoForks/pomdog
|
73798ae5f4a4c3b9b1e1e96239187c4b842c93b2
|
[
"MIT"
] | null | null | null |
// Copyright (c) 2013-2018 mogemimi. Distributed under the MIT license.
#pragma once
#include "Pomdog/Basic/Export.hpp"
#include "Pomdog/Signals/Connection.hpp"
#include "Pomdog/Signals/detail/SignalBody.hpp"
#include <functional>
#include <memory>
#include <utility>
namespace Pomdog {
template <typename... Arguments>
class POMDOG_EXPORT Signal<void(Arguments...)> final {
public:
Signal();
Signal(const Signal&) = delete;
Signal(Signal&&) = default;
Signal& operator=(const Signal&) = delete;
Signal& operator=(Signal&&) = default;
Connection Connect(const std::function<void(Arguments...)>& slot);
Connection Connect(std::function<void(Arguments...)>&& slot);
void operator()(Arguments... arguments);
std::size_t InvocationCount() const;
private:
typedef Detail::Signals::SignalBody<void(Arguments...)> SignalBody;
std::shared_ptr<SignalBody> body;
};
template <typename... Arguments>
Signal<void(Arguments...)>::Signal()
: body(std::make_shared<SignalBody>())
{
}
template <typename... Arguments>
Connection Signal<void(Arguments...)>::Connect(
const std::function<void(Arguments...)>& slot)
{
POMDOG_ASSERT(slot);
POMDOG_ASSERT(body);
return Connection{body->Connect(slot)};
}
template <typename... Arguments>
Connection Signal<void(Arguments...)>::Connect(
std::function<void(Arguments...)>&& slot)
{
POMDOG_ASSERT(slot);
POMDOG_ASSERT(body);
return Connection{body->Connect(std::move(slot))};
}
template <typename... Arguments>
void Signal<void(Arguments...)>::operator()(Arguments... arguments)
{
POMDOG_ASSERT(body);
body->operator()(std::forward<Arguments>(arguments)...);
}
template <typename... Arguments>
std::size_t Signal<void(Arguments...)>::InvocationCount() const
{
return body->InvocationCount();
}
} // namespace Pomdog
| 24.972973
| 71
| 0.695346
|
ValtoForks
|
d2f0dc52af1a6e750f1dd619a68210303c4483d7
| 423
|
hpp
|
C++
|
src/CodeLine.hpp
|
natiiix/rush
|
bd7e5d8bba696ca6dbea24ac6c7a2597ba4b51da
|
[
"MIT"
] | 2
|
2018-04-28T14:50:56.000Z
|
2018-05-14T17:39:22.000Z
|
src/CodeLine.hpp
|
natiiix/rush
|
bd7e5d8bba696ca6dbea24ac6c7a2597ba4b51da
|
[
"MIT"
] | null | null | null |
src/CodeLine.hpp
|
natiiix/rush
|
bd7e5d8bba696ca6dbea24ac6c7a2597ba4b51da
|
[
"MIT"
] | null | null | null |
#pragma once
#include <string>
struct CodeLine
{
public:
CodeLine(const std::string origin, const int number, const std::string code, const int indentation);
// Source file
const std::string origin;
// Line number in source file
const int number;
// Code on the line (without leading and trailing whitespace)
const std::string code;
// Number of leading whitespace characters
const int indentation;
};
| 22.263158
| 102
| 0.728132
|
natiiix
|
d2f3c9845b739c0a24fbbb36f442cd034d779f14
| 372
|
hpp
|
C++
|
pythran/pythonic/operator_/irshift.hpp
|
artas360/pythran
|
66dad52d52be71693043e9a7d7578cfb9cb3d1da
|
[
"BSD-3-Clause"
] | null | null | null |
pythran/pythonic/operator_/irshift.hpp
|
artas360/pythran
|
66dad52d52be71693043e9a7d7578cfb9cb3d1da
|
[
"BSD-3-Clause"
] | null | null | null |
pythran/pythonic/operator_/irshift.hpp
|
artas360/pythran
|
66dad52d52be71693043e9a7d7578cfb9cb3d1da
|
[
"BSD-3-Clause"
] | null | null | null |
#ifndef PYTHONIC_OPERATOR_IRSHIFT_HPP
#define PYTHONIC_OPERATOR_IRSHIFT_HPP
#include "pythonic/include/operator_/irshift.hpp"
#include "pythonic/utils/proxy.hpp"
namespace pythonic
{
namespace operator_
{
template <class A, class B>
A irshift(A a, B const &b)
{
return a >>= b;
}
PROXY_IMPL(pythonic::operator_, irshift);
}
}
#endif
| 14.88
| 49
| 0.693548
|
artas360
|
d2f59cdb8b1d7f29493b05ad0b08b67dbf0b0a19
| 3,972
|
cpp
|
C++
|
src/pwn++/disasm.cpp
|
hugsy/pwn--
|
9ce6993b61bdb83cd5cac1eeb90f9b7953a7c099
|
[
"MIT"
] | 64
|
2020-11-10T07:49:03.000Z
|
2022-03-12T17:16:55.000Z
|
src/pwn++/disasm.cpp
|
hugsy/pwn--
|
9ce6993b61bdb83cd5cac1eeb90f9b7953a7c099
|
[
"MIT"
] | 3
|
2021-07-14T03:48:37.000Z
|
2021-11-29T18:00:12.000Z
|
src/pwn++/disasm.cpp
|
hugsy/pwn--
|
9ce6993b61bdb83cd5cac1eeb90f9b7953a7c099
|
[
"MIT"
] | 2
|
2020-11-10T09:45:15.000Z
|
2021-04-21T12:23:44.000Z
|
#include "disasm.hpp"
#ifndef PWN_NO_DISASSEMBLER
#include <capstone/capstone.h>
using namespace pwn::log;
#define CS_DEFAULT_BASE_ADDRESS 0x40000
#if defined(_MSC_VER)
#pragma warning(disable: 26812 ) // because of cs_arch & cs_mode, TODO: fix
#endif
//
// todos:
// - move csh to globals
//
namespace pwn::disasm
{
// private
namespace
{
_Success_(return)
bool __build_insn(_In_ cs_insn _cs_insn, _Out_ insn_t& insn)
{
insn.address = _cs_insn.address;
insn.size = _cs_insn.size;
::memcpy(insn.bytes, _cs_insn.bytes, MIN( (size_t)_cs_insn.size, sizeof(insn.bytes)));
insn.mnemonic = pwn::utils::to_widestring(_cs_insn.mnemonic);
insn.operands = pwn::utils::to_widestring(_cs_insn.op_str);
return true;
}
_Success_(return)
bool __disassemble(_In_ cs_arch arch, _In_ cs_mode mode, _In_ const u8* code, _In_ const size_t code_size, _Out_ std::vector<insn_t>& insns)
{
cs_err err;
csh handle;
dbg(L"arch=%u mode=%u\n", arch, mode);
err = ::cs_open(arch, mode, &handle);
if (err != CS_ERR_OK)
{
err(L"cs_open() failed: %u\n", err);
return false;
}
cs_insn* cs_insns;
bool res = true;
size_t count = cs_disasm(handle, code, code_size, CS_DEFAULT_BASE_ADDRESS, 0, &cs_insns);
if (count > 0)
{
for (size_t i = 0; i < count; i++)
{
insn_t insn = {};
if (__build_insn(cs_insns[i], insn))
{
insns.push_back(insn);
}
else
{
res = false;
break;
}
}
cs_free(cs_insns, count);
}
else
{
err(L"Failed to disassemble given code!\n");
res = false;
}
cs_close(&handle);
return res;
}
}
/*++
Description:
x86 specific disassembly function
Arguments:
- code the code to disassemble
- code_size is the size of code
- insns is a vector of instructions
Returns:
TRUE on success, else FALSE
--*/
_Success_(return)
bool x86(_In_ const u8* code, _In_ const size_t code_size, _Out_ std::vector<insn_t>& insns)
{
return __disassemble(CS_ARCH_X86, CS_MODE_32, code, code_size, insns);
}
/*++
Description:
x64 specific disassembly function
Arguments:
- code the code to disassemble
- code_size is the size of code
- insns is a vector of instructions
Returns:
TRUE on success, else FALSE
--*/
_Success_(return)
bool x64(_In_ const u8* code, _In_ const size_t code_size, _Out_ std::vector<insn_t>& insns)
{
return __disassemble(CS_ARCH_X86, CS_MODE_64, code, code_size, insns);
}
/*++
Description:
Generic function for disassemble code based on the context
Arguments:
- code the code to disassemble
- code_size is the size of code
- insns is a vector of instructions
Returns:
TRUE on success, else FALSE
--*/
_Success_(return)
bool disassemble(_In_ const u8* code, _In_ const size_t code_size, _Out_ std::vector<insn_t>& insns)
{
switch (pwn::context::arch)
{
case pwn::context::architecture_t::x86:
return x86(code, code_size, insns);
case pwn::context::architecture_t::x64:
return x64(code, code_size, insns);
default:
break;
}
throw std::runtime_error("unsupported architecture\n");
}
}
#endif /* PWN_NO_DISASSEMBLER */
| 24.518519
| 148
| 0.53852
|
hugsy
|
96011c2c7ab57a7b21e77aa044ce2c730b999b33
| 534
|
cpp
|
C++
|
AtCoder/wupc2nd/b/main.cpp
|
H-Tatsuhiro/Com_Pro-Cpp
|
fd79f7821a76b11f4a6f83bbb26a034db577a877
|
[
"MIT"
] | null | null | null |
AtCoder/wupc2nd/b/main.cpp
|
H-Tatsuhiro/Com_Pro-Cpp
|
fd79f7821a76b11f4a6f83bbb26a034db577a877
|
[
"MIT"
] | 1
|
2021-10-19T08:47:23.000Z
|
2022-03-07T05:23:56.000Z
|
AtCoder/wupc2nd/b/main.cpp
|
H-Tatsuhiro/Com_Pro-Cpp
|
fd79f7821a76b11f4a6f83bbb26a034db577a877
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <cmath>
#include <algorithm>
#include <vector>
using namespace std;
template<class T> inline void chmin(T& a, T b) {if (a > b) a = b;}
int main() {
int n; string s; cin >> n >> s;
vector<int> dp(n, 10e6);
dp[0] = 0;
for (int i = 0; i < n; i++) {
for (int j = 1; j <= 3; j++) {
if (i + j < n) {
if (s[i + j] == 'X') chmin(dp[i + j], dp[i] + 1);
else chmin(dp[i + j], dp[i]);
}
}
}
cout << dp[n - 1] << endl;
}
| 25.428571
| 66
| 0.428839
|
H-Tatsuhiro
|
9608b8db0113b501101e6ca1831a8fe498e2f202
| 1,347
|
cpp
|
C++
|
src/utils/i2c_helper.cpp
|
JonLevin25/soviet_silvester
|
f75bd1d0f99c53c78dff120a54ae84b17325db5f
|
[
"MIT"
] | null | null | null |
src/utils/i2c_helper.cpp
|
JonLevin25/soviet_silvester
|
f75bd1d0f99c53c78dff120a54ae84b17325db5f
|
[
"MIT"
] | null | null | null |
src/utils/i2c_helper.cpp
|
JonLevin25/soviet_silvester
|
f75bd1d0f99c53c78dff120a54ae84b17325db5f
|
[
"MIT"
] | null | null | null |
#include "i2c_helper.h"
#include "Wire.h"
#include "common.h"
void (*ReceiveCallback)(uint16_t value);
void _receiveInternal(int len);
void wire_setup(bool is_master, int slave_addr)
{
if (is_master)
{
Wire.begin();
}
else
{
Wire.begin(slave_addr);
}
}
void wire_sendMsg(uint16_t value, int slave_addr)
{
Wire.beginTransmission(slave_addr);
const uint8_t *bytes = (const uint8_t *) &value;
P("Send msg: "); P(value);
Pln();
Wire.write(bytes, MSG_SIZE);
#ifdef ESP32
if (Wire.lastError() != 0) {
Serial.printf("WIRE ERROR: %s\n", Wire.getErrorText(Wire.lastError()));
}
#endif
Wire.endTransmission();
}
void wire_registerCallback(void (*callback)(uint16_t value))
{
ReceiveCallback = callback;
Wire.onReceive(_receiveInternal);
}
void _receiveInternal(int len)
{
if (len != sizeof(MSG_SIZE))
{
P("Message size ("); P(len); P(") did not match expected! ("); P(MSG_SIZE); P(')');
Pln();
// Workaround - if Wire is not fully read receiveEvent will not be called again.
P("Values: ");
while (Wire.available()) {
P(Wire.read(), HEX); P(' ');
}
Pln();
return;
}
static uint8_t buf[MSG_SIZE / sizeof(uint8_t)];
Wire.readBytes(buf, MSG_SIZE);
const uint16_t *pVal = (uint16_t *)buf;
ReceiveCallback(*pVal);
}
| 20.104478
| 88
| 0.628062
|
JonLevin25
|
960b787260567fd4676816c7d08790cf59ca5b48
| 2,027
|
cpp
|
C++
|
source/extract/extractPathData.cpp
|
guard3/g3DTZ
|
7f0fe646a3e02a688151e21b4c74b09c8c4d6d82
|
[
"MIT"
] | 11
|
2020-01-12T16:03:13.000Z
|
2021-11-14T17:19:51.000Z
|
source/extract/extractPathData.cpp
|
guard3/g3DTZ
|
7f0fe646a3e02a688151e21b4c74b09c8c4d6d82
|
[
"MIT"
] | 1
|
2020-12-18T21:37:23.000Z
|
2020-12-27T16:20:57.000Z
|
source/extract/extractPathData.cpp
|
guard3/g3DTZ
|
7f0fe646a3e02a688151e21b4c74b09c8c4d6d82
|
[
"MIT"
] | 5
|
2020-05-30T05:34:00.000Z
|
2021-12-05T18:54:11.000Z
|
#include "Extract.h"
#include "Train.h"
#include "Ferry.h"
#include "Plane.h"
#include "Utils.h"
#include "FileSystem.h"
#include <fstream>
bool ExtractPathData()
{
#ifdef LCS
if (!CFileSystem::CreateAndChangeFolder("paths"))
{
ErrorBoxCannotCreateFolder("paths");
return false;
}
#endif
/* Open flight.dat */
int i;
std::ofstream f("flight.dat");
if (!f)
{
ErrorBoxCannotCreateFile("flight.dat");
return false;
}
f << CPlane::GetNumPlaneNodes();
/* Print flight.dat lines */
for (i = 0; i < CPlane::GetNumPlaneNodes(); ++i)
{
f << std::endl << PrecisionAny(CPlane::GetPlaneNode(i)->GetPosition().x)
<< '\t' << CPlane::GetPlaneNode(i)->GetPosition().y
<< '\t' << PrecisionAny(CPlane::GetPlaneNode(i)->GetPosition().z);
}
f.close();
#ifdef LCS
/* Open ferry1.dat */
f.open("ferry1.dat");
if (!f)
{
ErrorBoxCannotCreateFile("ferry1.dat");
return false;
}
f << CFerry::GetNumNodes();
/* Print ferry1.dat lines*/
for (i = 0; i < CFerry::GetNumNodes(); ++i)
{
f << std::endl << PrecisionAny(CFerry::GetNode(i)->GetPosition().x)
<< '\t' << CFerry::GetNode(i)->GetPosition().y
<< '\t' << CFerry::GetNode(i)->GetPosition().z;
}
f.close();
/* A lambda that extracts train data */
auto extractTrain = [&i, &f](const char* filename, CTrainNode* nodes, int num) {
/* Open file */
f.open(filename);
if (!f)
{
ErrorBoxCannotCreateFile(filename);
return false;
}
f << num;
/* Print train lines */
for (i = 0; i < num; ++i)
{
f << std::endl << PrecisionAny(nodes[i].GetPosition().x)
<< '\t' << PrecisionAny(nodes[i].GetPosition().y)
<< '\t' << nodes[i].GetPosition().z;
}
f.close();
return true;
};
/* Extract train data */
#define CHECK(a) if (!(a)) return false;
CHECK(extractTrain("tracks.dat", CTrain::GetTrackNode(0), CTrain::GetNumTrackNodes() ));
CHECK(extractTrain("tracks2.dat", CTrain::GetTrackNode_S(0), CTrain::GetNumTrackNodes_S()));
CFileSystem::ResetFolder();
#endif
return true;
}
| 23.298851
| 93
| 0.617662
|
guard3
|
960c52eb5a5ad3a8da6ed1f2ee58da20c4458447
| 705
|
cpp
|
C++
|
Libraries/Math/Vector4.cpp
|
xycsoscyx/gekengine
|
cb9c933c6646169c0af9c7e49be444ff6f97835d
|
[
"MIT"
] | 1
|
2019-04-22T00:10:49.000Z
|
2019-04-22T00:10:49.000Z
|
Libraries/Math/Vector4.cpp
|
xycsoscyx/gekengine
|
cb9c933c6646169c0af9c7e49be444ff6f97835d
|
[
"MIT"
] | null | null | null |
Libraries/Math/Vector4.cpp
|
xycsoscyx/gekengine
|
cb9c933c6646169c0af9c7e49be444ff6f97835d
|
[
"MIT"
] | 2
|
2017-10-16T15:40:55.000Z
|
2019-04-22T00:10:50.000Z
|
#include "GEK/Math/Vector4.hpp"
namespace Gek
{
namespace Math
{
template <>
const Float4 Float4::Zero(0.0f, 0.0f, 0.0f, 0.0f);
template <>
const Float4 Float4::One(1.0f, 1.0f, 1.0f, 1.0f);
template <>
const Float4 Float4::Black(0.0f, 0.0f, 0.0f, 0.0f);
template <>
const Float4 Float4::White(1.0f, 1.0f, 1.0f, 1.0f);
template <>
const Int4 Int4::Zero(0, 0, 0, 0);
template <>
const Int4 Int4::One(1, 1, 1, 1);
template <>
const UInt4 UInt4::Zero(0U, 0U, 0U, 0U);
template <>
const UInt4 UInt4::One(1U, 1U, 1U, 1U);
}; // namespace Math
}; // namespace Gek
| 22.03125
| 59
| 0.51773
|
xycsoscyx
|
960f7b0fa20c6ae39966c3dd44098c895b20b1e2
| 12,909
|
cpp
|
C++
|
src/generated/CPACSRotorBladeAttachment.cpp
|
Mk-arc/tigl
|
45ace0b17008e2beab3286babe310a817fcd6578
|
[
"Apache-2.0"
] | 171
|
2015-04-13T11:24:34.000Z
|
2022-03-26T00:56:38.000Z
|
src/generated/CPACSRotorBladeAttachment.cpp
|
Mk-arc/tigl
|
45ace0b17008e2beab3286babe310a817fcd6578
|
[
"Apache-2.0"
] | 620
|
2015-01-20T08:34:36.000Z
|
2022-03-30T11:05:33.000Z
|
src/generated/CPACSRotorBladeAttachment.cpp
|
Mk-arc/tigl
|
45ace0b17008e2beab3286babe310a817fcd6578
|
[
"Apache-2.0"
] | 56
|
2015-02-09T13:33:56.000Z
|
2022-03-19T04:52:51.000Z
|
// Copyright (c) 2020 RISC Software GmbH
//
// This file was generated by CPACSGen from CPACS XML Schema (c) German Aerospace Center (DLR/SC).
// Do not edit, all changes are lost when files are re-generated.
//
// 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 <cassert>
#include "CCPACSRotorBladeAttachments.h"
#include "CPACSRotorBladeAttachment.h"
#include "CTiglError.h"
#include "CTiglLogging.h"
#include "CTiglUIDManager.h"
#include "TixiHelper.h"
namespace tigl
{
namespace generated
{
CPACSRotorBladeAttachment::CPACSRotorBladeAttachment(CCPACSRotorBladeAttachments* parent, CTiglUIDManager* uidMgr)
: m_uidMgr(uidMgr)
{
//assert(parent != NULL);
m_parent = parent;
}
CPACSRotorBladeAttachment::~CPACSRotorBladeAttachment()
{
if (m_uidMgr) m_uidMgr->TryUnregisterObject(m_uID);
if (m_uidMgr) {
if (!m_rotorBladeUID.empty()) m_uidMgr->TryUnregisterReference(m_rotorBladeUID, *this);
}
}
const CCPACSRotorBladeAttachments* CPACSRotorBladeAttachment::GetParent() const
{
return m_parent;
}
CCPACSRotorBladeAttachments* CPACSRotorBladeAttachment::GetParent()
{
return m_parent;
}
const CTiglUIDObject* CPACSRotorBladeAttachment::GetNextUIDParent() const
{
if (m_parent) {
return m_parent->GetNextUIDParent();
}
return nullptr;
}
CTiglUIDObject* CPACSRotorBladeAttachment::GetNextUIDParent()
{
if (m_parent) {
return m_parent->GetNextUIDParent();
}
return nullptr;
}
CTiglUIDManager& CPACSRotorBladeAttachment::GetUIDManager()
{
return *m_uidMgr;
}
const CTiglUIDManager& CPACSRotorBladeAttachment::GetUIDManager() const
{
return *m_uidMgr;
}
void CPACSRotorBladeAttachment::ReadCPACS(const TixiDocumentHandle& tixiHandle, const std::string& xpath)
{
// read attribute uID
if (tixi::TixiCheckAttribute(tixiHandle, xpath, "uID")) {
m_uID = tixi::TixiGetAttribute<std::string>(tixiHandle, xpath, "uID");
if (m_uID.empty()) {
LOG(WARNING) << "Required attribute uID is empty at xpath " << xpath;
}
}
else {
LOG(ERROR) << "Required attribute uID is missing at xpath " << xpath;
}
// read element name
if (tixi::TixiCheckElement(tixiHandle, xpath + "/name")) {
m_name = tixi::TixiGetElement<std::string>(tixiHandle, xpath + "/name");
if (m_name->empty()) {
LOG(WARNING) << "Optional element name is present but empty at xpath " << xpath;
}
}
// read element description
if (tixi::TixiCheckElement(tixiHandle, xpath + "/description")) {
m_description = tixi::TixiGetElement<std::string>(tixiHandle, xpath + "/description");
if (m_description->empty()) {
LOG(WARNING) << "Optional element description is present but empty at xpath " << xpath;
}
}
// read element azimuthAngles
if (tixi::TixiCheckElement(tixiHandle, xpath + "/azimuthAngles")) {
m_azimuthAngles_choice1 = boost::in_place(reinterpret_cast<CCPACSRotorBladeAttachment*>(this));
try {
m_azimuthAngles_choice1->ReadCPACS(tixiHandle, xpath + "/azimuthAngles");
} catch(const std::exception& e) {
LOG(ERROR) << "Failed to read azimuthAngles at xpath " << xpath << ": " << e.what();
m_azimuthAngles_choice1 = boost::none;
}
}
// read element numberOfBlades
if (tixi::TixiCheckElement(tixiHandle, xpath + "/numberOfBlades")) {
m_numberOfBlades_choice2 = tixi::TixiGetElement<int>(tixiHandle, xpath + "/numberOfBlades");
}
// read element hinges
if (tixi::TixiCheckElement(tixiHandle, xpath + "/hinges")) {
m_hinges = boost::in_place(reinterpret_cast<CCPACSRotorBladeAttachment*>(this), m_uidMgr);
try {
m_hinges->ReadCPACS(tixiHandle, xpath + "/hinges");
} catch(const std::exception& e) {
LOG(ERROR) << "Failed to read hinges at xpath " << xpath << ": " << e.what();
m_hinges = boost::none;
}
}
// read element rotorBladeUID
if (tixi::TixiCheckElement(tixiHandle, xpath + "/rotorBladeUID")) {
m_rotorBladeUID = tixi::TixiGetElement<std::string>(tixiHandle, xpath + "/rotorBladeUID");
if (m_rotorBladeUID.empty()) {
LOG(WARNING) << "Required element rotorBladeUID is empty at xpath " << xpath;
}
if (m_uidMgr && !m_rotorBladeUID.empty()) m_uidMgr->RegisterReference(m_rotorBladeUID, *this);
}
else {
LOG(ERROR) << "Required element rotorBladeUID is missing at xpath " << xpath;
}
if (m_uidMgr && !m_uID.empty()) m_uidMgr->RegisterObject(m_uID, *this);
if (!ValidateChoices()) {
LOG(ERROR) << "Invalid choice configuration at xpath " << xpath;
}
}
void CPACSRotorBladeAttachment::WriteCPACS(const TixiDocumentHandle& tixiHandle, const std::string& xpath) const
{
const std::vector<std::string> childElemOrder = { "name", "description", "azimuthAngles", "numberOfBlades", "hinges", "rotorBladeUID" };
// write attribute uID
tixi::TixiSaveAttribute(tixiHandle, xpath, "uID", m_uID);
// write element name
if (m_name) {
tixi::TixiCreateSequenceElementIfNotExists(tixiHandle, xpath + "/name", childElemOrder);
tixi::TixiSaveElement(tixiHandle, xpath + "/name", *m_name);
}
else {
if (tixi::TixiCheckElement(tixiHandle, xpath + "/name")) {
tixi::TixiRemoveElement(tixiHandle, xpath + "/name");
}
}
// write element description
if (m_description) {
tixi::TixiCreateSequenceElementIfNotExists(tixiHandle, xpath + "/description", childElemOrder);
tixi::TixiSaveElement(tixiHandle, xpath + "/description", *m_description);
}
else {
if (tixi::TixiCheckElement(tixiHandle, xpath + "/description")) {
tixi::TixiRemoveElement(tixiHandle, xpath + "/description");
}
}
// write element azimuthAngles
if (m_azimuthAngles_choice1) {
tixi::TixiCreateSequenceElementIfNotExists(tixiHandle, xpath + "/azimuthAngles", childElemOrder);
m_azimuthAngles_choice1->WriteCPACS(tixiHandle, xpath + "/azimuthAngles");
}
else {
if (tixi::TixiCheckElement(tixiHandle, xpath + "/azimuthAngles")) {
tixi::TixiRemoveElement(tixiHandle, xpath + "/azimuthAngles");
}
}
// write element numberOfBlades
if (m_numberOfBlades_choice2) {
tixi::TixiCreateSequenceElementIfNotExists(tixiHandle, xpath + "/numberOfBlades", childElemOrder);
tixi::TixiSaveElement(tixiHandle, xpath + "/numberOfBlades", *m_numberOfBlades_choice2);
}
else {
if (tixi::TixiCheckElement(tixiHandle, xpath + "/numberOfBlades")) {
tixi::TixiRemoveElement(tixiHandle, xpath + "/numberOfBlades");
}
}
// write element hinges
if (m_hinges) {
tixi::TixiCreateSequenceElementIfNotExists(tixiHandle, xpath + "/hinges", childElemOrder);
m_hinges->WriteCPACS(tixiHandle, xpath + "/hinges");
}
else {
if (tixi::TixiCheckElement(tixiHandle, xpath + "/hinges")) {
tixi::TixiRemoveElement(tixiHandle, xpath + "/hinges");
}
}
// write element rotorBladeUID
tixi::TixiCreateSequenceElementIfNotExists(tixiHandle, xpath + "/rotorBladeUID", childElemOrder);
tixi::TixiSaveElement(tixiHandle, xpath + "/rotorBladeUID", m_rotorBladeUID);
}
bool CPACSRotorBladeAttachment::ValidateChoices() const
{
return
(
(
(
// mandatory elements of this choice must be there
m_azimuthAngles_choice1.is_initialized()
&&
// elements of other choices must not be there
!(
m_numberOfBlades_choice2.is_initialized()
)
)
+
(
// mandatory elements of this choice must be there
m_numberOfBlades_choice2.is_initialized()
&&
// elements of other choices must not be there
!(
m_azimuthAngles_choice1.is_initialized()
)
)
== 1
)
)
;
}
const std::string& CPACSRotorBladeAttachment::GetUID() const
{
return m_uID;
}
void CPACSRotorBladeAttachment::SetUID(const std::string& value)
{
if (m_uidMgr && value != m_uID) {
if (m_uID.empty()) {
m_uidMgr->RegisterObject(value, *this);
}
else {
m_uidMgr->UpdateObjectUID(m_uID, value);
}
}
m_uID = value;
}
const boost::optional<std::string>& CPACSRotorBladeAttachment::GetName() const
{
return m_name;
}
void CPACSRotorBladeAttachment::SetName(const boost::optional<std::string>& value)
{
m_name = value;
}
const boost::optional<std::string>& CPACSRotorBladeAttachment::GetDescription() const
{
return m_description;
}
void CPACSRotorBladeAttachment::SetDescription(const boost::optional<std::string>& value)
{
m_description = value;
}
const boost::optional<CCPACSStringVector>& CPACSRotorBladeAttachment::GetAzimuthAngles_choice1() const
{
return m_azimuthAngles_choice1;
}
boost::optional<CCPACSStringVector>& CPACSRotorBladeAttachment::GetAzimuthAngles_choice1()
{
return m_azimuthAngles_choice1;
}
const boost::optional<int>& CPACSRotorBladeAttachment::GetNumberOfBlades_choice2() const
{
return m_numberOfBlades_choice2;
}
void CPACSRotorBladeAttachment::SetNumberOfBlades_choice2(const boost::optional<int>& value)
{
m_numberOfBlades_choice2 = value;
}
const boost::optional<CCPACSRotorHinges>& CPACSRotorBladeAttachment::GetHinges() const
{
return m_hinges;
}
boost::optional<CCPACSRotorHinges>& CPACSRotorBladeAttachment::GetHinges()
{
return m_hinges;
}
const std::string& CPACSRotorBladeAttachment::GetRotorBladeUID() const
{
return m_rotorBladeUID;
}
void CPACSRotorBladeAttachment::SetRotorBladeUID(const std::string& value)
{
if (m_uidMgr) {
if (!m_rotorBladeUID.empty()) m_uidMgr->TryUnregisterReference(m_rotorBladeUID, *this);
if (!value.empty()) m_uidMgr->RegisterReference(value, *this);
}
m_rotorBladeUID = value;
}
CCPACSStringVector& CPACSRotorBladeAttachment::GetAzimuthAngles_choice1(CreateIfNotExistsTag)
{
if (!m_azimuthAngles_choice1)
m_azimuthAngles_choice1 = boost::in_place(reinterpret_cast<CCPACSRotorBladeAttachment*>(this));
return *m_azimuthAngles_choice1;
}
void CPACSRotorBladeAttachment::RemoveAzimuthAngles_choice1()
{
m_azimuthAngles_choice1 = boost::none;
}
CCPACSRotorHinges& CPACSRotorBladeAttachment::GetHinges(CreateIfNotExistsTag)
{
if (!m_hinges)
m_hinges = boost::in_place(reinterpret_cast<CCPACSRotorBladeAttachment*>(this), m_uidMgr);
return *m_hinges;
}
void CPACSRotorBladeAttachment::RemoveHinges()
{
m_hinges = boost::none;
}
const CTiglUIDObject* CPACSRotorBladeAttachment::GetNextUIDObject() const
{
return this;
}
void CPACSRotorBladeAttachment::NotifyUIDChange(const std::string& oldUid, const std::string& newUid)
{
if (m_rotorBladeUID == oldUid) {
m_rotorBladeUID = newUid;
}
}
} // namespace generated
} // namespace tigl
| 34.608579
| 144
| 0.611279
|
Mk-arc
|
9614eca9ab12ba047c1420807e0caca0c58c17c8
| 2,035
|
cpp
|
C++
|
src/cDataPoint.cpp
|
JamesBremner/KMeans
|
00cb3ed4ed4aae3b45398797fa24fad12ac13391
|
[
"MIT"
] | null | null | null |
src/cDataPoint.cpp
|
JamesBremner/KMeans
|
00cb3ed4ed4aae3b45398797fa24fad12ac13391
|
[
"MIT"
] | null | null | null |
src/cDataPoint.cpp
|
JamesBremner/KMeans
|
00cb3ed4ed4aae3b45398797fa24fad12ac13391
|
[
"MIT"
] | null | null | null |
#define PYTHAGORUS
#include <vector>
#include <numeric>
#include "cDataPoint.h"
using namespace std;
cDataPoint cDataPoint::operator + ( cDataPoint b )
{
cDataPoint r( myDim );
std::transform(
d.begin(), d.end(), b.d.begin(), r.d.begin(),
[]( double a, double b)
{
return a+b;
} );
return r;
}
cDataPoint cDataPoint::operator - (cDataPoint b)
{
cDataPoint r( myDim );
std::transform(
d.begin(), d.end(), b.d.begin(), r.d.begin(),
[]( double a, double b)
{
return a-b;
} );
return r;
}
cDataPoint cDataPoint::operator / ( double s )
{
if( std::fabs(s) < 0.00000001 )
throw std::runtime_error("cDataPoint divide by zero");
cDataPoint r( myDim );
std::transform(
d.begin(), d.end(),
r.d.begin(),
[&s]( double a )
{
return a / s;
} );
return r;
}
double cDataPoint::dist(
const cDataPoint& ra,
const cDataPoint& rb )
{
#ifdef PYTHAGORUS
//cout << "dist " << ra.Text() << " " << rb.Text() << "\n";
// calculated squared difference between datapoints for each dimension
vector< double > squared_deltas( ra.myDim );
transform(
ra.d.begin(), ra.d.end(),
rb.d.begin(),
squared_deltas.begin(),
[](double a, double b)
{
double delta = a - b;
return delta * delta;
});
// return square root of sum of squared differences
return sqrt(
accumulate(
squared_deltas.begin(),
squared_deltas.end(),
0 ));
#endif // PYTHAGORUS
}
double cDataPoint::sum_all_distances(
const std::vector<cDataPoint>& locs ) const
{
double total = 0;
for( auto& l : locs )
{
total += dist( *this, l );
}
return total;
}
std::string cDataPoint::text() const
{
std::stringstream ss;
for( int k = 0; k < myDim; k++ )
ss << d[k] << " ";
return ss.str();
}
| 20.555556
| 74
| 0.521867
|
JamesBremner
|
961ac9d46a83c7daf8455f6b6ee393dd1f013ebb
| 7,675
|
cc
|
C++
|
src/xurl/main.cc
|
pjsaksa/x0
|
96b69e5a54b006e3d929b9934c2708f7967371bb
|
[
"MIT"
] | 24
|
2016-07-10T08:05:11.000Z
|
2021-11-16T10:53:48.000Z
|
src/xurl/main.cc
|
pjsaksa/x0
|
96b69e5a54b006e3d929b9934c2708f7967371bb
|
[
"MIT"
] | 14
|
2015-04-12T10:45:26.000Z
|
2016-06-28T22:27:50.000Z
|
src/xurl/main.cc
|
pjsaksa/x0
|
96b69e5a54b006e3d929b9934c2708f7967371bb
|
[
"MIT"
] | 4
|
2016-10-05T17:51:38.000Z
|
2020-04-20T07:45:23.000Z
|
// This file is part of the "x0" project, http://github.com/christianparpart/x0>
// (c) 2009-2018 Christian Parpart <christian@parpart.family>
//
// Licensed under the MIT License (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of
// the License at: http://opensource.org/licenses/MIT
#include <xzero/http/client/HttpClient.h>
#include <xzero/http/HttpRequest.h>
#include <xzero/http/HeaderFieldList.h>
#include <xzero/net/TcpEndPoint.h>
#include <xzero/executor/PosixScheduler.h>
#include <xzero/net/DnsClient.h>
#include <xzero/io/FileUtil.h>
#include <xzero/Application.h>
#include <xzero/RuntimeError.h>
#include <xzero/Uri.h>
#include <xzero/Flags.h>
#include <xzero/logging.h>
#include <unordered_map>
#include "sysconfig.h"
#include <iostream>
#include <unistd.h>
// #define PACKAGE_VERSION X0_VERSION
#define PACKAGE_HOMEPAGE_URL "https://xzero.io"
using namespace xzero;
using namespace xzero::http;
using namespace xzero::http::client;
using xzero::http::HttpRequestInfo;
using xzero::http::HttpVersion;
using xzero::http::HeaderField;
class ServicePortMapping { // {{{
public:
ServicePortMapping();
void loadFile(const std::string& path = "/etc/services");
void loadContent(const std::string& content);
int tcp(const std::string& name);
int udp(const std::string& name);
private:
std::unordered_map<std::string, int> tcp_;
std::unordered_map<std::string, int> udp_;
};
ServicePortMapping::ServicePortMapping()
: tcp_() {
tcp_["http"] = 80;
tcp_["https"] = 443;
}
int ServicePortMapping::tcp(const std::string& name) {
auto i = tcp_.find(name);
if (i != tcp_.end())
return i->second;
throw std::runtime_error{StringUtil::format("Unknown service '{}'", name)};
}
// }}}
class XurlLogTarget : public ::xzero::LogTarget { // {{{
public:
void log(LogLevel level,
const std::string& message) override;
};
void XurlLogTarget::log(LogLevel level, const std::string& message) {
printf("%s\n", message.c_str());
}
// }}}
class XUrl {
public:
XUrl();
int run(int argc, const char* argv[]);
private:
void addRequestHeader(const std::string& value);
Uri makeUri(const std::string& url);
IPAddress getIPAddress(const std::string& host);
int getPort(const Uri& uri);
void query(const Uri& uri);
private:
PosixScheduler scheduler_;
Flags flags_;
DnsClient dns_;
Duration connectTimeout_;
Duration readTimeout_;
Duration writeTimeout_;
XurlLogTarget logTarget_;
http::HeaderFieldList requestHeaders_;
};
XUrl::XUrl()
: scheduler_(CatchAndLogExceptionHandler("xurl")),
flags_(),
dns_(),
connectTimeout_(4_seconds),
readTimeout_(60_seconds),
writeTimeout_(10_seconds),
logTarget_(),
requestHeaders_()
{
Application::init();
//Application::logToStderr(LogLevel::Info);
Logger::get()->addTarget(&logTarget_);
requestHeaders_.push_back("User-Agent", "xurl/" PACKAGE_VERSION);
flags_.defineBool("help", 'h', "Prints this help.");
flags_.defineBool("head", 'I', "Performs a HEAD request.");
flags_.defineBool("verbose", 'v', "Be verbose (log level: info)");
flags_.defineString("output", 'o', "PATH", "Write response body to given file.");
flags_.defineString("log-level", 'L', "STRING", "Log level.", "warning");
flags_.defineString("method", 'X', "METHOD", "HTTP method", "GET");
flags_.defineNumber("connect-timeout", 0, "MS", "TCP connect() timeout", 10_seconds .milliseconds());
flags_.defineString("upload-file", 'T', "PATH", "Uploads given file.", "");
flags_.defineString("header", 'H', "HEADER", "Adds a custom request header",
std::nullopt,
std::bind(&XUrl::addRequestHeader, this, std::placeholders::_1));
flags_.defineBool("ipv4", '4', "Favor IPv4 for TCP/IP communication.");
flags_.defineBool("ipv6", '6', "Favor IPv6 for TCP/IP communication.");
flags_.enableParameters("URL", "URL to query");
}
void XUrl::addRequestHeader(const std::string& field) {
requestHeaders_.push_back(HeaderField::parse(field));
}
int XUrl::run(int argc, const char* argv[]) {
std::error_code ec = flags_.parse(argc, argv);
if (ec) {
fprintf(stderr, "Failed to parse flags. %s\n", ec.message().c_str());
return 1;
}
if (flags_.isSet("log-level"))
Logger::get()->setMinimumLogLevel(make_loglevel(flags_.getString("log-level")));
if (flags_.getBool("verbose"))
Logger::get()->setMinimumLogLevel(make_loglevel("info"));
if (flags_.getBool("help")) {
std::cerr
<< "xurl: Xzero HTTP Client " PACKAGE_VERSION
<< " [" PACKAGE_HOMEPAGE_URL "]" << std::endl
<< "Copyright (c) 2009-2018 by Christian Parpart <christian@parpart.family>" << std::endl
<< std::endl
<< "Usage: xurl [options ...]" << std::endl
<< std::endl
<< "Options:" << std::endl
<< flags_.helpText() << std::endl;
return 0;
}
if (flags_.parameters().empty()) {
logError("xurl: No URL given.");
return 1;
}
if (flags_.parameters().size() != 1) {
logError("xurl: Too many URLs given.");
return 1;
}
query(makeUri(flags_.parameters()[0]));
return 0;
}
Uri XUrl::makeUri(const std::string& url) {
Uri uri(url);
if (uri.path() == "")
uri.setPath("/");
return uri;
}
IPAddress XUrl::getIPAddress(const std::string& host) {
std::vector<IPAddress> ipaddresses = dns_.ipv4(host);
if (ipaddresses.empty())
throw std::runtime_error{StringUtil::format("Could not resolve {}.", host)};
return ipaddresses.front();
}
int XUrl::getPort(const Uri& uri) {
if (uri.port())
return uri.port();
return ServicePortMapping().tcp(uri.scheme());
}
void XUrl::query(const Uri& uri) {
IPAddress ipaddr = getIPAddress(uri.host());
int port = getPort(uri);
InetAddress inetAddr(ipaddr, port);
Duration keepAlive = 8_seconds;
std::string method = flags_.getString("method");
if (flags_.getBool("head")) {
method = "HEAD";
}
HugeBuffer body;
if (!flags_.getString("upload-file").empty()) {
method = "PUT";
body = FileUtil::read(flags_.getString("upload-file"));
}
requestHeaders_.overwrite("Host", uri.hostAndPort());
HttpRequest req(HttpVersion::VERSION_1_1,
method,
uri.pathAndQuery(),
requestHeaders_,
uri.scheme() == "https",
std::move(body));
req.setScheme(uri.scheme());
logInfo("* connecting to {}", inetAddr);
logInfo("> {} {} HTTP/{}", req.unparsedMethod(),
req.unparsedUri(),
req.version());
for (const HeaderField& field: req.headers())
if (field.name()[0] != ':')
logInfo("> {}: {}", field.name(), field.value());
logInfo(">");
HttpClient httpClient(&scheduler_, inetAddr,
connectTimeout_, readTimeout_, writeTimeout_,
keepAlive);
Future<HttpClient::Response> f = httpClient.send(req);
f.onSuccess([](HttpClient::Response& response) {
logInfo("< HTTP/{} {} {}", response.version(),
(int) response.status(),
response.reason());
for (const HeaderField& field: response.headers())
logInfo("< {}: {}", field.name(), field.value());
logInfo("<");
const BufferRef& content = response.content().getBuffer();
write(STDOUT_FILENO, content.data(), content.size());
});
f.onFailure([](std::error_code ec) {
logError("xurl: connect() failed. {}", ec.message());
});
scheduler_.runLoop();
}
int main(int argc, const char* argv[]) {
XUrl app;
return app.run(argc, argv);
}
| 28.113553
| 103
| 0.643388
|
pjsaksa
|
961c9e30e46b92210edf2bdfa18d746763879a07
| 993
|
hpp
|
C++
|
boost/time_series/traits/storage_category.hpp
|
ericniebler/time_series
|
4040119366cc21f25c7734bb355e4a647296a96d
|
[
"BSL-1.0"
] | 11
|
2015-02-21T11:23:44.000Z
|
2021-08-15T03:39:29.000Z
|
boost/time_series/traits/storage_category.hpp
|
ericniebler/time_series
|
4040119366cc21f25c7734bb355e4a647296a96d
|
[
"BSL-1.0"
] | null | null | null |
boost/time_series/traits/storage_category.hpp
|
ericniebler/time_series
|
4040119366cc21f25c7734bb355e4a647296a96d
|
[
"BSL-1.0"
] | 3
|
2015-05-09T02:25:42.000Z
|
2019-11-02T13:39:29.000Z
|
///////////////////////////////////////////////////////////////////////////////
/// \file storage_category.hpp
/// Given a concrete storage type, fetch its associated storage tag
//
// Copyright 2006 Eric Niebler. 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)
#ifndef BOOST_TIME_SERIES_TRAITS_STORAGE_CATEGORY_HPP_EAN_06_06_2006
#define BOOST_TIME_SERIES_TRAITS_STORAGE_CATEGORY_HPP_EAN_06_06_2006
namespace boost { namespace time_series { namespace traits
{
template<typename S>
struct storage_category
{};
template<typename S>
struct storage_category<S const>
: storage_category<S>
{};
template<typename S>
struct storage_category<S volatile>
: storage_category<S>
{};
template<typename S>
struct storage_category<S volatile const>
: storage_category<S>
{};
}}}
#endif
| 26.131579
| 80
| 0.644512
|
ericniebler
|
961db8aca0b8dd7991ff08d40589ad1c36d95ba3
| 2,668
|
cc
|
C++
|
squid/squid3-3.3.8.spaceify/test-suite/debug.cc
|
spaceify/spaceify
|
4296d6c93cad32bb735cefc9b8157570f18ffee4
|
[
"MIT"
] | 4
|
2015-01-20T15:25:34.000Z
|
2017-12-20T06:47:42.000Z
|
squid/squid3-3.3.8.spaceify/test-suite/debug.cc
|
spaceify/spaceify
|
4296d6c93cad32bb735cefc9b8157570f18ffee4
|
[
"MIT"
] | 4
|
2015-05-15T09:32:55.000Z
|
2016-02-18T13:43:31.000Z
|
squid/squid3-3.3.8.spaceify/test-suite/debug.cc
|
spaceify/spaceify
|
4296d6c93cad32bb735cefc9b8157570f18ffee4
|
[
"MIT"
] | null | null | null |
/*
* DEBUG: section 19 Store Memory Primitives
* AUTHOR: Robert Collins
*
* SQUID Web Proxy Cache http://www.squid-cache.org/
* ----------------------------------------------------------
*
* Squid is the result of efforts by numerous individuals from
* the Internet community; see the CONTRIBUTORS file for full
* details. Many organizations have provided support for Squid's
* development; see the SPONSORS file for full details. Squid is
* Copyrighted (C) 2001 by the Regents of the University of
* California; see the COPYRIGHT file for full details. Squid
* incorporates software developed and/or copyrighted by other
* sources; see the CREDITS file for full details.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
*
* Copyright (c) 2003 Robert Collins <robertc@squid-cache.org>
*/
#include "squid.h"
#include "Debug.h"
#include "mem_node.h"
#include "stmem.h"
class StreamTest
{
public:
std::ostream &serialise(std::ostream &);
int getAnInt() const;
char const *getACString() const;
};
std::ostream &operator << (std::ostream &aStream, StreamTest &anObject)
{
return anObject.serialise(aStream);
}
std::ostream&
StreamTest::serialise(std::ostream &aStream)
{
aStream << "stream test";
return aStream;
}
int
StreamTest::getAnInt() const
{
return 5;
}
char const *
StreamTest::getACString() const
{
return "ThisIsAStreamTest";
}
int
main(int argc, char **argv)
{
Debug::Levels[1] = 8;
debugs (1,1,"test" << "string");
debugs (1,9,"dont show this" << "string");
debugs (1,1,"test" << "string");
debugs (1,1,"test" << "string");
if (true)
debugs(1,9,"this won't compile if the macro is broken.");
else
debugs(1, DBG_IMPORTANT,"bar");
StreamTest aStreamObject;
StreamTest *streamPointer (&aStreamObject);
debugs(1, DBG_IMPORTANT,aStreamObject);
debugs(1, DBG_IMPORTANT,streamPointer->getAnInt() << " " << aStreamObject.getACString());
return 0;
}
| 29.644444
| 93
| 0.676912
|
spaceify
|
9624e47d3884fa98995e16448842b83cfbf002a1
| 1,284
|
cpp
|
C++
|
p59_Spiral_Matrix_II/p59.cpp
|
Song1996/Leetcode
|
ecb0a2de67a57b899a12d0cb18272fb37dbf3ceb
|
[
"MIT"
] | null | null | null |
p59_Spiral_Matrix_II/p59.cpp
|
Song1996/Leetcode
|
ecb0a2de67a57b899a12d0cb18272fb37dbf3ceb
|
[
"MIT"
] | null | null | null |
p59_Spiral_Matrix_II/p59.cpp
|
Song1996/Leetcode
|
ecb0a2de67a57b899a12d0cb18272fb37dbf3ceb
|
[
"MIT"
] | null | null | null |
#include <memory>
#include <vector>
#include <map>
#include <string>
#include <assert.h>
#include <algorithm>
using namespace std;
class Solution {
public:
vector<vector<int> > generateMatrix(int n) {
vector<vector<int> > ans;
for(int i = 0; i < n; i++){
vector<int> t(n,-1);
ans.push_back(t);
}
rehursive(ans, 1, 0, 0, n);
return ans;
}
void rehursive(vector<vector<int> >& ans, int start, int x, int y, int height){
if(height==0) return;
if(height==1) {
ans[x][y] = start;
return;
}
for(int i = 0; i < height-1; i++) ans[x][y+i] = start++;
for(int i = 0; i < height-1; i++) ans[x+i][y+height-1] = start++;
for(int i = 0; i < height-1; i++) ans[x+height-1][y+height-1-i] = start++;
for(int i = 0; i < height-1; i++) ans[x+height-1-i][y] = start++;
rehursive(ans,start,x+1,y+1,height-2);
}
};
int main () {
int x = 4;
Solution s;
vector<vector<int> > y = s.generateMatrix(x);
for(vector<vector<int> >::iterator it = y.begin(); it!=y.end(); it++){
for(vector<int>::iterator itt = it->begin(); itt!=it->end(); itt++){
printf("%2d ",*itt);
}printf("\n");
}
return 0;
}
| 29.181818
| 83
| 0.507788
|
Song1996
|
962b807c23f1c0dcba9e38d5c484db8f2ed7c8c1
| 3,300
|
cpp
|
C++
|
src/csv_small/csv_small.cpp
|
fuzzuf/fuzz_toys
|
e2952a17f54653e4ff8a9d1d3f96e6b46d70e8bb
|
[
"MIT"
] | 1
|
2021-12-29T02:48:00.000Z
|
2021-12-29T02:48:00.000Z
|
src/csv_small/csv_small.cpp
|
fuzzuf/fuzz_toys
|
e2952a17f54653e4ff8a9d1d3f96e6b46d70e8bb
|
[
"MIT"
] | null | null | null |
src/csv_small/csv_small.cpp
|
fuzzuf/fuzz_toys
|
e2952a17f54653e4ff8a9d1d3f96e6b46d70e8bb
|
[
"MIT"
] | 1
|
2022-01-03T07:22:15.000Z
|
2022-01-03T07:22:15.000Z
|
// SPDX-License-Identifier: MIT
// Copyright 2021 Ricerca Security, Inc.
#include <cstdint>
#include <vector>
#include <iterator>
#include <iostream>
#include <string>
#include <algorithm>
#include <stdexcept>
#include <tuple>
using csv_record_t = std::vector< std::string >;
using csv_t = std::vector< csv_record_t >;
struct invalid_csv : public std::runtime_error {
using std::runtime_error::runtime_error;
};
const char *parse_blank(
const char *begin, const char *end
) {
return std::find_if( begin, end, []( const auto &c ) {
return c != ' ' && c != '\t';
} );
}
const char *parse_eol(
const char *begin, const char *end
) {
return std::find_if( begin, end, []( const auto &c ) {
return c != '\x0d' && c != '\x0a';
} );
}
std::tuple< const char *, std::string > parse_quoted_token( const char *begin, const char *end ) {
auto meta = std::find_if( begin, end, []( const auto &c ) {
return c == '"';
} );
if( meta == end ) throw invalid_csv( "\"が閉じられていない" );
auto next = std::next( meta );
if( next != end && *next == '"' ) {
auto [last_quote,tail] = parse_quoted_token( std::next( next ), end );
return std::make_tuple( last_quote, std::string( begin, meta ) + '"' + tail );
}
auto end_of_token = parse_blank( next, end );
return std::make_tuple( end_of_token, std::string( begin, meta ) );
}
std::tuple< const char *, std::string > parse_token(
const char *begin, const char *end
) {
auto meta = std::find_if( begin, end, []( const auto &c ) {
return c == ',' || c == '\x0d' || c == '\x0a' || c == '"';
} );
if( meta == end ) return std::make_tuple( meta, std::string( begin, meta ) );
else if( *meta == '"' ) {
auto non_blank = parse_blank( begin, meta );
if( non_blank != meta ) throw invalid_csv( "\"の前に値がある" );
return parse_quoted_token( std::next( meta ), end );
}
return std::make_tuple( meta, std::string( begin, meta ) );
}
std::tuple< const char *, csv_record_t > parse_record(
const char *begin, const char *end
) {
csv_record_t record;
auto [head_end,head] = parse_token( begin, end );
record.push_back( std::move( head ) );
if( head_end == end ) return std::make_tuple( head_end, record );
else if( *head_end == ',' ) {
auto [tail_end,tail] = parse_record( std::next( head_end ), end );
record.insert( record.end(), tail.begin(), tail.end() );
return std::make_tuple( tail_end, record );
}
auto new_line = parse_eol( head_end, end );
return std::make_tuple( new_line, record );
}
std::tuple< const char *, csv_t > parse_csv(
const char *begin, const char *end
) {
csv_t csv;
auto [head_end,head] = parse_record( begin, end );
csv.push_back( std::move( head ) );
if( head_end == end ) return std::make_tuple( head_end, csv );
auto [tail_end,tail] = parse_csv( head_end, end );
csv.insert( csv.end(), tail.begin(), tail.end() );
return std::make_tuple( tail_end, csv );
}
int main() {
std::vector< char > data(
std::istreambuf_iterator< char >{ std::cin },
std::istreambuf_iterator< char >{}
);
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-variable"
auto [end,parsed] = parse_csv( data.data(), std::next( data.data(), data.size() ) );
#pragma GCC diagnostic pop
std::cout << parsed.size() << "lines" << std::endl;
}
| 34.020619
| 98
| 0.629697
|
fuzzuf
|
962c6882fea216549bb401db12975323f4890989
| 168
|
hpp
|
C++
|
src/autograph/glm_pixel_types.hpp
|
ennis/autograph
|
4dcbdb75bf088a3a8039fbb8df88cf512a4f8b7d
|
[
"MIT"
] | null | null | null |
src/autograph/glm_pixel_types.hpp
|
ennis/autograph
|
4dcbdb75bf088a3a8039fbb8df88cf512a4f8b7d
|
[
"MIT"
] | null | null | null |
src/autograph/glm_pixel_types.hpp
|
ennis/autograph
|
4dcbdb75bf088a3a8039fbb8df88cf512a4f8b7d
|
[
"MIT"
] | null | null | null |
#ifndef GLM_PIXEL_TYPES_HPP
#define GLM_PIXEL_TYPES_HPP
#include <glm/glm.hpp>
#include "pixel_format.hpp"
namespace ag
{
// TODO
}
#endif // !GLM_PIXEL_TYPES_HPP
| 12.923077
| 30
| 0.755952
|
ennis
|
962caa3aec774485d7adaa04c9cd8aa7d9a66d2c
| 1,608
|
hpp
|
C++
|
engine/effects/include/ModifyStatisticsEffect.hpp
|
prolog/shadow-of-the-wyrm
|
a1312c3e9bb74473f73c4e7639e8bd537f10b488
|
[
"MIT"
] | 60
|
2019-08-21T04:08:41.000Z
|
2022-03-10T13:48:04.000Z
|
engine/effects/include/ModifyStatisticsEffect.hpp
|
prolog/shadow-of-the-wyrm
|
a1312c3e9bb74473f73c4e7639e8bd537f10b488
|
[
"MIT"
] | 3
|
2021-03-18T15:11:14.000Z
|
2021-10-20T12:13:07.000Z
|
engine/effects/include/ModifyStatisticsEffect.hpp
|
prolog/shadow-of-the-wyrm
|
a1312c3e9bb74473f73c4e7639e8bd537f10b488
|
[
"MIT"
] | 8
|
2019-11-16T06:29:05.000Z
|
2022-01-23T17:33:43.000Z
|
#pragma once
#include "Effect.hpp"
#include "Modifier.hpp"
enum struct ModifyStatisticsDuration
{
MODIFY_STATISTICS_DURATION_PRESET = 0,
MODIFY_STATISTICS_DURATION_CALCULATE = 1
};
class ModifyStatisticsEffect : public Effect
{
public:
virtual std::string get_effect_identification_message(std::shared_ptr<Creature> creature) const override;
virtual Effect* clone() override;
void set_modifier(const Modifier& new_m);
Modifier get_modifier() const;
void set_spell_id(const std::string& new_spell_id);
std::string get_spell_id() const;
void set_source_id(const std::string& new_source_id);
std::string get_source_id() const;
virtual bool apply_modifiers(std::shared_ptr<Creature>, const Modifier& m, const ModifyStatisticsDuration msd, const double duration = -1) const;
virtual bool is_negative_effect() const override;
protected:
friend class SW_Engine_Effects_ModifyStatisticsEffect;
virtual bool effect_blessed(std::shared_ptr<Creature> creature, ActionManager * const am, const Coordinate& affected_coordinate, TilePtr affected_tile) override;
virtual bool effect_uncursed(std::shared_ptr<Creature> creature, ActionManager * const am, const Coordinate& affected_coordinate, TilePtr affected_tile) override;
virtual bool effect_cursed(std::shared_ptr<Creature> creature, ActionManager * const am, const Coordinate& affected_coordinate, TilePtr affected_tile) override;
virtual int get_primary_statistic_modifier(int stat_score, int stat_modifier) const;
Modifier m;
std::string spell_id;
std::string source_id;
};
| 37.395349
| 166
| 0.780473
|
prolog
|
963062eb16be1c8ce92aa0cdcd59cf9a3a302cef
| 482
|
cpp
|
C++
|
codeforces/contests/round/672-div2/a.cpp
|
tysm/cpsols
|
262212646203e516d1706edf962290de93762611
|
[
"MIT"
] | 4
|
2020-10-05T19:24:10.000Z
|
2021-07-15T00:45:43.000Z
|
codeforces/contests/round/672-div2/a.cpp
|
tysm/cpsols
|
262212646203e516d1706edf962290de93762611
|
[
"MIT"
] | null | null | null |
codeforces/contests/round/672-div2/a.cpp
|
tysm/cpsols
|
262212646203e516d1706edf962290de93762611
|
[
"MIT"
] | null | null | null |
#include <cpplib/stdinc.hpp>
int32_t main(){
desync();
int t;
cin >> t;
while(t--){
int n;
cin >> n;
vii vals;
for(int i=0; i<n; ++i){
int x;
cin >> x;
vals.eb(x, i);
}
sort(all(vals));
vi arr(n);
for(int i=0; i<n; ++i)
arr[vals[i].ss] = i;
reverse(all(arr));
cout << (is_sorted(all(arr))? "NO" : "YES") << endl;
}
return 0;
}
| 17.851852
| 60
| 0.377593
|
tysm
|
96318ac073987c3762033ccb03d68793921c741f
| 394
|
cpp
|
C++
|
code/TrainArrival.cpp
|
eskottova/MaturaProject
|
77e5dd61bc2860ebdc40a197d397f527eda3bda5
|
[
"OML"
] | 1
|
2020-11-06T20:58:24.000Z
|
2020-11-06T20:58:24.000Z
|
code/TrainArrival.cpp
|
eskottova/MaturaProject
|
77e5dd61bc2860ebdc40a197d397f527eda3bda5
|
[
"OML"
] | null | null | null |
code/TrainArrival.cpp
|
eskottova/MaturaProject
|
77e5dd61bc2860ebdc40a197d397f527eda3bda5
|
[
"OML"
] | null | null | null |
#include "TrainArrival.hpp"
Solution::TrainArrival::TrainArrival(Solution* sol, int time, Train* train, Station* station)
{
this->sol = sol;
this->time = time;
this->train = train;
this->station = station;
this->priority = 0;
}
bool Solution::TrainArrival::run()
{
this->train->set_station(this->station);
return this->train->unboard(this->station, this->time);
}
| 23.176471
| 93
| 0.664975
|
eskottova
|
9634cf5f239f1a7693ae31d218b09ba973526ca2
| 282
|
cpp
|
C++
|
binarysearch.io/easy/Narcissistic-number.cpp
|
wingkwong/competitive-programming
|
e8bf7aa32e87b3a020b63acac20e740728764649
|
[
"MIT"
] | 18
|
2020-08-27T05:27:50.000Z
|
2022-03-08T02:56:48.000Z
|
binarysearch.io/easy/Narcissistic-number.cpp
|
wingkwong/competitive-programming
|
e8bf7aa32e87b3a020b63acac20e740728764649
|
[
"MIT"
] | null | null | null |
binarysearch.io/easy/Narcissistic-number.cpp
|
wingkwong/competitive-programming
|
e8bf7aa32e87b3a020b63acac20e740728764649
|
[
"MIT"
] | 1
|
2020-10-13T05:23:58.000Z
|
2020-10-13T05:23:58.000Z
|
#include "solution.hpp"
using namespace std;
class Solution {
public:
bool solve(int n) {
int d=n>0?(int)log10((double)n)+1:1;
int ans=0, num=n;
while(n){
ans+=pow(n%10,d);
n/=10;
}
return ans==num;
}
};
| 16.588235
| 44
| 0.468085
|
wingkwong
|
963bbffe69af8ea32ba3dc7f6b350d028d123fd4
| 5,384
|
cpp
|
C++
|
src/app/pccclient.cpp
|
Alexyali/PCC-Uspace
|
30c2cfe1e276646aae03751b9df91889afea42dd
|
[
"BSD-3-Clause"
] | 98
|
2018-04-10T22:14:45.000Z
|
2022-03-11T07:02:18.000Z
|
src/app/pccclient.cpp
|
Alexyali/PCC-Uspace
|
30c2cfe1e276646aae03751b9df91889afea42dd
|
[
"BSD-3-Clause"
] | 22
|
2018-04-10T13:53:33.000Z
|
2021-10-11T05:40:18.000Z
|
src/app/pccclient.cpp
|
Alexyali/PCC-Uspace
|
30c2cfe1e276646aae03751b9df91889afea42dd
|
[
"BSD-3-Clause"
] | 57
|
2018-05-18T14:30:23.000Z
|
2022-03-20T14:05:07.000Z
|
#include "../core/udt.h"
#include <iostream>
#include <signal.h>
#ifndef WIN32
#include <cstdlib>
#include <cstring>
#include <netdb.h>
#include <unistd.h>
#else
#include <winsock2.h>
#include <ws2tcpip.h>
#include <wspiapi.h>
#endif
using namespace std;
#ifndef WIN32
void* monitor(void*);
#else
DWORD WINAPI monitor(LPVOID);
#endif
void intHandler(int dummy) {
//TODO (nathan jay): Print useful summary statistics.
exit(0);
}
int main(int argc, char* argv[]) {
if (argc < 4 || 0 == atoi(argv[3])) {
cout << "usage: " << argv[0]
<< " <send|recv> server_ip server_port "
<< "[control algorithm] [utility tag] [utility parameter]";
cout << endl;
return 0;
}
bool should_send = !strcmp(argv[1], "send");
signal(SIGINT, intHandler);
// use this function to initialize the UDT library
UDT::startup();
struct addrinfo hints, *local, *peer;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_flags = AI_PASSIVE;
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
if (0 != getaddrinfo(NULL, "9000", &hints, &local)) {
cout << "incorrect network address.\n" << endl;
return 0;
}
// CUDT class constructor will be called here.
UDTSOCKET client =
UDT::socket(local->ai_family, local->ai_socktype, local->ai_protocol);
// Set PCC control algorithm.
string pcc_control_algorithm = "Vivace";
if (argc >= 5) {
pcc_control_algorithm = argv[4];
}
UDT::setsockopt(client, 0, UDT_PCC, &pcc_control_algorithm,
pcc_control_algorithm.size());
// Set PCC utility tag and parameters.
string utility_tag = "Vivace";
if (argc >= 6) {
utility_tag = argv[5];
}
UDT::setsockopt(client, 0, UDT_UTAG, &utility_tag, utility_tag.size());
if (utility_tag == "HybridAllegro" || utility_tag == "HybridVivace" ||
utility_tag == "Scavenger" || utility_tag == "RateLimiter" ||
utility_tag == "Hybrid") {
if (argc < 7) {
cout << "Parameter should be provided for [" << utility_tag
<< "] utility function" << endl;
return 0;
} else {
UDT::setsockopt(client, 0, UDT_UPARAM, new float(atof(argv[6])),
sizeof(float));
}
}
if (utility_tag == "Proportional" || utility_tag == "TEST") {
if (argc < 7) {
UDT::setsockopt(client, 0, UDT_UPARAM, new float(900), sizeof(float));
UDT::setsockopt(client, 0, UDT_UPARAM, new float(11.35), sizeof(float));
} else if (argc == 7) {
UDT::setsockopt(client, 0, UDT_UPARAM, new float(atof(argv[6])),
sizeof(float));
UDT::setsockopt(client, 0, UDT_UPARAM, new float(11.35), sizeof(float));
} else {
UDT::setsockopt(client, 0, UDT_UPARAM, new float(atof(argv[6])),
sizeof(float));
UDT::setsockopt(client, 0, UDT_UPARAM, new float(atof(argv[7])),
sizeof(float));
}
}
#ifdef WIN32
// Windows UDP issue
// For better performance, modify HKLM\System\CurrentControlSet\Services\Afd\
// \Parameters\FastSendDatagramThreshold
UDT::setsockopt(client, 0, UDT_MSS, new int(1052), sizeof(int));
#endif
freeaddrinfo(local);
if (0 != getaddrinfo(argv[2], argv[3], &hints, &peer)) {
cout << "incorrect server/peer address. " << argv[1] << ":" << argv[2];
cout << endl;
return 0;
}
// connect to the server, implict bind
if (UDT::ERROR == UDT::connect(client, peer->ai_addr, peer->ai_addrlen)) {
cout << "connect: " << UDT::getlasterror().getErrorMessage() << endl;
return 0;
}
freeaddrinfo(peer);
// using CC method
int temp;
int size = 100000;
char* data = new char[size];
bzero(data, size);
#ifndef WIN32
pthread_create(new pthread_t, NULL, monitor, &client);
#else
CreateThread(NULL, 0, monitor, &client, 0, NULL);
#endif
if (should_send) {
while (true) {
int ssize = 0;
int ss;
while (ssize < size) {
if (UDT::ERROR ==
(ss = UDT::send(client, data + ssize, size - ssize, 0))) {
cout << "send:" << UDT::getlasterror().getErrorMessage() << endl;
break;
}
ssize += ss;
}
if (ssize < size) {
break;
}
}
} else {
while (true) {
int rsize = 0;
int rs;
while (rsize < size) {
if (UDT::ERROR ==
(rs = UDT::recv(client, data + rsize, size - rsize, 0))) {
cout << "recv:" << UDT::getlasterror().getErrorMessage() << endl;
break;
}
rsize += rs;
}
if (rsize < size) {
break;
}
}
}
UDT::close(client);
delete [] data;
// use this function to release the UDT library
UDT::cleanup();
return 1;
}
#ifndef WIN32
void* monitor(void* s)
#else
DWORD WINAPI monitor(LPVOID s)
#endif
{
UDTSOCKET u = *(UDTSOCKET*)s;
UDT::TRACEINFO perf;
cout << "SendRate(Mb/s)\tRTT(ms)\tCTotal\tLoss\tRecvACK\tRecvNAK" << endl;
int i=0;
while (true) {
#ifndef WIN32
usleep(1000000);
#else
Sleep(1000);
#endif
i++;
if (UDT::ERROR == UDT::perfmon(u, &perf)) {
cout << "perfmon: " << UDT::getlasterror().getErrorMessage() << endl;
break;
}
cout << i << "\t" << perf.mbpsSendRate << "\t" << perf.msRTT << "\t"
<< perf.pktSentTotal << "\t" << perf.pktSndLossTotal << endl;
}
#ifndef WIN32
return NULL;
#else
return 0;
#endif
}
| 24.252252
| 79
| 0.58841
|
Alexyali
|
963dd2ec775062256534e4470e3028e67f4b82fb
| 819
|
cpp
|
C++
|
solved-lightOj/1005.cpp
|
Maruf-Tuhin/Online_Judge
|
cf9b2a522e8b1a9623d3996a632caad7fd67f751
|
[
"MIT"
] | 1
|
2019-03-31T05:47:30.000Z
|
2019-03-31T05:47:30.000Z
|
solved-lightOj/1005.cpp
|
the-redback/competitive-programming
|
cf9b2a522e8b1a9623d3996a632caad7fd67f751
|
[
"MIT"
] | null | null | null |
solved-lightOj/1005.cpp
|
the-redback/competitive-programming
|
cf9b2a522e8b1a9623d3996a632caad7fd67f751
|
[
"MIT"
] | null | null | null |
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
long long fact[35];
main()
{
int i,n,mx,mn,k,t,T;
long long sum;
fact[0]=1;
for(i=1; i<=30; i++)
{
fact[i]=fact[i-1]*i;
}
sum=0;
scanf("%d",&T);
for(t=1; t<=T; t++)
{
sum=0;
scanf("%d %d",&n,&k);
if(k>n)
{
printf("Case %d: 0\n",t);
}
else
{
mx=max(k,n-k);
mn=min(k,n-k);
sum=1;
for(i=mx+1;i<=n;i++)
{
sum*=i;
}
if(sum!=0)
sum=sum/fact[mn];
for(i=n-k+1;i<=n;i++)
{
sum*=i;
}
printf("Case %d: %lld\n",t,sum);
}
}
return 0;
}
| 17.0625
| 44
| 0.334554
|
Maruf-Tuhin
|
9646070fcc51537b487142bbb3cd046068b14caf
| 1,246
|
cpp
|
C++
|
source/magma/light-controllers/point-light-controller.cpp
|
Breush/lava
|
1b1b1f0785300b93b4a9f35fca4490502fea6552
|
[
"MIT"
] | 15
|
2018-02-26T08:20:03.000Z
|
2022-03-06T03:25:46.000Z
|
source/magma/light-controllers/point-light-controller.cpp
|
Breush/lava
|
1b1b1f0785300b93b4a9f35fca4490502fea6552
|
[
"MIT"
] | 32
|
2018-02-26T08:26:38.000Z
|
2020-09-12T17:09:38.000Z
|
source/magma/light-controllers/point-light-controller.cpp
|
Breush/lava
|
1b1b1f0785300b93b4a9f35fca4490502fea6552
|
[
"MIT"
] | null | null | null |
#include <lava/magma/light-controllers/point-light-controller.hpp>
#include <lava/magma/light.hpp>
using namespace lava::magma;
void PointLightController::bind(Light& light)
{
m_light = &light;
// Force UBO update default values.
auto& ubo = m_light->ubo();
ubo.type = static_cast<uint32_t>(LightType::Point);
ubo.data[0].x = reinterpret_cast<const uint32_t&>(m_translation.x);
ubo.data[0].y = reinterpret_cast<const uint32_t&>(m_translation.y);
ubo.data[0].z = reinterpret_cast<const uint32_t&>(m_translation.z);
ubo.data[1].x = reinterpret_cast<const uint32_t&>(m_radius);
m_light->uboChanged();
}
// ----- Controls
void PointLightController::translation(const glm::vec3& translation)
{
m_translation = translation;
auto& ubo = m_light->ubo();
ubo.data[0].x = reinterpret_cast<const uint32_t&>(m_translation.x);
ubo.data[0].y = reinterpret_cast<const uint32_t&>(m_translation.y);
ubo.data[0].z = reinterpret_cast<const uint32_t&>(m_translation.z);
m_light->uboChanged();
}
void PointLightController::radius(float radius)
{
m_radius = radius;
auto& ubo = m_light->ubo();
ubo.data[1].x = reinterpret_cast<const uint32_t&>(m_radius);
m_light->uboChanged();
}
| 27.688889
| 71
| 0.698234
|
Breush
|
964ce5a1d8670c5d8f13a7ca44d1e029893d6a1c
| 23
|
cpp
|
C++
|
base/Windows/singx86/precomp.cpp
|
sphinxlogic/Singularity-RDK-2.0
|
2968c3b920a5383f7360e3e489aa772f964a7c42
|
[
"MIT"
] | null | null | null |
base/Windows/singx86/precomp.cpp
|
sphinxlogic/Singularity-RDK-2.0
|
2968c3b920a5383f7360e3e489aa772f964a7c42
|
[
"MIT"
] | null | null | null |
base/Windows/singx86/precomp.cpp
|
sphinxlogic/Singularity-RDK-2.0
|
2968c3b920a5383f7360e3e489aa772f964a7c42
|
[
"MIT"
] | null | null | null |
#include "singx86.h"
| 11.5
| 22
| 0.652174
|
sphinxlogic
|
964d728f48652640c73d7c32beef1b77ce1eec4e
| 903
|
hpp
|
C++
|
include/TagFile.hpp
|
lpraz/tiger
|
b56f2fb3833cd24a9f99de0d454dd25ca794f299
|
[
"MIT"
] | null | null | null |
include/TagFile.hpp
|
lpraz/tiger
|
b56f2fb3833cd24a9f99de0d454dd25ca794f299
|
[
"MIT"
] | null | null | null |
include/TagFile.hpp
|
lpraz/tiger
|
b56f2fb3833cd24a9f99de0d454dd25ca794f299
|
[
"MIT"
] | null | null | null |
/**
* @file
* author lpraz
*
* @section DESCRIPTION
* Header file for the TagFile class.
*/
#ifndef TAGFILE_HPP
#define TAGFILE_HPP
// Stdlib includes
#include <fstream>
#include <string>
#include <unordered_map>
#include <vector>
namespace Tiger {
/**
* Represents, and provides access to, tiger's tag file, which holds
* all tags and the files they are attached to.
*/
class TagFile {
private:
const std::string tagFilePath = "/.tiger";
std::string homeDirectory;
std::unordered_map<std::string, std::vector<std::string>>
tagDict;
std::string readQuotedString(std::istream& stream);
public:
TagFile();
void close();
std::unordered_map<std::string, std::vector<std::string>>&
getTags(void);
};
}
#endif
| 22.02439
| 72
| 0.568106
|
lpraz
|
9652b7a6ff68a6e6f440f15052414cd7910a5932
| 10,243
|
cpp
|
C++
|
Chapter11/scratchpad.cpp
|
trantrongquy/Hands-On-System-Programming-with-CPP
|
c29f464c4df79f0d5a55a61f02a2558be74a329c
|
[
"MIT"
] | 88
|
2018-07-20T17:38:40.000Z
|
2022-03-16T15:00:20.000Z
|
Chapter11/scratchpad.cpp
|
trantrongquy/Hands-On-System-Programming-with-CPP
|
c29f464c4df79f0d5a55a61f02a2558be74a329c
|
[
"MIT"
] | 1
|
2020-01-01T08:12:24.000Z
|
2020-01-01T08:12:24.000Z
|
Chapter11/scratchpad.cpp
|
trantrongquy/Hands-On-System-Programming-with-CPP
|
c29f464c4df79f0d5a55a61f02a2558be74a329c
|
[
"MIT"
] | 46
|
2019-01-27T15:19:45.000Z
|
2022-03-04T13:21:23.000Z
|
//
// Copyright (C) 2018 Rian Quinn <rianquinn@gmail.com>
//
// 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.
// -----------------------------------------------------------------------------
// Section: Stream Based IO
// -----------------------------------------------------------------------------
#if SNIPPET01
#include <ctime>
#include <iostream>
int main()
{
auto t = time(nullptr);
std::cout << "time: " << t << '\n';
}
// > g++ -std=c++17 scratchpad.cpp; ./a.out
// time: 1531603643
#endif
#if SNIPPET02
#include <ctime>
#include <iostream>
int main()
{
time_t t;
time(&t);
std::cout << "time: " << t << '\n';
}
// > g++ -std=c++17 scratchpad.cpp; ./a.out
// time: 1531603652
#endif
#if SNIPPET03
#include <ctime>
#include <iostream>
int main()
{
auto t = time(nullptr);
std::cout << "time: " << ctime(&t);
}
// > g++ -std=c++17 scratchpad.cpp; ./a.out
// time: Sat Jul 14 15:27:44 2018
#endif
#if SNIPPET05
#include <ctime>
#include <iostream>
int main()
{
auto t = time(nullptr);
std::cout << "time: " << asctime(localtime(&t));
}
// > g++ -std=c++17 scratchpad.cpp; ./a.out
// time: Sat Jul 14 15:28:59 2018
#endif
#if SNIPPET06
#include <ctime>
#include <iostream>
int main()
{
auto t = time(nullptr);
std::cout << "time: " << asctime(gmtime(&t));
}
// > g++ -std=c++17 scratchpad.cpp; ./a.out
// time: Sat Jul 14 21:46:12 2018
#endif
#if SNIPPET07
#include <ctime>
#include <iostream>
int main()
{
auto t = time(nullptr);
char buf[256]{};
strftime(buf, sizeof(buf), "%m/%d/%Y", localtime(&t));
std::cout << "time: " << buf << '\n';
}
// > g++ -std=c++17 scratchpad.cpp; ./a.out
// time: 07/14/2018
#endif
#if SNIPPET08
#include <ctime>
#include <iostream>
int main()
{
auto t = time(nullptr);
char buf[256]{};
strftime(buf, sizeof(buf), "%H:%M", localtime(&t));
std::cout << "time: " << buf << '\n';
}
// > g++ -std=c++17 scratchpad.cpp; ./a.out
// time: 15:41
#endif
#if SNIPPET09
#include <ctime>
#include <iostream>
int main()
{
auto t = time(nullptr);
char buf[256]{};
strftime(buf, sizeof(buf), "%a %b %d %H:%M:%S %Y", localtime(&t));
std::cout << "time: " << buf << '\n';
}
// > g++ -std=c++17 scratchpad.cpp; ./a.out
// time: Sat Jul 14 15:44:57 2018
#endif
#if SNIPPET10
#include <ctime>
#include <iostream>
#include <unistd.h>
int main()
{
auto t1 = time(nullptr);
sleep(2);
auto t2 = time(nullptr);
std::cout << "diff: " << difftime(t2, t1) << '\n';
std::cout << "diff: " << t2 - t1 << '\n';
}
// > g++ -std=c++17 scratchpad.cpp; ./a.out
// diff: 2
#endif
#if SNIPPET11
#include <ctime>
#include <iostream>
int main()
{
auto t1 = time(nullptr);
auto lt = localtime(&t1);
auto t2 = mktime(lt);
std::cout << "time: " << ctime(&t2);
}
// > g++ -std=c++17 scratchpad.cpp; ./a.out
// time: Sat Jul 14 16:00:13 2018
#endif
#if SNIPPET12
#include <ctime>
#include <iostream>
int main()
{
std::cout << "clock: " << clock() << '\n';
}
// > g++ -std=c++17 scratchpad.cpp; ./a.out
// clock: 2002
#endif
#if SNIPPET13
#include <ctime>
#include <iostream>
#include <unistd.h>
int main()
{
auto c1 = clock();
sleep(2);
auto c2 = clock();
std::cout << "clock: " <<
static_cast<double>(c2 - c1) / CLOCKS_PER_SEC << '\n';
}
// > g++ -std=c++17 scratchpad.cpp; ./a.out
// clock: 3.2e-05
#endif
#if SNIPPET04
#include <ctime>
#include <iostream>
#include <unistd.h>
int main()
{
auto c1 = clock();
auto t1 = time(nullptr);
while(time(nullptr) - t1 <= 2);
auto c2 = clock();
std::cout << "clock: " <<
static_cast<double>(c2 - c1) / CLOCKS_PER_SEC << '\n';
}
// > g++ -std=c++17 scratchpad.cpp; ./a.out
// clock: 2.05336
#endif
#if SNIPPET14
#include <chrono>
#include <iostream>
int main()
{
auto t = std::chrono::system_clock::now();
std::cout << "time: " << std::chrono::system_clock::to_time_t(t) << '\n';
}
// > g++ -std=c++17 scratchpad.cpp; ./a.out
// time: 1531606644
#endif
#if SNIPPET15
#include <chrono>
#include <iostream>
template<typename C, typename D>
std::ostream &
operator<<(std::ostream &os, std::chrono::time_point<C,D> &obj)
{
auto t = std::chrono::system_clock::to_time_t(obj);
return os << ctime(&t);
}
int main()
{
auto now = std::chrono::system_clock::now();
std::cout << "time: " << now;
}
// > g++ -std=c++17 scratchpad.cpp; ./a.out
// time: Sat Jul 14 19:01:55 2018
#endif
#if SNIPPET16
#include <chrono>
#include <iostream>
using namespace std::chrono;
template<typename C, typename D>
std::ostream &
operator<<(std::ostream &os, std::chrono::time_point<C,D> &obj)
{
auto t = std::chrono::system_clock::to_time_t(obj);
return os << ctime(&t);
}
int main()
{
auto now = std::chrono::system_clock::now();
std::cout << "time: " << now;
now += 1h;
std::cout << "time: " << now;
now -= 1h;
std::cout << "time: " << now;
}
// > g++ -std=c++17 scratchpad.cpp; ./a.out
// time: 1531606644
#endif
#if SNIPPET17
#include <chrono>
#include <iostream>
int main()
{
auto now1 = std::chrono::system_clock::now();
auto now2 = std::chrono::system_clock::now();
std::cout << std::boolalpha;
std::cout << "compare: " << (now1 < now2) << '\n';
std::cout << "compare: " << (now1 > now2) << '\n';
std::cout << "compare: " << (now1 <= now2) << '\n';
std::cout << "compare: " << (now1 >= now2) << '\n';
std::cout << "compare: " << (now1 == now2) << '\n';
std::cout << "compare: " << (now1 != now2) << '\n';
}
// > g++ -std=c++17 scratchpad.cpp; ./a.out
// compare: true
// compare: false
// compare: true
// compare: false
// compare: false
// compare: true
#endif
#if SNIPPET18
#include <chrono>
#include <iostream>
#include <unistd.h>
int main()
{
using namespace std::chrono;
auto now1 = system_clock::now();
sleep(2);
auto now2 = system_clock::now();
std::cout << "time: " <<
duration_cast<seconds>(now2 - now1).count() << '\n';
std::cout << "time: " <<
duration_cast<milliseconds>(now2 - now1).count() << '\n';
std::cout << "time: " <<
duration_cast<nanoseconds>(now2 - now1).count() << '\n';
}
// > g++ -std=c++17 scratchpad.cpp; ./a.out
// time: 2
// time: 2001
// time: 2001415132
#endif
#if SNIPPET19
#include <chrono>
#include <iostream>
int main()
{
using namespace std::chrono;
seconds t(42);
t++;
std::cout << "time: " << t.count() << '\n';
t--;
std::cout << "time: " << t.count() << '\n';
t += 1s;
std::cout << "time: " << t.count() << '\n';
t -= 1s;
std::cout << "time: " << t.count() << '\n';
t %= 2s;
std::cout << "time: " << t.count() << '\n';
}
// > g++ -std=c++17 scratchpad.cpp; ./a.out
// time: 43
// time: 42
// time: 43
// time: 42
// time: 0
#endif
#if SNIPPET20
#include <chrono>
#include <iostream>
int main()
{
using namespace std::chrono;
auto t1 = 0s;
auto t2 = 42s;
std::cout << std::boolalpha;
std::cout << "compare: " << (t1 < t2) << '\n';
std::cout << "compare: " << (t1 > t2) << '\n';
std::cout << "compare: " << (t1 <= t2) << '\n';
std::cout << "compare: " << (t1 >= t2) << '\n';
std::cout << "compare: " << (t1 == t2) << '\n';
std::cout << "compare: " << (t1 != t2) << '\n';
}
// > g++ -std=c++17 scratchpad.cpp; ./a.out
// compare: true
// compare: false
// compare: true
// compare: false
// compare: false
// compare: true
#endif
#if SNIPPET21
#include <chrono>
#include <iostream>
int main()
{
using namespace std::chrono;
auto s1 = -42001ms;
std::cout << "floor: " << floor<seconds>(s1).count() << '\n';
std::cout << "ceil: " << ceil<seconds>(s1).count() << '\n';
std::cout << "round: " << round<seconds>(s1).count() << '\n';
std::cout << "abs: " << abs(s1).count() << '\n';
}
// > g++ -std=c++17 scratchpad.cpp; ./a.out
// floor: -43
// ceil: -42
// round: -42
// abs: 42001
#endif
#if SNIPPET22
#include <chrono>
#include <iostream>
#include <unistd.h>
int main()
{
using namespace std::chrono;
auto now1 = steady_clock::now();
sleep(2);
auto now2 = steady_clock::now();
std::cout << "time: " <<
duration_cast<seconds>(now2 - now1).count() << '\n';
std::cout << "time: " <<
duration_cast<milliseconds>(now2 - now1).count() << '\n';
std::cout << "time: " <<
duration_cast<nanoseconds>(now2 - now1).count() << '\n';
}
// > g++ -std=c++17 scratchpad.cpp; ./a.out
// time: 2
// time: 2001
// time: 2001447628
#endif
#if SNIPPET23
#include <chrono>
#include <iostream>
#include <unistd.h>
int main()
{
using namespace std::chrono;
auto now1 = high_resolution_clock::now();
sleep(2);
auto now2 = high_resolution_clock::now();
std::cout << "time: " <<
duration_cast<seconds>(now2 - now1).count() << '\n';
std::cout << "time: " <<
duration_cast<milliseconds>(now2 - now1).count() << '\n';
std::cout << "time: " <<
duration_cast<nanoseconds>(now2 - now1).count() << '\n';
}
// > g++ -std=c++17 scratchpad.cpp; ./a.out
// time: 2
// time: 2000
// time: 2002297281
#endif
| 18.323792
| 81
| 0.564776
|
trantrongquy
|
96559ccb364778fca550241e6fd8640c84f2f4e7
| 339
|
cc
|
C++
|
leetcode/remove-duplicates-from-sorted-array-ii.cc
|
Waywrong/leetcode-solution
|
55115aeab4040f5ff84bdce6ffcfe4a98f879616
|
[
"MIT"
] | null | null | null |
leetcode/remove-duplicates-from-sorted-array-ii.cc
|
Waywrong/leetcode-solution
|
55115aeab4040f5ff84bdce6ffcfe4a98f879616
|
[
"MIT"
] | null | null | null |
leetcode/remove-duplicates-from-sorted-array-ii.cc
|
Waywrong/leetcode-solution
|
55115aeab4040f5ff84bdce6ffcfe4a98f879616
|
[
"MIT"
] | null | null | null |
// Remove Duplicates from Sorted Array II
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if (nums.size() < 3) return nums.size();
int res = 2;
for (int i=2; i<nums.size(); i++)
if (nums[i] != nums[res-2])
nums[res ++] = nums[i];
return res;
}
};
| 26.076923
| 51
| 0.501475
|
Waywrong
|
965839996ac0a15314ad338778889306508917c5
| 799
|
cpp
|
C++
|
C++/LeetCode/0064.cpp
|
Nimesh-Srivastava/DSA
|
db33aa138f0df8ab6015d2e8ec3ddde1c6838848
|
[
"MIT"
] | 4
|
2021-08-28T19:16:50.000Z
|
2022-03-04T19:46:31.000Z
|
C++/LeetCode/0064.cpp
|
Nimesh-Srivastava/DSA
|
db33aa138f0df8ab6015d2e8ec3ddde1c6838848
|
[
"MIT"
] | 8
|
2021-10-29T19:10:51.000Z
|
2021-11-03T12:38:00.000Z
|
C++/LeetCode/0064.cpp
|
Nimesh-Srivastava/DSA
|
db33aa138f0df8ab6015d2e8ec3ddde1c6838848
|
[
"MIT"
] | 4
|
2021-09-06T05:53:07.000Z
|
2021-12-24T10:31:40.000Z
|
class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
int row = grid.size();
int col = grid[0].size();
vector<vector<int>> dp(row, vector<int>(col, 0));
for(int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
if(i == 0 && j == 0)
dp[0][0] = grid[0][0];
else if(i == 0)
dp[0][j] = dp[0][j - 1] + grid[0][j];
else if(j == 0)
dp[i][0] = dp[i - 1][0] + grid[i][0];
else
dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j];
}
}
return dp[row - 1][col - 1];
}
};
| 27.551724
| 76
| 0.305382
|
Nimesh-Srivastava
|
965d9a6bf93ab6056fdfdef9b6439480a7ad1472
| 4,987
|
cpp
|
C++
|
cpp/test/counters/CounterTest.cpp
|
yukonfb/profilo
|
baf0ef6e4c140f5b1cdf110b90698f9e8ca7c375
|
[
"Apache-2.0"
] | null | null | null |
cpp/test/counters/CounterTest.cpp
|
yukonfb/profilo
|
baf0ef6e4c140f5b1cdf110b90698f9e8ca7c375
|
[
"Apache-2.0"
] | null | null | null |
cpp/test/counters/CounterTest.cpp
|
yukonfb/profilo
|
baf0ef6e4c140f5b1cdf110b90698f9e8ca7c375
|
[
"Apache-2.0"
] | null | null | null |
/**
* Copyright 2004-present, Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <counters/Counter.h>
#include <profilo/MultiBufferLogger.h>
#include <vector>
using facebook::profilo::logger::MultiBufferLogger;
using facebook::profilo::mmapbuf::Buffer;
namespace facebook {
namespace profilo {
namespace counters {
constexpr auto kTid = 12345;
constexpr auto kCounterType = QuickLogConstants::THREAD_CPU_TIME;
constexpr auto kValueA = 22;
constexpr auto kValueB = 44;
constexpr auto kTimestamp1 = 1;
constexpr auto kTimestamp2 = 2;
constexpr auto kTimestamp3 = 3;
constexpr auto kTimestamp4 = 4;
using namespace ::testing;
class TracedCounterTest : public Test {
protected:
TracedCounterTest()
: buffer(std::make_shared<Buffer>(100)),
logger(),
counter_(logger, kCounterType, kTid) {
logger.addBuffer(buffer);
}
std::vector<StandardEntry> writtenEntries() {
auto& rb = buffer->ringBuffer();
auto cursor = rb.currentTail();
std::vector<StandardEntry> entries{};
logger::Packet packet{};
while (rb.tryRead(packet, cursor)) {
StandardEntry entry{};
StandardEntry::unpack(entry, packet.data, packet.size);
entries.emplace_back(entry);
cursor.moveForward();
}
return entries;
}
std::shared_ptr<Buffer> buffer;
MultiBufferLogger logger;
Counter counter_;
};
TEST_F(TracedCounterTest, testTimestampInvariantIsProtected) {
counter_.record(kValueA, kTimestamp1);
EXPECT_THROW(counter_.record(kValueB, kTimestamp1), std::runtime_error);
}
TEST_F(TracedCounterTest, testSinglePointLoggingCorrectness) {
counter_.record(kValueA, kTimestamp1);
auto entries = writtenEntries();
EXPECT_EQ(entries.size(), 1);
StandardEntry& loggedEntry = entries.front();
EXPECT_EQ(loggedEntry.type, EntryType::COUNTER);
EXPECT_EQ(loggedEntry.timestamp, kTimestamp1);
EXPECT_EQ(loggedEntry.tid, kTid);
EXPECT_EQ(loggedEntry.callid, kCounterType);
EXPECT_EQ(loggedEntry.extra, kValueA);
}
TEST_F(TracedCounterTest, testZeroInitalCounterValueIsLogged) {
counter_.record(0, kTimestamp1);
counter_.record(0, kTimestamp2);
counter_.record(kValueA, kTimestamp3);
EXPECT_EQ(writtenEntries().size(), 3);
}
//
// * --- x
//
// [*] - logged point
// [x] - skipped point
//
TEST_F(TracedCounterTest, testDuplicatePointsAreIgnored) {
counter_.record(kValueA, kTimestamp1);
counter_.record(kValueA, kTimestamp2);
EXPECT_EQ(writtenEntries().size(), 1);
}
//
// *
// /
// *
//
TEST_F(TracedCounterTest, testMovingAdjacentValuesAreLogged) {
counter_.record(kValueA, kTimestamp1);
counter_.record(kValueB, kTimestamp2);
auto entries = writtenEntries();
EXPECT_EQ(entries.size(), 2);
StandardEntry& aEntry = entries.front();
EXPECT_EQ(aEntry.timestamp, kTimestamp1);
EXPECT_EQ(aEntry.extra, kValueA);
StandardEntry& bEntry = entries.back();
EXPECT_EQ(bEntry.timestamp, kTimestamp2);
EXPECT_EQ(bEntry.extra, kValueB);
}
//
// *
// /
// * --- *
//
TEST_F(TracedCounterTest, testThreePointsWithOneDuplicate) {
counter_.record(kValueA, kTimestamp1);
counter_.record(kValueA, kTimestamp2);
counter_.record(kValueB, kTimestamp3);
auto entries = writtenEntries();
EXPECT_EQ(entries.size(), 3);
StandardEntry aEntry = entries.at(0);
EXPECT_EQ(aEntry.timestamp, kTimestamp1);
EXPECT_EQ(aEntry.extra, kValueA);
StandardEntry bEntry = entries.at(1);
EXPECT_EQ(bEntry.timestamp, kTimestamp2);
EXPECT_EQ(bEntry.extra, kValueA);
StandardEntry cEntry = entries.at(2);
EXPECT_EQ(cEntry.timestamp, kTimestamp3);
EXPECT_EQ(cEntry.extra, kValueB);
}
//
// *
// /
// * --- x --- *
//
TEST_F(TracedCounterTest, testFourPointsWithOneDuplicate) {
counter_.record(kValueA, kTimestamp1);
counter_.record(kValueA, kTimestamp2);
counter_.record(kValueA, kTimestamp3);
counter_.record(kValueB, kTimestamp4);
auto entries = writtenEntries();
EXPECT_EQ(entries.size(), 3);
StandardEntry aEntry = entries.at(0);
EXPECT_EQ(aEntry.timestamp, kTimestamp1);
EXPECT_EQ(aEntry.extra, kValueA);
StandardEntry bEntry = entries.at(1);
EXPECT_EQ(bEntry.timestamp, kTimestamp3);
EXPECT_EQ(bEntry.extra, kValueA);
StandardEntry cEntry = entries.at(2);
EXPECT_EQ(cEntry.timestamp, kTimestamp4);
EXPECT_EQ(cEntry.extra, kValueB);
}
} // namespace counters
} // namespace profilo
} // namespace facebook
| 28.016854
| 75
| 0.722278
|
yukonfb
|
965fff031c981f9671d0d3af785583b50662e8d9
| 946
|
hpp
|
C++
|
libs/core/render/include/bksge/core/render/gl/detail/primitive_topology.hpp
|
myoukaku/bksge
|
0f8b60e475a3f1709723906e4796b5e60decf06e
|
[
"MIT"
] | 4
|
2018-06-10T13:35:32.000Z
|
2021-06-03T14:27:41.000Z
|
libs/core/render/include/bksge/core/render/gl/detail/primitive_topology.hpp
|
myoukaku/bksge
|
0f8b60e475a3f1709723906e4796b5e60decf06e
|
[
"MIT"
] | 566
|
2017-01-31T05:36:09.000Z
|
2022-02-09T05:04:37.000Z
|
libs/core/render/include/bksge/core/render/gl/detail/primitive_topology.hpp
|
myoukaku/bksge
|
0f8b60e475a3f1709723906e4796b5e60decf06e
|
[
"MIT"
] | 1
|
2018-07-05T04:40:53.000Z
|
2018-07-05T04:40:53.000Z
|
/**
* @file primitive_topology.hpp
*
* @brief PrimitiveTopology クラスの定義
*
* @author myoukaku
*/
#ifndef BKSGE_CORE_RENDER_GL_DETAIL_PRIMITIVE_TOPOLOGY_HPP
#define BKSGE_CORE_RENDER_GL_DETAIL_PRIMITIVE_TOPOLOGY_HPP
#include <bksge/core/render/fwd/primitive_topology_fwd.hpp>
#include <bksge/core/render/gl/detail/gl_h.hpp>
namespace bksge
{
namespace render
{
namespace gl
{
/**
* @brief PrimitiveTopology を OpenGL の enum に変換
*/
class PrimitiveTopology
{
public:
explicit PrimitiveTopology(bksge::PrimitiveTopology primitive_topology);
operator ::GLenum() const;
private:
::GLenum const m_primitive_topology;
};
} // namespace gl
} // namespace render
} // namespace bksge
#include <bksge/fnd/config.hpp>
#if defined(BKSGE_HEADER_ONLY)
#include <bksge/core/render/gl/detail/inl/primitive_topology_inl.hpp>
#endif
#endif // BKSGE_CORE_RENDER_GL_DETAIL_PRIMITIVE_TOPOLOGY_HPP
| 18.92
| 74
| 0.741015
|
myoukaku
|
96687eee874273b28afda7452f3b3524e12d269c
| 5,327
|
cpp
|
C++
|
src/opt/gundam.cpp
|
Luberry/passinglink
|
5f6c337818812b7dd6baad73f7fc0009cc26a5e5
|
[
"MIT"
] | 76
|
2020-03-09T20:30:59.000Z
|
2022-03-29T13:39:47.000Z
|
src/opt/gundam.cpp
|
Project-Alpaca/passinglink
|
f259466d2e8aafca6c8511df3b1259156954e907
|
[
"MIT"
] | 24
|
2020-08-08T23:07:12.000Z
|
2022-03-31T20:38:07.000Z
|
src/opt/gundam.cpp
|
Project-Alpaca/passinglink
|
f259466d2e8aafca6c8511df3b1259156954e907
|
[
"MIT"
] | 18
|
2020-07-31T01:23:44.000Z
|
2022-03-23T01:14:45.000Z
|
#include "opt/gundam.h"
#include <shell/shell.h>
#include "input/queue.h"
#if defined(CONFIG_PASSINGLINK_BT)
#include <bluetooth/bluetooth.h>
#include <bluetooth/gatt.h>
#include "bt/bt.h"
#endif
#include <logging/log.h>
#define LOG_LEVEL LOG_LEVEL_INF
LOG_MODULE_REGISTER(gundam);
#if defined(CONFIG_PASSINGLINK_OPT_GUNDAM_CAMERA)
static uint8_t current_cam = 1;
namespace opt {
namespace gundam {
void reset_cam(uint8_t x) {
current_cam = x;
}
void adjust_cam(int8_t offset, bool record) {
if (input_queue_is_active()) {
LOG_ERR("input queue is currently active, aborting");
return;
}
size_t count = 0;
bool up = false;
if (record) {
current_cam += offset;
}
if (offset == 0) {
return;
} else if (offset > 0) {
count = offset;
up = true;
} else {
count = -offset;
up = false;
}
if (offset != 0) {
InputQueue* head = input_queue_alloc();
if (!head) {
LOG_ERR("failed to allocate!");
return;
}
InputQueue* cur = head;
for (size_t i = 0; i < count; ++i) {
cur->state = {};
if (up) {
cur->state.stick_up = 1;
} else {
cur->state.stick_down = 1;
}
cur->delay = K_USEC(33'333);
cur = input_queue_append(cur);
if (!cur) {
LOG_ERR("failed to allocate!");
input_queue_free(head);
return;
}
cur->state = {};
cur->delay = K_USEC(33'333);
cur = input_queue_append(cur);
if (!cur) {
LOG_ERR("failed to allocate!");
input_queue_free(head);
return;
}
}
cur->state = {};
cur->delay = K_USEC(0);
input_queue_set_active(head, true);
}
}
void set_cam(uint8_t x, bool record) {
adjust_cam(x - current_cam, record);
}
} // namespace gundam
} // namespace opt
#if defined(CONFIG_SHELL)
static int cmd_cam(const struct shell* shell, size_t argc, char** argv) {
if (argc != 2) {
shell_print(shell, "usage: cam [next | prev | reset | NUMBER]");
return 0;
}
size_t count = 0;
bool up = false;
if (strcmp(argv[1], "reset") == 0) {
opt::gundam::reset_cam(1);
} else if (strcmp(argv[1], "next") == 0) {
opt::gundam::adjust_cam(1, false);
} else if (strcmp(argv[1], "prev") == 0) {
opt::gundam::adjust_cam(-1, false);
} else {
int x = argv[1][0] - '0';
if (x < 0 || x > 9) {
shell_print(shell, "usage: cam [next | prev | reset | NUMBER]");
return 0;
}
opt::gundam::set_cam(x, true);
}
return 0;
}
SHELL_CMD_REGISTER(cam, NULL, "Gundam spectator camera control", cmd_cam);
#endif
#if defined(CONFIG_PASSINGLINK_BT)
static struct bt_uuid_128 bt_gundam_svc_uuid = BT_UUID_INIT_128(0x00, 0x28, PL_BT_UUID_PREFIX);
static struct bt_uuid_128 bt_gundam_camera_uuid = BT_UUID_INIT_128(0x01, 0x28, PL_BT_UUID_PREFIX);
static struct bt_uuid_128 bt_gundam_reset_uuid = BT_UUID_INIT_128(0x02, 0x28, PL_BT_UUID_PREFIX);
static ssize_t bt_gundam_read(struct bt_conn* conn, const struct bt_gatt_attr* attr, void* buf,
uint16_t len, uint16_t offset) {
return bt_gatt_attr_read(conn, attr, buf, len, offset, ¤t_cam, 1);
}
static ssize_t bt_gundam_write(struct bt_conn* conn, const struct bt_gatt_attr* attr,
const void* buf, uint16_t len, uint16_t offset, uint8_t flags) {
if (offset > 0 || len != 1) {
LOG_ERR("bt: write: invalid length (len = %d, offset = %d)", len, offset);
return BT_GATT_ERR(BT_ATT_ERR_INVALID_OFFSET);
}
uint8_t x = static_cast<const uint8_t*>(buf)[0];
LOG_INF("bt: setting camera to %d", x);
opt::gundam::set_cam(x, true);
return len;
}
static ssize_t bt_gundam_reset_read(struct bt_conn* conn, const struct bt_gatt_attr* attr,
void* buf, uint16_t len, uint16_t offset) {
return bt_gatt_attr_read(conn, attr, buf, len, offset, ¤t_cam, 1);
}
static ssize_t bt_gundam_reset_write(struct bt_conn* conn, const struct bt_gatt_attr* attr,
const void* buf, uint16_t len, uint16_t offset,
uint8_t flags) {
if (offset > 0 || len != 1) {
LOG_ERR("bt: write: invalid length (len = %d, offset = %d)", len, offset);
return BT_GATT_ERR(BT_ATT_ERR_INVALID_OFFSET);
}
uint8_t x = static_cast<const uint8_t*>(buf)[0];
LOG_INF("bt: resetting camera to %d", x);
opt::gundam::reset_cam(x);
return len;
}
// clang-format off
BT_GATT_SERVICE_DEFINE(bt_gundam_svc,
BT_GATT_PRIMARY_SERVICE(&bt_gundam_svc_uuid),
BT_GATT_CHARACTERISTIC(
&bt_gundam_camera_uuid.uuid,
BT_GATT_CHRC_READ | BT_GATT_CHRC_WRITE,
#if CONFIG_PASSINGLINK_BT_AUTHENTICATION
BT_GATT_PERM_READ_ENCRYPT | BT_GATT_PERM_WRITE_ENCRYPT,
#else
BT_GATT_PERM_READ | BT_GATT_PERM_WRITE,
#endif
bt_gundam_read,
bt_gundam_write,
¤t_cam
),
BT_GATT_CHARACTERISTIC(
&bt_gundam_reset_uuid.uuid,
BT_GATT_CHRC_READ | BT_GATT_CHRC_WRITE,
#if CONFIG_PASSINGLINK_BT_AUTHENTICATION
BT_GATT_PERM_READ_ENCRYPT | BT_GATT_PERM_WRITE_ENCRYPT,
#else
BT_GATT_PERM_READ | BT_GATT_PERM_WRITE,
#endif
bt_gundam_reset_read,
bt_gundam_reset_write,
¤t_cam
),
);
// clang-format on
#endif // defined(CONFIG_PASSINGLINK_BT)
#endif // defined(CONFIG_PASSINGLINK_OPT_GUNDAM_CAMERA)
| 26.502488
| 98
| 0.65046
|
Luberry
|
9668c17b458731e039b2f1251155f48cf884dcf5
| 2,040
|
cpp
|
C++
|
src/lcao_wavefunction/lcao_wavefunction__gf_overlap_factor.cpp
|
violador/catalyst
|
40d5c1dd04269a0764a9804711354a474bc43c15
|
[
"Unlicense"
] | null | null | null |
src/lcao_wavefunction/lcao_wavefunction__gf_overlap_factor.cpp
|
violador/catalyst
|
40d5c1dd04269a0764a9804711354a474bc43c15
|
[
"Unlicense"
] | null | null | null |
src/lcao_wavefunction/lcao_wavefunction__gf_overlap_factor.cpp
|
violador/catalyst
|
40d5c1dd04269a0764a9804711354a474bc43c15
|
[
"Unlicense"
] | null | null | null |
// ../src/lcao_wavefunction/lcao_wavefunction__gf_overlap_factor.cpp ------------------- //
//
// File author: Humberto Jr.
//
// Date: 10/2013
//
// Description: Given two or three unormalized GF exponents, alpha and beta, centered
// at atom A and atom B, respectively; or alpha, beta and gamma, centered
// at atom A, atom B and atom C, respectively; and also the distances, d,
// between A and B; or between A and B and P(A, B) and C; this function
// returns the overlap factor of a GF product.
//
// References: A. Szabo and N. Ostlund; Modern Quantum Chemistry - Introduction to
// Advanced Electronic Sctructure.
//
// J. Chem. Phys. 84, 3963 (1986); http://dx.doi.org/10.1063/1.450106
// ------------------------------------------------------------------------------------- //
//
//
//
inline double gf_overlap_factor(const double &alpha, // The GF exponent at atom A.
const double &beta, // The GF exponent at atom B.
const double &d) // The A-B distance.
{
//
// A. Szabo and N. Ostlund;
// Modern Quantum Chemistry - Introduction to Advanced Electronic Sctructure;
// Appendix A;
// pag. 411;
// equation (A.3):
return gsl_sf_exp(-alpha*beta*gsl_pow_2(d)/(alpha + beta));
};
//
//
//
inline double gf_overlap_factor(const double &alpha, // The GF exponent at atom A.
const double &beta, // The GF exponent at atom B.
const double &gamma, // The GF exponent at atom C.
const double &d1, // The A-B distance.
const double &d2) // The P(A, B)-C distance.
{
//
// S. Obara and A. Saika;
// The Journal of Chemical Physics;
// Efficient recursive computation of molecular integrals over cartesian Gaussian functions;
// equation (11):
return gf_overlap_factor(alpha, beta, d1)*gf_overlap_factor(alpha + beta, gamma, d2);
};
| 41.632653
| 93
| 0.560784
|
violador
|
9669850843ce05dc79504459c295642a94b1821a
| 3,676
|
cpp
|
C++
|
src/lib/top_level/semifields/semifield_flag_orbit_node.cpp
|
abetten/orbiter
|
5994d0868a26c37676d6aadfc66a1f1bcb715c4b
|
[
"RSA-MD"
] | 15
|
2016-10-27T15:18:28.000Z
|
2022-02-09T11:13:07.000Z
|
src/lib/top_level/semifields/semifield_flag_orbit_node.cpp
|
abetten/orbiter
|
5994d0868a26c37676d6aadfc66a1f1bcb715c4b
|
[
"RSA-MD"
] | 4
|
2019-12-09T11:49:11.000Z
|
2020-07-30T17:34:45.000Z
|
src/lib/top_level/semifields/semifield_flag_orbit_node.cpp
|
abetten/orbiter
|
5994d0868a26c37676d6aadfc66a1f1bcb715c4b
|
[
"RSA-MD"
] | 15
|
2016-06-10T20:05:30.000Z
|
2020-12-18T04:59:19.000Z
|
/*
* semifield_flag_orbit_node.cpp
*
* Created on: Apr 17, 2019
* Author: betten
*/
#include "orbiter.h"
using namespace std;
namespace orbiter {
namespace top_level {
semifield_flag_orbit_node::semifield_flag_orbit_node()
{
downstep_primary_orbit = 0;
downstep_secondary_orbit = 0;
pt_local = 0;
pt = 0;
downstep_orbit_len = 0;
f_long_orbit = FALSE;
upstep_orbit = 0;
f_fusion_node = FALSE;
fusion_with = 0;
fusion_elt = NULL;
//longinteger_object go;
gens = NULL;
//null();
}
semifield_flag_orbit_node::~semifield_flag_orbit_node()
{
//freeself();
}
void semifield_flag_orbit_node::init(
int downstep_primary_orbit, int downstep_secondary_orbit,
int pt_local, long int pt, int downstep_orbit_len, int f_long_orbit,
int verbose_level)
{
int f_v = (verbose_level >= 1);
if (f_v) {
cout << "semifield_flag_orbit_node:init" << endl;
}
semifield_flag_orbit_node::downstep_primary_orbit = downstep_primary_orbit;
semifield_flag_orbit_node::downstep_secondary_orbit = downstep_secondary_orbit;
semifield_flag_orbit_node::pt_local = pt_local;
semifield_flag_orbit_node::pt = pt;
semifield_flag_orbit_node::downstep_orbit_len = downstep_orbit_len;
semifield_flag_orbit_node::f_long_orbit = f_long_orbit;
if (f_v) {
cout << "semifield_flag_orbit_node:init done" << endl;
}
}
void semifield_flag_orbit_node::group_order(longinteger_object &go)
{
if (f_long_orbit) {
go.create(1, __FILE__, __LINE__);
}
else {
semifield_flag_orbit_node::go.assign_to(go);
}
}
int semifield_flag_orbit_node::group_order_as_int()
{
if (f_long_orbit) {
return 1;
}
else {
return go.as_int();;
}
}
void semifield_flag_orbit_node::write_to_file_binary(
semifield_lifting *SL, ofstream &fp,
int verbose_level)
{
int f_v = (verbose_level >= 1);
if (f_v) {
cout << "semifield_flag_orbit_node::write_to_file_binary" << endl;
}
fp.write((char *) &downstep_primary_orbit, sizeof(int));
fp.write((char *) &downstep_secondary_orbit, sizeof(int));
fp.write((char *) &pt_local, sizeof(int));
fp.write((char *) &pt, sizeof(long int));
fp.write((char *) &downstep_orbit_len, sizeof(int));
fp.write((char *) &f_long_orbit, sizeof(int));
fp.write((char *) &f_fusion_node, sizeof(int));
if (f_fusion_node) {
fp.write((char *) &fusion_with, sizeof(int));
SL->SC->A->element_write_to_file_binary(fusion_elt, fp, 0);
}
else {
fp.write((char *) &upstep_orbit, sizeof(int));
}
if (!f_long_orbit) {
gens->write_to_file_binary(fp, verbose_level - 1);
}
if (f_v) {
cout << "semifield_flag_orbit_node::write_to_file_binary done" << endl;
}
}
void semifield_flag_orbit_node::read_from_file_binary(
semifield_lifting *SL, ifstream &fp,
int verbose_level)
{
int f_v = (verbose_level >= 1);
if (f_v) {
cout << "semifield_flag_orbit_node::read_from_file_binary" << endl;
}
fp.read((char *) &downstep_primary_orbit, sizeof(int));
fp.read((char *) &downstep_secondary_orbit, sizeof(int));
fp.read((char *) &pt_local, sizeof(int));
fp.read((char *) &pt, sizeof(long int));
fp.read((char *) &downstep_orbit_len, sizeof(int));
fp.read((char *) &f_long_orbit, sizeof(int));
fp.read((char *) &f_fusion_node, sizeof(int));
if (f_fusion_node) {
fp.read((char *) &fusion_with, sizeof(int));
fusion_elt = NEW_int(SL->SC->A->elt_size_in_int);
SL->SC->A->element_read_from_file_binary(fusion_elt, fp, 0);
}
else {
fp.read((char *) &upstep_orbit, sizeof(int));
}
if (!f_long_orbit) {
gens = NEW_OBJECT(strong_generators);
gens->read_from_file_binary(SL->SC->A, fp, verbose_level - 1);
}
if (f_v) {
cout << "semifield_flag_orbit_node::read_from_file_binary done" << endl;
}
}
}}
| 23.414013
| 80
| 0.711915
|
abetten
|
966b498192a76bcce81cf2ab5c577dd1bbb8372d
| 8,247
|
cpp
|
C++
|
src/ivorium_graphics/Elements/Image.cpp
|
ivorne/ivorium
|
1d876b6dcabe29b3110d3058f997e59c40cd6a2b
|
[
"Apache-2.0"
] | 3
|
2021-02-26T02:59:09.000Z
|
2022-02-08T16:44:21.000Z
|
src/ivorium_graphics/Elements/Image.cpp
|
ivorne/ivorium
|
1d876b6dcabe29b3110d3058f997e59c40cd6a2b
|
[
"Apache-2.0"
] | null | null | null |
src/ivorium_graphics/Elements/Image.cpp
|
ivorne/ivorium
|
1d876b6dcabe29b3110d3058f997e59c40cd6a2b
|
[
"Apache-2.0"
] | null | null | null |
#include "Image.hpp"
#include "../Defs.hpp"
namespace iv
{
Image::Image( Instance * inst ) :
Elem( inst ),
SlotChild( this ),
TranslucentElem( this ),
cm( inst, this, "Image", ClientMarker::Status() ),
attr_filename( &this->cm, "/ivorium_graphics/empty.png" ),
shading( &this->cm ),
texture( inst, ResourcePath() ),
shader( inst ),
square( inst )
{
this->cm.inherits( this->Elem::cm, this->SlotChild::cm, this->TranslucentElem::cm );
this->cm.owns( this->texture.cm, this->shader.cm, this->square.cm );
}
void Image::status( iv::TableDebugView * view )
{
static iv::TableId DebugTable = TableId::create( "Image" );
auto row = view->Table( DebugTable ).Row( this );
row.Column( "filename", this->attr_filename.Get() );
row.Column( "fittingStage", this->shading.fittingStage );
row.Column( "pixelizeStage", this->shading.pixelizeStage )
.Hint( "size", this->shading.pixelizeSize.Get() )
.Hint( "offset", this->shading.pixelizeOffset.Get() );
row.Column( "resizeStage", this->shading.resizeStage )
.Hint( "anchor", this->shading.resizeAnchor.Get() );
row.Column( "filteringStage", this->shading.filteringStage )
.Hint( "filteringAlphaThreshold", this->shading.filteringAlphaThreshold.Get() )
.Hint( "filteringAlphaWidth", this->shading.filteringAlphaWidth.Get() );
row.Column( "alpha", this->shading.alpha.Get() );
row.Column( "colorTransform", this->shading.colorTransform.Get() );
}
void Image::first_pass_impl( ElementRenderer * er )
{
this->cm.log( SRC_INFO, Defs::Log::ElementFirstPass, "First pass." );
if( this->attr_filename.dirty() )
{
this->cm.log( SRC_INFO, Defs::Log::ElementFirstPass, "Refresh preferred_size (filename changed)." );
er->Notify_FirstPass_Refresh( this );
// read texture
this->texture.path( this->attr_filename.Get() );
this->attr_filename.clear_dirty();
// update prefsize
if( this->texture.get() )
{
int2 prefsize = this->texture->metadata().size;
float density = this->texture->metadata().density;
this->preferredSize.Set( float3( prefsize.x / density, prefsize.y / density, 0 ) );
}
else
{
this->preferredSize.Set( float3( 0, 0, 0 ) );
}
}
// queue render
if( this->shading.alpha.Get() != 0.0f )
{
GLuint shader_id = this->shader.get() ? this->shader->program_id() : 0;
GLuint texture_id = this->texture.get() ? this->texture->gl_texture()->texture_id() : 0;
if( shader_id && texture_id )
{
if( this->attr_translucent.Get() )
{
this->cm.log( SRC_INFO, Defs::Log::ElementFirstPass, "Queue render pass (translucent)." );
er->AddRenderable_Translucent( this, shader_id, texture_id );
}
else
{
this->cm.log( SRC_INFO, Defs::Log::ElementFirstPass, "Queue render pass (solid)." );
er->AddRenderable_Solid( this, shader_id, texture_id );
}
}
else
{
this->cm.log( SRC_INFO, Defs::Log::ElementFirstPass, "Render skipped (shader or texture are not loaded yet)." );
}
}
else
{
this->cm.log( SRC_INFO, Defs::Log::ElementFirstPass, "Render skipped (alpha == 0)." );
}
}
void Image::second_pass_impl( ElementRenderer * er )
{
}
void Image::render( CameraState const & camera, std::optional< float > draw_order_depth )
{
this->cm.log( SRC_INFO, Defs::Log::ElementRenderPass, "Render ", this->attr_filename.Get(), "." );
float3 size = this->size.Get();
this->shader->Render(
this->cm,
camera,
draw_order_depth,
this->modelTransform.Get(),
this->scissor.Get(),
this->attr_preblend.Get(),
this->attr_translucent.Get(),
this->square->gl_mesh(),
float3( size.x, size.y, 0.0f ),
float2( 1.0f, 1.0f ),
this->texture->gl_texture(),
this->texture->metadata().density,
this->texture->metadata().msdf_pixelRange,
this->shading
);
}
float Image::texcoord_frame_transform_px( float coord_image_px, float tex_size, float image_size )
{
float coord_tex_px;
if( coord_image_px < image_size * 0.5 )
{// left half
if( coord_image_px < tex_size / 2.0f )
coord_tex_px = coord_image_px;
else
coord_tex_px = tex_size / 2.0f;
}
else
{// right half
if( image_size - coord_image_px < tex_size / 2.0f )
coord_tex_px = tex_size - ( image_size - coord_image_px );
else
coord_tex_px = tex_size / 2.0f;
}
return coord_tex_px;
}
bool Image::picking_test_pixel_perfect( float2 local_pos )
{
if( !this->texture.get() )
return false;
if( !this->texture->metadata().hitmap )
return true;
float2 size( this->size.Get().x, this->size.Get().y );
float2 texsize( this->texture->metadata().size );
float dpi = this->texture->metadata().density;
int2 texpos;
if( this->shading.resizeStage == FlatShader::ResizeStage::Scale )
{
texpos = local_pos / size * texsize;
}
else if( this->shading.resizeStage == FlatShader::ResizeStage::Repeat )
{
auto resizeAnchor = this->shading.resizeAnchor.Get();
texpos = local_pos - resizeAnchor * size + resizeAnchor * texsize / dpi;
texpos.x = sig_mod( texpos.x, texsize.x / dpi ) * dpi;
texpos.y = sig_mod( texpos.y, texsize.y / dpi ) * dpi;
}
else if( this->shading.resizeStage == FlatShader::ResizeStage::Frame )
{
texpos = int2( Image::texcoord_frame_transform_px( local_pos.x, texsize.x / dpi, size.x ) * dpi, Image::texcoord_frame_transform_px( local_pos.y, texsize.y / dpi, size.y ) * dpi );
}
else // FlatShader::ResizeStage::Fixed
{
auto resizeAnchor = this->shading.resizeAnchor.Get();
texpos = ( local_pos - resizeAnchor * size + resizeAnchor * texsize / dpi ) * dpi;
}
this->cm.log( SRC_INFO, Defs::Log::Picking,
"pixel_text:", Context::Endl(),
" texsize=", texsize, Context::Endl(),
" texpos=", texpos );
return this->texture->hittest( texpos.x, texsize.y - texpos.y - 1 );
}
Image * Image::enabled( bool val )
{
this->Elem::enabled( val );
return this;
}
Image * Image::preblend( float4 val )
{
this->TranslucentElem::preblend( val );
return this;
}
Image * Image::translucent( bool val )
{
this->TranslucentElem::translucent( val );
return this;
}
Image * Image::filename( ResourcePath const & val )
{
this->attr_filename.Set( val );
return this;
}
Image * Image::fittingStage( FlatShader::FittingStage v )
{
this->shading.fittingStage = v;
return this;
}
Image * Image::pixelizeStage( FlatShader::PixelizeStage v )
{
this->shading.pixelizeStage = v;
return this;
}
Image * Image::pixelizeSize( float2 v )
{
this->shading.pixelizeSize.Set( v );
return this;
}
Image * Image::pixelizeOffset( float2 v )
{
this->shading.pixelizeOffset.Set( v );
return this;
}
Image * Image::resizeStage( FlatShader::ResizeStage v )
{
this->shading.resizeStage = v;
return this;
}
Image * Image::resizeAnchor( float2 v )
{
this->shading.resizeAnchor.Set( v );
return this;
}
Image * Image::filteringStage( FlatShader::FilteringStage v )
{
this->shading.filteringStage = v;
return this;
}
Image * Image::filteringAlphaThreshold( float v )
{
this->shading.filteringAlphaThreshold.Set( v );
return this;
}
Image * Image::filteringAlphaWidth( float v )
{
this->shading.filteringAlphaWidth.Set( v );
return this;
}
Image * Image::alpha( float v )
{
this->shading.alpha.Set( v );
return this;
}
Image * Image::colorTransform( float4x4 const & v )
{
this->shading.colorTransform.Set( v );
return this;
}
}
| 27.955932
| 188
| 0.594883
|
ivorne
|
966d2deb9c74807018858614ea6a231d246b5c1b
| 2,059
|
cpp
|
C++
|
00-Keypoint_in_WangDao/Chapter_02-List/01-LinkList/00-Basic_LinkList/00-LinkList_Basic_Operation/03-LinkList_Merge/00-LinkList_Merge.cpp
|
ysl970629/kaoyan_data_structure
|
d0a469bf0e9e7040de21eca38dc19961aa7e9a53
|
[
"MIT"
] | 2
|
2021-03-24T03:29:16.000Z
|
2022-03-29T16:34:30.000Z
|
00-Keypoint_in_WangDao/Chapter_02-List/01-LinkList/00-Basic_LinkList/00-LinkList_Basic_Operation/03-LinkList_Merge/00-LinkList_Merge.cpp
|
ysl2/kaoyan-data-structure
|
d0a469bf0e9e7040de21eca38dc19961aa7e9a53
|
[
"MIT"
] | null | null | null |
00-Keypoint_in_WangDao/Chapter_02-List/01-LinkList/00-Basic_LinkList/00-LinkList_Basic_Operation/03-LinkList_Merge/00-LinkList_Merge.cpp
|
ysl2/kaoyan-data-structure
|
d0a469bf0e9e7040de21eca38dc19961aa7e9a53
|
[
"MIT"
] | null | null | null |
#include <cstdlib>
#include <iostream>
typedef int ElemType;
typedef struct LinkNode {
ElemType data;
struct LinkNode *next;
} LinkNode, *LinkList;
void outPut(LinkList L) {
LinkNode *p = L->next;
while (p != NULL) {
std::cout << p->data << " ";
p = p->next;
}
std::cout << std::endl;
}
void rearInsert(LinkList &L, ElemType x) {
LinkNode *s = new LinkNode;
s->data = x;
L->next = s;
L = s;
}
void rearInsertCreate(LinkList &L, ElemType arr[], int length) {
L = new LinkNode;
LinkNode *p = L;
for (int i = 0; i < length; i++) {
rearInsert(p, arr[i]);
}
p->next = NULL;
}
// 合并两个递增有序的单链表,使其合并后依然保持有序
// 本题也是求A = A ∪ B的算法
// 山大书上采用定义了一个C链表返回的方式,实际上这并不是必须要这么做,也可以直接用A返回:
void merge(LinkList &A, LinkList &B) {
LinkNode *p = A->next;
LinkNode *q = B->next;
A->next = NULL;
LinkNode *r = A;
while (p != NULL && q != NULL) {
if (p->data == q->data) {
r->next = p;
r = r->next;
p = p->next;
LinkNode *temp = q->next;
delete q;
q = temp;
} else if (p->data < q->data) {
r->next = p;
r = r->next;
p = p->next;
} else {
r->next = q;
r = r->next;
q = q->next;
}
}
while (p != NULL) {
r->next = p;
r = r->next;
p = p->next;
}
while (q != NULL) {
r->next = q;
r = r->next;
q = q->next;
}
r->next = NULL;
delete B;
}
void test() {
ElemType arr1[] = {-7, 3, 12, 23};
int length1 = sizeof(arr1) / sizeof(arr1[0]);
ElemType arr2[] = {-2, 4, 9, 15};
int length2 = sizeof(arr2) / sizeof(arr2[0]);
LinkList L1 = NULL;
LinkList L2 = NULL;
rearInsertCreate(L1, arr1, length1);
rearInsertCreate(L2, arr2, length2);
outPut(L1);
outPut(L2);
merge(L1, L2);
outPut(L1);
}
int main() {
test();
return 0;
}
// 输出结果:
// -7 3 12 23
// -2 4 9 15
// -7 -2 3 4 9 12 15 23
| 20.79798
| 64
| 0.478388
|
ysl970629
|
966daf453c54569fbcb3ddde71f005e916051547
| 2,221
|
hpp
|
C++
|
ql/experimental/math/mersennetwister_multithreaded.hpp
|
universe1987/QuantLib
|
bbb0145aff285853755b9f6ed013f53a41163acb
|
[
"BSD-3-Clause"
] | 4
|
2016-03-28T15:05:23.000Z
|
2020-02-17T23:05:57.000Z
|
ql/experimental/math/mersennetwister_multithreaded.hpp
|
universe1987/QuantLib
|
bbb0145aff285853755b9f6ed013f53a41163acb
|
[
"BSD-3-Clause"
] | 1
|
2015-02-02T20:32:43.000Z
|
2015-02-02T20:32:43.000Z
|
ql/experimental/math/mersennetwister_multithreaded.hpp
|
pcaspers/quantlib
|
bbb0145aff285853755b9f6ed013f53a41163acb
|
[
"BSD-3-Clause"
] | 10
|
2015-01-26T14:50:24.000Z
|
2015-10-23T07:41:30.000Z
|
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
Copyright (C) 2015 Peter Caspers
This file is part of QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/
QuantLib is free software: you can redistribute it and/or modify it
under the terms of the QuantLib license. You should have received a
copy of the license along with this program; if not, please email
<quantlib-dev@lists.sf.net>. The license is also available online at
<http://quantlib.org/license.shtml>.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the license for more details.
*/
/*! \file mersennetwister_multithreaded.hpp
\brief multi threaded mersenne twister (for 8 threads)
*/
#ifndef quantlib_mersennetwister_multithreaded_hpp
#define quantlib_mersennetwister_multithreaded_hpp
#include <ql/experimental/math/dynamiccreator.hpp>
namespace QuantLib {
class MersenneTwisterMultiThreaded {
public:
typedef Sample<Real> sample_type;
static const Size maxNumberOfThreads = 8;
// if given seed is 0 then a clock based seed is used
MersenneTwisterMultiThreaded(const unsigned long seed = 0);
sample_type next(unsigned int threadId) const;
Real nextReal(unsigned int threadId) const;
unsigned long operator()(unsigned int threadId) const;
unsigned long nextInt32(unsigned int threadId) const;
private:
mutable boost::shared_ptr<MersenneTwisterCustomRng<Mtdesc19937_0> > m0_;
mutable boost::shared_ptr<MersenneTwisterCustomRng<Mtdesc19937_1> > m1_;
mutable boost::shared_ptr<MersenneTwisterCustomRng<Mtdesc19937_2> > m2_;
mutable boost::shared_ptr<MersenneTwisterCustomRng<Mtdesc19937_3> > m3_;
mutable boost::shared_ptr<MersenneTwisterCustomRng<Mtdesc19937_4> > m4_;
mutable boost::shared_ptr<MersenneTwisterCustomRng<Mtdesc19937_5> > m5_;
mutable boost::shared_ptr<MersenneTwisterCustomRng<Mtdesc19937_6> > m6_;
mutable boost::shared_ptr<MersenneTwisterCustomRng<Mtdesc19937_7> > m7_;
};
} // namespace QuantLib
#endif
| 37.016667
| 79
| 0.772625
|
universe1987
|
967c25a79ba911480e420fce42afd2c1e68c7452
| 1,321
|
cpp
|
C++
|
field/field_base.cpp
|
085astatine/2Ddiffusion
|
31d1b82f0ac7854072a1b07aa10f48654968792d
|
[
"MIT"
] | null | null | null |
field/field_base.cpp
|
085astatine/2Ddiffusion
|
31d1b82f0ac7854072a1b07aa10f48654968792d
|
[
"MIT"
] | null | null | null |
field/field_base.cpp
|
085astatine/2Ddiffusion
|
31d1b82f0ac7854072a1b07aa10f48654968792d
|
[
"MIT"
] | null | null | null |
#include "./field_base.h"
namespace field{
// constructor
FieldBase::FieldBase(
const std::shared_ptr<std::vector<double>>& xPointer,
const std::shared_ptr<std::vector<double>>& yPointer,
const std::shared_ptr<Eigen::MatrixXd>& zPointer)
: x_ptr_(xPointer),
y_ptr_(yPointer),
z_ptr_(zPointer){}
// x座標列のpointerを返す
const std::shared_ptr<std::vector<double>>&
FieldBase::x_pointer() const{
return x_ptr_;
}
// y座標列のpointerを返す
const std::shared_ptr<std::vector<double>>&
FieldBase::y_pointer() const{
return y_ptr_;
}
// 値列のpointerを返す
const std::shared_ptr<Eigen::MatrixXd>&
FieldBase::z_pointer() const{
return z_ptr_;
}
// 値を返す
const double& FieldBase::operator()(
const std::ptrdiff_t& i,
const std::ptrdiff_t& k) const{
return z()(i, k);
}
// x座標列を返す
const std::vector<double>& FieldBase::x_list() const{
return *x_pointer();
}
// y座標列を返す
const std::vector<double>& FieldBase::y_list() const{
return *y_pointer();
}
// 値列を返す
const Eigen::MatrixXd& FieldBase::z() const{
return *z_pointer();
}
// x座標値を返す
const double& FieldBase::x(const std::ptrdiff_t& i) const{
return x_list()[i];
}
// y座標値を返す
const double& FieldBase::y(const std::ptrdiff_t& k) const{
return y_list()[k];
}
}// end namespace field
| 24.462963
| 65
| 0.660863
|
085astatine
|
967ee230ef9cd7c1ee66d6c61b2ac70933f8fd33
| 1,347
|
cpp
|
C++
|
Code/Lecture_05/critical.cpp
|
Alexhuyi/cme213-spring-2021
|
3cc49d369f1041c0cf4f960cb6efa28c04acdf60
|
[
"MIT"
] | 20
|
2021-03-26T18:27:47.000Z
|
2022-03-30T03:00:14.000Z
|
Code/Lecture_05/critical.cpp
|
rishucoding/cme213-spring-2021
|
8758831af9f74c939f2f1170e30dbf72ede8859a
|
[
"MIT"
] | null | null | null |
Code/Lecture_05/critical.cpp
|
rishucoding/cme213-spring-2021
|
8758831af9f74c939f2f1170e30dbf72ede8859a
|
[
"MIT"
] | 15
|
2021-04-02T07:50:41.000Z
|
2022-03-23T12:45:02.000Z
|
#include <cstdio>
#include <cassert>
#include <set>
#include <cmath>
#include <iostream>
#include <fstream>
using namespace std;
bool is_prime_test(int n)
{
if (n <= 3)
return n > 1;
else if ((n % 2 == 0) || (n % 3 == 0))
return false;
for (int i = 5; i * i <= n; i += 6)
if ((n % i == 0) || (n % (i + 2) == 0))
return false; // Not a prime
return true; // Must be prime
}
int main(void)
{
const int n = 104729;
// Calculate all prime numbers smaller than n
set<int> m;
#pragma omp parallel for
for (int i = 2; i <= n; ++i)
{
bool is_prime = is_prime_test(i);
#pragma omp critical
if (is_prime)
m.insert(i); /* Save this prime */
}
printf("Number of prime numbers smaller than %d: %ld\n", n, m.size());
// Check
{
// Read primes from a file to test m
auto it = m.begin();
int count = 0; /* Read only the first 10,000 primes */
ifstream prime_file("10000.txt");
while (it != m.end() && count < 10000)
{
int next_prime;
prime_file >> next_prime; // Read from file
assert(*it == next_prime); // Test
++it;
++count;
}
prime_file.close();
printf("PASS\n");
}
return 0;
}
| 21.046875
| 74
| 0.495917
|
Alexhuyi
|
967f1f0cbe97dee25652a6124bb6b327574c0fc0
| 3,210
|
cpp
|
C++
|
src/db/db.cpp
|
divad-nhok/obsidian_fork
|
e5bee2b706f78249564f06c88a18be086b17c895
|
[
"MIT"
] | 7
|
2015-01-04T13:50:24.000Z
|
2022-01-22T01:03:57.000Z
|
src/db/db.cpp
|
divad-nhok/obsidian_fork
|
e5bee2b706f78249564f06c88a18be086b17c895
|
[
"MIT"
] | 1
|
2018-08-16T00:46:58.000Z
|
2018-08-16T00:46:58.000Z
|
src/db/db.cpp
|
divad-nhok/obsidian_fork
|
e5bee2b706f78249564f06c88a18be086b17c895
|
[
"MIT"
] | 9
|
2016-08-31T05:42:00.000Z
|
2022-01-21T21:37:47.000Z
|
//!
//! Contains implementation of the database structure used for persistent
//! storage of the MCMC data.
//!
//! \file db/db.cpp
//! \author Lachlan McCalman
//! \date 2014
//! \license Affero General Public License version 3 or later
//! \copyright (c) 2014, NICTA
//!
#include <glog/logging.h>
#include "db/db.hpp"
#include "leveldb/write_batch.h"
#include "leveldb/cache.h"
#include "leveldb/options.h"
#include "leveldb/filter_policy.h"
namespace stateline
{
namespace db
{
Database::Database(const DBSettings& s)
: cacheNumBytes_(s.cacheSizeMB * 1048576)
{
options_.block_cache = leveldb::NewLRUCache(cacheNumBytes_); // Cache in MB
options_.filter_policy = leveldb::NewBloomFilterPolicy(10); // smart filtering -- bits per key?
if (!s.recover)
{
options_.error_if_exists = true;
options_.create_if_missing = true;
} else
{
options_.error_if_exists = false;
options_.create_if_missing = false;
}
leveldb::Status status = leveldb::DB::Open(options_, s.directory, &db_);
if (!status.ok())
{
if (s.recover)
{
LOG(ERROR)<< "Could not recover database. Check the path in the config file and disk write permissions";
}
else
{
LOG(ERROR) << "Could not create database. Database may already exist and would be overwritten";
}
exit(EXIT_FAILURE);
}
writeOptions_.sync = false;
}
uint Database::cacheSize()
{
return cacheNumBytes_;
}
std::string Database::get(const leveldb::Slice& key)
{
std::string s;
leveldb::Status status = db_->Get(readOptions_, key, &s);
CHECK(status.ok()) << "key is " << key.ToString();
return s;
}
void Database::put(const leveldb::Slice& key, const leveldb::Slice& value)
{
leveldb::Status status = db_->Put(writeOptions_, key, value);
CHECK(status.ok());
}
void Database::batch(leveldb::WriteBatch& batch)
{
db_->Write(writeOptions_, &batch);
}
void Database::remove(const leveldb::Slice& key)
{
leveldb::Status status = db_->Delete(writeOptions_, key);
CHECK(status.ok());
}
void Database::swap(const std::vector<std::string>& keys1, const std::vector<std::string>& keys2)
{
CHECK_EQ(keys1.size(), keys2.size());
uint size = keys1.size();
leveldb::WriteBatch batch;
std::vector<std::string> values1(size);
std::vector<std::string> values2(size);
for (uint i = 0; i < keys1.size(); i++)
{
std::string value1;
std::string value2;
leveldb::Status s1 = db_->Get(readOptions_, keys1[i], &value1);
leveldb::Status s2 = db_->Get(readOptions_, keys2[i], &value2);
CHECK(s1.ok() && s2.ok()) << s1.ToString() << " " << s2.ToString();
values1[i] = value2;
values2[i] = value1;
batch.Put(keys1[i], values1[i]);
batch.Put(keys2[i], values2[i]);
}
db_->Write(writeOptions_, &batch);
}
Database::~Database()
{
delete db_;
delete options_.block_cache;
}
} // namespace db
} // namespace obsidian
| 27.435897
| 114
| 0.601558
|
divad-nhok
|
967f5d15614308935e488d97348ad0654d69c653
| 1,157
|
cpp
|
C++
|
Assignment 2/server/mainwindow.cpp
|
chendante/Computer-Networking-Assignments
|
a97b7067e8fce840fd9e368a12e71ab5eb528ead
|
[
"Apache-2.0"
] | 1
|
2021-06-16T03:12:33.000Z
|
2021-06-16T03:12:33.000Z
|
Assignment 2/server/mainwindow.cpp
|
chendante/Computer-Networking-Assignments
|
a97b7067e8fce840fd9e368a12e71ab5eb528ead
|
[
"Apache-2.0"
] | null | null | null |
Assignment 2/server/mainwindow.cpp
|
chendante/Computer-Networking-Assignments
|
a97b7067e8fce840fd9e368a12e71ab5eb528ead
|
[
"Apache-2.0"
] | null | null | null |
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QByteArray>
#include <QDataStream>
#include <QDateTime>
#include <QString>
#include <QDebug>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonValue>
#include <QTcpSocket>
#include <QThread>
#include "mytcpsocket.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
tcpServer = new QTcpServer(this);
//令tcpserver监听任何ip连接到本地25端口的命令
if(!tcpServer->listen(QHostAddress::Any,25))
{
qDebug()<<tcpServer->errorString();
close();
}
connect(tcpServer,&QTcpServer::newConnection,this,&MainWindow::NewConnect);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::GetMessage(QString str)
{
QString now = this->ui->textEdit->toPlainText();
now.append(str);
this->ui->textEdit->setText(now);
}
void MainWindow::GetContent(QString str)
{
this->ui->textBrowser->setHtml(str);
}
void MainWindow::NewConnect()
{
this->GetMessage("*** 收到连接请求\r\n");
mytcpsocket* tcp = new mytcpsocket(tcpServer->nextPendingConnection(),this);
}
| 21.425926
| 80
| 0.694036
|
chendante
|
968ecd4a39dda38cb8e30871ccc2a5de55a6b5ef
| 1,875
|
cpp
|
C++
|
code/cpp/RemoveDuplicatesFromSortedArray/RemoveDuplicatesFromSortedArrayTest.cpp
|
ganquan/leetcode
|
80d8b4c01c8841e51f677e7a4698c43575afa6d2
|
[
"Apache-2.0"
] | null | null | null |
code/cpp/RemoveDuplicatesFromSortedArray/RemoveDuplicatesFromSortedArrayTest.cpp
|
ganquan/leetcode
|
80d8b4c01c8841e51f677e7a4698c43575afa6d2
|
[
"Apache-2.0"
] | null | null | null |
code/cpp/RemoveDuplicatesFromSortedArray/RemoveDuplicatesFromSortedArrayTest.cpp
|
ganquan/leetcode
|
80d8b4c01c8841e51f677e7a4698c43575afa6d2
|
[
"Apache-2.0"
] | null | null | null |
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <vector>
#include "RemoveDuplicatesFromSortedArray.cpp"
using namespace std;
// Constraints:
// 1 <= nums.length <= 3 * 104
// -100 <= nums[i] <= 100
// nums is sorted in non-decreasing order.
class RemoveDuplicatesFromSortedArrayTest : public ::testing::Test {
protected:
void SetUp() override { s = Solution(); }
// void TearDown() override {}
Solution s;
void test(vector<int>& input, vector<int>& expect) {
s.removeDuplicates(input);
auto k = expect.size();
for (int i = 0; i < k; i++) {
EXPECT_EQ(input[i], expect[i]);
}
};
};
// example testcase
TEST_F(RemoveDuplicatesFromSortedArrayTest, example1) {
vector<int> input = {1, 1, 2};
vector<int> expect = {1, 2};
test(input, expect);
}
TEST_F(RemoveDuplicatesFromSortedArrayTest, example2) {
vector<int> input = {0, 0, 1, 1, 1, 2, 2, 3, 3, 4};
vector<int> expect = {0, 1, 2, 3, 4};
test(input, expect);
}
//no duplicate
TEST_F(RemoveDuplicatesFromSortedArrayTest, input1) {
vector<int> input = {0, 1, 2, 3 ,4};
vector<int> expect = {0, 1, 2, 3, 4};
test(input, expect);
}
// all dupulicate
TEST_F(RemoveDuplicatesFromSortedArrayTest, input2) {
vector<int> input = {3, 3, 3, 3, 3};
vector<int> expect = {3};
test(input, expect);
}
TEST_F(RemoveDuplicatesFromSortedArrayTest, input3) {
vector<int> input = {1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3};
vector<int> expect = {1, 2, 3};
test(input, expect);
}
TEST_F(RemoveDuplicatesFromSortedArrayTest, input4) {
vector<int> input = {1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3};
vector<int> expect = {1, 2, 3};
test(input, expect);
}
TEST_F(RemoveDuplicatesFromSortedArrayTest, input5) {
vector<int> input = {1};
vector<int> expect = {1};
test(input, expect);
}
| 22.321429
| 68
| 0.613867
|
ganquan
|
968ff951bee9ad40431cde2b9a5e2b7fd4d3a12d
| 14,364
|
cpp
|
C++
|
GameAI.cpp
|
ButchDean/AntiVirusGame2
|
51b6cd45a5fea3ddd194769ab8fa4b4f8b1b69b3
|
[
"BSD-3-Clause"
] | 1
|
2017-09-26T06:26:17.000Z
|
2017-09-26T06:26:17.000Z
|
GameAI.cpp
|
ButchDean/AntiVirusGame2
|
51b6cd45a5fea3ddd194769ab8fa4b4f8b1b69b3
|
[
"BSD-3-Clause"
] | null | null | null |
GameAI.cpp
|
ButchDean/AntiVirusGame2
|
51b6cd45a5fea3ddd194769ab8fa4b4f8b1b69b3
|
[
"BSD-3-Clause"
] | null | null | null |
/*!\file GameAI.cpp
* \brief Function to handle NPC behaviour.
* \author Dean N. Butcher
* \version 2.1
* \date August 2004
*/
#include <windows.h>
#include <math.h>
#include "GameAI.h"
#include "FramerateSync.h"
/*! The rate at which chains gravitate toward each other or power-ups. */
const float GRAVITATION_MOVE_RATE = 10.0f;
/*! The maximum chain length. */
const int SPHERENUMS = 7;
/*! Has a collision occurred? */
bool gbCollision;
/*! Sphere coordinate references to keep them chained. */
TranslationCoords SphereObjectCoords[SPHERENUMS];
/*! Ensure that chain is not extended more than once for function ApplyGameRules(). */
bool chainExtended[] = {false, false, false};
bool EstablishCollision(TranslationCoords SphereA, TranslationCoords SphereB, float TWO_RADIUS)
// Enter Pythagoras to determine if a collision has taken place! Essentially a modification of 'Bounding Sphere'.
{
static bool bAlreadyNotified = false;
float x_squared, y_squared, z_squared, hypotenuse_xy, hypotenuse_yz, hypotenuse_xz;
// Compute the squares of the differences between the spheres on each of the three axes.
x_squared = powf(SphereA.xcoord - SphereB.xcoord, 2.0f);
y_squared = powf(SphereA.ycoord - SphereB.ycoord, 2.0f);
z_squared = powf(SphereA.zcoord - SphereB.zcoord, 2.0f);
// Compute hypotenuse for each of the three planes in 3D space.
hypotenuse_xy = sqrtf(x_squared + y_squared);
hypotenuse_yz = sqrtf(y_squared + z_squared);
hypotenuse_xz = sqrtf(x_squared + z_squared);
if((hypotenuse_xy <= TWO_RADIUS) && (hypotenuse_yz <= TWO_RADIUS) && (hypotenuse_xz <= TWO_RADIUS))
{
if(!bAlreadyNotified) // Notify on first instance of current collision.
return bAlreadyNotified = gbCollision = true;
return false; // Once notified, return false even though collision has been detected.
}
else
return bAlreadyNotified = gbCollision = false; // No collision occured.
}
TranslationCoords ComputeNextSpherePosition(TranslationCoords alphaSphere, bool longUp, bool longDown, bool latL, bool latR)
// Leading sphere is tracked according to keypress, and following sphere will line-up in that direction.
{
const float MOVE_INLINE_CONSTANT = 10.0f;
const float SPHERE_CIRCUMFERENCE = 60.0f;
static TranslationCoords betaSphere;
if(longUp)
{
betaSphere.xcoord = alphaSphere.xcoord;
betaSphere.ycoord = alphaSphere.ycoord;
betaSphere.zcoord = alphaSphere.zcoord - SPHERE_CIRCUMFERENCE;
}
else if(longDown)
{
betaSphere.xcoord = alphaSphere.xcoord;
betaSphere.ycoord = alphaSphere.ycoord;
betaSphere.zcoord = alphaSphere.zcoord + SPHERE_CIRCUMFERENCE;
}
if(latR)
{
betaSphere.xcoord = alphaSphere.xcoord - SPHERE_CIRCUMFERENCE;
betaSphere.ycoord = alphaSphere.ycoord;
betaSphere.zcoord = alphaSphere.zcoord;
}
else if(latL)
{
betaSphere.xcoord = alphaSphere.xcoord + SPHERE_CIRCUMFERENCE;
betaSphere.ycoord = alphaSphere.ycoord;
betaSphere.zcoord = alphaSphere.zcoord;
}
return betaSphere;
}
void AttractGameObjects(TranslationCoords &alphaObject, TranslationCoords &betaObject)
// Depending on the outcome of priorities, this function brings objects together.
{
const float FAST_GRAVITATION_MOVE_RATE = 2.0f * GRAVITATION_MOVE_RATE;
alphaObject.ycoord = 170.0f; betaObject.ycoord = 170.0f; // Used to refine collision detection.
if(alphaObject.xcoord <= (betaObject.xcoord - SPHERE_RADIUS))
betaObject.xcoord -= FAST_GRAVITATION_MOVE_RATE;
else if(alphaObject.xcoord >= (betaObject.xcoord + SPHERE_RADIUS))
betaObject.xcoord += FAST_GRAVITATION_MOVE_RATE;
if(alphaObject.ycoord <= (betaObject.ycoord - SPHERE_RADIUS))
betaObject.ycoord -= FAST_GRAVITATION_MOVE_RATE;
else if(alphaObject.ycoord >= (betaObject.ycoord + SPHERE_RADIUS))
betaObject.ycoord += FAST_GRAVITATION_MOVE_RATE;
if(alphaObject.zcoord <= (betaObject.zcoord - SPHERE_RADIUS))
betaObject.zcoord -= FAST_GRAVITATION_MOVE_RATE;
else if(alphaObject.zcoord >= (betaObject.zcoord + SPHERE_RADIUS))
betaObject.zcoord += FAST_GRAVITATION_MOVE_RATE;
}
void RepelGameObjects(TranslationCoords &alphaObject, TranslationCoords &betaObject, float leftLimit, float rightLimit, float farendLimit, float nearendLimit)
// Depending on the outcome of priorities, this function progressively sets object further apart.
{
const float FAST_GRAVITATION_MOVE_RATE = 1.8f * GRAVITATION_MOVE_RATE;
const float TOO_CLOSE_OUTER = 35.0f * SPHERE_DIAMETER;
const float TOO_CLOSE_INNER = 0.0f * SPHERE_DIAMETER;
// Check against boundaries of environment to ensure object don't fly off the edge!
if(betaObject.xcoord <= leftLimit)
betaObject.xcoord += FAST_GRAVITATION_MOVE_RATE;
if(betaObject.xcoord >= rightLimit)
betaObject.xcoord -= FAST_GRAVITATION_MOVE_RATE;
if(betaObject.zcoord <= nearendLimit)
betaObject.zcoord += FAST_GRAVITATION_MOVE_RATE;
if(betaObject.zcoord >= farendLimit)
betaObject.zcoord -= FAST_GRAVITATION_MOVE_RATE;
// Ensure objects are sufficiently spaced apart.
// On the x-axis.
if(alphaObject.xcoord > betaObject.xcoord)
if(betaObject.xcoord > (alphaObject.xcoord - TOO_CLOSE_OUTER) && betaObject.xcoord < (alphaObject.xcoord - TOO_CLOSE_INNER))
betaObject.xcoord -= FAST_GRAVITATION_MOVE_RATE;
if(alphaObject.xcoord < betaObject.xcoord)
if(betaObject.xcoord < (alphaObject.xcoord + TOO_CLOSE_OUTER) && betaObject.xcoord > (alphaObject.xcoord + TOO_CLOSE_INNER))
betaObject.xcoord += FAST_GRAVITATION_MOVE_RATE;
}
void PrioritisationEngine(TranslationCoords *alphaObject, TranslationCoords *betaObject, TranslationCoords *gammaObject,
int alphaLength, int betaLength, int gammaLength,
POWERUP_TYPE alphaType, POWERUP_TYPE betaType, POWERUP_TYPE gammaType, void (*AttractObj)(TranslationCoords &alphaObject, TranslationCoords &betaObject),
void (*RepelObj)(TranslationCoords &alphaObject, TranslationCoords &betaObject, float leftLimit, float rightLimit, float farendLimit, float nearendLimit),
float leftLimit, float rightLimit, float farendLimit, float nearendLimit,
TranslationCoords *SupBlastCoord1, TranslationCoords *RebirthCoord1, TranslationCoords *InvisiCoord,
TranslationCoords *SupBlastCoord2, TranslationCoords *RebirthCoord2, const bool SupBlast1, const bool Rebirth1,
const bool Invisi, const bool SupBlast2, const bool Rebirth2)
// Decides the actions of NPC chains: alpha = player, beta = first AI, gamma = second AI. This function is not specific to any environment.
// The invisibility power up is ignored by engine so that AI cannot "see" you.
{
// If all characters exist in environment.
if(betaObject)
{
if((betaLength > alphaLength) && alphaType != Invisibility)
(*AttractObj)(*alphaObject, *betaObject);
else
if(betaType == NoPowerUp || betaType == Rebirth || betaType == Invisibility)
{
if(!Rebirth2)
(*AttractObj)(*RebirthCoord2, *betaObject);
else
if(!Rebirth1)
(*AttractObj)(*RebirthCoord1, *betaObject);
else
if(!Invisi)
(*AttractObj)(*InvisiCoord, *betaObject);
else
if(!SupBlast2)
(*AttractObj)(*SupBlastCoord2, *betaObject);
else
if(!SupBlast1)
(*AttractObj)(*SupBlastCoord1, *betaObject);
}
if((betaType == SupremeBlast || betaType == SupaFly) && alphaType != Invisibility)
(*AttractObj)(*alphaObject, *betaObject);
if(alphaType == Invisibility)
{
if(!Rebirth2)
(*AttractObj)(*RebirthCoord2, *betaObject);
else
if(!Rebirth1)
(*AttractObj)(*RebirthCoord1, *betaObject);
else
if(!Invisi)
(*AttractObj)(*InvisiCoord, *betaObject);
else
if(!SupBlast2)
(*AttractObj)(*SupBlastCoord2, *betaObject);
else
if(!SupBlast1)
(*AttractObj)(*SupBlastCoord1, *betaObject);
}
}
if(gammaObject)
{
if((gammaLength > alphaLength) && alphaType != Invisibility)
(*AttractObj)(*alphaObject, *gammaObject);
else
if(gammaType == NoPowerUp || gammaType == Rebirth || gammaType == Invisibility)
{
if(!SupBlast1)
(*AttractObj)(*SupBlastCoord1, *gammaObject);
else
if(!SupBlast2)
(*AttractObj)(*SupBlastCoord2, *gammaObject);
else
if(!Invisi)
(*AttractObj)(*InvisiCoord, *gammaObject);
else
if(!Rebirth1)
(*AttractObj)(*RebirthCoord1, *gammaObject);
else
if(!Rebirth2)
(*AttractObj)(*RebirthCoord2, *gammaObject);
}
if((gammaType == SupremeBlast || gammaType == SupaFly) && alphaType != Invisibility)
(*AttractObj)(*alphaObject, *gammaObject);
if(alphaType == Invisibility)
{
if(!SupBlast1)
(*AttractObj)(*SupBlastCoord1, *gammaObject);
else
if(!SupBlast2)
(*AttractObj)(*SupBlastCoord2, *gammaObject);
else
if(!Invisi)
(*AttractObj)(*InvisiCoord, *gammaObject);
else
if(!Rebirth1)
(*AttractObj)(*RebirthCoord1, *gammaObject);
else
if(!Rebirth2)
(*AttractObj)(*RebirthCoord2, *gammaObject);
}
}
if(alphaType == SupremeBlast || alphaType == SupaFly)
{
if(gammaObject)
(*RepelObj)(*alphaObject, *gammaObject, leftLimit, rightLimit, farendLimit, nearendLimit);
if(betaObject)
(*RepelObj)(*alphaObject, *betaObject, leftLimit, rightLimit, farendLimit, nearendLimit);
}
if(gammaObject && betaObject)
{
(*RepelObj)(*betaObject, *gammaObject, leftLimit, rightLimit, farendLimit, nearendLimit);
(*RepelObj)(*gammaObject, *betaObject, leftLimit, rightLimit, farendLimit, nearendLimit);
}
}
void ApplyGameRules(TranslationCoords alphaObject, TranslationCoords betaObject, TranslationCoords gammaObject, int &alphaLength, int &betaLength, int &gammaLength,
POWERUP_TYPE alphaType, POWERUP_TYPE betaType, POWERUP_TYPE gammaType, int &alphaScore, int &betaScore, int &gammaScore)
// Applies the game rules on establishing a collision between two objects.
{
if(EstablishCollision(alphaObject, betaObject, COLLISION_SENSITIVITY) && !chainExtended[0])
{
if(alphaType == NoPowerUp || alphaType == Rebirth || alphaType == Invisibility)
{
if(betaType == SupremeBlast || betaType == SupaFly)
{
betaLength += alphaLength;
alphaLength = 2;
SetChainExtended(chainExtended[0], chainExtended[1], chainExtended[2]);
}
}
if(alphaType == SupremeBlast)
{
if(betaType == NoPowerUp || betaType == Rebirth || betaType == Invisibility)
{
alphaLength += betaLength;
betaLength = 2;
SetChainExtended(chainExtended[0], chainExtended[1], chainExtended[2]);
}
}
if(alphaType == SupaFly)
{
if(betaType == NoPowerUp || betaType == Rebirth || betaType == Invisibility || betaType == SupremeBlast)
{
alphaLength += betaLength;
betaLength = 2;
SetChainExtended(chainExtended[0], chainExtended[1], chainExtended[2]);
}
if(betaType == SupaFly)
{
alphaLength = 2;
betaLength = 2;
SetChainExtended(chainExtended[0], chainExtended[1], chainExtended[2]);
}
}
}
if(EstablishCollision(alphaObject, gammaObject, COLLISION_SENSITIVITY) && !chainExtended[1])
{
if(alphaType == NoPowerUp || alphaType == Rebirth || alphaType == Invisibility)
{
if(gammaType == SupremeBlast || gammaType == SupaFly)
{
gammaLength += alphaLength;
alphaLength = 2;
SetChainExtended(chainExtended[1], chainExtended[3], chainExtended[2]);
}
}
if(alphaType == SupremeBlast)
{
if(gammaType == NoPowerUp || gammaType == Rebirth || gammaType == Invisibility)
{
alphaLength += gammaLength;
gammaLength = 2;
SetChainExtended(chainExtended[1], chainExtended[3], chainExtended[2]);
}
}
if(alphaType == SupaFly)
{
if(gammaType == NoPowerUp || gammaType == Rebirth || gammaType == Invisibility || gammaType == SupremeBlast)
{
alphaLength += gammaLength;
gammaLength = 2;
SetChainExtended(chainExtended[1], chainExtended[3], chainExtended[2]);
}
if(gammaType == SupaFly)
{
alphaLength = 2;
gammaLength = 2;
SetChainExtended(chainExtended[1], chainExtended[3], chainExtended[2]);
}
}
}
if(EstablishCollision(betaObject, gammaObject, COLLISION_SENSITIVITY) && !chainExtended[2])
{
if(betaType == NoPowerUp || betaType == Rebirth || betaType == Invisibility)
{
if(gammaType == SupremeBlast || gammaType == SupaFly)
{
gammaLength += betaLength;
betaLength = 2;
SetChainExtended(chainExtended[2], chainExtended[1], chainExtended[3]);
}
}
if(betaType == SupremeBlast)
{
if(gammaType == NoPowerUp || gammaType == Rebirth || gammaType == Invisibility)
{
betaLength += gammaLength;
gammaLength = 2;
SetChainExtended(chainExtended[2], chainExtended[1], chainExtended[3]);
}
}
if(betaType == SupaFly)
{
if(gammaType == NoPowerUp || gammaType == Rebirth || gammaType == Invisibility || gammaType == SupremeBlast)
{
betaLength += gammaLength;
gammaLength = 2;
SetChainExtended(chainExtended[2], chainExtended[1], chainExtended[3]);
}
if(gammaType == SupaFly)
{
betaLength = 2;
gammaLength = 2;
SetChainExtended(chainExtended[2], chainExtended[1], chainExtended[3]);
}
}
}
// Ensure that if Rebirth power up held then chain length is equal to the longest length...
if(alphaType == Rebirth)
{
if(alphaLength < betaLength)
alphaLength = betaLength;
if(alphaLength < gammaLength)
alphaLength = betaLength;
}
if(betaType == Rebirth)
{
if(betaLength < alphaLength)
betaLength = alphaLength;
if(betaLength < gammaLength)
betaLength = gammaLength;
}
if(gammaType == Rebirth)
{
if(gammaLength < alphaLength)
gammaLength = alphaLength;
if(gammaLength < betaLength)
gammaLength = betaLength;
}
}
void SetChainExtended(bool &chainA, bool &chainB, bool &chainC)
// Support function for ApplyGameRules() to control chain length extentions.
// Prevents chains from extending too long or too short.
{
chainA = true;
if(chainB)
chainB = false;
if(chainC)
chainC = false;
}
| 33.797647
| 165
| 0.693261
|
ButchDean
|
f7b90e74ae714b91fbb72ded989144477802a0ec
| 4,270
|
cpp
|
C++
|
src/cpp/node.cpp
|
DDRDmakar/LSCL
|
f43e3792c11ba65bf404046cc37be418671bffea
|
[
"Apache-2.0"
] | null | null | null |
src/cpp/node.cpp
|
DDRDmakar/LSCL
|
f43e3792c11ba65bf404046cc37be418671bffea
|
[
"Apache-2.0"
] | 2
|
2019-08-29T09:40:52.000Z
|
2019-10-06T12:30:32.000Z
|
src/cpp/node.cpp
|
DDRDmakar/LSCL
|
f43e3792c11ba65bf404046cc37be418671bffea
|
[
"Apache-2.0"
] | null | null | null |
/*
*
* Copyright 2019 Nikita Makarevich
*
* 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 "node.hpp"
namespace LSCL
{
Node::Node(Node_internal &newcore) : core(&newcore) { check_core(); }
Node::Node(Node_internal *newcore) : core( newcore) { check_core(); }
Node::Node(const std::unique_ptr<Node_internal> &newcore) : core(newcore.get()) { check_core(); }
inline void Node::check_core(void) const
{
// Throw an exception if node si constructed from link or attached node
if (core->type == NODETYPE_ATTACHED || core->type == NODETYPE_LINK)
throw LSCL::Exception::Exception_access("Invalid Node constructor arguments. Node core cannot be of type ATTACHED or LINK, it is LSCL internal type.");
}
Node_internal* Node::resolve_destination_node(Node_internal *destination) const
{
while (true)
{
switch (destination->type)
{
case NODETYPE_LINK:
{
destination = static_cast<Link*>(destination)->linked;
if (!destination) throw LSCL::Exception::Exception_access("Accessed link is NULL (not assigned)");
break;
}
case NODETYPE_ATTACHED:
{
destination = static_cast<Attached*>(destination)->attached;
if (!destination) throw LSCL::Exception::Exception_access("Accessed attached node is NULL (not assigned)");
break;
}
default:
{
return destination;
}
}
}
return destination;
}
NODETYPE Node::get_type(void)
{
return core->type;
}
Node Node::get_parent(void) const
{
return Node(core->parent);////////////////////////////////////////////////////////////////////////////////////////////////
}
size_t Node::size(void) const
{
return core->size();
}
//=====[ S C A L A R ]=====//
//=====[ L I S T ]=====//
Node Node::operator[](const size_t idx)
{
return Node(
resolve_destination_node(
static_cast<LSCL::List*>(core)->at(idx)
)
);
}
void Node::insert(const Node &element, const size_t idx)
{
insert(element.core, idx);
}
void Node::insert(Node_internal *element, const size_t idx)
{
if (core->type != NODETYPE_LIST) throw LSCL::Exception::Exception_modify("Trying to insert element into non-list node");
LSCL::List::lscl_list &l = static_cast<LSCL::List*>(core)->values_list;
if (idx == SIZE_MAX) // idx == last position
{
l.push_back(element);
}
else
{
l.insert(l.begin() + idx, element);
}
}
bool Node::remove(const size_t idx)
{
if (core->type != NODETYPE_LIST) throw LSCL::Exception::Exception_modify("Trying to remove element by index from non-list node");
LSCL::List::lscl_list &l = static_cast<LSCL::List*>(core)->values_list;
if (idx >= l.size()) return false;
delete l[idx];
l.erase(l.begin() + idx);
return true;
}
//=====[ M A P ]=====//
Node Node::operator[](const std::string &key)
{
return Node(
resolve_destination_node(
static_cast<LSCL::Map*>(core)->at(key)
)
);
}
void Node::insert(const Node &element, const std::string &key)
{
insert(element.core, key);
}
void Node::insert(Node_internal *element, const std::string &key)
{
if (core->type != NODETYPE_MAP) throw LSCL::Exception::Exception_modify("Trying to insert element by key into non-map node");
static_cast<LSCL::Map*>(core)->values_map.emplace(std::make_pair(key, element)); // Insert node
}
bool Node::remove(const std::string &key)
{
if (core->type != NODETYPE_MAP) throw LSCL::Exception::Exception_modify("Trying to remove element by key from non-map node");
LSCL::Map::lscl_map &m = static_cast<LSCL::Map*>(core)->values_map;
auto res = m.find(key);
if (res != m.end()) // If such key exists
{
delete m[key];
m.erase(res);
return true;
}
else return false;
}
} // namespace LSCL
| 26.358025
| 154
| 0.651522
|
DDRDmakar
|
f7bc320399eb46c65c3db519dcc6b512b443c670
| 311
|
cpp
|
C++
|
extras2/Shapes/main.cpp
|
stefanaciudin/CommandDefense
|
cae223bf72019b2098764664be5de2f052d57d6c
|
[
"MIT"
] | null | null | null |
extras2/Shapes/main.cpp
|
stefanaciudin/CommandDefense
|
cae223bf72019b2098764664be5de2f052d57d6c
|
[
"MIT"
] | null | null | null |
extras2/Shapes/main.cpp
|
stefanaciudin/CommandDefense
|
cae223bf72019b2098764664be5de2f052d57d6c
|
[
"MIT"
] | null | null | null |
#include "Cerc.h"
#include "Dreptunghi.h"
#include "DreptunghiRotit.h"
#include "Forma.h"
#include "Forme.h"
#include "Oval.h"
int main()
{
Forme f;
Cerc c;
c.set(10, 10, 100);
Oval o;
o.set(20, 20, 50, 100);
DreptunghiRotit p;
p.set(5, 5, 2, 10, 30);
f.Add(&c);
f.Add(&o);
f.Add(&p);
f.Paint();
}
| 14.809524
| 28
| 0.598071
|
stefanaciudin
|
f7c1ebe78f268fb936659b3d041358f8ce820276
| 14,899
|
cpp
|
C++
|
template.cpp
|
Powerman1254/Game
|
f48be9fc0eb592b310002d6e6d0edc7d05ebe8a2
|
[
"Unlicense"
] | null | null | null |
template.cpp
|
Powerman1254/Game
|
f48be9fc0eb592b310002d6e6d0edc7d05ebe8a2
|
[
"Unlicense"
] | null | null | null |
template.cpp
|
Powerman1254/Game
|
f48be9fc0eb592b310002d6e6d0edc7d05ebe8a2
|
[
"Unlicense"
] | null | null | null |
// Template, BUAS version https://www.buas.nl/games
// IGAD/BUAS(NHTV)/UU - Jacco Bikker - 2006-2020
// Note:
// this version of the template uses SDL2 for all frame buffer interaction
// see: https://www.libsdl.org
#ifdef _MSC_VER
#pragma warning (disable : 4530) // complaint about exception handler
#pragma warning (disable : 4311) // pointer truncation from HANDLE to long
#endif
//#define FULLSCREEN
//#define ADVANCEDGL
#include "template.h"
#include <corecrt_math.h>
#include <cstdio>
#include <fcntl.h>
#include <io.h>
#include <iostream>
#include <SDL.h>
#include "game.h"
#include "surface.h"
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include "Exit.h"
#include "Menu.h"
#ifdef ADVANCEDGL
#define GLEW_BUILD
extern "C"
{
#include "glew.h"
}
#include "gl.h"
#include "wglext.h"
#endif
namespace tmpl8 {
// Math Stuff
// ----------------------------------------------------------------------------
vec3 normalize(const vec3& v) { return v.normalized(); }
vec3 cross(const vec3& a, const vec3& b) { return a.cross(b); }
float dot(const vec3& a, const vec3& b) { return a.dot(b); }
vec3 operator * (const float& s, const vec3& v) { return { v.x * s, v.y * s, v.z * s }; }
vec3 operator * (const vec3& v, const float& s) { return { v.x * s, v.y * s, v.z * s }; }
vec4 operator * (const float& s, const vec4& v) { return { v.x * s, v.y * s, v.z * s, v.w * s }; }
vec4 operator * (const vec4& v, const float& s) { return { v.x * s, v.y * s, v.z * s, v.w * s }; }
vec4 operator * (const vec4& v, const mat4& M)
{
const vec4 mx(M.cell[0], M.cell[4], M.cell[8], M.cell[12]);
const vec4 my(M.cell[1], M.cell[5], M.cell[9], M.cell[13]);
const vec4 mz(M.cell[2], M.cell[6], M.cell[10], M.cell[14]);
const vec4 mw(M.cell[3], M.cell[7], M.cell[11], M.cell[15]);
return v.x * mx + v.y * my + v.z * mz + v.w * mw;
}
mat4::mat4()
{
memset(cell, 0, 64);
cell[0] = cell[5] = cell[10] = cell[15] = 1;
}
mat4 mat4::identity()
{
mat4 r;
memset(r.cell, 0, 64);
r.cell[0] = r.cell[5] = r.cell[10] = r.cell[15] = 1.0f;
return r;
}
mat4 mat4::rotate(const vec3 l, const float a)
{
// http://inside.mines.edu/fs_home/gmurray/ArbitraryAxisRotation
mat4 M;
const float u = l.x, v = l.y, w = l.z, ca = cosf(a), sa = sinf(a);
M.cell[0] = u * u + (v * v + w * w) * ca, M.cell[1] = u * v * (1 - ca) - w * sa;
M.cell[2] = u * w * (1 - ca) + v * sa, M.cell[4] = u * v * (1 - ca) + w * sa;
M.cell[5] = v * v + (u * u + w * w) * ca, M.cell[6] = v * w * (1 - ca) - u * sa;
M.cell[8] = u * w * (1 - ca) - v * sa, M.cell[9] = v * w * (1 - ca) + u * sa;
M.cell[10] = w * w + (u * u + v * v) * ca;
M.cell[3] = M.cell[7] = M.cell[11] = M.cell[12] = M.cell[13] = M.cell[14] = 0, M.cell[15] = 1;
return M;
}
mat4 mat4::rotatex(const float a)
{
mat4 M;
const float ca = cosf(a), sa = sinf(a);
M.cell[5] = ca, M.cell[6] = -sa;
M.cell[9] = sa, M.cell[10] = ca;
return M;
}
mat4 mat4::rotatey(const float a)
{
mat4 M;
const float ca = cosf(a), sa = sinf(a);
M.cell[0] = ca, M.cell[2] = sa;
M.cell[8] = -sa, M.cell[10] = ca;
return M;
}
mat4 mat4::rotatez(const float a)
{
mat4 M;
const float ca = cosf(a), sa = sinf(a);
M.cell[0] = ca, M.cell[1] = -sa;
M.cell[4] = sa, M.cell[5] = ca;
return M;
}
[[ noreturn ]] void NotifyUser(const char* s)
{
const HWND hApp = FindWindow(nullptr, TemplateVersion); // NOLINT(misc-misplaced-const)
MessageBox(hApp, s, "ERROR", MB_OK);
exit(0); // NOLINT(concurrency-mt-unsafe)
}
}
using namespace tmpl8;
using namespace std;
#ifdef ADVANCEDGL
PFNGLGENBUFFERSPROC glGenBuffers = 0;
PFNGLBINDBUFFERPROC glBindBuffer = 0;
PFNGLBUFFERDATAPROC glBufferData = 0;
PFNGLMAPBUFFERPROC glMapBuffer = 0;
PFNGLUNMAPBUFFERPROC glUnmapBuffer = 0;
typedef BOOL(APIENTRY* PFNWGLSWAPINTERVALFARPROC)(int);
PFNWGLSWAPINTERVALFARPROC wglSwapIntervalEXT = 0;
unsigned int framebufferTexID[2];
GLuint fbPBO[2];
unsigned char* framedata = 0;
#endif
int ACTWIDTH, ACTHEIGHT;
static bool firstframe = true;
Surface* surface = 0;
Game* game = 0;
SDL_Window* window = 0;
#ifdef _MSC_VER
bool redirectIO()
{
CONSOLE_SCREEN_BUFFER_INFO coninfo;
AllocConsole();
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &coninfo);
coninfo.dwSize.Y = 500;
SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), coninfo.dwSize);
HANDLE h1 = GetStdHandle(STD_OUTPUT_HANDLE);
int h2 = _open_osfhandle(reinterpret_cast<intptr_t>(h1), _O_TEXT);
const FILE* fp = _fdopen(h2, "w");
*stdout = *fp; // NOLINT(misc-non-copyable-objects)
setvbuf(stdout, NULL, _IONBF, 0);
h1 = GetStdHandle(STD_INPUT_HANDLE), h2 = _open_osfhandle(reinterpret_cast<intptr_t>(h1), _O_TEXT);
fp = _fdopen(h2, "r"), * stdin = *fp; // NOLINT(misc-non-copyable-objects)
setvbuf(stdin, NULL, _IONBF, 0);
h1 = GetStdHandle(STD_ERROR_HANDLE), h2 = _open_osfhandle(reinterpret_cast<intptr_t>(h1), _O_TEXT);
fp = _fdopen(h2, "w"), * stderr = *fp; // NOLINT(misc-non-copyable-objects)
setvbuf(stderr, NULL, _IONBF, 0);
ios::sync_with_stdio();
// ReSharper disable once CppEntityAssignedButNoRead
FILE* stream;
if ((stream = freopen("CON", "w", stdout)) == NULL)
return false;
if ((stream = freopen("CON", "w", stderr)) == NULL)
return false;
return true;
}
#endif
#ifdef ADVANCEDGL
bool createFBtexture()
{
glGenTextures(2, framebufferTexID);
if (glGetError()) return false;
for (int i = 0; i < 2; i++)
{
glBindTexture(GL_TEXTURE_2D, framebufferTexID[i]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, ScreenWidth, ScreenHeight, 0, GL_BGRA, GL_UNSIGNED_BYTE, NULL);
glBindTexture(GL_TEXTURE_2D, 0);
if (glGetError()) return false;
}
const int sizeMemory = 4 * ScreenWidth * ScreenHeight;
glGenBuffers(2, fbPBO);
glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, fbPBO[0]);
glBufferData(GL_PIXEL_UNPACK_BUFFER_ARB, sizeMemory, NULL, GL_STREAM_DRAW_ARB);
glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, fbPBO[1]);
glBufferData(GL_PIXEL_UNPACK_BUFFER_ARB, sizeMemory, NULL, GL_STREAM_DRAW_ARB);
glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, 0);
glBindTexture(GL_TEXTURE_2D, framebufferTexID[0]);
glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, fbPBO[0]);
framedata = (unsigned char*)glMapBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, GL_WRITE_ONLY_ARB);
if (!framedata) return false;
memset(framedata, 0, ScreenWidth * ScreenHeight * 4);
return (glGetError() == 0);
}
bool init()
{
fbPBO[0] = fbPBO[1] = -1;
glGenBuffers = (PFNGLGENBUFFERSPROC)wglGetProcAddress("glGenBuffersARB");
glBindBuffer = (PFNGLBINDBUFFERPROC)wglGetProcAddress("glBindBufferARB");
glBufferData = (PFNGLBUFFERDATAPROC)wglGetProcAddress("glBufferDataARB");
glMapBuffer = (PFNGLMAPBUFFERPROC)wglGetProcAddress("glMapBufferARB");
glUnmapBuffer = (PFNGLUNMAPBUFFERPROC)wglGetProcAddress("glUnmapBufferARB");
wglSwapIntervalEXT = (PFNWGLSWAPINTERVALFARPROC)wglGetProcAddress("wglSwapIntervalEXT");
if ((!glGenBuffers) || (!glBindBuffer) || (!glBufferData) || (!glMapBuffer) || (!glUnmapBuffer)) return false;
if (glGetError()) return false;
int screenx, screeny;
#ifdef FULLSCREEN
screenx = GetSystemMetrics(SM_CXFULLSCREEN), screeny = GetSystemMetrics(SM_CYFULLSCREEN);
#else
screenx = ScreenWidth, screeny = ScreenHeight;
#endif
glViewport(0, 0, screenx, screeny);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, 1, 0, 1, -1, 1);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glEnable(GL_TEXTURE_2D);
glShadeModel(GL_SMOOTH);
if (!createFBtexture()) return false;
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT);
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
glBlendFunc(GL_SRC_ALPHA, GL_ONE);
if (wglSwapIntervalEXT) wglSwapIntervalEXT(0);
surface = new Surface(ScreenWidth, ScreenHeight, 0, ScreenWidth);
return true;
}
void swap()
{
static int index = 0;
int nextindex;
glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER_ARB);
glBindTexture(GL_TEXTURE_2D, framebufferTexID[index]);
glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, fbPBO[index]);
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, ScreenWidth, ScreenHeight, GL_BGRA, GL_UNSIGNED_BYTE, 0);
nextindex = (index + 1) % 2;
index = (index + 1) % 2;
glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, fbPBO[nextindex]);
framedata = (unsigned char*)glMapBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, GL_WRITE_ONLY_ARB);
glColor3f(1.0f, 1.0f, 1.0f);
glBegin(GL_QUADS);
glNormal3f(0, 0, 1);
glTexCoord2f(0.0f, 0.0f);
glVertex2f(0.0f, 1.0f);
glTexCoord2f(1.0f, 0.0f);
glVertex2f(1.0f, 1.0f);
glTexCoord2f(1.0f, 1.0f);
glVertex2f(1.0f, 0.0f);
glTexCoord2f(0.0f, 1.0f);
glVertex2f(0.0f, 0.0f);
glEnd();
glBindTexture(GL_TEXTURE_2D, 0);
SDL_GL_SwapWindow(window);
}
#endif
int exitapp = 0;
bool isFullscreen = false;
int main(int argc, char** argv)
{
SDL_SetHintWithPriority(SDL_HINT_RENDER_VSYNC, "0", SDL_HINT_OVERRIDE);
srand(static_cast<int>(time(NULL))); // NOLINT(cert-msc51-cpp)
#ifdef _MSC_VER
/*if (!redirectIO())
return 1;*/
#endif
printf("application started.\n");
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_GAMECONTROLLER) < 0)
{
fprintf(stderr, "Couldn't initialize SDL: %s\n", SDL_GetError());
exitapp = 1;
}
#ifdef ADVANCEDGL
#ifdef FULLSCREEN
window = SDL_CreateWindow(TemplateVersion, 100, 100, ScreenWidth, ScreenHeight, SDL_WINDOW_FULLSCREEN_DESKTOP | SDL_WINDOW_OPENGL);
isFullscreen = true;
#else
window = SDL_CreateWindow(TemplateVersion, 100, 100, ScreenWidth, ScreenHeight, SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL);
#endif
SDL_GLContext glContext = SDL_GL_CreateContext(window);
init();
#else
#ifdef FULLSCREEN
window = SDL_CreateWindow(TemplateVersion, 100, 100, ScreenWidth, ScreenHeight, SDL_WINDOW_FULLSCREEN_DESKTOP);
isFullscreen = true;
#else
window = SDL_CreateWindow(TemplateVersion, 100, 100, ScreenWidth, ScreenHeight, SDL_WINDOW_SHOWN);
#endif
surface = new Surface(ScreenWidth, ScreenHeight);
surface->Clear(0);
SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
SDL_Texture* frameBuffer = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, ScreenWidth, ScreenHeight);
#endif
SDL_Surface* icon = SDL_LoadBMP("assets/UI/icon.bmp");
SDL_SetWindowIcon(window, icon);
SDL_FreeSurface(icon);
SDL_DisplayMode display;
SDL_GetCurrentDisplayMode(0, &display);
SDL_SetWindowResizable(window, SDL_TRUE);
SDL_SetWindowMinimumSize(window, ScreenWidth / 2, ScreenHeight / 2);
game = new Game({ static_cast<float>(display.w), static_cast<float>(display.h) }, isFullscreen);
game->SetTarget(surface);
SDL_GameController* gameController = NULL;
for (int i = 0; i < SDL_NumJoysticks(); ++i) {
if (SDL_IsGameController(i)) {
gameController = SDL_GameControllerOpen(i);
if (gameController)
{
break;
}
fprintf(stderr, "Could not open gamecontroller %i: %s\n", i, SDL_GetError());
}
}
while (!exitapp)
{
#ifdef ADVANCEDGL
swap();
surface->SetBuffer((Pixel*)framedata);
#else
void* target = 0;
int pitch;
SDL_LockTexture(frameBuffer, NULL, &target, &pitch);
if (pitch == (surface->GetWidth() * 4))
{
memcpy(target, surface->GetBuffer(), ScreenWidth * ScreenHeight * 4);
}
else
{
unsigned char* t = static_cast<unsigned char*>(target);
for (int i = 0; i < ScreenHeight; i++)
{
memcpy(t, surface->GetBuffer() + i * ScreenWidth, ScreenWidth * 4);
t += pitch;
}
}
SDL_UnlockTexture(frameBuffer);
SDL_RenderCopy(renderer, frameBuffer, NULL, NULL);
SDL_RenderPresent(renderer);
#endif
if (firstframe)
{
game->Init();
firstframe = false;
}
game->Tick();
// event loop
SDL_Event event;
while (SDL_PollEvent(&event))
{
switch (event.type)
{
case SDL_QUIT:
exitapp = 1;
break;
case SDL_KEYDOWN:
if (event.key.keysym.sym == SDLK_ESCAPE)
{
game->GetMenu()->GetExitButton()->OnClick(game->GetMenu());
}
if (event.key.keysym.sym == SDLK_F11)
{
isFullscreen = !isFullscreen;
game->setFullscreen(isFullscreen);
if (isFullscreen)
SDL_SetWindowFullscreen(window, SDL_WINDOW_FULLSCREEN_DESKTOP);
else
SDL_SetWindowFullscreen(window, 0);
}
game->KeyDown(event.key.keysym.scancode);
game->GetMenu()->KeyDown(event.key.keysym.sym);
break;
case SDL_KEYUP:
game->KeyUp(event.key.keysym.scancode);
break;
case SDL_MOUSEMOTION:
game->MouseMove(event.motion.x, event.motion.y);
break;
case SDL_MOUSEBUTTONUP:
game->MouseUp(event.button.button);
break;
case SDL_MOUSEBUTTONDOWN:
game->MouseDown(event.button.button);
break;
case SDL_CONTROLLERAXISMOTION:
if (event.caxis.value < -3200 || event.caxis.value > 3200)
game->JoystickMove(event.caxis.axis, event.caxis.value);
else
game->JoystickMove(event.caxis.axis, 0);
break;
case SDL_CONTROLLERBUTTONDOWN:
if (event.cbutton.button == SDL_CONTROLLER_BUTTON_B || event.cbutton.button == SDL_CONTROLLER_BUTTON_BACK)
{
game->GetMenu()->GetExitButton()->OnClick(game->GetMenu());
}
game->ButtonDown(event.cbutton.button);
break;
case SDL_CONTROLLERBUTTONUP:
game->ButtonUp(event.cbutton.button);
break;
case SDL_WINDOWEVENT:
switch (event.window.event)
{
case SDL_WINDOWEVENT_RESIZED:
game->resizeWindow({ static_cast<float>(event.window.data1), static_cast<float>(event.window.data2) });
break;
default:
break;
}
break;
default:
break;
}
}
}
game->Shutdown();
delete game;
SDL_GameControllerClose(gameController);
SDL_Quit();
return 0;
}
void ExitProgram()
{
exitapp = 1;
}
| 32.817181
| 140
| 0.642258
|
Powerman1254
|
f7c33633c8923207367aaa2f7db77e9c101734c2
| 1,011
|
cpp
|
C++
|
test/optional/bind.cpp
|
freundlich/fcppt
|
17df1b1ad08bf2435f6902d5465e3bc3fe5e3022
|
[
"BSL-1.0"
] | 13
|
2015-02-21T18:35:14.000Z
|
2019-12-29T14:08:29.000Z
|
test/optional/bind.cpp
|
cpreh/fcppt
|
17df1b1ad08bf2435f6902d5465e3bc3fe5e3022
|
[
"BSL-1.0"
] | 5
|
2016-08-27T07:35:47.000Z
|
2019-04-21T10:55:34.000Z
|
test/optional/bind.cpp
|
freundlich/fcppt
|
17df1b1ad08bf2435f6902d5465e3bc3fe5e3022
|
[
"BSL-1.0"
] | 8
|
2015-01-10T09:22:37.000Z
|
2019-12-01T08:31:12.000Z
|
// Copyright Carl Philipp Reh 2009 - 2021.
// 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)
#include <fcppt/catch/begin.hpp>
#include <fcppt/catch/end.hpp>
#include <fcppt/optional/bind.hpp>
#include <fcppt/optional/object.hpp>
#include <fcppt/optional/output.hpp>
#include <fcppt/config/external_begin.hpp>
#include <catch2/catch.hpp>
#include <string>
#include <fcppt/config/external_end.hpp>
FCPPT_CATCH_BEGIN
TEST_CASE("optional::bind", "[optional]")
{
using optional_string = fcppt::optional::object<std::string>;
CHECK(fcppt::optional::bind(optional_string{"test2"}, [](std::string const &_value) {
return optional_string{"test1" + _value};
}) == optional_string{"test1test2"});
CHECK(fcppt::optional::bind(optional_string{"test2"}, [](std::string const &) {
return optional_string{};
}) == optional_string{});
}
FCPPT_CATCH_END
| 31.59375
| 87
| 0.69634
|
freundlich
|
f7c33e57fa0224e12969cac480d12e4f320435bf
| 6,361
|
cc
|
C++
|
tensorflow/core/tpu/kernels/xla/segment_reduction_ops.cc
|
Dynmi/tensorflow
|
74f953df1b3a3e2f32ffdd0065322a0aa9df53e2
|
[
"Apache-2.0"
] | 1
|
2020-10-21T08:14:38.000Z
|
2020-10-21T08:14:38.000Z
|
tensorflow/core/tpu/kernels/xla/segment_reduction_ops.cc
|
Dynmi/tensorflow
|
74f953df1b3a3e2f32ffdd0065322a0aa9df53e2
|
[
"Apache-2.0"
] | 3
|
2021-08-25T16:13:38.000Z
|
2022-02-10T02:04:06.000Z
|
tensorflow/core/tpu/kernels/xla/segment_reduction_ops.cc
|
Dynmi/tensorflow
|
74f953df1b3a3e2f32ffdd0065322a0aa9df53e2
|
[
"Apache-2.0"
] | null | null | null |
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may 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 "tensorflow/compiler/tf2xla/lib/scatter.h"
#include "tensorflow/compiler/tf2xla/xla_helpers.h"
#include "tensorflow/compiler/tf2xla/xla_op_kernel.h"
#include "tensorflow/compiler/tf2xla/xla_op_registry.h"
#include "tensorflow/compiler/xla/client/xla_builder.h"
#include "tensorflow/core/tpu/tpu_defs.h"
namespace tensorflow {
namespace {
// TODO(b/32945756): Add a scatter op in XLA and move this to a HLO optimization
// pass. Optimization for UnsortedSegmentSum on TPU: use k-hot matmul. This
// optimization requires:
// 1. data has dtype supported by TPU matmul and has rank of 1 or 2.
// 2. indices has rank of 1.
// 3. matmul op count is less than 800 billion.
//
// Example of calculating UnsortedSegmentSum by k-hot matmul:
// data shape [A, B]
// indices shape [A]
// num_segment N
// output shape [N, B]
// matmul op count N * A * B
// Step 1: create k-hot matrix
// k-hot matrix has shape of [A, N], where row i is responsible for
// collecting the sum of the i-th segment, concretely
// k-hot[i][j] = 1 if indices[i] = j
// Step 2: perform matmul
// the final result is obtained by multiplying k-hot matrix with data
// matrix, namely
// k-hot * data => result
// shape: [N, A] * [A, B] => [N, B]
xla::XlaOp KHotMatmul(XlaOpKernelContext* ctx, xla::XlaBuilder* builder,
const xla::XlaOp data, const xla::XlaOp indices,
int64 num_segments) {
DataType data_dtype = ctx->input_type(0);
xla::PrimitiveType indices_type = ctx->input_xla_type(1);
TensorShape data_shape = ctx->InputShape(0);
TensorShape indices_shape = ctx->InputShape(1);
xla::XlaOp linspace = xla::Iota(builder, indices_type, num_segments);
xla::XlaOp linspace_col = xla::Reshape(linspace, {num_segments, 1});
TensorShape indices_row_shape = indices_shape;
indices_row_shape.InsertDim(0, 1);
xla::XlaOp indices_row = xla::Reshape(indices, indices_row_shape.dim_sizes());
xla::XlaOp k_hot = xla::Eq(indices_row, linspace_col);
xla::XlaOp k_hot_with_data_dtype =
XlaHelpers::ConvertElementType(k_hot, data_dtype);
// F32 version of the KHotMatmul. It splits the F32 data into three
// BF16 partial data and run KHotMatmul for each of them. The final result
// is the summation of three BF16 results.
// Note that this still doesn't fully retain f32 precision.
// In particular, values smaller than 2^-111 may see loss of precision.
xla::PrecisionConfig precision_config;
if (data_dtype == DT_FLOAT) {
precision_config.add_operand_precision(xla::PrecisionConfig::HIGHEST);
} else {
CHECK_EQ(data_dtype, DT_BFLOAT16);
precision_config.add_operand_precision(xla::PrecisionConfig::DEFAULT);
}
precision_config.add_operand_precision(xla::PrecisionConfig::DEFAULT);
return xla::Dot(k_hot_with_data_dtype, data, &precision_config);
}
class UnsortedSegmentSum : public XlaOpKernel {
public:
explicit UnsortedSegmentSum(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {
OP_REQUIRES_OK(ctx, ctx->GetAttr("T", &dtype_));
}
void Compile(XlaOpKernelContext* ctx) override {
// output = unsorted_segment_sum(data, indices, num_segments)
// Compute a tensor such that:
// output[i] = sum over {j where indices[j] == i} of data[j]
// output[i] == 0 if i does not appear in indices
//
// Contrast with segment_sum(), which assumes indices are sorted and that
// max(indices)+1 is the desired size of the output.
//
// The returned output tensor has the same type as data, and the same shape
// as data with the first indices.rank dimensions are replaced
// by a single dimension with size num_segments.
xla::XlaOp data = ctx->Input(0);
TensorShape data_shape = ctx->InputShape(0);
xla::XlaOp indices = ctx->Input(1);
TensorShape indices_shape = ctx->InputShape(1);
int64 num_segments;
OP_REQUIRES_OK(ctx, ctx->ConstantInputAsIntScalar(2, &num_segments));
OP_REQUIRES(ctx, data_shape.dims() >= indices_shape.dims(),
errors::InvalidArgument(
"UnsortedSegmentSum requires that indices' rank be"
" less than or equal to data's rank."));
// Validate that indices.shape is a prefix of data.shape.
for (int d = 0; d < indices_shape.dims(); ++d) {
OP_REQUIRES(ctx, (data_shape.dim_size(d) == indices_shape.dim_size(d)),
errors::InvalidArgument(
"UnsortedSegmentSum requires indices shape to be prefix"
" of data_shape, but dimension ",
d, " differs ", data_shape.dim_size(d), " vs. ",
indices_shape.dim_size(d)));
}
xla::XlaBuilder* builder = ctx->builder();
TensorShape buffer_shape = data_shape;
buffer_shape.RemoveDimRange(0, indices_shape.dims());
buffer_shape.InsertDim(0, num_segments);
auto buffer = xla::Broadcast(XlaHelpers::Zero(builder, dtype_),
buffer_shape.dim_sizes());
auto combiner = [](xla::XlaOp a, xla::XlaOp b, xla::XlaBuilder* builder) {
return a + b;
};
auto result = XlaScatter(buffer, /*updates=*/data, indices,
/*indices_are_vectors=*/false, combiner, builder);
OP_REQUIRES_OK(ctx, result.status());
ctx->SetOutput(0, result.ValueOrDie());
}
private:
DataType dtype_;
};
REGISTER_XLA_OP(Name("UnsortedSegmentSum")
.Device(DEVICE_TPU_XLA_JIT)
.CompileTimeConstantInput("num_segments"),
UnsortedSegmentSum);
} // namespace
} // namespace tensorflow
| 43.568493
| 80
| 0.669549
|
Dynmi
|
f7d5f7f3b94b9ba05563c949a2d79a0f3c46b745
| 1,024
|
cpp
|
C++
|
oop-rubook/cp3/3-7.cpp
|
lymven-io/OOP
|
dd4f8487c15b4b58c7d24b0f7c0f0ad90b9ee54a
|
[
"MIT"
] | null | null | null |
oop-rubook/cp3/3-7.cpp
|
lymven-io/OOP
|
dd4f8487c15b4b58c7d24b0f7c0f0ad90b9ee54a
|
[
"MIT"
] | null | null | null |
oop-rubook/cp3/3-7.cpp
|
lymven-io/OOP
|
dd4f8487c15b4b58c7d24b0f7c0f0ad90b9ee54a
|
[
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
class A {
int row, col;
int **a;
public:
A() {
a = 0;
row = col = 0;
}
A(int r, int c);
~A();
void set();
void show();
};
A::A(int r, int c) {
row = r;
col = c;
a = new int *[row]; // set up row
for (int i = 0; i < row; i++)
a[i] = new int[col]; // set up column
}
A::~A() {
if (a != 0) {
for (int i = 0; i < row; i++)
delete[] a[i]; // delete column
delete[] a; // delete row
}
}
void A::set() {
for (int i = 0; i < row; i++)
for (int j = 0; j < col; j++) {
cout << "Input a[" << i << "][" << j << "]=";
cin >> a[i][j];
}
}
void A::show() {
for (int i = 0; i < row; i++)
for (int j = 0; j < col; j++)
cout << "a[" << i << "][" << j << "]=" << a[i][j] << endl;
}
int main() {
A x(2, 3);
x.set();
x.show();
return 0;
}
| 17.964912
| 70
| 0.337891
|
lymven-io
|
f7e59177fa61a301bc2dce220226205c0a2ec2a0
| 356
|
cpp
|
C++
|
src/eexception/eexcp.cpp
|
PowerAngelXD/EytionLang
|
fb270724b6336d4fc947496cfe702da52b64047f
|
[
"MIT"
] | 6
|
2021-10-17T07:10:23.000Z
|
2022-01-16T05:05:05.000Z
|
src/eexception/eexcp.cpp
|
PowerAngelXD/EytionLang
|
fb270724b6336d4fc947496cfe702da52b64047f
|
[
"MIT"
] | null | null | null |
src/eexception/eexcp.cpp
|
PowerAngelXD/EytionLang
|
fb270724b6336d4fc947496cfe702da52b64047f
|
[
"MIT"
] | null | null | null |
#include "eexcp.h"
using namespace eexcp;
EyparseError::EyparseError(string title, string content, int line ,int col){
message = (string)("EytionError {" + title + "}: " + content + "\nline: " + to_string(line) + "\ncol: " + to_string(col));
}
EyparseError::~EyparseError() throw() {}
const char* EyparseError::what(){
return message.c_str();
}
| 27.384615
| 126
| 0.660112
|
PowerAngelXD
|
f7e8f4131dec4b37267f3d500aa6b53c515cda73
| 1,793
|
cpp
|
C++
|
Inheritance/Inheritance.cpp
|
rastabrandy02/Programming2
|
8dba0e75c01dc884df09f19bcacf1140ca9ca501
|
[
"MIT"
] | null | null | null |
Inheritance/Inheritance.cpp
|
rastabrandy02/Programming2
|
8dba0e75c01dc884df09f19bcacf1140ca9ca501
|
[
"MIT"
] | null | null | null |
Inheritance/Inheritance.cpp
|
rastabrandy02/Programming2
|
8dba0e75c01dc884df09f19bcacf1140ca9ca501
|
[
"MIT"
] | 1
|
2021-02-22T08:43:48.000Z
|
2021-02-22T08:43:48.000Z
|
#include <iostream>
using namespace std;
class Building {
protected:
string name;
public:
Building() {};
Building(string name)
{
this->name = name;
}
string GetName()
{
return name;
}
~Building() {};
};
class Warehouse : public Building
{
private:
int wood;
int rocks;
int wheat;
public:
Warehouse(string name, int wood, int rocks, int wheat)
{
this->name = name;
this->wood = wood;
this->rocks = rocks;
this->wheat = wheat;
}
void PrintResources()
{
cout << "---" << name << "---" << endl;
cout << "Wood: " << wood << endl;
cout << "Rocks: " << rocks << endl;
cout << "Wheat: " << wheat << endl;
}
~Warehouse() {};
};
class House : public Building
{
private:
int floors;
int inhabitants;
int servants;
public:
House(string name, int floors, int inhabitants, int servants)
{
this->name = name;
this->floors = floors;
this->inhabitants = inhabitants;
this->servants = servants;
}
void PrintHouse()
{
cout << "---" << name << "---" << endl;
cout << "Floors: " << floors << endl;
cout << "Inhabitants: " << inhabitants << endl;
cout << "Servants: " << servants << endl;
}
~House() {};
};
class Temple : public Building
{
private:
string god;
int priests;
public:
Temple(string name, string god, int priests)
{
this->name = name;
this->god = god;
this->priests = priests;
}
void PrintTemple()
{
cout << "---" << name << "---" << endl;
cout << "God: " << god << endl;
cout << "Priests: " << priests << endl;
}
~Temple() {};
};
int main()
{
Warehouse w("East Warehouse", 10, 20, 30);
House h("Agripa's house", 2, 5, 10);
Temple t("Mercury's temple", "Mercury", 3);
cout << "Warehouse name: " << w.GetName() << endl << endl;
w.PrintResources();
h.PrintHouse();
t.PrintTemple();
return 0;
}
| 16.757009
| 62
| 0.587284
|
rastabrandy02
|
f7eb0cab88c4315bf00c753eb4e27b86c477cf51
| 295
|
hpp
|
C++
|
src/3d/private/gltf.hpp
|
kochol/ari2
|
ca185191531acc1954cd4acfec2137e32fdb5c2d
|
[
"MIT"
] | 81
|
2018-12-11T20:48:41.000Z
|
2022-03-18T22:24:11.000Z
|
src/3d/private/gltf.hpp
|
kochol/ari2
|
ca185191531acc1954cd4acfec2137e32fdb5c2d
|
[
"MIT"
] | 7
|
2020-04-19T11:50:39.000Z
|
2021-11-12T16:08:53.000Z
|
src/3d/private/gltf.hpp
|
kochol/ari2
|
ca185191531acc1954cd4acfec2137e32fdb5c2d
|
[
"MIT"
] | 4
|
2019-04-24T11:51:29.000Z
|
2021-03-10T05:26:33.000Z
|
#pragma once
#include "core/string/String.hpp"
#include <functional>
#include "en/ComponentHandle.hpp"
#include "3d/Node3D.hpp"
namespace ari::en
{
void LoadGltfScene(const core::String& _path, std::function<void(core::Array<ComponentHandle<Node3D>>)> OnModel);
} // namespace ari::en
| 24.583333
| 117
| 0.728814
|
kochol
|
f7ef973d849fb5ebc567f36ec2c246873cada16d
| 1,361
|
hpp
|
C++
|
libraries/chain/include/graphene/chain/protocol/greatrace_parameters.hpp
|
finteh/crowdwiz-core
|
d0d2b5e2294c74da5b7304fd76ddab9cc87c18e5
|
[
"MIT"
] | 8
|
2020-11-29T20:19:52.000Z
|
2021-11-02T21:01:41.000Z
|
libraries/chain/include/graphene/chain/protocol/greatrace_parameters.hpp
|
finteh/crowdwiz-core
|
d0d2b5e2294c74da5b7304fd76ddab9cc87c18e5
|
[
"MIT"
] | 5
|
2021-03-06T10:58:34.000Z
|
2021-08-07T09:51:09.000Z
|
libraries/chain/include/graphene/chain/protocol/greatrace_parameters.hpp
|
finteh/crowdwiz-core
|
d0d2b5e2294c74da5b7304fd76ddab9cc87c18e5
|
[
"MIT"
] | 5
|
2020-10-22T17:01:27.000Z
|
2022-02-02T12:53:47.000Z
|
#pragma once
#include <graphene/chain/protocol/base.hpp>
#include <graphene/chain/protocol/types.hpp>
namespace graphene
{
namespace chain
{
struct greatrace_chain_parameters
{
uint32_t vote_duration = (24*60*60);
uint8_t min_team_status = 4;
share_type min_team_volume = 0;
share_type min_gr_bet = (GRAPHENE_BLOCKCHAIN_PRECISION * int64_t(5));
uint16_t min_votes = 50;
uint8_t min_vote_last_rank = 7;
uint16_t interval_1 = 7;
uint16_t interval_2 = 21;
uint16_t interval_3 = 7;
uint16_t interval_4 = 21;
uint16_t interval_5 = 7;
uint16_t interval_6 = 21;
uint16_t interval_7 = 7;
uint16_t interval_8 = 7;
uint16_t interval_9 = 21;
uint16_t interval_10 = 7;
uint16_t interval_11 = 21;
uint16_t interval_12 = 7;
uint16_t interval_13 = 21;
uint16_t interval_14 = 7;
uint16_t apostolos_reward = (GRAPHENE_1_PERCENT)*1;
};
} } // namespace graphene::chain
FC_REFLECT(graphene::chain::greatrace_chain_parameters,
(vote_duration)
(min_team_status)
(min_team_volume)
(min_gr_bet)
(min_votes)
(min_vote_last_rank)
(interval_1)
(interval_2)
(interval_3)
(interval_4)
(interval_5)
(interval_6)
(interval_7)
(interval_8)
(interval_9)
(interval_10)
(interval_11)
(interval_12)
(interval_13)
(interval_14)
(apostolos_reward)
)
| 23.465517
| 75
| 0.700955
|
finteh
|
f7fa7934a0f3e34c508e7aa19326aeaadf2bdafe
| 4,723
|
cpp
|
C++
|
test/function/functions_test.cpp
|
phisiart/peloton
|
c2becb9d6f2e2c8f48696a371b0d7c0ff79d56fc
|
[
"Apache-2.0"
] | 1
|
2017-04-17T15:19:36.000Z
|
2017-04-17T15:19:36.000Z
|
test/function/functions_test.cpp
|
phisiart/peloton
|
c2becb9d6f2e2c8f48696a371b0d7c0ff79d56fc
|
[
"Apache-2.0"
] | 5
|
2017-04-23T17:16:14.000Z
|
2017-04-25T03:14:16.000Z
|
test/function/functions_test.cpp
|
phisiart/peloton-p3
|
c2becb9d6f2e2c8f48696a371b0d7c0ff79d56fc
|
[
"Apache-2.0"
] | null | null | null |
//===----------------------------------------------------------------------===//
//
// Peloton
//
// functions_test.cpp
//
// Identification: test/function/functions_test.cpp
//
// Copyright (c) 2015-2017, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "catalog/catalog.h"
#include "catalog/proc_catalog.h"
#include "catalog/language_catalog.h"
#include "common/harness.h"
#include "concurrency/transaction_manager_factory.h"
#include "sql/testing_sql_util.h"
#include "type/ephemeral_pool.h"
#include "type/value_factory.h"
namespace peloton {
namespace test {
class FunctionsTests : public PelotonTest {
public:
static type::Value TestFunc(
UNUSED_ATTRIBUTE const std::vector<type::Value> &args) {
return type::ValueFactory::GetIntegerValue(0);
}
virtual void SetUp() override {
auto catalog = catalog::Catalog::GetInstance();
catalog->Bootstrap();
}
};
TEST_F(FunctionsTests, CatalogTest) {
auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
auto catalog = catalog::Catalog::GetInstance();
auto &pg_language = catalog::LanguageCatalog::GetInstance();
// Test "internal" language
auto txn = txn_manager.BeginTransaction();
auto internal_lang = pg_language.GetLanguageByName("internal", txn);
EXPECT_NE(nullptr, internal_lang);
internal_lang = pg_language.GetLanguageByOid(internal_lang->GetOid(), txn);
EXPECT_NE(nullptr, internal_lang);
EXPECT_EQ("internal", internal_lang->GetName());
// test add/del language
type::EphemeralPool pool;
std::string lanname = "foo_lang";
pg_language.InsertLanguage(lanname, &pool, txn);
auto inserted_lang = pg_language.GetLanguageByName(lanname, txn);
EXPECT_NE(nullptr, inserted_lang);
inserted_lang = pg_language.GetLanguageByOid(inserted_lang->GetOid(), txn);
EXPECT_NE(nullptr, inserted_lang);
EXPECT_EQ(lanname, inserted_lang->GetName());
pg_language.DeleteLanguage(lanname, txn);
inserted_lang = pg_language.GetLanguageByName(lanname, txn);
EXPECT_EQ(nullptr, inserted_lang);
txn_manager.CommitTransaction(txn);
auto &pg_proc = catalog::ProcCatalog::GetInstance();
// test pg_proc
txn = txn_manager.BeginTransaction();
std::string func_name = "test_func";
std::vector<type::TypeId> arg_types{type::TypeId::VARCHAR,
type::TypeId::INTEGER};
catalog->AddBuiltinFunction(
func_name, arg_types, type::TypeId::INTEGER, internal_lang->GetOid(),
"TestFunc", function::BuiltInFuncType{OperatorId::Add, TestFunc}, txn);
auto inserted_proc = pg_proc.GetProcByName(func_name, arg_types, txn);
EXPECT_NE(nullptr, inserted_proc);
EXPECT_EQ(internal_lang->GetOid(), inserted_proc->GetLangOid());
type::TypeId ret_type = inserted_proc->GetRetType();
EXPECT_EQ(type::TypeId::INTEGER, ret_type);
std::string func = inserted_proc->GetSrc();
EXPECT_EQ("TestFunc", func);
txn_manager.CommitTransaction(txn);
auto func_data = catalog->GetFunction(func_name, arg_types);
EXPECT_EQ(ret_type, func_data.return_type_);
EXPECT_EQ((int64_t)TestFunc, (int64_t)func_data.func_.impl);
}
TEST_F(FunctionsTests, FuncCallTest) {
auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
auto txn = txn_manager.BeginTransaction();
catalog::Catalog::GetInstance()->CreateDatabase(DEFAULT_DB_NAME, txn);
txn_manager.CommitTransaction(txn);
TestingSQLUtil::ExecuteSQLQuery("CREATE TABLE test(a DECIMAL, s VARCHAR);");
TestingSQLUtil::ExecuteSQLQuery("INSERT INTO test VALUES (4.0, 'abc');");
std::vector<StatementResult> result;
std::vector<FieldInfo> tuple_descriptor;
std::string error_message;
int rows_affected;
TestingSQLUtil::ExecuteSQLQuery("SELECT SQRT(a), SUBSTR(s,1,2) FROM test;",
result, tuple_descriptor, rows_affected,
error_message);
EXPECT_EQ(1, result[0].second.size());
EXPECT_EQ('2', result[0].second[0]);
EXPECT_EQ(2, result[1].second.size());
EXPECT_EQ(result[1].second[0], 'a');
EXPECT_EQ(result[1].second[1], 'b');
TestingSQLUtil::ExecuteSQLQuery("SELECT ASCII(s) FROM test;", result,
tuple_descriptor, rows_affected,
error_message);
EXPECT_EQ(2, result[0].second.size());
EXPECT_EQ('9', result[0].second[0]);
EXPECT_EQ('7', result[0].second[1]);
// free the database just created
txn = txn_manager.BeginTransaction();
catalog::Catalog::GetInstance()->DropDatabaseWithName(DEFAULT_DB_NAME, txn);
txn_manager.CommitTransaction(txn);
}
} // namespace test
} // namespace peloton
| 35.780303
| 80
| 0.688545
|
phisiart
|
f7fc3344cc6a11d68e99912d77da7c59118f4d1a
| 1,060
|
cc
|
C++
|
02_ArrayPointer/PointerFunctions.cc
|
pataya235/UdemyCpp_Template-main
|
46583e2d252005eaba3a8a6f04b112454722e315
|
[
"MIT"
] | null | null | null |
02_ArrayPointer/PointerFunctions.cc
|
pataya235/UdemyCpp_Template-main
|
46583e2d252005eaba3a8a6f04b112454722e315
|
[
"MIT"
] | null | null | null |
02_ArrayPointer/PointerFunctions.cc
|
pataya235/UdemyCpp_Template-main
|
46583e2d252005eaba3a8a6f04b112454722e315
|
[
"MIT"
] | null | null | null |
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
//Call by Value (local copy)
void f(int *p_function)
{
cout << "(F): p_function = " << p_function << endl;
cout << "(F): &p_function = " << &p_function << endl; //Other adress as p_number
}
//Call by Reference (ab Übergabe von Argumenten > 8 Byte sinnvoll)
void g(int *&p_function)
{
cout << "(G): p_function = " << p_function << endl;
cout << "(G): &p_function = " << &p_function << endl; //Same adress as p_number
}
void f1(int number) //CallByValue
{
number++;
}
void f2(int &number) //CallByReference
{
number++;
}
int f3(int number) //CallByValue
{
number++;
return number;
}
int main()
{
int *p_number = new int{4};
cout << "(MAIN): p_number = " << p_number << endl;
cout << "(MAIN): &p_number = " << &p_number << endl;
f(p_number);
g(p_number);
int num = 0;
cout << num << endl;
f1(num);
cout << num << endl;
f2(num);
cout << num << endl;
num = f3(num);
cout << num << endl;
return 0;
}
| 19.272727
| 84
| 0.566038
|
pataya235
|
f7fd68aa525880face4a8f077500d30963e1fc46
| 456
|
cpp
|
C++
|
ViAn/GUI/DrawingItems/lineitem.cpp
|
NFCSKL/NFC-ViAn
|
ce04b78b4c9695374d71198f57d4236a5cad1525
|
[
"MIT"
] | 1
|
2019-12-08T03:53:03.000Z
|
2019-12-08T03:53:03.000Z
|
ViAn/GUI/DrawingItems/lineitem.cpp
|
NFCSKL/NFC-ViAn
|
ce04b78b4c9695374d71198f57d4236a5cad1525
|
[
"MIT"
] | 182
|
2018-02-08T11:03:26.000Z
|
2019-06-27T15:27:47.000Z
|
ViAn/GUI/DrawingItems/lineitem.cpp
|
NFCSKL/NFC-ViAn
|
ce04b78b4c9695374d71198f57d4236a5cad1525
|
[
"MIT"
] | null | null | null |
#include "lineitem.h"
LineItem::LineItem(Line* line) : ShapeItem(LINE_ITEM) {
m_line = line;
setFlags(flags() | Qt::ItemIsDragEnabled);
setText(0, line->get_name());
const QIcon line_icon(":/Icons/line.png");
setIcon(0, line_icon);
map = QPixmap(16,16);
update_shape_color();
update_show_icon(m_line->get_show());
}
LineItem::~LineItem() {}
void LineItem::remove() {}
Line* LineItem::get_shape() {
return m_line;
}
| 20.727273
| 55
| 0.651316
|
NFCSKL
|
7904824af205e1bfc436f0b933814d959fcbde9e
| 110
|
cpp
|
C++
|
AnimationProgramming/AnimationProgramming/AnimationProgramming.cpp
|
maxbrundev/OpenGL-Skeletal-Animation
|
4a0981dc222d4195663b180eaa5a4288aab7477c
|
[
"MIT"
] | null | null | null |
AnimationProgramming/AnimationProgramming/AnimationProgramming.cpp
|
maxbrundev/OpenGL-Skeletal-Animation
|
4a0981dc222d4195663b180eaa5a4288aab7477c
|
[
"MIT"
] | null | null | null |
AnimationProgramming/AnimationProgramming/AnimationProgramming.cpp
|
maxbrundev/OpenGL-Skeletal-Animation
|
4a0981dc222d4195663b180eaa5a4288aab7477c
|
[
"MIT"
] | null | null | null |
#include "CSimulation.h"
int main()
{
CSimulation simulation;
Run(&simulation, 1400, 800);
return 0;
}
| 12.222222
| 29
| 0.672727
|
maxbrundev
|
79088f2cc4556cb5994df5d525a416b19d17a8ca
| 68
|
cpp
|
C++
|
accumulate.cpp
|
Abodi-Massarweh/itertools-cfar-a
|
464b54f7c18c3687a7f729b2f1811901edcdaf55
|
[
"MIT"
] | null | null | null |
accumulate.cpp
|
Abodi-Massarweh/itertools-cfar-a
|
464b54f7c18c3687a7f729b2f1811901edcdaf55
|
[
"MIT"
] | null | null | null |
accumulate.cpp
|
Abodi-Massarweh/itertools-cfar-a
|
464b54f7c18c3687a7f729b2f1811901edcdaf55
|
[
"MIT"
] | null | null | null |
//
// Created by abodi on 13/06/2020.
//
#include "accumulate.hpp"
| 11.333333
| 34
| 0.647059
|
Abodi-Massarweh
|
790e9571bb0395b770d873e2c3afff6fc57787f1
| 917
|
hpp
|
C++
|
lab/tmp_test.hpp
|
sabel83/metaparse_tutorial
|
819fddf6bf06736861adbeabeb30967f56b7e8d0
|
[
"BSL-1.0"
] | 24
|
2015-07-14T01:56:03.000Z
|
2021-09-16T07:48:46.000Z
|
lab/tmp_test.hpp
|
sabel83/metaparse_tutorial
|
819fddf6bf06736861adbeabeb30967f56b7e8d0
|
[
"BSL-1.0"
] | 1
|
2017-10-01T12:31:25.000Z
|
2017-10-04T12:16:47.000Z
|
lab/tmp_test.hpp
|
sabel83/metaparse_tutorial
|
819fddf6bf06736861adbeabeb30967f56b7e8d0
|
[
"BSL-1.0"
] | 2
|
2017-08-22T20:31:11.000Z
|
2019-02-23T07:32:29.000Z
|
#ifndef TMP_TEST_HPP
#define TMP_TEST_HPP
// Copyright Abel Sinkovics (abel@sinkovics.hu) 2013.
// 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)
#include <boost/type_traits/is_same.hpp>
#include <iostream>
#ifdef REMOVE_BRACKET
#error REMOVE_BRACKET already defined
#endif
#define REMOVE_BRACKET(...) __VA_ARGS__
#ifdef TEST_SAME
#error TEST_SAME already defined
#endif
#define TEST_SAME(A, B) \
(test_same<REMOVE_BRACKET A, REMOVE_BRACKET B>(#A, #B, __FILE__, __LINE__))
template <class A, class B>
bool test_same(
const char* a_,
const char* b_,
const char* fn_,
unsigned int line_
)
{
const bool ok = boost::is_same<A, B>::type::value;
if (!ok)
{
std::cout
<< fn_ << ":" << line_ << " ERROR: " << a_ << " != " << b_ << std::endl;
}
return ok;
}
#endif
| 21.325581
| 78
| 0.672846
|
sabel83
|
7910a61296b73c3d4877c1667ee4463a409d4363
| 642
|
hpp
|
C++
|
include/system/ActionCreator.hpp
|
thebartekbanach/simple-aqua-controller
|
338331072155b9f98fb07b6a1e31e6d3c1f650fa
|
[
"MIT"
] | 1
|
2019-11-18T13:22:57.000Z
|
2019-11-18T13:22:57.000Z
|
include/system/ActionCreator.hpp
|
thebartekbanach/simple-aqua-controller
|
338331072155b9f98fb07b6a1e31e6d3c1f650fa
|
[
"MIT"
] | null | null | null |
include/system/ActionCreator.hpp
|
thebartekbanach/simple-aqua-controller
|
338331072155b9f98fb07b6a1e31e6d3c1f650fa
|
[
"MIT"
] | null | null | null |
#pragma once
#include <RtcDS1302.h>
#include <LiquidCrystal_PCF8574.h>
#include "../control/joystick/JoystickActions.hpp"
class ActionCreator {
public:
virtual ~ActionCreator() {};
virtual void setup(LiquidCrystal_PCF8574* lcd) = 0;
virtual ActionCreator* update(const RtcDateTime &time, const JoystickActions &action) = 0;
};
class CommonActionCreator: public ActionCreator {
protected:
LiquidCrystal_PCF8574* lcd;
virtual void setup() {}
public:
virtual ~CommonActionCreator() {};
virtual void setup(LiquidCrystal_PCF8574* lcd) { this->lcd = lcd; setup(); }
};
| 24.692308
| 98
| 0.674455
|
thebartekbanach
|
79175dc9d7605437a47bddccdbd0c9609900bdba
| 1,991
|
hpp
|
C++
|
include/ui/List.hpp
|
charanyaarvind/StratifyAPI
|
adfd1bc8354489378d53c6acd77ebedad5790b4f
|
[
"BSD-3-Clause"
] | null | null | null |
include/ui/List.hpp
|
charanyaarvind/StratifyAPI
|
adfd1bc8354489378d53c6acd77ebedad5790b4f
|
[
"BSD-3-Clause"
] | null | null | null |
include/ui/List.hpp
|
charanyaarvind/StratifyAPI
|
adfd1bc8354489378d53c6acd77ebedad5790b4f
|
[
"BSD-3-Clause"
] | null | null | null |
/* Copyright 2014-2016 Tyler Gilbert, Inc; All Rights Reserved
*
*/
#ifndef UI_LIST_HPP_
#define UI_LIST_HPP_
#include "../draw/Animation.hpp"
#include "../chrono/Timer.hpp"
#include "LinkedElement.hpp"
#include "ListAttr.hpp"
namespace ui {
/*! \brief List Class
* \ingroup list
* \details The List class makes a list of
* elements that are drawn in a vertical list. This
* is the primary Element used in menus.
*/
class List : public LinkedElement, public ListAttr {
public:
List(LinkedElement * parent = 0);
/*! \details Return a points to item \a i in the list */
virtual LinkedElement & at(list_attr_size_t i) = 0;
/*! \details Return a pointer to the currently selected item */
inline LinkedElement & current(){ return at(selected()); }
virtual Element * handle_event(const Event & event, const draw::DrawingAttr & attr);
virtual void draw_to_scale(const draw::DrawingScaledAttr & attr);
void draw_item_to_scale(const draw::DrawingScaledAttr & attr, sg_size_t x_offset, list_attr_size_t item);
protected:
void init(void);
void handle_down_button_actuation(const ui::Event & event, const draw::DrawingAttr & attr);
void handle_up_button_actuation(const ui::Event & event, const draw::DrawingAttr & attr);
void handle_select_button_actuation(const ui::Event & event, const draw::DrawingAttr & attr);
void animate_scroll(i8 dir, const draw::DrawingAttr & attr);
draw::Animation m_scroll_animation;
list_attr_size_t m_draw_animation_item;
list_attr_size_t m_draw_animation_offset;
i8 m_select_top_bottom;
chrono::Timer m_scroll_timer;
private:
};
//list of items of the same type
template<typename type, int n_items> class ListTemplate : public List {
public:
ListTemplate(LinkedElement * parent = 0) : List(parent){}
Element * at(list_attr_size_t i){ return m_items + i; }
list_attr_size_t size() const { return n_items; }
type * at_item(u32 i){ return m_items + i; }
private:
type m_items[n_items];
};
}
#endif /* UI_LIST_HPP_ */
| 28.042254
| 106
| 0.741838
|
charanyaarvind
|
792572a03a875982d5a124af4aa5b18aed4043bb
| 5,716
|
cpp
|
C++
|
UI-Qt/QXMenuBar.cpp
|
frinkr/FontViewer
|
69b5706e557ecd33515c5c8d6ba8fc1d6f06e0c0
|
[
"MIT"
] | 2
|
2019-05-08T06:31:34.000Z
|
2020-08-30T00:35:09.000Z
|
UI-Qt/QXMenuBar.cpp
|
frinkr/FontViewer
|
69b5706e557ecd33515c5c8d6ba8fc1d6f06e0c0
|
[
"MIT"
] | 1
|
2018-05-07T09:29:02.000Z
|
2018-05-07T09:29:02.000Z
|
UI-Qt/QXMenuBar.cpp
|
frinkr/FontViewer
|
69b5706e557ecd33515c5c8d6ba8fc1d6f06e0c0
|
[
"MIT"
] | 2
|
2018-09-10T07:16:28.000Z
|
2022-01-07T06:41:01.000Z
|
#include "QXMenuBar.h"
#include "QXApplication.h"
#include "QXDocumentWindowManager.h"
QXMenuBar::QXMenuBar(QWidget * parent)
: QMenuBar(parent)
{
menuFile = addMenu(tr("&File")); {
actionOpen = menuFile->addAction(tr("&Open"), []() {
QXDocumentWindowManager::instance()->showFontListWindow();
}, QKeySequence(QKeySequence::Open));
actionOpenFromFile = menuFile->addAction(tr("Open from &File"), []() {
QXDocumentWindowManager::instance()->doNativeOpenFileDialog(QXDocumentWindowManager::FileTypeFilter::Font);
}, QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_O));
actionOpenFromPDF = menuFile->addAction(tr("Open Embedded Font from PDF"), [] {
QXDocumentWindowManager::instance()->doNativeOpenFileDialog(QXDocumentWindowManager::FileTypeFilter::PDF);
});
actionClose = menuFile->addAction(tr("&Close"), [parent]() {
if (parent) {
parent->close();
}
else {
if (auto window = qApp->activeWindow())
window->close();
}
}, QKeySequence(QKeySequence::Close));
actionCloseAll = menuFile->addAction(tr("Close &All"), [parent]() {
QXDocumentWindowManager::instance()->closeAllDocuments();
});
menuFile->addSeparator();
menuRecent = menuFile->addMenu(tr("Open &Recent"));
connect(menuRecent, &QMenu::aboutToShow, [this]() {
QXDocumentWindowManager::instance()->reloadRecentMenu(menuRecent);
foreach (QAction * action, menuRecent->actions()) {
if (!action->isSeparator() && !action->menu()) {
connect(action, &QAction::triggered, [action]() {
QVariant data = action->data();
if (data.canConvert<QXFontURI>()) {
QXFontURI uri = data.value<QXFontURI>();
QXDocumentWindowManager::instance()->openFontURI(uri);
}
});
}
}
});
actionPreferences = menuFile->addAction(tr("&Preferences"), []() {
qApp->preferences();
}, QKeySequence(QKeySequence::Preferences));
actionQuit = menuFile->addAction(tr("&Quit"), []() {
QXDocumentWindowManager::instance()->closeAllDocumentsAndQuit();
}, QKeySequence(QKeySequence::Quit));
actionQuit->setMenuRole(QAction::QuitRole);
}
menuEdit = addMenu(tr("&Edit")); {
actionCopy = menuEdit->addAction(tr("&Copy"));
actionCopy->setShortcut(QKeySequence::Copy);
actionSearch = menuEdit->addAction(tr("&Find"));
actionSearch->setShortcut(QKeySequence::Find);
}
menuView = addMenu(tr("&View")); {
actionToolBar = menuView->addAction(tr("&Tool Bar"));
actionToolBar->setCheckable(true);
actionToolBar->setChecked(true);
actionStatusBar = menuView->addAction(tr("&Status Bar"));
actionStatusBar->setCheckable(true);
actionStatusBar->setChecked(true);
menuView->addSeparator();
actionCharacterCode = menuView->addAction(tr("&Character Code"));
actionCharacterCode->setCheckable(true);
actionGlyphName = menuView->addAction(tr("&Glyph Name"));
actionGlyphName->setCheckable(true);
actionGlyphID = menuView->addAction(tr("Glyph &ID"));
actionGlyphID->setCheckable(true);
menuView->addSeparator();
#ifndef Q_OS_MAC
actionFullScreen = menuView->addAction(tr("&Full Screen"));
actionFullScreen->setShortcut(QKeySequence::FullScreen);
actionFullScreen->setCheckable(true);
#else
actionFullScreen = nullptr;
#endif
actionShowAllGlyphs = menuView->addAction(tr("&Show All Glyphs"));
actionShowAllGlyphs->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_G));
actionShowAllGlyphs->setCheckable(true);
QActionGroup * group = new QActionGroup(this);
group->addAction(actionCharacterCode);
group->addAction(actionGlyphName);
group->addAction(actionGlyphID);
group->setExclusive(true);
actionGlyphName->setChecked(true);
connect(group, &QActionGroup::triggered, [this](QAction * action) {
QXGlyphLabel label = QXGlyphLabel::GlyphName;
if (action == actionCharacterCode)
label = QXGlyphLabel::CharCode;
else if (action == actionGlyphName)
label = QXGlyphLabel::GlyphName;
else if (action == actionGlyphID)
label = QXGlyphLabel::GlyphID;
emit glyphLabelActionTriggered(action, label);
});
}
menuWindow = addMenu(tr("&Window")); {
actionMinimize = menuWindow->addAction(tr("&Minimize"), [parent]() {
if (parent)
parent->showMinimized();
}, QKeySequence(Qt::CTRL | Qt::Key_M));
actionMaximize = menuWindow->addAction(tr("&Zoom"), [parent]() {
if (parent)
parent->showMaximized();
});
menuWindow->addSeparator();
connect(menuWindow, &QMenu::aboutToShow, [this]() {
QXDocumentWindowManager::instance()->aboutToShowWindowMenu(menuWindow);
});
}
menuHelp = addMenu(tr("&Help")); {
actionAbout = menuHelp->addAction(tr("About"), qApp, &QXApplication::about);
actionAbout->setMenuRole(QAction::AboutRole);
actionAboutFonts = menuHelp->addAction(tr("About Font Database"), qApp, &QXApplication::aboutFonts);
actionAboutFonts->setMenuRole(QAction::AboutQtRole);
}
}
| 37.854305
| 119
| 0.595346
|
frinkr
|
7928cfd3ae9e6ddb440f6599fd9b7e1c41689000
| 6,985
|
cpp
|
C++
|
cppbind/header.cpp
|
findstr/zproto
|
be310b698b993a9018e64c56aabb000da836df97
|
[
"MIT"
] | 8
|
2017-06-02T12:12:10.000Z
|
2020-09-19T11:25:51.000Z
|
cppbind/header.cpp
|
findstr/zproto
|
be310b698b993a9018e64c56aabb000da836df97
|
[
"MIT"
] | null | null | null |
cppbind/header.cpp
|
findstr/zproto
|
be310b698b993a9018e64c56aabb000da836df97
|
[
"MIT"
] | 6
|
2016-01-09T14:23:13.000Z
|
2020-11-17T07:23:55.000Z
|
#include <assert.h>
#include <vector>
#include <string>
#include <sstream>
#include <unordered_set>
#include "zproto.hpp"
#include "header.h"
static std::unordered_set<struct zproto_struct *> protocol;
static std::unordered_set<struct zproto_struct *> defined;
struct prototype_args {
int level;
std::vector<std::string> type;
std::vector<std::string> fields;
std::vector<std::string> encode;
std::vector<std::string> iters;
};
const char *funcproto = "\
%sprotected:\n\
%s\
%svirtual int _encode_field(struct zproto_args *args) const;\n\
%svirtual int _decode_field(struct zproto_args *args);\n\
%s\
%spublic:\n\
%svirtual void _reset();\n\
%s\
";
static std::string
tab(int level)
{
std::string str;
str.reserve(level);
for (int i = 0; i < level; i++)
str += "\t";
return str;
}
static int prototype_cb(struct zproto_args *args);
static void
formatst(struct zproto *z, struct zproto_struct *st, struct prototype_args &newargs)
{
char buff[2048];
std::string t1 = tab(newargs.level);
std::string t2 = tab(newargs.level - 1);
std::string iterwrapper;
std::string iterdefine;
int count;
struct zproto_struct *const*start, *const*end;
start = zproto_child(z, st, &count);
end = start + count;
while (start < end) {
struct zproto_struct *child = *start;
assert(protocol.count(child) == 0);
assert(defined.count(child) == 0);
struct prototype_args nnewargs;
nnewargs.level = newargs.level + 1;
formatst(z, child, nnewargs);
newargs.type.insert(newargs.type.end(),
nnewargs.fields.begin(), nnewargs.fields.end());
++start;
}
zproto_travel(st, prototype_cb, &newargs);
//subtype
newargs.fields.insert(
newargs.fields.begin(),
newargs.type.begin(),
newargs.type.end()
);
//open
const char *herit;
if (protocol.count(st))
herit = ":public wirepimpl";
else
herit = ":public wire ";
newargs.fields.insert(
newargs.fields.begin(),
t2 + "struct " + zproto_name(st) + herit + "{\n");
if (newargs.iters.size()) {
std::stringstream ss;
ss << t1 << "union iterator_wrapper {\n";
ss << t1 << t1 << "iterator_wrapper(){};\n";
for (const auto &iter:newargs.iters)
ss << t1 << t1 << iter;
ss << t1 << "};\n";
iterwrapper = ss.str();
iterdefine = t1 + "mutable union iterator_wrapper _mapiterator;\n";
}
//member function
char wirep_query[2048];
if (protocol.count(st)) {
snprintf(wirep_query, 2048,
"%svirtual int _tag() const;\n"
"%svirtual const char *_name() const;\n"
"%svirtual zproto_struct *_query() const;\n"
"%sstatic void _load(wiretree &t);\n"
"%sprivate:\n"
"%sstatic zproto_struct *_st;\n",
t1.c_str(),
t1.c_str(),
t1.c_str(),
t1.c_str(),
t2.c_str(),
t1.c_str());
} else {
wirep_query[0] = 0;
}
snprintf(buff, 2048, funcproto,
t2.c_str(),
iterwrapper.c_str(),
t1.c_str(),
t1.c_str(),
iterdefine.c_str(),
t2.c_str(),
t1.c_str(),
wirep_query);
newargs.fields.push_back(buff);
//close
newargs.fields.insert(
newargs.fields.end(),
t2 + "};\n"
);
defined.insert(st);
return ;
}
struct find_field_ud {
int tag;
std::string type;
};
static std::string
typestr(int type, struct zproto_struct *st)
{
static struct {
int type;
const char *name;
} types[] = {
{ZPROTO_BLOB, "std::string"},
{ZPROTO_STRING, "std::string"},
{ZPROTO_BOOLEAN, "bool"},
{ZPROTO_FLOAT, "float"},
{ZPROTO_BYTE, "int8_t"},
{ZPROTO_SHORT, "int16_t"},
{ZPROTO_INTEGER, "int32_t"},
{ZPROTO_LONG, "int64_t"},
{ZPROTO_UBYTE, "uint8_t"},
{ZPROTO_USHORT, "uint16_t"},
{ZPROTO_UINTEGER, "uint32_t"},
{ZPROTO_ULONG, "uint64_t"},
};
for (size_t i = 0; i < sizeof(types)/ sizeof(types[0]); i++) {
if (types[i].type == type)
return types[i].name;
}
assert(type == ZPROTO_STRUCT);
return std::string("struct ") + zproto_name(st);
}
static int
find_field_type(struct zproto_args *args)
{
struct find_field_ud *ud = (struct find_field_ud *)args->ud;
if (ud->tag == args->tag)
ud->type = typestr(args->type, NULL);
return 0;
}
static int
prototype_cb(struct zproto_args *args)
{
struct prototype_args *ud = (struct prototype_args *)args->ud;
char buff[2048];
std::string type;
std::string iter;
std::string subtype;
std::string defval;
if (args->maptag) {
std::string str;
assert(args->idx >= 0);
struct find_field_ud fud;
fud.tag = args->maptag;
zproto_travel(args->sttype, find_field_type, &fud);
assert(fud.type != "");
str = "std::unordered_map<" + fud.type + ", %s> %s%s;\n";
iter = "std::unordered_map<" + fud.type + ", %s>::const_iterator %s;\n";
type = tab(ud->level) + str;
} else if(args->idx >= 0) {
type = tab(ud->level) + "std::vector<%s> %s%s;\n";
} else {
type = tab(ud->level) + "%s %s%s;\n";
switch (args->type) {
case ZPROTO_BOOLEAN:
defval = " = false";
break;
case ZPROTO_BYTE:
case ZPROTO_SHORT:
case ZPROTO_LONG:
case ZPROTO_INTEGER:
case ZPROTO_UBYTE:
case ZPROTO_USHORT:
case ZPROTO_ULONG:
case ZPROTO_UINTEGER:
defval = " = 0";
break;
case ZPROTO_FLOAT:
defval = " = 0.0f";
break;
}
}
subtype = typestr(args->type, args->sttype);
snprintf(buff, 2048, type.c_str(), subtype.c_str(), args->name, defval.c_str());
ud->fields.push_back(buff);
if (iter.size()) {
snprintf(buff, 2048, iter.c_str(), subtype.c_str(), args->name);
ud->iters.push_back(buff);
}
return 0;
}
static void
dump_vecstring(FILE *fp, const std::vector<std::string> &tbl)
{
for (const auto &str:tbl)
fprintf(fp, "%s", str.c_str());
return;
}
static void
dumpst(FILE *fp, struct zproto *z)
{
int count;
struct zproto_struct *const* start, *const* end;
start = zproto_child(z, NULL, &count);
end = start + count;
while (start < end) {
struct prototype_args args;
struct zproto_struct *st = *start;
args.level = 1;
formatst(z, st, args);
dump_vecstring(fp, args.fields);
++start;
}
}
static void
wiretree(FILE *fp)
{
fprintf(fp, "%s",
"class serializer:public wiretree {\n"
"\tserializer();\n"
"public:\n"
"\tstatic serializer &instance();\n"
"};\n");
}
const char *wirep =
"struct wirepimpl:public wirep {\n"
"protected:\n"
" virtual wiretree &_wiretree() const;\n"
"};\n\n";
void
header(const char *name, std::vector<const char *> &space, struct zproto *z)
{
FILE *fp;
int count;
struct zproto_struct *const* start, *const* end;
std::string path = name;
path += ".hpp";
start = zproto_child(z, NULL, &count);
end = start + count;
while (start < end) {
struct zproto_struct *st = *start;
protocol.insert(st);
++start;
}
fp = fopen(path.c_str(), "wb+");
fprintf(fp, "#ifndef __%s_h\n#define __%s_h\n", name, name);
fprintf(fp, "#include \"zprotowire.h\"\n");
for (const auto p:space)
fprintf(fp, "namespace %s {\n", p);
fprintf(fp, "%s", "\nusing namespace zprotobuf;\n\n");
fprintf(fp, "%s", wirep);
dumpst(fp, z);
wiretree(fp);
fprintf(fp, "\n");
for (size_t i = 0; i < space.size(); i++)
fprintf(fp, "}");
fprintf(fp, "\n#endif\n");
fclose(fp);
}
| 23.439597
| 84
| 0.646528
|
findstr
|
79309ab3a8919e190dd911fefe0cf0ad5a19b2f1
| 552
|
hpp
|
C++
|
include/warbler/ast/expression/prefix.hpp
|
ikehirzel/c-spiel
|
44a465ae40b04145046979d30c14ec8266dc463f
|
[
"MIT"
] | null | null | null |
include/warbler/ast/expression/prefix.hpp
|
ikehirzel/c-spiel
|
44a465ae40b04145046979d30c14ec8266dc463f
|
[
"MIT"
] | null | null | null |
include/warbler/ast/expression/prefix.hpp
|
ikehirzel/c-spiel
|
44a465ae40b04145046979d30c14ec8266dc463f
|
[
"MIT"
] | null | null | null |
#ifndef WARBLER_AST_EXPRESSION_PREFIX_HPP
#define WARBLER_AST_EXPRESSION_PREFIX_HPP
// local headers
#include <warbler/token.hpp>
#include <warbler/result.hpp>
namespace warbler
{
enum PrefixType
{
PREFIX_INCREMENT,
PREFIX_DECREMENT,
PREFIX_REFERENCE,
PREFIX_DEREFERENCE
};
class Prefix
{
private:
PrefixType _type;
public:
Prefix(PrefixType type);
static Result<Prefix> parse(TokenIterator& iter);
static Result<std::vector<Prefix>> parse_list(TokenIterator& iter);
void print_tree(u32 depth = 0) const;
};
}
#endif
| 15.333333
| 69
| 0.755435
|
ikehirzel
|
a6adbd50af976d369de4071ac5f3116ceac6eb5d
| 1,123
|
cpp
|
C++
|
OpenGLSolution/BRDF/Source/Graphics/Core/PixarAttenuation.cpp
|
AlfonsoLRz/BRDFMeasurements
|
1c83db1dcd0e42d75422dec31486bfbf70df9112
|
[
"MIT"
] | 14
|
2021-08-23T04:59:21.000Z
|
2022-03-25T10:34:55.000Z
|
OpenGLSolution/BRDF/Source/Graphics/Core/PixarAttenuation.cpp
|
AlfonsoLRz/BRDFMeasurements
|
1c83db1dcd0e42d75422dec31486bfbf70df9112
|
[
"MIT"
] | null | null | null |
OpenGLSolution/BRDF/Source/Graphics/Core/PixarAttenuation.cpp
|
AlfonsoLRz/BRDFMeasurements
|
1c83db1dcd0e42d75422dec31486bfbf70df9112
|
[
"MIT"
] | 6
|
2021-08-05T17:10:10.000Z
|
2022-03-31T17:26:47.000Z
|
#include "stdafx.h"
#include "PixarAttenuation.h"
void PixarAttenuation::applyAttenuation(Light* light, RenderingShader* shader)
{
auto coefficients = light->getKCoefficients();
shader->setSubroutineUniform(GL_FRAGMENT_SHADER, "attenuationUniform", "pixarAttenuation");
shader->setUniform("fMax", light->getMaxAttFactor());
shader->setUniform("fC", light->getFactorC());
shader->setUniform("distC", light->getDistanceC());
shader->setUniform("exponentSE", light->getExponentSE());
shader->setUniform("k0", coefficients[0]);
shader->setUniform("k1", coefficients[1]);
}
void PixarAttenuation::applyAttenuation4ColouredPoints(Light* light, RenderingShader* shader)
{
auto coefficients = light->getKCoefficients();
shader->setSubroutineUniform(GL_VERTEX_SHADER, "attenuationUniform", "pixarAttenuation");
shader->setUniform("fMax", light->getMaxAttFactor());
shader->setUniform("fC", light->getFactorC());
shader->setUniform("distC", light->getDistanceC());
shader->setUniform("exponentSE", light->getExponentSE());
shader->setUniform("k0", coefficients[0]);
shader->setUniform("k1", coefficients[1]);
}
| 36.225806
| 93
| 0.756011
|
AlfonsoLRz
|
a6aec947e605ca7a3ef20347bf11bec46a335d1b
| 2,536
|
cpp
|
C++
|
src/Engine/Utils/Ini/INIReader.cpp
|
avraal/Projector
|
bb234f03ccf34ed829a130c664b7adad400653f4
|
[
"Zlib"
] | null | null | null |
src/Engine/Utils/Ini/INIReader.cpp
|
avraal/Projector
|
bb234f03ccf34ed829a130c664b7adad400653f4
|
[
"Zlib"
] | null | null | null |
src/Engine/Utils/Ini/INIReader.cpp
|
avraal/Projector
|
bb234f03ccf34ed829a130c664b7adad400653f4
|
[
"Zlib"
] | null | null | null |
#include <algorithm>
#include "INIReader.hpp"
#include "ini.hpp"
INIReader::INIReader(const std::string &fileName)
{
_error = ini_parse(fileName.c_str(), ValueHandler, this);
}
int INIReader::ParseError() const
{
return _error;
}
std::string INIReader::Get(const std::string §ion, const std::string &name, const std::string &defaultValue) const
{
std::string key = MakeKey(section, name);
return _values.count(key) ? _values.find(key)->second : defaultValue;
}
std::string
INIReader::GetString(const std::string §ion, const std::string &name, const std::string &defaultValue) const
{
const std::string str = Get(section, name, "");
return str.empty() ? defaultValue : str;
}
long INIReader::GetInteger(const std::string §ion, const std::string &name, long defaultValue) const
{
std::string valstr = Get(section, name, "");
const char *value = valstr.c_str();
char *end;
long n = std::strtol(value, &end, 0);
return end > value ? n : defaultValue;
}
double INIReader::GetReal(const std::string §ion, const std::string &name, double defaultValue) const
{
std::string valstr = Get(section, name, "");
const char *value = valstr.c_str();
char *end;
long n = std::strtod(value, &end);
return end > value ? n : defaultValue;
}
bool INIReader::GetBoolean(const std::string §ion, const std::string &name, bool defaultValue) const
{
std::string valstr = Get(section, name, "");
std::transform(valstr.begin(), valstr.end(), valstr.begin(), ::tolower);
if (valstr == "true" || valstr == "yes" || valstr == "on" || valstr == "1")
{
return true;
} else if (valstr == "false" || valstr == "no" || valstr == "off" || valstr == "0")
{
return false;
} else
{
return defaultValue;
}
}
bool INIReader::HasValue(const std::string §ion, const std::string &name) const
{
std::string key = MakeKey(section, name);
return _values.count(key);
}
std::string INIReader::MakeKey(const std::string §ion, const std::string &name)
{
std::string key = section + "=" + name;
std::transform(key.begin(), key.end(), key.begin(),::tolower);
return key;
}
int INIReader::ValueHandler(void *user, const char *section, const char *name, const char *value)
{
INIReader *reader = static_cast<INIReader*>(user);
std::string key = MakeKey(section, name);
if (reader->_values[key].size() > 0)
{
reader->_values[key] += "\n";
}
reader->_values[key] += value;
return 1;
}
| 33.368421
| 118
| 0.645505
|
avraal
|
a6b7528d1d624725d1b3d1789a538101c7498502
| 809
|
hpp
|
C++
|
src/Game.hpp
|
Ghabriel/ecs-arkanoid
|
af005bc89ce535616c7a006c7c76b2a414c90901
|
[
"Apache-2.0"
] | 1
|
2019-07-12T04:54:44.000Z
|
2019-07-12T04:54:44.000Z
|
src/Game.hpp
|
Ghabriel/ecs-arkanoid
|
af005bc89ce535616c7a006c7c76b2a414c90901
|
[
"Apache-2.0"
] | null | null | null |
src/Game.hpp
|
Ghabriel/ecs-arkanoid
|
af005bc89ce535616c7a006c7c76b2a414c90901
|
[
"Apache-2.0"
] | null | null | null |
#pragma once
#include <memory>
#include <SFML/Graphics.hpp>
#include "engine-glue/ecs.hpp"
#include "engine/state-management/StateMachine.hpp"
#include "states/RunningState.hpp"
#include "states/WaitingState.hpp"
class Game {
public:
void init(float width, float height) {
stateMachine.registerState("waiting", std::make_unique<WaitingState>(world, stateMachine));
stateMachine.registerState("running", std::make_unique<RunningState>(world, stateMachine));
stateMachine.pushState("waiting");
}
void update(const sf::Time& elapsedTime) {
stateMachine.getState().update(elapsedTime);
}
void render(sf::RenderWindow& window) {
stateMachine.getState().render(window);
}
private:
ecs::World world;
state::StateMachine stateMachine;
};
| 26.966667
| 99
| 0.703337
|
Ghabriel
|
a6b9bf47555c24aaf2eb266a7d9b26cf60c64e68
| 1,536
|
cpp
|
C++
|
example/simple_benchmark.cpp
|
RoadAR/benchmark
|
00f9bd742953b12128ca2c565fb41aca5cd1f97f
|
[
"Apache-2.0"
] | 5
|
2022-02-12T13:38:42.000Z
|
2022-02-28T16:54:27.000Z
|
example/simple_benchmark.cpp
|
RoadAR/benchmark
|
00f9bd742953b12128ca2c565fb41aca5cd1f97f
|
[
"Apache-2.0"
] | null | null | null |
example/simple_benchmark.cpp
|
RoadAR/benchmark
|
00f9bd742953b12128ca2c565fb41aca5cd1f97f
|
[
"Apache-2.0"
] | null | null | null |
//
// Created by Alexander Graschenkov on 11.02.2022.
//
#include <iostream>
#include <chrono>
#include <thread>
#include <roadar/benchmark.hpp>
//using namespace roadar;
inline void sleep_ms(long long val) {
std::this_thread::sleep_for(std::chrono::milliseconds(val));
}
void algorithm1() {
R_BENCHMARK_SCOPED_L("algo_1");
for (int i = 0; i < 10; i++) {
R_BENCHMARK_SCOPED("step_1_1");
sleep_ms(10);
r_bench.reset("step_1_2");
sleep_ms(5);
}
for (int i = 0; i < 10; i++) {
R_BENCHMARK_SCOPED_L("scoped");
R_BENCHMARK_START("step_1_2");
R_BENCHMARK("part_1") {
sleep_ms(15);
}
R_BENCHMARK("part_2") {
sleep_ms(15);
}
R_BENCHMARK_STOP("step_1_2");
}
// this will be not captured by children `algo_1`
// so you will see in missed percent
sleep_ms(25);
}
void algorithm2() {
R_BENCHMARK_START("algo_2");
for (int i = 0; i < 50; i++) {
R_BENCHMARK_START("step_2_1");
sleep_ms((long long)i);
R_BENCHMARK_STOP("step_2_1");
}
R_BENCHMARK_STOP("algo_2");
}
int main(int argc, const char * argv[]) {
std::cout << "Program started" << std::endl;
std::thread t1(algorithm1);
std::thread t2(algorithm1);
std::thread t3(algorithm1);
std::thread t4(algorithm1);
std::thread t5(algorithm2);
t1.join();
t2.join();
t3.join();
t4.join();
t5.join();
R_BENCHMARK_START("test not finished");
sleep_ms(10);
std::cout << "Done" << std::endl;
std::cout << R_BENCHMARK_LOG(roadar::Field::lastAverage) << std::endl;
return 0;
}
| 21.942857
| 72
| 0.636719
|
RoadAR
|
a6c6f0b107e7834958ced169a9c43456fe628137
| 447
|
cpp
|
C++
|
04_cpp_fundamentals_2/code/01_file_io.cpp
|
estimand/intro-to-cpp
|
adab5eddc9ee66e4da940a4cb80249569749d53c
|
[
"CC-BY-4.0"
] | null | null | null |
04_cpp_fundamentals_2/code/01_file_io.cpp
|
estimand/intro-to-cpp
|
adab5eddc9ee66e4da940a4cb80249569749d53c
|
[
"CC-BY-4.0"
] | null | null | null |
04_cpp_fundamentals_2/code/01_file_io.cpp
|
estimand/intro-to-cpp
|
adab5eddc9ee66e4da940a4cb80249569749d53c
|
[
"CC-BY-4.0"
] | 3
|
2017-12-13T10:07:06.000Z
|
2021-02-07T07:36:31.000Z
|
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
ifstream input("01_input.txt"); // Default mode: ios::in
if (!input) {
cerr << "Unable to open input file" << endl;
return 1;
}
ofstream output("01_output.txt"); // Default mode: ios::out | ios::trunc
int n;
while (input >> n)
{
output << n * n << endl;
}
input.close();
output.close();
return 0;
}
| 15.964286
| 76
| 0.541387
|
estimand
|
a6cda9e87e5522a59a5fb87d743c0f3515b3934b
| 3,821
|
cpp
|
C++
|
plugins/FCNPC-master/src/CPlayerManager.cpp
|
vmgeremias/sampserver
|
3117254be340c9f92211246986146626822a4db6
|
[
"BSD-3-Clause"
] | null | null | null |
plugins/FCNPC-master/src/CPlayerManager.cpp
|
vmgeremias/sampserver
|
3117254be340c9f92211246986146626822a4db6
|
[
"BSD-3-Clause"
] | null | null | null |
plugins/FCNPC-master/src/CPlayerManager.cpp
|
vmgeremias/sampserver
|
3117254be340c9f92211246986146626822a4db6
|
[
"BSD-3-Clause"
] | null | null | null |
/* =========================================
FCNPC - Fully Controllable NPC
----------------------
- File: PlayerManager.cpp
- Author(s): OrMisicL
=========================================*/
#include "Main.hpp"
extern CServer *pServer;
bool bCreated = false;
CPlayerManager::CPlayerManager()
{
for (int i = 0; i < MAX_PLAYERS; i++) {
m_pNpcArray[i] = NULL;
}
}
CPlayerManager::~CPlayerManager()
{
for (auto &pPlayer : m_pNpcArray) {
SAFE_DELETE(pPlayer);
}
}
WORD CPlayerManager::AddPlayer(char *szName)
{
// Make sure the name is valid
if (!pServer->IsValidNickName(szName)) {
logprintf("[FCNPC] Error: NPC '%s' not created. Name '%s' is invalid.", szName, szName);
return INVALID_PLAYER_ID;
}
// Check name for already connected NPCs
WORD wPlayerId = GetId(szName);
if (wPlayerId != INVALID_PLAYER_ID) {
return wPlayerId;
}
// Make sure the name is not exists
if (pServer->DoesNameExist(szName)) {
logprintf("[FCNPC] Error: NPC '%s' not created. Another player already connected with that name.", szName, szName);
return INVALID_PLAYER_ID;
}
// Create the player in SAMP server
wPlayerId = CFunctions::NewPlayer(szName);
if (wPlayerId == INVALID_PLAYER_ID) {
logprintf("[FCNPC] Error: NPC '%s' not created. The maxplayers limit in server.cfg has been reached.", szName);
return INVALID_PLAYER_ID;
}
// Create the player instance
m_pNpcArray[wPlayerId] = new CPlayerData(wPlayerId, szName);
// Try to setup the player
if (!SetupPlayer(wPlayerId)) {
SAFE_DELETE(m_pNpcArray[wPlayerId]);
CFunctions::DeletePlayer(wPlayerId);
logprintf("[FCNPC] Error: NPC '%s' not created. Name '%s' is invalid or the maxnpc limit in server.cfg has been reached.", szName, szName);
return INVALID_PLAYER_ID;
}
m_vNpcID.push_back(wPlayerId);
// Call the created callback
CCallbackManager::OnCreate(wPlayerId);
return wPlayerId;
}
bool CPlayerManager::DeletePlayer(WORD wPlayerId)
{
// If he's not connected then dont go any further
if (!m_pNpcArray[wPlayerId]) {
return false;
}
// Destroy the player
m_vNpcID.erase(std::remove(m_vNpcID.begin(), m_vNpcID.end(), wPlayerId), m_vNpcID.end());
m_pNpcArray[wPlayerId]->Destroy();
SAFE_DELETE(m_pNpcArray[wPlayerId]);
// Call the created callback
CCallbackManager::OnDestroy(wPlayerId);
return true;
}
bool CPlayerManager::ResetPlayer(WORD wPlayerId)
{
// If he's not connected then dont go any further
CPlayerData *pPlayerData = pServer->GetPlayerManager()->GetAt(wPlayerId);
if (!pPlayerData) {
return false;
}
CPlayer *pPlayer = pPlayerData->GetInterface();
if (!pPlayer) {
return false;
}
// Reset player data
pPlayer->bReadyToSpawn = false;
pPlayerData->SetSpawnedStatus(false);
return true;
}
void CPlayerManager::ResetAllPlayers()
{
for (auto &id : m_vNpcID) {
ResetPlayer(id);
}
}
void CPlayerManager::Process()
{
if (!pNetGame->pGameModePool) {
return;
}
// Process all the players
for (auto &id : m_vNpcID) {
m_pNpcArray[id]->Process();
}
}
bool CPlayerManager::IsNpcConnected(WORD wPlayerId)
{
return IsPlayerConnected(wPlayerId) && IsNPC(wPlayerId);
}
bool CPlayerManager::IsPlayerConnected(WORD wPlayerId)
{
if (wPlayerId >= MAX_PLAYERS) {
return false;
}
return pNetGame->pPlayerPool->bIsPlayerConnected[wPlayerId] != 0;
}
WORD CPlayerManager::GetId(char *szName)
{
for (auto &id : m_vNpcID) {
if (!strcmp(szName, pNetGame->pPlayerPool->szName[id])) {
return id;
}
}
return INVALID_PLAYER_ID;
}
CPlayerData *CPlayerManager::GetAt(WORD wPlayerId)
{
if (!IsNpcConnected(wPlayerId)) {
return NULL;
}
return m_pNpcArray[wPlayerId];
}
bool CPlayerManager::SetupPlayer(WORD wPlayerId)
{
// Setup the NPC
return m_pNpcArray[wPlayerId]->Setup();
}
bool CPlayerManager::IsNPC(WORD wPlayerId)
{
return !!m_pNpcArray[wPlayerId];
}
| 22.476471
| 141
| 0.695891
|
vmgeremias
|
a6d859b202e2158b4649c227de8bf56a845b5c13
| 2,781
|
cpp
|
C++
|
LeetCode/587. Erect the Fence.cpp
|
anubhawbhalotia/Competitive-Programming
|
32d7003abf9af4999b3dfa78fe1df9022ebbf50b
|
[
"MIT"
] | null | null | null |
LeetCode/587. Erect the Fence.cpp
|
anubhawbhalotia/Competitive-Programming
|
32d7003abf9af4999b3dfa78fe1df9022ebbf50b
|
[
"MIT"
] | null | null | null |
LeetCode/587. Erect the Fence.cpp
|
anubhawbhalotia/Competitive-Programming
|
32d7003abf9af4999b3dfa78fe1df9022ebbf50b
|
[
"MIT"
] | 1
|
2020-05-20T18:36:31.000Z
|
2020-05-20T18:36:31.000Z
|
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<ll> vl;
typedef pair<int,int> pi;
typedef pair<ll,ll> pl;
typedef set<int> si;
typedef set<ll> sl;
typedef multiset<int> msi;
typedef multiset<ll> msl;
#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define lb lower_bound
#define ub upper_bound
#define beg(x) x.begin()
#define en(x) x.end()
#define all(v) beg(v), en(v)
#define f(i,s,n) for(int i=s;i<n;i++)
#define fe(i,s,n) for(int i=s;i<=n;i++)
#define fr(i,s,n) for(int i=s;i>n;i--)
#define fre(i,s,n) for(int i=s;i>=n;i--)
const int MOD = 998244353;
template <typename T,typename U, typename V,typename W>
auto operator+=(const pair<T,U> & l, pair<V,W> & r)
-> pair<decltype(l.first+r.first),decltype(l.second+r.second)>
{
return {l.first+r.first,l.second+r.second};
}
template <typename T,typename U, typename V,typename W>
auto operator+(const pair<T,U> & l, pair<V,W> & r)
-> pair<decltype(l.first+r.first),decltype(l.second+r.second)>
{
return {l.first+r.first,l.second+r.second};
}
class Solution {
public:
unordered_set <int> s;
inline int orientation(vi p, vi q, vi r)
{
return ((q[0] - p[0]) * (r[1] - q[1])) - ((q[1] - p[1]) * (r[0] -
q[0]));
}
int findLeftmostPoint(vvi p)
{
int m = 0;
f(i, 0, p.size())
{
s.insert(i);
if(p[i][0] < p[m][0])
m = i;
}
return m;
}
inline int euclDist(vi p, vi q)
{
return ((p[1] - q[1]) * (p[1] - q[1])) + ((p[0] - q[0]) * (p[0] - q[0]));
}
vvi outerTrees(vvi& pts)
{
if(pts.size() <= 2)
return pts;
int p = findLeftmostPoint(pts);
int start = p;
vvi ans;
s.erase(p);
int q = *s.begin();
vi f;
f.resize(pts.size(), 0);
int x = 1;
do
{
ans.pb(pts[p]);
f[p]++;
f[q]++;
f(i, 0, pts.size())
{
if(f[i] == x)
continue;
f[i]++;
int orient = orientation(pts[p], pts[q], pts[i]);
if(orient < 0 || (orient == 0 && euclDist(pts[p], pts[i]) < euclDist(pts[p], pts[q])
&& s.find(i) != s.end()))
q = i;
}
p = q;
s.erase(p);
int flag = 0;
if(s.empty())
{
ans.pb(pts[p]);
return ans;
}
q = *s.begin();
x++;
}while(p != start);
return ans;
}
};
| 27.264706
| 92
| 0.460985
|
anubhawbhalotia
|
a6dc6404df3ed219eb9d63cb59d8a9726db57fb5
| 250
|
cpp
|
C++
|
ch0104/ch0104_10.cpp
|
sun1218/openjudge
|
07e44235fc6ac68bf8e8125577dcd008b08d59ec
|
[
"MIT"
] | null | null | null |
ch0104/ch0104_10.cpp
|
sun1218/openjudge
|
07e44235fc6ac68bf8e8125577dcd008b08d59ec
|
[
"MIT"
] | null | null | null |
ch0104/ch0104_10.cpp
|
sun1218/openjudge
|
07e44235fc6ac68bf8e8125577dcd008b08d59ec
|
[
"MIT"
] | 1
|
2021-05-16T13:36:06.000Z
|
2021-05-16T13:36:06.000Z
|
#include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;
int main(void)
{
int n1,n2;
scanf("%d%d",&n1,&n2);
if (n1<60&&n2<60){
printf("0");
}
else if (n1<60||n2<60){
printf("1");
}
else{
printf("0");
}
return 0;
}
| 12.5
| 24
| 0.568
|
sun1218
|
a6e29a77798707fc75b8bbab75be7b63e1884ef3
| 9,451
|
hpp
|
C++
|
Include/Injector/Mathematics/Matrix3.hpp
|
InjectorGames/Inject
|
09e74a83c287b81fd8272c10d6bae2b1aa785c0e
|
[
"BSD-3-Clause"
] | 2
|
2019-12-10T16:26:58.000Z
|
2020-04-17T11:47:42.000Z
|
Include/Injector/Mathematics/Matrix3.hpp
|
InjectorGames/Inject
|
09e74a83c287b81fd8272c10d6bae2b1aa785c0e
|
[
"BSD-3-Clause"
] | 28
|
2020-08-17T12:39:50.000Z
|
2020-11-16T20:42:50.000Z
|
Include/Injector/Mathematics/Matrix3.hpp
|
InjectorGames/InjectorEngine
|
09e74a83c287b81fd8272c10d6bae2b1aa785c0e
|
[
"BSD-3-Clause"
] | null | null | null |
#pragma once
#include "Injector/Mathematics/Matrix2.hpp"
#include "Injector/Mathematics/Vector3.hpp"
namespace Injector
{
template<class T = float>
struct Matrix3 final
{
T m00, m01, m02;
T m10, m11, m12;
T m20, m21, m22;
Matrix3() noexcept :
m00(static_cast<T>(1)),
m01(static_cast<T>(0)),
m02(static_cast<T>(0)),
m10(static_cast<T>(0)),
m11(static_cast<T>(1)),
m12(static_cast<T>(0)),
m20(static_cast<T>(0)),
m21(static_cast<T>(0)),
m22(static_cast<T>(1))
{
}
Matrix3(T value) noexcept :
m00(value), m01(value), m02(value),
m10(value), m11(value), m12(value),
m20(value), m21(value), m22(value)
{
}
Matrix3(
T _m00, T _m01, T _m02,
T _m10, T _m11, T _m12,
T _m20, T _m21, T _m22) noexcept :
m00(_m00), m01(_m01), m02(_m02),
m10(_m10), m11(_m11), m12(_m12),
m20(_m20), m21(_m21), m22(_m22)
{
}
Matrix3(
const Vector3<T>& column0,
const Vector3<T>& column1,
const Vector3<T>& column2) noexcept :
m00(column0.x), m01(column0.y), m02(column0.z),
m10(column1.x), m11(column1.y), m12(column1.z),
m20(column2.x), m21(column2.y), m22(column2.z)
{
}
std::string getString() const noexcept
{
auto ss = std::stringstream();
ss <<
m00 << " " << m01 << " " << m02 << "; " <<
m10 << " " << m11 << " " << m12 << "; " <<
m20 << " " << m21 << " " << m22;
return ss.str();
}
T getDeterminant() const noexcept
{
return
m00 * (m11 * m22 - m21 * m12) -
m10 * (m01 * m22 - m21 * m02) +
m20 * (m01 * m12 - m11 * m02);
}
Matrix3<T> getTransposed() const noexcept
{
return Matrix3(
m00, m10, m20,
m01, m11, m21,
m02, m12, m22);
}
Matrix3<T> getInverted() const noexcept
{
auto determinant = static_cast<T>(1) / getDeterminant();
return Matrix3(
(m11 * m22 - m21 * m12) * determinant,
-(m01 * m22 - m21 * m02) * determinant,
(m01 * m12 - m11 * m02) * determinant,
-(m10 * m22 - m20 * m12) * determinant,
(m00 * m22 - m20 * m02) * determinant,
-(m00 * m12 - m10 * m02) * determinant,
(m10 * m21 - m20 * m11) * determinant,
-(m00 * m21 - m20 * m01) * determinant,
(m00 * m11 - m10 * m01) * determinant);
}
Vector3<T> getRow0() const noexcept
{
return Vector3<T>(m00, m10, m20);
}
Vector3<T> getRow1() const noexcept
{
return Vector3<T>(m01, m11, m21);
}
Vector3<T> getRow2() const noexcept
{
return Vector3<T>(m02, m12, m22);
}
void setRow0(const Vector3<T>& vector) noexcept
{
m00 = vector.x;
m10 = vector.y;
m20 = vector.z;
}
void setRow1(const Vector3<T>& vector) noexcept
{
m01 = vector.x;
m11 = vector.y;
m21 = vector.z;
}
void setRow2(const Vector3<T>& vector) noexcept
{
m02 = vector.x;
m12 = vector.y;
m22 = vector.z;
}
Vector3<T> getColumn0() const noexcept
{
return Vector3<T>(m00, m01, m02);
}
Vector3<T> getColumn1() const noexcept
{
return Vector3<T>(m10, m11, m12);
}
Vector3<T> getColumn2() const noexcept
{
return Vector3<T>(m20, m21, m22);
}
void setColumn0(const Vector3<T>& vector) noexcept
{
m00 = vector.x;
m01 = vector.y;
m02 = vector.z;
}
void setColumn1(const Vector3<T>& vector) noexcept
{
m10 = vector.x;
m11 = vector.y;
m12 = vector.z;
}
void setColumn2(const Vector3<T>& vector) noexcept
{
m20 = vector.x;
m22 = vector.y;
m22 = vector.z;
}
bool operator==(const Matrix3<T>& matrix) const noexcept
{
return
getColumn0() == matrix.getColumn0() &&
getColumn1() == matrix.getColumn1() &&
getColumn2() == matrix.getColumn2();
}
bool operator!=(const Matrix3<T>& matrix) const noexcept
{
return
getColumn0() != matrix.getColumn0() ||
getColumn1() != matrix.getColumn1() ||
getColumn2() != matrix.getColumn2();
}
Matrix3<T>& operator--() noexcept
{
setColumn0(--getColumn0());
setColumn1(--getColumn1());
setColumn2(--getColumn2());
return *this;
}
Matrix3<T>& operator++() noexcept
{
setColumn0(++getColumn0());
setColumn1(++getColumn1());
setColumn2(++getColumn2());
return *this;
}
Matrix3<T> operator--(int) noexcept
{
auto result = Matrix3<T>(*this);
setColumn0(--getColumn0());
setColumn1(--getColumn1());
setColumn2(--getColumn2());
return result;
}
Matrix3<T> operator++(int) noexcept
{
auto result = Matrix3<T>(*this);
setColumn0(++getColumn0());
setColumn1(++getColumn1());
setColumn2(++getColumn2());
return result;
}
Matrix3<T> operator-() const noexcept
{
return Matrix3<T>(
-getColumn0(),
-getColumn1(),
-getColumn2());
}
Matrix3<T> operator-(
const Matrix3<T>& matrix) const noexcept
{
return Matrix3<T>(
getColumn0() - matrix.getColumn0(),
getColumn1() - matrix.getColumn1(),
getColumn2() - matrix.getColumn2());
}
Matrix3<T> operator+(
const Matrix3<T>& matrix) const noexcept
{
return Matrix3<T>(
getColumn0() + matrix.getColumn0(),
getColumn1() + matrix.getColumn1(),
getColumn2() + matrix.getColumn2());
}
Matrix3<T> operator/(
const Matrix3<T>& matrix) const noexcept
{
return *this * matrix.getInverted();
}
Vector3<T> operator/(
const Vector3<T>& vector) const noexcept
{
return getInverted() * vector;
}
Matrix3<T> operator*(
const Matrix3<T>& matrix) const noexcept
{
auto a0 = getColumn0();
auto a1 = getColumn1();
auto a2 = getColumn2();
auto b0 = matrix.getColumn0();
auto b1 = matrix.getColumn1();
auto b2 = matrix.getColumn2();
return Matrix3<T>(
a0 * b0.x + a1 * b0.y + a2 * b0.z,
a0 * b1.x + a1 * b1.y + a2 * b1.z,
a0 * b2.x + a1 * b2.y + a2 * b2.z);
}
Vector3<T> operator*(
const Vector3<T>& vector) const noexcept
{
return
getColumn0() * Vector3<T>(vector.x) +
getColumn1() * Vector3<T>(vector.y) +
getColumn2() * Vector3<T>(vector.z);
}
Matrix3<T>& operator-=(
const Matrix3<T>& matrix) noexcept
{
setColumn0(getColumn0() - matrix.getColumn0());
setColumn1(getColumn1() - matrix.getColumn1());
setColumn2(getColumn2() - matrix.getColumn2());
return *this;
}
Matrix3<T>& operator+=(
const Matrix3<T>& matrix) noexcept
{
setColumn0(getColumn0() + matrix.getColumn0());
setColumn1(getColumn1() + matrix.getColumn1());
setColumn2(getColumn2() + matrix.getColumn2());
return *this;
}
Matrix3<T>& operator/=(
const Matrix3<T>& matrix) noexcept
{
return *this *= matrix.getInverted();
}
Matrix3<T>& operator*=(
const Matrix3<T>& matrix) noexcept
{
auto a0 = getColumn0();
auto a1 = getColumn1();
auto a2 = getColumn2();
auto b0 = matrix.getColumn0();
auto b1 = matrix.getColumn1();
auto b2 = matrix.getColumn2();
setColumn0(a0 * b0.x + a1 * b0.y + a2 * b0.z);
setColumn1(a0 * b1.x + a1 * b1.y + a2 * b1.z);
setColumn2(a0 * b2.x + a1 * b2.y + a2 * b2.z);
return *this;
}
Matrix3<T> operator-(
T value) const noexcept
{
auto vector = Vector3<T>(value);
return Matrix3<T>(
getColumn0() - vector,
getColumn1() - vector,
getColumn2() - vector);
}
Matrix3<T> operator+(
T value) const noexcept
{
auto vector = Vector3<T>(value);
return Matrix3<T>(
getColumn0() + vector,
getColumn1() + vector,
getColumn2() + vector);
}
Matrix3<T> operator/(
T value) const noexcept
{
auto vector = Vector3<T>(value);
return Matrix3<T>(
getColumn0() / vector,
getColumn1() / vector,
getColumn2() / vector);
}
Matrix3<T> operator*(
T value) const noexcept
{
auto vector = Vector3<T>(value);
return Matrix3<T>(
getColumn0() * vector,
getColumn1() * vector,
getColumn2() * vector);
}
Matrix3<T>& operator-=(
T value) noexcept
{
auto vector = Vector3<T>(value);
setColumn0(getColumn0() - vector);
setColumn1(getColumn1() - vector);
setColumn2(getColumn2() - vector);
return *this;
}
Matrix3<T>& operator+=(
T value) noexcept
{
auto vector = Vector3<T>(value);
setColumn0(getColumn0() + vector);
setColumn1(getColumn1() + vector);
setColumn2(getColumn2() + vector);
return *this;
}
Matrix3<T>& operator/=(
T value) noexcept
{
auto vector = Vector3<T>(value);
setColumn0(getColumn0() / vector);
setColumn1(getColumn1() / vector);
setColumn2(getColumn2() / vector);
return *this;
}
Matrix3<T>& operator*=(
T value) noexcept
{
auto vector = Vector3<T>(value);
setColumn0(getColumn0() * vector);
setColumn1(getColumn1() * vector);
setColumn2(getColumn2() * vector);
return *this;
}
struct Less
{
bool operator()(
const Matrix3& a,
const Matrix3& b) const noexcept
{
return
std::tie(
a.m00, a.m01, a.m02,
a.m10, a.m11, a.m12,
a.m20, a.m21, a.m22) <
std::tie(
b.m00, b.m01, b.m02,
b.m10, b.m11, b.m12,
b.m20, b.m21, b.m22);
}
};
};
using FloatMatrix3 = Matrix3<float>;
using DoubleMatrix3 = Matrix3<double>;
using CharMatrix3 = Matrix3<char>;
using ByteMatrix3 = Matrix3<uint8_t>;
using SbyteMatrix3 = Matrix3<int8_t>;
using ShortMatrix3 = Matrix3<int16_t>;
using UshortMatrix3 = Matrix3<uint16_t>;
using IntMatrix3 = Matrix3<int32_t>;
using UintMatrix3 = Matrix3<uint32_t>;
using LongMatrix3 = Matrix3<int64_t>;
using UlongMatrix3 = Matrix3<uint64_t>;
using SizeMatrix3 = Matrix3<size_t>;
}
| 23.22113
| 59
| 0.60438
|
InjectorGames
|
a6eb7c3696c885d67b2af4dc6ec1e72b67f269fa
| 11,912
|
cpp
|
C++
|
libs/RplidarConnector.cpp
|
badpaybad/rplidaropencv
|
5a8d98280c3ac29f1a140982d769884d6d1fb85f
|
[
"MIT"
] | null | null | null |
libs/RplidarConnector.cpp
|
badpaybad/rplidaropencv
|
5a8d98280c3ac29f1a140982d769884d6d1fb85f
|
[
"MIT"
] | null | null | null |
libs/RplidarConnector.cpp
|
badpaybad/rplidaropencv
|
5a8d98280c3ac29f1a140982d769884d6d1fb85f
|
[
"MIT"
] | null | null | null |
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <iostream>
#include "rplidar.h" //RPLIDAR standard sdk, all-in-one header
#include <math.h>
#include <cmath>
#include <chrono>
#include <ctime>
#include <thread>
#include <mutex>
#include <functional>
#include "common.h"
#include "common.h"
#ifdef _WIN32
#include <Windows.h>
#define delay(x) ::Sleep(x);
#else
#include <unistd.h>
static inline void delay(_word_size_t ms)
{
while (ms >= 1000)
{
usleep(1000 * 1000);
ms -= 1000;
};
if (ms != 0)
usleep(ms * 1000);
}
#endif
using namespace rp::standalone::rplidar;
class RplidarConnector
{
public:
int _scanDiameterMilimet = 10000;
int _scanRadius = 5000;
float _mapRatio;
int _mapWidth;
int _mapHeight;
int _stop = 0;
const char *_opt_com_path = NULL;
_u32 _opt_com_baudrate;
RPlidarDriver *_drv;
/**
* @brief angle, distance
*
*/
std::function<void(float, float)> _onLidarCapture = NULL;
/**
* @brief x,y, Lidar.x, Lidar.y, mapRatio, scanDeameter, angle, distance
*
*/
std::function<void(RplidarPoint)> _onLidarPositionCalculated = NULL;
std::function<void(RplidarPoint[],int)> _onFrameCaptured = NULL;
/**
* @brief
*
* @param portCOM_Connect win: "\\\\.\\COM4" , linux: /dev/ttyUSB0
* @param opt_com_baudrate 115200
* @param scanDiameterMilimet 10000
*/
void init(const char *portCOM_Connect, _u32 opt_com_baudrate = 115200, int scanRadiusMilimet = 5000, float mapRatio = 0)
{
_opt_com_path = portCOM_Connect;
_scanRadius = scanRadiusMilimet;
_scanDiameterMilimet = _scanRadius * 2;
if (mapRatio == 0)
_mapRatio = (float)_scanDiameterMilimet / 1000.0f;
else
_mapRatio = mapRatio;
_mapWidth = _scanDiameterMilimet;
_mapHeight = _scanDiameterMilimet;
// create the driver instance
_drv = RPlidarDriver::CreateDriver();
_opt_com_baudrate = opt_com_baudrate;
std::cout << "\nopt_com_path: " << _opt_com_path << " opt_com_baudrate:" << opt_com_baudrate << " [need to check window (\\\\.\\COM4) or linux (/dev/ttyUSB0)]";
if (!_drv)
{
std::cout << "\ninsufficent memory, exit\n";
throw "\ninsufficent memory, exit\n";
}
}
void registerHandle(std::function<void(RplidarPoint[],int)> onFrameCaptured,
std::function<void(RplidarPoint)> onLidarPositionCalculated = NULL,
std::function<void(float, float)> onLidarCapture = NULL)
{
_onFrameCaptured = onFrameCaptured;
_onLidarCapture = onLidarCapture;
_onLidarPositionCalculated = onLidarPositionCalculated;
}
u_result capture_and_display(RPlidarDriver *drv)
{
float pi = _pi31416;
u_result ans;
rplidar_response_measurement_node_hq_t nodes[_maxPoints];
size_t count = _countof(nodes);
ans = drv->grabScanDataHq(nodes, count);
if (IS_OK(ans) || ans == RESULT_OPERATION_TIMEOUT)
{
drv->ascendScanData(nodes, count);
int x, y = 0;
int newX = _mapWidth / 2;
int newY = _mapHeight / 2;
RplidarPoint frame[_maxPoints];
for (int posNext = 1; posNext < (int)count; ++posNext)
{
int pos = posNext - 1;
//float tmpDis = nodes[pos].distance_q2 / 4.0f;
float tmpDis = nodes[pos].dist_mm_q2 / 4.0f;
//float tmpDis = nodes[pos].dist_mm_q2;
//float tmpAng = (nodes[pos].angle_q6_checkbit >> RPLIDAR_RESP_MEASUREMENT_ANGLE_SHIFT) / 64.0f;
float tmpAng = nodes[pos].angle_z_q14 * 90.f / 16384.0f;
if (tmpDis > 0.0f && tmpDis <= _scanRadius)
{
if (_onLidarCapture && _onLidarCapture != NULL)
try
{
_onLidarCapture(tmpAng, tmpDis);
}
catch (...)
{
}
if (tmpAng >= 0 && tmpAng <= 90)
{
x = cos((90 - tmpAng) * pi / 180) * tmpDis;
y = cos(tmpAng * pi / 180) * tmpDis;
x = newX + std::abs(x);
y = newY - std::abs(y);
}
else if (tmpAng > 90 && tmpAng <= 180)
{
x = cos((tmpAng - 90) * pi / 180) * tmpDis;
y = cos((180 - tmpAng) * pi / 180) * tmpDis;
x = newX + std::abs(x);
y = newY + std::abs(y);
}
else if (tmpAng > 180 && tmpAng <= 270)
{
x = cos((270 - tmpAng) * pi / 180) * tmpDis;
y = cos((tmpAng - 180) * pi / 180) * tmpDis;
x = newX - std::abs(x);
y = newY + std::abs(y);
}
else
{
x = cos((tmpAng - 270) * pi / 180) * tmpDis;
y = cos((360 - tmpAng) * pi / 180) * tmpDis;
x = newX - std::abs(x);
y = newY - std::abs(y);
}
if (x == 0 && y == 0)
continue;
if (x < 0 || y < 0)
continue;
if (_onLidarPositionCalculated && _onLidarPositionCalculated != NULL)
try
{
_onLidarPositionCalculated(RplidarPoint(x, y, newX, newY, _mapRatio, _scanDiameterMilimet, tmpAng, tmpDis));
}
catch (...)
{
}
frame[pos] = RplidarPoint(x, y, newX, newY, _mapRatio, _scanDiameterMilimet, tmpAng, tmpDis);
}
}
if (_onFrameCaptured && _onFrameCaptured != NULL)
try
{
_onFrameCaptured(frame,_maxPoints);
}
catch (...)
{
}
}
else
{
printf("error code: %x\n", ans);
}
return ans;
}
u_result connect_rplidar(RPlidarDriver *drv, const char *opt_com_path, _u32 opt_com_baudrate)
{
u_result op_result;
rplidar_response_device_info_t devinfo;
// try to connect
if (IS_FAIL(drv->connect(opt_com_path, opt_com_baudrate)))
{
throw "\r\nconnect_rplidar:Error, cannot bind to the specified serial port: " + std::string(opt_com_path);
}
// retrieving the device info
////////////////////////////////////////
op_result = drv->getDeviceInfo(devinfo);
if (IS_FAIL(op_result))
{
if (op_result == RESULT_OPERATION_TIMEOUT)
{
// you can check the detailed failure reason
std::cout << "\r\nconnect_rplidar:Error, operation time out.\n";
//throw "\r\nEconnect_rplidar:rror, operation time out.\n";
}
else
{
std::cout << "\r\nconnect_rplidar:Error : calling drv->reset(); error code: " << std::to_string(op_result);
//throw "\r\nconnect_rplidar:Error : calling drv->reset(); error code: " + std::to_string(op_result);
}
}
std::cout << "\r\nRplidar connected";
return op_result;
}
u_result disconnect_rplidar(RPlidarDriver *drv)
{
auto result = drv->reset();
std::this_thread::sleep_for(std::chrono::milliseconds(2000));
result = drv->stop();
result = drv->stopMotor();
RPlidarDriver::DisposeDriver(drv);
std::cout << "\r\nRplidar Disconnected";
return result;
}
/**
* @brief loop infinity, should call use thread
*
*/
void start()
{
rplidar_response_device_health_t healthinfo;
auto op_result = connect_rplidar(_drv, _opt_com_path, _opt_com_baudrate);
std::cout << "\n\rStarted";
while (_stop == 0)
{
try
{
// check the device health
////////////////////////////////////////
op_result = _drv->getHealth(healthinfo,5000U);
if (IS_OK(op_result))
{
// the macro IS_OK is the preperred way to judge whether the operation is succeed.
switch (healthinfo.status)
{
case RPLIDAR_STATUS_OK:
break;
case RPLIDAR_STATUS_WARNING:
break;
case RPLIDAR_STATUS_ERROR:
std::cout << "\n errorcode: " << healthinfo.error_code;
throw "\n errorcode: " + healthinfo.error_code;
break;
}
}
else
{
std::cout << "\n Error : calling drv->reset(); cannot retrieve the lidar health code: " << op_result;
throw "\n Error : calling drv->reset(); cannot retrieve the lidar health code: " + op_result;
}
if (healthinfo.status == RPLIDAR_STATUS_ERROR)
{
std::cout << "\n Error, rplidar internal error detected. Please reboot the device to retry.\n";
throw "\n Error, rplidar internal error detected. Please reboot the device to retry.\n";
// enable the following code if you want rplidar to be reboot by software
// drv->reset();
}
// take only one 360 deg scan and display the result as a histogram
////////////////////////////////////////////////////////////////////////////////
if (IS_FAIL(_drv->startScan(0, 1))) // you can force rplidar to perform scan operation regardless whether the motor is rotating
{
std::cout << "\nError, cannot start the scan operation.\n";
throw "\nError, cannot start the scan operation.\n";
}
if (IS_FAIL(capture_and_display(_drv)))
{
std::cout << "\nError, cannot grab scan data.\n";
throw "\nError, cannot grab scan data.\n";
}
std::this_thread::sleep_for(std::chrono::microseconds(1)); // this oki
}
catch (char *msg)
{
std::cout << msg;
}
catch (std::string msg)
{
std::cout << msg;
}
catch (...)
{
std::cout << "\nERROR rplidar restarting ...";
disconnect_rplidar(_drv);
std::this_thread::sleep_for(std::chrono::milliseconds(2000));
_drv = RPlidarDriver::CreateDriver();
connect_rplidar(_drv, _opt_com_path, _opt_com_baudrate);
}
}
}
void stop()
{
_stop = 1;
}
};
| 33.55493
| 169
| 0.465329
|
badpaybad
|
a6f205dbb1a696ba8603aa9a223c22b3a3061fa2
| 841
|
hpp
|
C++
|
SDK/ARKSurvivalEvolved_BossArenaManager_Spider_classes.hpp
|
2bite/ARK-SDK
|
c38ca9925309516b2093ad8c3a70ed9489e1d573
|
[
"MIT"
] | 10
|
2020-02-17T19:08:46.000Z
|
2021-07-31T11:07:19.000Z
|
SDK/ARKSurvivalEvolved_BossArenaManager_Spider_classes.hpp
|
2bite/ARK-SDK
|
c38ca9925309516b2093ad8c3a70ed9489e1d573
|
[
"MIT"
] | 9
|
2020-02-17T18:15:41.000Z
|
2021-06-06T19:17:34.000Z
|
SDK/ARKSurvivalEvolved_BossArenaManager_Spider_classes.hpp
|
2bite/ARK-SDK
|
c38ca9925309516b2093ad8c3a70ed9489e1d573
|
[
"MIT"
] | 3
|
2020-07-22T17:42:07.000Z
|
2021-06-19T17:16:13.000Z
|
#pragma once
// ARKSurvivalEvolved (329.9) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_BossArenaManager_Spider_structs.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass BossArenaManager_Spider.BossArenaManager_Spider_C
// 0x0000 (0x0618 - 0x0618)
class ABossArenaManager_Spider_C : public ABossArenaManager_C
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass BossArenaManager_Spider.BossArenaManager_Spider_C");
return ptr;
}
void UserConstructionScript();
void ExecuteUbergraph_BossArenaManager_Spider(int EntryPoint);
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 21.025
| 116
| 0.649227
|
2bite
|
a6f294997cf2f989f8396cca5e188dd28b103eca
| 1,392
|
cpp
|
C++
|
FRBDK/BitmapFontGenerator/source/ac_image.cpp
|
patridge/FlatRedBall
|
01e0212afeb977a10244796494dcaf9c800a3770
|
[
"MIT"
] | 110
|
2016-01-14T14:46:16.000Z
|
2022-03-27T19:00:48.000Z
|
FRBDK/BitmapFontGenerator/source/ac_image.cpp
|
patridge/FlatRedBall
|
01e0212afeb977a10244796494dcaf9c800a3770
|
[
"MIT"
] | 471
|
2016-08-21T14:48:15.000Z
|
2022-03-31T20:22:50.000Z
|
FRBDK/BitmapFontGenerator/source/ac_image.cpp
|
patridge/FlatRedBall
|
01e0212afeb977a10244796494dcaf9c800a3770
|
[
"MIT"
] | 33
|
2016-01-25T23:30:03.000Z
|
2022-02-18T07:24:45.000Z
|
#include <string.h>
#include "ac_image.h"
#define FAIL(r) {returnCode = (r); goto cleanup;}
cImage::cImage()
{
pixels = 0;
width = 0;
height = 0;
isTopDown = true;
}
cImage::cImage(int width, int height)
{
pixels = new PIXEL[width*height];
if( pixels )
{
this->width = width;
this->height = height;
}
else
{
this->width = 0;
this->height = 0;
}
}
cImage::~cImage()
{
if( pixels )
delete[] pixels;
}
int cImage::CopyToDC(HDC dc, int x, int y, int w, int h)
{
if( pixels == 0 )
return 0;
BITMAPINFO bmi;
GetBitmapInfoHeader((BITMAPINFOHEADER *)&bmi);
StretchDIBits(dc, x, y, w, h, 0, 0, width, height, pixels, &bmi, DIB_RGB_COLORS, SRCCOPY);
return 0;
}
void cImage::GetBitmapInfoHeader(BITMAPINFOHEADER *bmih)
{
bmih->biSize = sizeof(BITMAPINFOHEADER);
bmih->biBitCount = 32;
bmih->biWidth = width;
bmih->biHeight = isTopDown ? -height : height;
bmih->biCompression = BI_RGB;
bmih->biPlanes = 1;
bmih->biSizeImage = 0;
bmih->biClrImportant = 0;
bmih->biClrUsed = 0;
bmih->biXPelsPerMeter = 0;
bmih->biYPelsPerMeter = 0;
}
int cImage::Create(int w, int h)
{
if( pixels ) delete[] pixels;
pixels = new PIXEL[w*h];
width = w;
height = h;
return 0;
}
void cImage::Clear(PIXEL color)
{
for( int y = 0; y < height; y++ )
for( int x = 0; x < width; x++ )
pixels[y*width+x] = color;
}
| 17.4
| 91
| 0.614224
|
patridge
|
a6f6d9b79a25c99a4c4b87626b72b1145617a24b
| 914
|
hpp
|
C++
|
cc/vision/tag.hpp
|
PEQUI-VSSS/VSSS-EMC
|
0c2b61e308f754ca91df52e46ba48828168223df
|
[
"MIT"
] | 9
|
2017-07-18T12:37:09.000Z
|
2018-05-01T14:41:48.000Z
|
cc/vision/tag.hpp
|
PEQUI-MEC/VSSS-EMC
|
0c2b61e308f754ca91df52e46ba48828168223df
|
[
"MIT"
] | 31
|
2018-07-31T13:10:01.000Z
|
2022-03-26T16:00:25.000Z
|
cc/vision/tag.hpp
|
PEQUI-MEC/VSSS-EMC
|
0c2b61e308f754ca91df52e46ba48828168223df
|
[
"MIT"
] | 2
|
2017-10-01T16:09:20.000Z
|
2018-05-01T17:39:59.000Z
|
#ifndef TAG_HPP_
#define TAG_HPP_
#include "opencv2/opencv.hpp"
#include <iostream>
#include <vector>
#define ROBOT_RADIUS 17 // valor encontrado empiricamente (quanto menor, mais próximos os robôs podem ficar sem dar errado)
class Tag {
public:
cv::Point position;
cv::Point frontPoint;
cv::Point rearPoint;
double area;
bool left;
/// <summary>
/// Constroi a tag
/// </summary>
/// <param name="pos">Posição da tag</param>
/// <param name="myarea">Corresponde ao tagArea</param>
Tag(cv::Point pos, double myarea);
/// <summary>
/// Seta os pontos frontPoint e rearPoint aleatoriamente
/// </summary>
/// <param name="myLine">Linha encontrada pelo fitline</param>
void setLine(cv::Vec4f myLine);
/// <summary>
/// Inverte os pontos frontPoint e rearPoint depois que a visão determinar a ordem correta
/// </summary>
void switchPoints();
};
#endif /* TAG_HPP_ */
| 22.85
| 123
| 0.683807
|
PEQUI-VSSS
|
a6fdf19c225b356e9478ea73bd99e394adfeda17
| 129
|
cpp
|
C++
|
boards/px4/sitl/src/spi.cpp
|
Diksha-agg/Firmware_val
|
1efc1ba06997d19df3ed9bd927cfb24401b0fe03
|
[
"BSD-3-Clause"
] | null | null | null |
boards/px4/sitl/src/spi.cpp
|
Diksha-agg/Firmware_val
|
1efc1ba06997d19df3ed9bd927cfb24401b0fe03
|
[
"BSD-3-Clause"
] | null | null | null |
boards/px4/sitl/src/spi.cpp
|
Diksha-agg/Firmware_val
|
1efc1ba06997d19df3ed9bd927cfb24401b0fe03
|
[
"BSD-3-Clause"
] | null | null | null |
version https://git-lfs.github.com/spec/v1
oid sha256:de102294106dac5ca236ec401b7442ac5cb6d82b5e3606dd25025633a2416c22
size 1875
| 32.25
| 75
| 0.883721
|
Diksha-agg
|
4706b0bb91bf80a66bae7d29d377f67e219977ea
| 734
|
hpp
|
C++
|
Server/common/SharedMemoryQueue.hpp
|
grasmanek94/PT34-2016NJ
|
7888976b0810a89f3d564498614b15ab0baca096
|
[
"MIT"
] | null | null | null |
Server/common/SharedMemoryQueue.hpp
|
grasmanek94/PT34-2016NJ
|
7888976b0810a89f3d564498614b15ab0baca096
|
[
"MIT"
] | null | null | null |
Server/common/SharedMemoryQueue.hpp
|
grasmanek94/PT34-2016NJ
|
7888976b0810a89f3d564498614b15ab0baca096
|
[
"MIT"
] | null | null | null |
#ifndef IPCQUEUE_H
#define IPCQUEUE_H
#include <semaphore.h>
#include <string>
#include "SharedMemoryQueueMessage.hpp"
#include "RawQueue.hpp"
class SharedMemoryQueue
{
private:
RawQueue* queue_shared_memory;
sem_t* queue_operation_semaphore;
sem_t* memory_prepare_semaphore;
int shm_fd;
std::string queue_name;
int deletion_fd_protection;
bool Wait();
bool Post();
bool TryWait();
public:
SharedMemoryQueue(const std::string& queue_name);
~SharedMemoryQueue();
bool Push(SharedMemoryQueueMessage* item);
bool Pop(SharedMemoryQueueMessage* item);
// nonblocking functions
bool TryPush(SharedMemoryQueueMessage* item);
bool TryPop(SharedMemoryQueueMessage* item);
size_t Count() const;
void Clear();
};
#endif
| 19.315789
| 50
| 0.777929
|
grasmanek94
|
470d5d5efb557d2bcc3423201f8146f9c9fc5584
| 9,120
|
hpp
|
C++
|
med/set.hpp
|
Denis-G-P/med
|
eca046fd49e4bb12135a0263e4d4a59ed45bfb7f
|
[
"MIT"
] | null | null | null |
med/set.hpp
|
Denis-G-P/med
|
eca046fd49e4bb12135a0263e4d4a59ed45bfb7f
|
[
"MIT"
] | null | null | null |
med/set.hpp
|
Denis-G-P/med
|
eca046fd49e4bb12135a0263e4d4a59ed45bfb7f
|
[
"MIT"
] | null | null | null |
/**
@file
set IE container - tagged elements in any order
@copyright Denis Priyomov 2016-2017
Distributed under the MIT License
(See accompanying file LICENSE or visit https://github.com/cppden/med)
*/
#pragma once
#include "config.hpp"
#include "exception.hpp"
#include "optional.hpp"
#include "container.hpp"
#include "encode.hpp"
#include "decode.hpp"
#include "name.hpp"
#include "tag.hpp"
#include "meta/unique.hpp"
namespace med {
namespace sl {
struct set_name
{
template <class IE, typename TAG, class CODEC>
static constexpr bool check(TAG const& tag, CODEC&)
{
using mi = meta::produce_info_t<CODEC, IE>;
using tag_t = meta::list_first_t<mi>;
return tag_t::match(tag);
}
template <class IE, typename TAG, class CODEC>
static constexpr char const* apply(TAG const&, CODEC&)
{
return name<IE>();
}
template <typename TAG, class CODEC>
static constexpr char const* apply(TAG const&, CODEC&)
{
return nullptr;
}
};
struct set_enc
{
template <class PREV_IE, class IE, class TO, class ENCODER>
static constexpr void apply(TO const& to, ENCODER& encoder)
{
call_if<not std::is_void_v<PREV_IE>
&& is_callable_with_v<ENCODER, NEXT_CONTAINER_ELEMENT>
>::call(encoder, NEXT_CONTAINER_ELEMENT{}, to);
using mi = meta::produce_info_t<ENCODER, IE>;
IE const& ie = to;
constexpr bool explicit_meta = explicit_meta_in<mi, get_field_type_t<IE>>();
if constexpr (is_multi_field_v<IE>)
{
CODEC_TRACE("[%s]*%zu: %s", name<IE>(), ie.count(), class_name<mi>());
check_arity(encoder, ie);
call_if<is_callable_with_v<ENCODER, HEADER_CONTAINER>>::call(encoder, HEADER_CONTAINER{}, ie);
call_if<is_callable_with_v<ENCODER, ENTRY_CONTAINER>>::call(encoder, ENTRY_CONTAINER{}, ie);
bool first = true;
for (auto& field : ie)
{
//field was pushed but not set... do we need a new error?
if (not field.is_set()) { MED_THROW_EXCEPTION(missing_ie, name<IE>(), ie.count(), ie.count()-1) }
if (not first) { call_if<is_callable_with_v<ENCODER, NEXT_CONTAINER_ELEMENT>>::call(encoder, NEXT_CONTAINER_ELEMENT{}, to); }
if constexpr (explicit_meta)
{
sl::ie_encode<meta::list_rest_t<mi>, void>(encoder, field);
}
else
{
sl::ie_encode<mi, void>(encoder, field);
}
first = false;
}
call_if<is_callable_with_v<ENCODER, EXIT_CONTAINER>>::call(encoder, EXIT_CONTAINER{}, ie);
}
else //single-instance field
{
if (ie.is_set())
{
CODEC_TRACE("[%s]%s: %s", name<IE>(), class_name<IE>(), class_name<mi>());
call_if<is_callable_with_v<ENCODER, HEADER_CONTAINER>>::call(encoder, HEADER_CONTAINER{}, to);
if constexpr (explicit_meta)
{
sl::ie_encode<meta::list_rest_t<mi>, void>(encoder, ie);
}
else
{
sl::ie_encode<mi, void>(encoder, ie);
}
}
else if constexpr (!is_optional_v<IE>)
{
MED_THROW_EXCEPTION(missing_ie, name<IE>(), 1, 0)
}
}
}
template <class PREV_IE, class TO, class ENCODER>
static constexpr void apply(TO const&, ENCODER&) {}
};
struct set_dec
{
template <class IE, class TO, class DECODER, class HEADER, class... DEPS>
static bool check(TO&, DECODER&, HEADER const& header, DEPS&...)
{
using mi = meta::produce_info_t<DECODER, IE>;
using tag_t = meta::list_first_t<mi>;
return tag_t::match( get_tag(header) );
}
template <class IE, class TO, class DECODER, class HEADER, class... DEPS>
static constexpr void apply(TO& to, DECODER& decoder, HEADER const&, DEPS&... deps)
{
using mi = meta::produce_info_t<DECODER, IE>;
//pop back the tag we've read as we have non-fixed tag inside
using tag_t = meta::list_first_t<mi>;
if constexpr (not tag_t::is_const) { decoder(POP_STATE{}); }
IE& ie = to;
if constexpr (is_multi_field_v<IE>)
{
CODEC_TRACE("[%s]*%zu", name<IE>(), ie.count());
//TODO: looks strange since it doesn't match encode's calls
//call_if<is_callable_with_v<DECODER, HEADER_CONTAINER>>::call(decoder, HEADER_CONTAINER{}, ie);
call_if<is_callable_with_v<DECODER, ENTRY_CONTAINER>>::call(decoder, ENTRY_CONTAINER{}, ie);
if constexpr (is_callable_with_v<DECODER, NEXT_CONTAINER_ELEMENT>)
{
while (decoder(PUSH_STATE{}, ie))
{
if (auto const num = ie.count())
{
decoder(NEXT_CONTAINER_ELEMENT{}, ie);
if (num >= IE::max)
{
MED_THROW_EXCEPTION(extra_ie, name<IE>(), IE::max, num)
}
}
auto* field = ie.push_back(decoder);
sl::ie_decode<meta::list_rest_t<mi>, void>(decoder, *field, deps...);
}
}
else
{
if (ie.count() >= IE::max)
{
MED_THROW_EXCEPTION(extra_ie, name<IE>(), IE::max, ie.count())
}
auto* field = ie.push_back(decoder);
sl::ie_decode<meta::list_rest_t<mi>, void>(decoder, *field, deps...);
}
call_if<is_callable_with_v<DECODER, EXIT_CONTAINER>>::call(decoder, EXIT_CONTAINER{}, ie);
}
else //single-instance field
{
CODEC_TRACE("%c[%s]", ie.is_set()?'+':'-', name<IE>());
if (not ie.is_set())
{
return sl::ie_decode<meta::list_rest_t<mi>, void>(decoder, ie, deps...);
//return med::decode(decoder, ie);
}
MED_THROW_EXCEPTION(extra_ie, name<IE>(), 2, 1)
}
}
template <class TO, class DECODER, class HEADER, class... DEPS>
static constexpr void apply(TO&, DECODER&, HEADER const& header, DEPS&...)
{
MED_THROW_EXCEPTION(unknown_tag, name<TO>(), get_tag(header))
}
};
struct set_check
{
template <class IE, class TO, class DECODER>
static constexpr void apply(TO const& to, DECODER& decoder)
{
IE const& ie = to;
if constexpr (is_multi_field_v<IE>)
{
check_arity(decoder, ie);
}
else //single-instance field
{
if (not (is_optional_v<IE> || ie.is_set()))
{
MED_THROW_EXCEPTION(missing_ie, name<IE>(), 1, 0)
}
}
}
template <class TO, class DECODER>
static constexpr void apply(TO const&, DECODER&) {}
};
} //end: namespace sl
namespace detail {
template <class L, class = void> struct set_container;
template <template <class...> class L, class HEADER, class... IEs>
struct set_container<L<HEADER, IEs...>, std::enable_if_t<has_get_tag<HEADER>::value>> : container<IEs...>
{
using header_type = HEADER;
static constexpr bool plain_header = false; //compound header e.g. a sequence
};
template <template <class...> class L, class IE1, class... IEs>
struct set_container<L<IE1, IEs...>, std::enable_if_t<!has_get_tag<IE1>::value>> : container<IE1, IEs...>
{
static constexpr bool plain_header = true; //plain header e.g. a tag
};
} //end: namespace detail
template <class... IEs>
struct set : detail::set_container<meta::typelist<IEs...>>
{
using ies_types = typename detail::set_container<meta::typelist<IEs...>>::ies_types;
template <typename TAG, class CODEC>
static constexpr char const* name_tag(TAG const& tag, CODEC& codec)
{
return meta::for_if<ies_types>(sl::set_name{}, tag, codec);
}
template <class ENCODER>
void encode(ENCODER& encoder) const
{
meta::foreach_prev<ies_types>(sl::set_enc{}, this->m_ies, encoder);
}
template <class DECODER, class... DEPS>
void decode(DECODER& decoder, DEPS&... deps)
{
static_assert(std::is_void_v<meta::unique_t<tag_getter<DECODER>, ies_types>>
, "SEE ERROR ON INCOMPLETE TYPE/UNDEFINED TEMPLATE HOLDING IEs WITH CLASHED TAGS");
//?TODO: check all IEs have covariant tag
if constexpr (set::plain_header)
{
using IE = meta::list_first_t<ies_types>; //use 1st IE since all have similar tag
using mi = meta::produce_info_t<DECODER, IE>;
using tag_t = meta::list_first_t<mi>;
//TODO: how to join 2 branches w/o having unused bool
if constexpr (is_callable_with_v<DECODER, NEXT_CONTAINER_ELEMENT>) //json-like
{
bool first = true;
while (decoder(PUSH_STATE{}, *this)) //NOTE: this usage doesn't address IE which corresponds to PUSH_STATE
{
if (not first) { decoder(NEXT_CONTAINER_ELEMENT{}, *this); }
value<std::size_t> header;
header.set_encoded(sl::decode_tag<tag_t, false>(decoder));
CODEC_TRACE("tag=%#zx", std::size_t(get_tag(header)));
call_if<is_callable_with_v<DECODER, HEADER_CONTAINER>>::call(decoder, HEADER_CONTAINER{}, *this);
meta::for_if<ies_types>(sl::set_dec{}, this->m_ies, decoder, header, deps...);
first = false;
}
}
else
{
while (decoder(PUSH_STATE{}, *this))
{
value<std::size_t> header;
header.set_encoded(sl::decode_tag<tag_t, false>(decoder));
CODEC_TRACE("tag=%#zx", std::size_t(get_tag(header)));
meta::for_if<ies_types>(sl::set_dec{}, this->m_ies, decoder, header, deps...);
}
}
}
else //compound header
{
using header_type = typename detail::set_container<meta::typelist<IEs...>>::header_type;
while (decoder(PUSH_STATE{}, *this))
{
header_type header;
med::decode(decoder, header, deps...);
decoder(POP_STATE{}); //restore back for IE to decode itself (?TODO: better to copy instead)
CODEC_TRACE("tag=%#zx", std::size_t(get_tag(header)));
meta::for_if<ies_types>(sl::set_dec{}, this->m_ies, decoder, header, deps...);
}
}
meta::foreach<ies_types>(sl::set_check{}, this->m_ies, decoder);
}
};
} //end: namespace med
| 30
| 129
| 0.672259
|
Denis-G-P
|
4715c714b632932e1e01975935371c49b88838c1
| 10,782
|
cpp
|
C++
|
unittests/performance.tests.cpp
|
attcs/Octree
|
67cbb925bee3609ae18a977ad7162e38efefad00
|
[
"MIT"
] | 4
|
2022-01-22T09:34:44.000Z
|
2022-02-13T12:18:33.000Z
|
unittests/performance.tests.cpp
|
attcs/Octree
|
67cbb925bee3609ae18a977ad7162e38efefad00
|
[
"MIT"
] | null | null | null |
unittests/performance.tests.cpp
|
attcs/Octree
|
67cbb925bee3609ae18a977ad7162e38efefad00
|
[
"MIT"
] | null | null | null |
#include "pch.h"
using namespace OrthoTree;
#ifdef _M_X64
namespace PerformaceTest
{
#ifdef _DEBUG
autoce N1M = 1000;
#else
autoce N1M = 1000000;
#endif // _DEBUG
autoce rMax = 8.0;
template<size_t nDim>
static constexpr BoundingBoxND<nDim> CreateBox(PointND<nDim> const& pt, double size)
{
using Ad = AdaptorGeneral<nDim, PointND<nDim>, BoundingBoxND<nDim>>;
auto box = BoundingBoxND<nDim>{ pt, pt };
auto& ptMax = Ad::box_max(box);
for (size_t iDim = 0; iDim < nDim; ++iDim)
Ad::point_comp(ptMax, static_cast<dim_type>(iDim)) += size;
return box;
}
template<dim_type nDim>
static BoundingBoxND<nDim> CreateSearcBox(double rBegin, double rSize)
{
auto pt = PointND<nDim>{};
for (dim_type iDim = 0; iDim < nDim; ++iDim)
pt[iDim] = rBegin;
return CreateBox<nDim>(pt, rSize);
}
template<dim_type nDim, size_t nNumber>
static vector<PointND<nDim>> CreatePoints()
{
auto aPoint = vector<PointND<nDim>>(nNumber);
if (nNumber <= 1)
return aPoint;
size_t iNumber = 1;
// Corner points
{
for (dim_type iDim = 0; iDim < nDim && iNumber < nNumber; ++iDim, ++iNumber)
aPoint[iNumber][iDim] = rMax;
if (iNumber == nNumber)
return aPoint;
for (dim_type iDim = 0; iDim < nDim; ++iDim)
aPoint[iNumber][iDim] = rMax;
++iNumber;
}
// Angle points
{
autoc nRemain = nNumber - iNumber;
autoc rStep = rMax / (nRemain + 2);
for (size_t iRemain = 1; iNumber < nNumber; ++iNumber, ++iRemain)
for (dim_type iDim = 0; iDim < nDim && iNumber < nNumber; ++iDim)
aPoint[nNumber - iNumber - 1][iDim] = iRemain * rStep;
}
return aPoint;
}
template<dim_type nDim, size_t nNumber>
static vector<PointND<nDim>> CreateRandomPoints()
{
auto aPoint = vector<PointND<nDim>>(nNumber);
if (nNumber <= 1)
return aPoint;
size_t iNumber = 1;
// Corner points
{
for (dim_type iDim = 0; iDim < nDim && iNumber < nNumber; ++iDim, ++iNumber)
aPoint[iNumber][iDim] = rMax;
if (iNumber == nNumber)
return aPoint;
for (dim_type iDim = 0; iDim < nDim; ++iDim)
aPoint[iNumber][iDim] = rMax;
++iNumber;
}
srand(0);
{
for (size_t iRemain = 1; iNumber < nNumber; ++iNumber, ++iRemain)
for (dim_type iDim = 0; iDim < nDim && iNumber < nNumber; ++iDim)
aPoint[nNumber - iNumber - 1][iDim] = (rand() % 100) * (rMax / 100.0);
}
return aPoint;
}
template<dim_type nDim, size_t nNumber>
static vector<BoundingBoxND<nDim>> CreateBoxes()
{
if (nNumber == 0)
return {};
autoce rMax = 8.0;
autoce rUnit = 1.0;
auto aBox = vector<BoundingBoxND<nDim>>(nNumber);
aBox[0] = CreateBox(PointND<nDim>(), rMax);
if (nNumber == 1)
return aBox;
size_t iNumber = 1;
// Corner points
{
for (dim_type iDim = 0; iDim < nDim && iNumber < nNumber; ++iDim, ++iNumber)
{
aBox[iNumber].Min[iDim] = rMax - rUnit;
aBox[iNumber] = CreateBox(aBox[iNumber].Min, rUnit);
}
if (iNumber == nNumber)
return aBox;
for (dim_type iDim = 0; iDim < nDim; ++iDim)
aBox[iNumber].Min[iDim] = rMax - rUnit;
aBox[iNumber] = CreateBox(aBox[iNumber].Min, rUnit);
++iNumber;
}
// Angle points
{
autoc nRemain = nNumber - iNumber;
autoc rStep = (rMax - rUnit) / (nRemain + 2);
for (size_t iRemain = 1; iNumber < nNumber; ++iNumber, ++iRemain)
{
autoc iNumberBox = nNumber - iNumber - 1;
for (dim_type iDim = 0; iDim < nDim && iNumber < nNumber; ++iDim)
aBox[iNumberBox].Min[iDim] = iRemain * rStep;
aBox[iNumberBox] = CreateBox(aBox[iNumberBox].Min, rUnit);
}
}
return aBox;
}
template<dim_type nDim, size_t nNumber>
static vector<BoundingBoxND<nDim>> CreateRandomBoxes()
{
if (nNumber == 0)
return {};
autoce rMax = 8.0;
autoce rUnit = 1.0;
auto aBox = vector<BoundingBoxND<nDim>>(nNumber);
aBox[0] = CreateBox(PointND<nDim>(), rMax);
if (nNumber == 1)
return aBox;
size_t iNumber = 1;
// Corner points
{
for (dim_type iDim = 0; iDim < nDim && iNumber < nNumber; ++iDim, ++iNumber)
{
aBox[iNumber].Min[iDim] = rMax - rUnit;
aBox[iNumber] = CreateBox(aBox[iNumber].Min, rUnit);
}
if (iNumber == nNumber)
return aBox;
for (dim_type iDim = 0; iDim < nDim; ++iDim)
aBox[iNumber].Min[iDim] = rMax - rUnit;
aBox[iNumber] = CreateBox(aBox[iNumber].Min, rUnit);
++iNumber;
}
srand(0);
{
for (size_t iRemain = 1; iNumber < nNumber; ++iNumber, ++iRemain)
{
autoc iNumberBox = nNumber - iNumber - 1;
for (dim_type iDim = 0; iDim < nDim && iNumber < nNumber; ++iDim)
aBox[iNumberBox].Min[iDim] = (rand() % 100) * (rMax / 100.0);
aBox[iNumberBox] = CreateBox(aBox[iNumberBox].Min, (rand() % 100) * (4.0 * rUnit / 100.0));
}
}
return aBox;
}
namespace PreCalculated
{
// Points
autoc sPoint2D_10M = CreatePoints<2, 10 * N1M>();
autoc aPoint2D_10M = std::span(sPoint2D_10M);
autoc aPoint2D_1M = aPoint2D_10M.subspan(0, N1M);
autoc sPoint3D_10M = CreatePoints<3, 10*N1M>();
autoc aPoint3D_10M = std::span(sPoint3D_10M);
autoc aPoint3D_1M = aPoint3D_10M.subspan(0, N1M);
autoc aPoint3D_10MR = CreateRandomPoints<3, 10 * N1M>();
autoc aPoint4D_1M = CreatePoints<4, N1M>();
autoc aPoint16D_1M = CreatePoints<16, N1M>();
autoc aPoint63D_1M = CreatePoints<63, N1M>();
autoc TreePoint2D = QuadtreePoint::Create<std::execution::parallel_unsequenced_policy>(aPoint2D_10M, 4);
autoc TreePoint3D = OctreePoint::Create<std::execution::parallel_unsequenced_policy>(aPoint3D_10M, 4);
// Boxes
autoc sBox2D_10M = CreateBoxes<2, 10*N1M>();
autoc aBox2D_10M = std::span(sBox2D_10M);
autoc aBox2D_1M = aBox2D_10M.subspan(0, N1M);
autoc sBox3D_10M = CreateBoxes<3, 10*N1M>();
autoc aBox3D_10M = std::span(sBox3D_10M);
autoc aBox3D_1M = aBox3D_10M.subspan(0, N1M);
autoc aBox3D_10MR = CreateRandomBoxes<3, 10 * N1M>();
autoc aBox4D_1M = CreateBoxes<4, N1M>();
autoc aBox63D_1M = CreateBoxes<63, N1M>();
autoc box2D = BoundingBox2D{ Point2D{}, Point2D{ rMax, rMax} };
autoc box3D = BoundingBox3D{ Point3D{}, Point3D{ rMax, rMax, rMax} };
autoc TreeBox2D_10M = QuadtreeBox::Create<std::execution::parallel_unsequenced_policy>(aBox2D_10M, 4, box2D);
autoc TreeBox3D_10M = OctreeBox::Create<std::execution::parallel_unsequenced_policy>(aBox3D_10M, 4, box3D);
}
TEST_CLASS(PointTest)
{
private:
template<dim_type nDim>
static TreePointND<nDim> CreateTest(unsigned depth, std::span<PointND<nDim> const> const& aPoint, bool fPar = false)
{
autoc box = CreateSearcBox<nDim>(0.0, rMax);
auto nt = fPar
? TreePointND<nDim>::template Create<std::execution::parallel_unsequenced_policy>(aPoint, depth, box)
: TreePointND<nDim>::Create(aPoint, depth, box)
;
return nt;
}
public:
TEST_METHOD(Create_2D_1M_d3) { CreateTest<2>(3, PreCalculated::aPoint2D_1M); }
TEST_METHOD(Create_2D_1M_d4) { CreateTest<2>(4, PreCalculated::aPoint2D_1M); }
TEST_METHOD(Create_3D_1M_d3) { CreateTest<3>(3, PreCalculated::aPoint3D_1M); }
TEST_METHOD(Create_3D_1M_d4) { CreateTest<3>(4, PreCalculated::aPoint3D_1M); }
TEST_METHOD(Create_3D_10M_d4_S) { CreateTest<3>(4, PreCalculated::sPoint3D_10M); }
TEST_METHOD(Create_3D_10M_d4_S_PAR) { CreateTest<3>(4, PreCalculated::aPoint3D_10M, true); }
TEST_METHOD(Create_3D_10M_d4_R) { CreateTest<3>(4, PreCalculated::aPoint3D_10MR); }
TEST_METHOD(Create_3D_10MR_d4_R_PAR) { CreateTest<3>(4, PreCalculated::aPoint3D_10MR, true); }
TEST_METHOD(Create_4D_1M_d2) { CreateTest<4>(2, PreCalculated::aPoint4D_1M); }
TEST_METHOD(Create_16D_1M_d3) { CreateTest<16>(3, PreCalculated::aPoint16D_1M, true); }
TEST_METHOD(Create_63D_1M_d3) { CreateTest<63>(3, PreCalculated::aPoint63D_1M); }
TEST_METHOD(RangeSearch_2D_10M)
{
autoce n = 100;
autoc search_box = CreateSearcBox<2>(3.5, 1.0);
auto vvid = vector<vector<size_t>>(n);
for (int i = 0; i < n; ++i)
vvid[i] = PreCalculated::TreePoint2D.RangeSearch(search_box, PreCalculated::aPoint2D_10M);
}
TEST_METHOD(RangeSearch_3D_10M)
{
autoce n = 100;
autoc search_box = CreateSearcBox<3>(3.5, 1.0);
auto vvid = vector<vector<size_t>>(n);
for (int i = 0; i < n; ++i)
vvid[i] = PreCalculated::TreePoint3D.RangeSearch(search_box, PreCalculated::aPoint3D_10M);
}
};
TEST_CLASS(BoxTest)
{
private:
template<dim_type nDim>
static auto CreateTest(unsigned depth, std::span<BoundingBoxND<nDim> const> const& aBox, bool fPar = false)
{
autoc box = CreateSearcBox<nDim>(0.0, rMax);
auto nt = fPar
? TreeBoxND<nDim>::template Create<std::execution::parallel_unsequenced_policy>(aBox, depth, box)
: TreeBoxND<nDim>::Create(aBox, depth, box)
;
return nt;
}
public:
TEST_METHOD(Create_2D_1M_d3) { CreateTest(3, PreCalculated::aBox2D_1M); }
TEST_METHOD(Create_2D_1M_d4) { CreateTest(4, PreCalculated::aBox2D_1M); }
TEST_METHOD(Create_3D_1M_d3) { CreateTest(3, PreCalculated::aBox3D_1M); }
TEST_METHOD(Create_3D_1M_d4) { CreateTest(4, PreCalculated::aBox3D_1M); }
TEST_METHOD(Create_3D_10M_d4_S) { CreateTest(4, PreCalculated::aBox3D_10M); }
TEST_METHOD(Create_3D_10M_d4_S_PAR) { CreateTest<3>(4, PreCalculated::aBox3D_10M, true); }
TEST_METHOD(Create_3D_10M_d4_R) { CreateTest<3>(4, PreCalculated::aBox3D_10MR); }
TEST_METHOD(Create_3D_10M_d4_R_PAR) { CreateTest<3>(4, PreCalculated::aBox3D_10MR, true); }
TEST_METHOD(Create_4D_1M_d4) { CreateTest<4>(4, PreCalculated::aBox4D_1M); }
TEST_METHOD(Create_63D_1M_d4) { CreateTest<63>(4, PreCalculated::aBox63D_1M, true); }
TEST_METHOD(RangeSearch_2D_10M)
{
autoce nDim = 2;
autoce n = 10;
autoc search_box = CreateSearcBox<nDim>(3.5, 1.0);
auto vvid = vector<vector<size_t>>(n);
for (int i = 0; i < n; ++i)
vvid[i] = PreCalculated::TreeBox2D_10M.RangeSearch(search_box, PreCalculated::aBox2D_10M);
}
TEST_METHOD(RangeSearch_3D_10M)
{
autoce nDim = 3;
autoce n = 10;
autoc search_box = CreateSearcBox<nDim>(3.5, 1.0);
auto vvid = vector<vector<size_t>>(n);
for (int i = 0; i < n; ++i)
vvid[i] = PreCalculated::TreeBox3D_10M.RangeSearch(search_box, PreCalculated::aBox3D_10MR);
}
};
}
#endif
| 29.378747
| 120
| 0.634205
|
attcs
|
4715e18a2e95bf27a067cf2b8c4419a052924d00
| 4,924
|
cpp
|
C++
|
Engine/src/Platform/GraphicsAPI/DirectX/dxBuffers.cpp
|
Light3039/Light
|
cc4fc0293164ca48efdc833d0054d3ff8e60b65d
|
[
"Apache-2.0"
] | 23
|
2021-05-23T10:13:55.000Z
|
2022-03-24T14:49:30.000Z
|
Engine/src/Platform/GraphicsAPI/DirectX/dxBuffers.cpp
|
Light3039/Light
|
cc4fc0293164ca48efdc833d0054d3ff8e60b65d
|
[
"Apache-2.0"
] | 1
|
2021-09-07T12:26:33.000Z
|
2021-09-27T19:06:00.000Z
|
Engine/src/Platform/GraphicsAPI/DirectX/dxBuffers.cpp
|
Light3039/Light
|
cc4fc0293164ca48efdc833d0054d3ff8e60b65d
|
[
"Apache-2.0"
] | 3
|
2021-05-30T17:31:47.000Z
|
2021-09-20T06:42:39.000Z
|
#include "dxBuffers.h"
#include "dxSharedContext.h"
namespace Light {
//======================================== CONSTANT_BUFFER ========================================//
dxConstantBuffer::dxConstantBuffer(ConstantBufferIndex index, unsigned int size, Ref<dxSharedContext> sharedContext)
: m_Context(sharedContext),
m_Buffer(nullptr),
m_Map{},
m_Index(static_cast<int>(index))
{
D3D11_BUFFER_DESC bDesc = {};
bDesc.ByteWidth = size;
bDesc.Usage = D3D11_USAGE_DYNAMIC;
bDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
bDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
HRESULT hr;
DXC(m_Context->GetDevice()->CreateBuffer(&bDesc, nullptr, &m_Buffer));
m_Context->GetDeviceContext()->VSSetConstantBuffers(m_Index, 1u, m_Buffer.GetAddressOf());
}
void dxConstantBuffer::Bind()
{
m_Context->GetDeviceContext()->VSSetConstantBuffers(m_Index, 1u, m_Buffer.GetAddressOf());
}
void* dxConstantBuffer::Map()
{
m_Context->GetDeviceContext()->VSSetConstantBuffers(m_Index, 1u, m_Buffer.GetAddressOf());
m_Context->GetDeviceContext()->Map(m_Buffer.Get(), NULL, D3D11_MAP_WRITE_DISCARD, NULL, &m_Map);
return m_Map.pData;
}
void dxConstantBuffer::UnMap()
{
m_Context->GetDeviceContext()->Unmap(m_Buffer.Get(), NULL);
}
//======================================== CONSTANT_BUFFER ========================================//
//================================================== VERTEX_BUFFER ==================================================//
dxVertexBuffer::dxVertexBuffer(float* vertices, unsigned int stride, unsigned int count, Ref<dxSharedContext> sharedContext)
: m_Context(sharedContext),
m_Buffer(nullptr),
m_Map{},
m_Stride(stride)
{
// buffer desc
D3D11_BUFFER_DESC bDesc = {};
bDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
bDesc.Usage = D3D11_USAGE_DYNAMIC;
bDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
bDesc.ByteWidth = count * stride;
bDesc.StructureByteStride = stride;
// create buffer
HRESULT hr;
DXC(m_Context->GetDevice()->CreateBuffer(&bDesc, nullptr, &m_Buffer));
}
dxVertexBuffer::~dxVertexBuffer()
{
UnBind();
}
void* dxVertexBuffer::Map()
{
m_Context->GetDeviceContext()->Map(m_Buffer.Get(), NULL, D3D11_MAP_WRITE_DISCARD, NULL, &m_Map);
return m_Map.pData;
}
void dxVertexBuffer::UnMap()
{
m_Context->GetDeviceContext()->Unmap(m_Buffer.Get(), NULL);
}
void dxVertexBuffer::Bind()
{
static const unsigned int offset = 0u;
m_Context->GetDeviceContext()->IASetVertexBuffers(0u, 1u, m_Buffer.GetAddressOf(), &m_Stride, &offset);
}
void dxVertexBuffer::UnBind()
{
static const unsigned int offset = 0u;
static ID3D11Buffer* buffer = nullptr;
m_Context->GetDeviceContext()->IASetVertexBuffers(0u, 1u, &buffer, &m_Stride, &offset);
}
//================================================== VERTEX_BUFFER ==================================================//
//======================================== INDEX_BUFFER ========================================//
dxIndexBuffer::dxIndexBuffer(unsigned int* indices, unsigned int count, Ref<dxSharedContext> sharedContext)
: m_Context(sharedContext),
m_Buffer(nullptr)
{
// generate indices if not provided
bool hasIndices = !!indices;
if (!hasIndices)
{
// check
if (count % 6 != 0)
{
LT_ENGINE_WARN("dxIndexBuffer::dxIndexBuffer: 'indices' can only be null if count is multiple of 6");
LT_ENGINE_WARN("dxIndexBuffer::dxIndexBuffer: adding {} to 'count' -> {}", (6 - (count % 6)), count + (6 - (count % 6)));
count = count + (6 - (count % 6));
}
// create indices
indices = new unsigned int[count];
unsigned int offset = 0;
for (unsigned int i = 0; i < count; i += 6)
{
indices[i + 0] = offset + 0u;
indices[i + 1] = offset + 3u;
indices[i + 2] = offset + 2u;
indices[i + 3] = offset + 2u;
indices[i + 4] = offset + 1u;
indices[i + 5] = offset + 0u;
offset += 4u;
}
}
// buffer desc
D3D11_BUFFER_DESC bDesc = {};
bDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
bDesc.Usage = D3D11_USAGE_DEFAULT;
bDesc.ByteWidth = count * sizeof(unsigned int);
bDesc.StructureByteStride = sizeof(unsigned int);
// subresource data
D3D11_SUBRESOURCE_DATA sDesc = {};
sDesc.pSysMem = indices;
// create buffer
HRESULT hr;
DXC(m_Context->GetDevice()->CreateBuffer(&bDesc, &sDesc, &m_Buffer));
// delete indices
if (!hasIndices)
delete[] indices;
}
dxIndexBuffer::~dxIndexBuffer()
{
UnBind();
}
void dxIndexBuffer::Bind()
{
m_Context->GetDeviceContext()->IASetIndexBuffer(m_Buffer.Get(), DXGI_FORMAT_R32_UINT, 0u);
}
void dxIndexBuffer::UnBind()
{
static const unsigned int offset = 0u;
static ID3D11Buffer* buffer = nullptr;
m_Context->GetDeviceContext()->IASetIndexBuffer(buffer, DXGI_FORMAT_R32_UINT, offset);
}
//======================================== INDEX_BUFFER ========================================//
}
| 28.964706
| 125
| 0.623071
|
Light3039
|
4717979c7beff3864ffdc112727ef20b9a2a89a1
| 600
|
hpp
|
C++
|
src/libtgcat/cache.hpp
|
artkulak/telegram_categorization_2
|
4362b9575899443ed538288a52b0bf6da6b9964b
|
[
"Unlicense"
] | null | null | null |
src/libtgcat/cache.hpp
|
artkulak/telegram_categorization_2
|
4362b9575899443ed538288a52b0bf6da6b9964b
|
[
"Unlicense"
] | null | null | null |
src/libtgcat/cache.hpp
|
artkulak/telegram_categorization_2
|
4362b9575899443ed538288a52b0bf6da6b9964b
|
[
"Unlicense"
] | null | null | null |
#ifndef CACHE_HPP
#define CACHE_HPP
#include <string>
class Cache final
{
public:
void set(const std::string &data, const std::string &code) noexcept
{
set_data(data);
set_code(code);
}
void set_data(const std::string &data) noexcept { _data = data; }
void set_code(const std::string &code) noexcept { _code = code; }
std::string get_data() const noexcept { return _data; }
std::string get_code() const noexcept { return _code; }
void reset() noexcept
{
_data.clear();
_code.clear();
}
private:
std::string _data;
std::string _code;
};
#endif // CACHE_HPP
| 20
| 69
| 0.668333
|
artkulak
|
471ba86c789da3f7b571fc0d0afaeea732b6a02c
| 505
|
cpp
|
C++
|
sort-colors/sort-colors.cpp
|
arpitkekri/My-Leetcode-Solution-In-CPP
|
345f1c53c627fce33ee84672c5d3661863367040
|
[
"MIT"
] | 4
|
2021-06-21T04:32:12.000Z
|
2021-11-02T04:20:36.000Z
|
sort-colors/sort-colors.cpp
|
arpitkekri/My-Leetcode-Solution-In-CPP
|
345f1c53c627fce33ee84672c5d3661863367040
|
[
"MIT"
] | null | null | null |
sort-colors/sort-colors.cpp
|
arpitkekri/My-Leetcode-Solution-In-CPP
|
345f1c53c627fce33ee84672c5d3661863367040
|
[
"MIT"
] | 2
|
2021-08-19T11:27:18.000Z
|
2021-09-26T14:51:30.000Z
|
class Solution {
public:
void sortColors(vector<int>& nums) {
int n = nums.size();
int ptr0 = -1, ptr2 = n;
for(int i = 0; i < n; i++) {
if(nums[i] == 0 && ptr0 < i) {
ptr0++;
swap(nums[i], nums[ptr0]);
i--;
}
else if(nums[i] == 2 && ptr2 > i) {
ptr2--;
swap(nums[ptr2], nums[i]);
i--;
}
else continue;
}
}
};
| 25.25
| 47
| 0.332673
|
arpitkekri
|
471d6cd413d69e50d26862a9b49a01954b83b5b4
| 1,492
|
hpp
|
C++
|
src/CGData.hpp
|
zabookey/Kokkos-HPCG
|
7ca081e51a275c4fb6b21e8871788e88e8715dbc
|
[
"BSD-3-Clause"
] | 5
|
2015-07-10T16:35:08.000Z
|
2021-09-13T03:29:37.000Z
|
src/CGData.hpp
|
zabookey/Kokkos-HPCG
|
7ca081e51a275c4fb6b21e8871788e88e8715dbc
|
[
"BSD-3-Clause"
] | null | null | null |
src/CGData.hpp
|
zabookey/Kokkos-HPCG
|
7ca081e51a275c4fb6b21e8871788e88e8715dbc
|
[
"BSD-3-Clause"
] | null | null | null |
//@HEADER
// ***************************************************
//
// Kokkos HPCG: Refactored code to replace most/all
// allocated arrays with views.
//
//
//
//
//
// ***************************************************
//@HEADER
/*!
@file CGData.hpp
HPCG data structure
*/
#ifndef CGDATA_HPP
#define CGDATA_HPP
#include "SparseMatrix.hpp"
#include "Vector.hpp"
struct CGData_STRUCT {
Vector r; //!< pointer to residual vector
Vector z; //!< pointer to preconditioned residual vector
Vector p; //!< pointer to direction vector
Vector Ap; //!< pointer to Krylov vector
};
typedef struct CGData_STRUCT CGData;
/*!
Constructor for the data structure of CG vectors.
@param[in] A the data structure that describes the problem matrix and its structure
@param[out] data the data structure for CG vectors that will be allocated to get it ready for use in CG iterations
*/
inline void InitializeSparseCGData(SparseMatrix & A, CGData & data){
local_int_t nrow = A.localNumberOfRows;
local_int_t ncol = A.localNumberOfColumns;
InitializeVector(data.r, nrow);
InitializeVector(data.z, ncol);
InitializeVector(data.p, ncol);
InitializeVector(data.Ap, nrow);
return;
}
/*!
Destructor for the CG vectors data.
@param[inout] data the CG vectors data structure whose storage is deallocated
*/
inline void DeleteCGData(CGData & data) {
DeleteVector (data.r);
DeleteVector (data.z);
DeleteVector (data.p);
DeleteVector (data.Ap);
return;
}
#endif
| 22.606061
| 115
| 0.668231
|
zabookey
|
471d896e837084e6c713e3447978fd538b5fe7cd
| 10,516
|
hpp
|
C++
|
include/async/result.hpp
|
Dennisbonke/libasync
|
017d9e6eae1ceb8725834c37d0fb9fb2591801dc
|
[
"MIT"
] | null | null | null |
include/async/result.hpp
|
Dennisbonke/libasync
|
017d9e6eae1ceb8725834c37d0fb9fb2591801dc
|
[
"MIT"
] | null | null | null |
include/async/result.hpp
|
Dennisbonke/libasync
|
017d9e6eae1ceb8725834c37d0fb9fb2591801dc
|
[
"MIT"
] | null | null | null |
#ifndef ASYNC_RESULT_HPP
#define ASYNC_RESULT_HPP
#include <atomic>
#include <type_traits>
#include <utility>
#include <async/basic.hpp>
namespace async {
// ----------------------------------------------------------------------------
// Basic result<T> class implementation.
// ----------------------------------------------------------------------------
template<typename T>
struct result_reference {
result_reference()
: object{nullptr} { }
result_reference(awaitable<T> *obj)
: object{obj} { }
awaitable<T> *get_awaitable() const {
return object;
}
protected:
awaitable<T> *object;
};
namespace detail {
template<typename T>
struct result_promise;
template<typename T>
struct result_base {
friend void swap(result_base &a, result_base &b) {
using std::swap;
swap(a.object, b.object);
}
result_base()
: object{nullptr} { }
result_base(const result_base &) = delete;
result_base(result_base &&other)
: result_base() {
swap(*this, other);
}
explicit result_base(awaitable<T> *obj)
: object{obj} { }
~result_base() {
if(object)
object->drop();
}
result_base &operator= (result_base other) {
swap(*this, other);
return *this;
}
awaitable<T> *get_awaitable() {
return object;
}
protected:
awaitable<T> *object;
};
}
template<typename T>
struct [[nodiscard]] result : private detail::result_base<T> {
private:
using detail::result_base<T>::object;
public:
using detail::result_base<T>::get_awaitable;
using value_type = T;
using promise_type = detail::result_promise<T>;
result() = default;
explicit result(awaitable<T> *obj)
: detail::result_base<T>{obj} { }
operator result_reference<T> () {
return result_reference<T>{object};
}
bool ready() {
assert(object);
return object->ready();
}
void then(callback<void()> awaiter) {
assert(object);
object->then(awaiter);
}
T &value() {
return object->value();
}
};
template<>
struct [[nodiscard]] result<void> : private detail::result_base<void> {
private:
using detail::result_base<void>::object;
public:
using detail::result_base<void>::get_awaitable;
using value_type = void;
using promise_type = detail::result_promise<void>;
result() = default;
explicit result(awaitable<void> *obj)
: detail::result_base<void>{obj} { }
operator result_reference<void> () {
return result_reference<void>{object};
}
bool ready() {
assert(object);
return object->ready();
}
void then(callback<void()> awaiter) {
assert(object);
object->then(awaiter);
}
};
namespace detail {
template<typename T>
struct result_promise : private async::awaitable<T> {
result_promise() { }
private:
void submit() override {
auto handle = corons::coroutine_handle<result_promise>::from_promise(*this);
handle.resume();
}
void dispose() override {
auto handle = corons::coroutine_handle<result_promise>::from_promise(*this);
handle.destroy();
}
public:
async::result<T> get_return_object() {
return async::result<T>{this};
}
auto initial_suspend() { return corons::suspend_always{}; }
auto final_suspend() noexcept {
struct awaiter {
awaiter(result_promise *p)
: _p{p} { }
bool await_ready() noexcept {
return false;
}
void await_suspend(corons::coroutine_handle<>) noexcept {
_p->set_ready();
}
void await_resume() noexcept {
platform::panic("libasync: Internal fatal error:"
" Coroutine resumed from final suspension point");
}
private:
result_promise *_p;
};
return awaiter{this};
}
void return_value(T value) {
async::awaitable<T>::emplace_value(std::move(value));
}
template<typename X>
void return_value(X &&value) {
async::awaitable<T>::emplace_value(std::forward<X>(value));
}
void unhandled_exception() {
platform::panic("libasync: Unhandled exception in coroutine");
}
};
template<>
struct result_promise<void> : private async::awaitable<void> {
result_promise() { }
private:
void submit() override {
auto handle = corons::coroutine_handle<result_promise>::from_promise(*this);
handle.resume();
}
void dispose() override {
auto handle = corons::coroutine_handle<result_promise>::from_promise(*this);
handle.destroy();
}
public:
async::result<void> get_return_object() {
return async::result<void>{this};
}
auto initial_suspend() { return corons::suspend_always{}; }
auto final_suspend() noexcept {
struct awaiter {
awaiter(result_promise *p)
: _p{p} { }
bool await_ready() noexcept {
return false;
}
void await_suspend(corons::coroutine_handle<>) noexcept {
_p->set_ready();
}
void await_resume() noexcept {
platform::panic("libasync: Internal fatal error:"
" Coroutine resumed from final suspension point");
}
private:
result_promise *_p;
};
return awaiter{this};
}
void return_void() {
async::awaitable<void>::emplace_value();
}
void unhandled_exception() {
platform::panic("libasync: Unhandled exception in coroutine");
}
};
}
// ----------------------------------------------------------------------------
// Sender/receiver support for result<T>.
// ----------------------------------------------------------------------------
namespace detail {
template<typename T, typename Receiver>
struct result_operation {
result_operation(result<T> res, Receiver rcv)
: res_{std::move(res)}, rcv_{std::move(rcv)} { }
result_operation(const result_operation &) = delete;
result_operation &operator= (const result_operation &) = delete;
void start() {
res_.then([this] () {
execution::set_value(rcv_, std::move(res_.value()));
});
}
private:
result<T> res_;
Receiver rcv_;
};
template<typename Receiver>
struct result_operation<void, Receiver> {
result_operation(result<void> res, Receiver rcv)
: res_{std::move(res)}, rcv_{std::move(rcv)} { }
result_operation(const result_operation &) = delete;
result_operation &operator= (const result_operation &) = delete;
void start() {
res_.then([this] {
execution::set_value(rcv_);
});
}
private:
result<void> res_;
Receiver rcv_;
};
};
template<typename T, typename Receiver>
detail::result_operation<T, Receiver> connect(result<T> s, Receiver r) {
return {std::move(s), std::move(r)};
}
template<typename T>
sender_awaiter<result<T>, T> operator co_await(result<T> res) {
return {std::move(res)};
};
// ----------------------------------------------------------------------------
// promise<T> class implementation.
// ----------------------------------------------------------------------------
namespace detail {
enum : unsigned int {
has_value = 1,
has_awaiter = 2
};
template<typename T>
struct promise_state : awaitable<T> {
using awaitable<T>::emplace_value;
using awaitable<T>::set_ready;
void submit() override {
_active = true;
if(_raised)
set_ready();
}
void dispose() override {
// TODO: Review assertions here.
delete this;
}
void raise() {
_raised = true;
if(_active)
set_ready();
}
private:
bool _active = false;
bool _raised = false;
};
template<>
struct promise_state<void> : awaitable<void> {
using awaitable<void>::set_ready;
void submit() override {
_active = true;
if(_raised)
set_ready();
}
void dispose() override {
// TODO: Review assertions here.
delete this;
}
void raise() {
_raised = true;
if(_active)
set_ready();
}
private:
bool _active = false;
bool _raised = false;
};
template<typename T>
struct promise_base {
friend void swap(promise_base &a, promise_base &b) {
using std::swap;
swap(a.setter, b.setter);
swap(a.getter, b.getter);
}
promise_base() {
auto st = new promise_state<T>{};
setter = st;
getter = st;
}
promise_base(const promise_base &) = delete;
promise_base(promise_base &&other)
: setter(nullptr), getter(nullptr) {
swap(*this, other);
}
~promise_base() {
// TODO: Review this condition.
//assert(!setter && !getter);
}
promise_base &operator= (promise_base other) {
swap(*this, other);
return *this;
}
protected:
promise_state<T> *setter;
promise_state<T> *getter;
};
}
template<typename T>
struct promise : private detail::promise_base<T> {
private:
using detail::promise_base<T>::setter;
using detail::promise_base<T>::getter;
public:
void set_value(T value) {
assert(setter);
auto s = std::exchange(setter, nullptr);
s->emplace_value(std::move(value));
s->raise();
}
result<T> async_get() {
assert(getter);
return result<T>{std::exchange(getter, nullptr)};
}
};
template<>
struct promise<void> : private detail::promise_base<void> {
private:
using detail::promise_base<void>::setter;
using detail::promise_base<void>::getter;
public:
void set_value() {
assert(setter);
auto s = std::exchange(setter, nullptr);
s->raise();
}
result<void> async_get() {
assert(getter);
return result<void>{std::exchange(getter, nullptr)};
}
};
// ----------------------------------------------------------------------------
// pledge<T> class implementation.
// ----------------------------------------------------------------------------
namespace detail {
template<typename T>
struct pledge_base : awaitable<T> {
pledge_base()
: _retrieved(false) { }
pledge_base(const pledge_base &) = delete;
~pledge_base() {
assert(_retrieved);
}
pledge_base &operator= (const pledge_base &other) = delete;
void submit() override {
_active = true;
if(_raised)
awaitable<T>::set_ready();
}
void dispose() override {
// TODO
//std::cout << "libasync: Handle dispose() for pledge" << std::endl;
}
result<T> async_get() {
assert(!std::exchange(_retrieved, true));
return result<T>{this};
}
void set_ready() {
_raised = true;
if(_active)
awaitable<T>::set_ready();
}
protected:
bool _retrieved;
bool _active = false;
bool _raised = false;
};
template<typename T>
struct pledge : private pledge_base<T> {
using pledge_base<void>::emplace_value;
using pledge_base<void>::async_get;
};
template<>
struct pledge<void> : private pledge_base<void> {
using pledge_base<void>::async_get;
};
}
using detail::pledge;
// TODO: Support non-void results.
template<typename A>
async::result<void> make_result(A awaitable) {
co_await std::forward<A>(awaitable);
}
} // namespace async
#endif // ASYNC_RESULT_HPP
| 19.992395
| 79
| 0.627425
|
Dennisbonke
|
471e53a1cf60a08083b61f6aac28fcf9c768d92c
| 7,190
|
cpp
|
C++
|
src/Module.cpp
|
szellmann/fakeOwl
|
f938504b9dbb218aa0aad0b47513cebd79e47e13
|
[
"MIT"
] | 4
|
2021-05-01T20:53:27.000Z
|
2021-05-05T00:35:55.000Z
|
src/Module.cpp
|
szellmann/fakeOwl
|
f938504b9dbb218aa0aad0b47513cebd79e47e13
|
[
"MIT"
] | null | null | null |
src/Module.cpp
|
szellmann/fakeOwl
|
f938504b9dbb218aa0aad0b47513cebd79e47e13
|
[
"MIT"
] | null | null | null |
#include <dlfcn.h>
#include "Bounds.h"
#include "ClosestHit.h"
#include "Intersect.h"
#include "Logging.h"
#include "Miss.h"
#include "Module.h"
#include "RayGen.h"
namespace fake
{
Module::Module(const char* lib)
{
FAKE_LOG_DBG << "Creating module from library: " << lib;
handle = dlopen(lib, RTLD_NOW);
if (handle != nullptr)
FAKE_LOG_DBG << "Success!";
else
{
FAKE_LOG(fake::logging::Level::Error) << "Could not create module from library: " << lib;
return;
}
optixLaunchParamsSym = dlsym(handle, "optixLaunchParams");
if (optixLaunchParamsSym != nullptr)
FAKE_LOG_DBG << "Module has optixLaunchParams";
fakePrepareRayGenSym = dlsym(handle, "fakePrepareRayGen");
if (fakePrepareRayGenSym == nullptr)
{
FAKE_LOG(fake::logging::Level::Error) << "Missing symbol for fakePrepareRayGen(): " << lib;
}
fakePrepareIntersectionSym = dlsym(handle, "fakePrepareIntersection");
if (fakePrepareIntersectionSym == nullptr)
{
FAKE_LOG(fake::logging::Level::Error) << "Missing symbol for fakePrepareIntersection(): " << lib;
}
fakeGetIntersectionResultSym = dlsym(handle, "fakeGetIntersectionResult");
if (fakeGetIntersectionResultSym == nullptr)
{
FAKE_LOG(fake::logging::Level::Error) << "Missing symbol for fakeGetIntersectionResult(): " << lib;
}
fakePrepareClosestHitSym = dlsym(handle, "fakePrepareClosestHit");
if (fakePrepareClosestHitSym == nullptr)
{
FAKE_LOG(fake::logging::Level::Error) << "Missing symbol for fakePrepareClosestHit(): " << lib;
}
fakePrepareMissSym = dlsym(handle, "fakePrepareMiss");
if (fakePrepareMissSym == nullptr)
{
FAKE_LOG(fake::logging::Level::Error) << "Missing symbol for fakePrepareMiss(): " << lib;
}
fakeResetPreviousProgramStateSym = dlsym(handle, "fakeResetPreviousProgramState");
if (fakeResetPreviousProgramStateSym == nullptr)
{
FAKE_LOG(fake::logging::Level::Error) << "Missing symbol for fakeResetPreviousProgramState(): " << lib;
}
}
Module::~Module()
{
FAKE_LOG_DBG << "Releasing module";
// Destroy all programs associated with this module
for (size_t i = 0; i < programEntries.size(); ++i)
{
Program* program = (Program*)GetManagedResource(programEntries[i].handle);
FAKE_LOG_DBG << "Releasing program (type " << program->type << "): " << program->name;
delete program;
UnregisterManagedResource(programEntries[i].handle);
}
dlclose(handle);
}
void Module::buildPrograms()
{
for (size_t i = 0; i < programEntries.size(); ++i)
{
Program* program = (Program*)GetManagedResource(programEntries[i].handle);
FAKE_LOG_DBG << "Building program (type " << program->type << "): " << program->name;
program->build();
}
}
Program* Module::createProgram(Program::Type pt, const char* name,
std::size_t sizeOfVarStruct,
OWLVarDecl* vars,
int numVars)
{
FAKE_LOG_DBG << "Creating program (type " << pt << "): " << name;
Program* program = nullptr;
if (pt == Program::PtBounds)
program = new Bounds;
if (pt == Program::PtClosestHit)
{
program = new ClosestHit;
ClosestHit* ch = (ClosestHit*)program;
ch->fakePrepareClosestHitSym = fakePrepareClosestHitSym;
}
else if (pt == Program::PtMiss)
{
program = new Miss(sizeOfVarStruct, vars, numVars);
Miss* missProg = (Miss*)program;
missProg->fakePrepareMissSym = fakePrepareMissSym;
// This is rayType order
miss.push_back(missProg);
}
else if (pt == Program::PtIntersect)
{
program = new Intersect;
Intersect* isect = (Intersect*)program;
isect->fakePrepareIntersectionSym = fakePrepareIntersectionSym;
isect->fakeGetIntersectionResultSym = fakeGetIntersectionResultSym;
}
else if (pt == Program::PtRayGen)
{
program = new RayGen(sizeOfVarStruct, vars, numVars);
RayGen* rayGen = (RayGen*)program;
rayGen->fakePrepareRayGenSym = fakePrepareRayGenSym;
}
if (program != nullptr)
{
program->resourceHandle = RegisterManagedResource((ManagedResource)program);
program->setContext(context);
program->module = this;
program->type = pt;
program->name = name;
program->fakeResetPreviousProgramStateSym = fakeResetPreviousProgramStateSym;
programEntries.push_back({pt, program->resourceHandle});
FAKE_LOG_DBG << "Success!";
}
else
FAKE_LOG(fake::logging::Level::Error) << "Unsuccessful!";
return program;
}
void Module::releaseProgram(Program* program)
{
FAKE_LOG_DBG << "Releasing program (type " << program->type << "): " << program->name;
programEntries.erase(std::remove_if(programEntries.begin(),
programEntries.end(),
[program](ProgramEntry ent)
{ return ent.type == program->type
&& ent.handle == program->resourceHandle; }),
programEntries.end());
UnregisterManagedResource(program->resourceHandle);
delete program;
}
void Module::setMissProg(int rayType, Miss* missProg)
{
if (rayType >= miss.size())
{
// As miss progs are set in some of the original examples
// before the ray type count was set (if ever), be
// robust towards that (but issue a warning)
FAKE_LOG(fake::logging::Level::Warning) << "rayType " << rayType
<< " exceeds rayType count:"
<< miss.size()
<< " -- setting rayType count to "
<< rayType+1;
miss.resize(rayType+1);
}
miss[rayType] = missProg;
}
bool Module::haveMissProg(int rayType)
{
return rayType >= 0 && rayType < miss.size();
}
Miss* Module::getMissProg(int rayType)
{
if (rayType >= miss.size())
{
FAKE_LOG(fake::logging::Level::Error) << "rayType " << rayType
<< " exceeds rayType count:"
<< miss.size();
return nullptr;
}
return miss[rayType];
}
} // fake
| 35.95
| 115
| 0.538248
|
szellmann
|
4724154aa62de09d998b90046699355132942ce8
| 1,310
|
cpp
|
C++
|
codeforces/B - Gluttony/Wrong answer on test 8.cpp
|
kzvd4729/Problem-Solving
|
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
|
[
"MIT"
] | 1
|
2022-02-11T16:55:36.000Z
|
2022-02-11T16:55:36.000Z
|
codeforces/B - Gluttony/Wrong answer on test 8.cpp
|
kzvd4729/Problem-Solving
|
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
|
[
"MIT"
] | null | null | null |
codeforces/B - Gluttony/Wrong answer on test 8.cpp
|
kzvd4729/Problem-Solving
|
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
|
[
"MIT"
] | null | null | null |
/****************************************************************************************
* @author: kzvd4729 created: Apr/18/2020 19:15
* solution_verdict: Wrong answer on test 8 language: GNU C++14
* run_time: 1918 ms memory_used: 7800 KB
* problem: https://codeforces.com/contest/891/problem/B
****************************************************************************************/
#include<bits/stdc++.h>
#define long long long
using namespace std;
const int N=1e6;
int aa[N+2],bb[N+2],n;long tt;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
bool dfs(int i,long a,long b)
{
if(a==tt-1)return true;
if(i==n)return (a==-1)|(a!=b);
return dfs(i+1,a,b)&dfs(i+1,a+aa[i],b+bb[i]);
}
int main()
{
ios_base::sync_with_stdio(0);cin.tie(0);
cin>>n;
for(int i=0;i<n;i++)cin>>aa[i],tt+=aa[i];vector<int>v;
for(int i=0;i<n;i++)v.push_back(i);
while(clock()<CLOCKS_PER_SEC*1.9)
{
shuffle(v.begin(),v.end(),rng);
for(int i=0;i<n;i++)bb[i]=aa[v[i]];
if(!dfs(0,-1,-1))continue;
for(int i=0;i<n;i++)cout<<bb[i]<<" ";
cout<<endl;exit(0);
}
cout<<-1<<endl;
return 0;
}
| 37.428571
| 111
| 0.449618
|
kzvd4729
|
472b11fbe5d2f94009f83029054a8e83a57b0f96
| 2,041
|
cpp
|
C++
|
arch/platform/platform-i386.cpp
|
IGR2014/kernale
|
a8b43cf7d89c3d92b14ffdb88683023048f4bf78
|
[
"MIT"
] | 4
|
2019-08-09T09:20:40.000Z
|
2021-09-10T00:59:30.000Z
|
arch/platform/platform-i386.cpp
|
IGR2014/kernale
|
a8b43cf7d89c3d92b14ffdb88683023048f4bf78
|
[
"MIT"
] | 12
|
2017-10-24T14:22:46.000Z
|
2020-07-17T16:20:39.000Z
|
arch/platform/platform-i386.cpp
|
IGR2014/kernale
|
a8b43cf7d89c3d92b14ffdb88683023048f4bf78
|
[
"MIT"
] | 1
|
2019-08-01T07:49:36.000Z
|
2019-08-01T07:49:36.000Z
|
////////////////////////////////////////////////////////////////
//
// Platform description for x86
//
// File: platform-i386.cpp
// Date: 24 Sep 2021
//
// Copyright (c) 2017 - 2021, Igor Baklykov
// All rights reserved.
//
//
#include <platform.hpp>
#include <arch/i386/types.hpp>
#include <arch/i386/idt.hpp>
#include <arch/i386/exceptions.hpp>
#include <arch/i386/gdt.hpp>
#include <arch/i386/paging.hpp>
#include <arch/i386/irq.hpp>
#include <arch/i386/fpu.hpp>
#include <klib/kprint.hpp>
// i386 namespace
namespace igros::i386 {
// Initialize i386
static void i386Init() noexcept {
klib::kprintf("Initializing i386 platform...", __func__);
// Setup Interrupts Descriptor Table
i386::idt::init();
// Init exceptions
i386::except::init();
// Setup Global Descriptors Table
i386::gdt::init();
// Setup paging (And identity map first 4MB where kernel physically is)
i386::paging::init();
// Init interrupts
i386::irq::init();
// Enable interrupts
i386::irq::enable();
// Check FPU
i386::fpu::check();
}
// Finalize i386
static void i386Finalize() noexcept {
klib::kprintf("%s:\tNot implemented yet!", __func__);
}
// Shutdown i386
static void i386Shutdown() noexcept {
klib::kprintf("%s:\tNot implemented yet!", __func__);
}
// Reboot i386
static void i386Reboot() noexcept {
klib::kprintf("%s:\tNot implemented yet!", __func__);
}
// Suspend i386
static void i386Suspend() noexcept {
klib::kprintf("%s:\tNot implemented yet!", __func__);
}
// Wakeup i386
static void i386Wakeup() noexcept {
klib::kprintf("%s:\tNot implemented yet!", __func__);
}
} // namespace igros::i386
// OS platform
namespace igros::platform {
// Platform description
const description_t CURRENT_PLATFORM {
"i386",
i386::i386Init,
i386::i386Finalize,
i386::i386Shutdown,
i386::i386Reboot,
i386::i386Suspend,
i386::i386Wakeup
};
} // namespace igros::platform
| 19.815534
| 74
| 0.623224
|
IGR2014
|
473269a99351cb3e6124658ab463885ad3b16bd5
| 1,378
|
hpp
|
C++
|
lib/PDB.hpp
|
atfrank/PCASA
|
cbb71ac4c1e822e731d854c364621dc80008e1b8
|
[
"MIT"
] | 3
|
2017-04-17T15:38:16.000Z
|
2019-07-26T12:15:19.000Z
|
lib/PDB.hpp
|
atfrank/PCASA
|
cbb71ac4c1e822e731d854c364621dc80008e1b8
|
[
"MIT"
] | 1
|
2019-09-23T13:44:55.000Z
|
2019-09-24T04:05:17.000Z
|
lib/PDB.hpp
|
atfrank/PCASA
|
cbb71ac4c1e822e731d854c364621dc80008e1b8
|
[
"MIT"
] | null | null | null |
//Sean M. Law
//Aaron T. Frank
/*
This file is part of MoleTools.
MoleTools is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
MoleTools is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with MoleTools. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef PDB_H
#define PDB_H
#include <map>
#include <string>
class Molecule;
class Residue;
class Atom;
class PDB {
private:
std::map<std::string, int> chnMap;
std::string format; //Output format
public:
PDB();
static void writePDBFormat (Molecule* mol, std::ostringstream &out, bool selFlag=true);
static Molecule* readPDB (const std::string ifile, const int model=0, const std::string format="", const bool hetFlag=true, const bool remFlag=false);
Atom* processAtomLine (std::string line, Atom* lastAtom);
static std::string formatCHARMMResName (Atom* atmEntry);
static int formatCHARMMResId(Atom* atmEntry, Residue* lastRes, Residue* nextRes);
};
#endif
| 29.319149
| 154
| 0.74238
|
atfrank
|
47397e57a48af795a9c36effcd51cb1d8327828c
| 3,910
|
cpp
|
C++
|
areashot.cpp
|
yushuiqiang/ChatRoomClient
|
a39ce6af4434950a96dad2a2aaaec43a0422728b
|
[
"MIT"
] | null | null | null |
areashot.cpp
|
yushuiqiang/ChatRoomClient
|
a39ce6af4434950a96dad2a2aaaec43a0422728b
|
[
"MIT"
] | null | null | null |
areashot.cpp
|
yushuiqiang/ChatRoomClient
|
a39ce6af4434950a96dad2a2aaaec43a0422728b
|
[
"MIT"
] | 1
|
2020-04-29T18:05:34.000Z
|
2020-04-29T18:05:34.000Z
|
#include "areashot.h"
#include "ui_areashot.h"
areashot::areashot(QWidget *parent) :
QWidget(parent),
ui(new Ui::areashot)
{
ui->setupUi(this);
this->setWindowFlags(Qt::FramelessWindowHint);
//取得屏幕大小,初始化 cutScreen
cutScreen = new myScreen(QApplication::desktop()->size());
resize(cutScreen->width(),cutScreen->height());
// this->show();
//保存全屏
this->hide();
fullScreen = new QPixmap();
*fullScreen = QPixmap::grabWindow(QApplication::desktop()->winId(),0,0,cutScreen->width(),cutScreen->height());
//设置透明度实现模糊背景
QPixmap pix(cutScreen->width(),cutScreen->height());
pix.fill((QColor(160,160,165,192)));
bgScreen = new QPixmap(*fullScreen);
QPainter p(bgScreen);
p.drawPixmap(0,0,pix);
// 截图信息显示区域背景
infoPix = new QPixmap(WIDTH_SHOW,HEIGHT_SHOW);
QPainter infoP(infoPix);
infoP.setBrush(QBrush(QColor(Qt::black),Qt::SolidPattern));
infoP.drawRect(0,0,WIDTH_SHOW,HEIGHT_SHOW);
// input = new myInputDialog(this);
//show init screen
this->show();
}
areashot::~areashot()
{
delete ui;
}
void areashot::paintEvent(QPaintEvent *e)
{
int x = cutScreen->getLeftUp().x();
int y = cutScreen->getLeftUp().y();
int w = cutScreen->getRightDown().x()-x;
int h = cutScreen->getRightDown().y()-y;
QPainter painter(this);
QPen pen; pen.setColor(Qt::green); pen.setWidth(1); pen.setStyle(Qt::SolidLine);
painter.setPen(pen);
painter.drawPixmap(0,0,*bgScreen); //画模糊背景
if( w!=0 && h!=0 ) painter.drawPixmap(x,y,fullScreen->copy(x,y,w,h)); //画截取区域
painter.drawRect(x,y,w,h); //截取区域边框
//显示截取区域信息 width height
painter.drawPixmap(x,y-32,*infoPix);
painter.drawText(x+2,y-20,QString("截图范围:(%1 x %2)-(%3 x %4) 图片大小:(%5 x %6)").arg(x).arg(y).arg(x+w).arg(y+h).arg(w).arg(h));
painter.drawText(x+2,y-6,QString("使用说明:(%1)").arg("S保存图片,F全屏截图,ESC退出程序,双击设置宽高"));
}
void areashot::mousePressEvent(QMouseEvent *e)
{
int status = cutScreen->getStatus();
if( status==SELECT ) // 记录鼠标
{
cutScreen->setStart( e->pos() );
}
else if( status==MOV ) //
{
// 不在截图区域内,重新选择
if( cutScreen->isInArea(e->pos())==false )
{
cutScreen->setStart( e->pos() );
cutScreen->setStatus(SELECT);
}
// 在截图区域,移动截图 鼠标指针成十字
else
{
movPos = e->pos();
this->setCursor(Qt::SizeAllCursor);
}
}
update();
}
void areashot::mouseMoveEvent(QMouseEvent *e)
{
if( cutScreen->getStatus()==SELECT ) // 选择区域
{
cutScreen->setEnd( e->pos() );
}
else if( cutScreen->getStatus()==MOV ) //移动所选区域
{
QPoint p(e->x()-movPos.x(),e->y()-movPos.y());
cutScreen->move(p);
movPos = e->pos();
}
update();
}
void areashot::mouseReleaseEvent(QMouseEvent *e)
{
if( cutScreen->getStatus()==SELECT )// SELECT状态下 释放鼠标
{
cutScreen->setStatus(MOV);//移动、撤销
}
else if( cutScreen->getStatus()==MOV )// 鼠标成正常状态
{
this->setCursor(Qt::ArrowCursor);
}
}
void areashot::keyReleaseEvent(QKeyEvent *e)
{
if( e->key()==Qt::Key_Escape )// esc 退出
{
this->close();
}
else if( e->key()==Qt::Key_F )// f 截取全屏
{
//saveFullScreen();
emit(fullshot(fullScreen));
this->close();
}
}
void areashot::mouseDoubleClickEvent(QMouseEvent *e)
{
int x = cutScreen->getLeftUp().x();
int y = cutScreen->getLeftUp().y();
int w = cutScreen->getRightDown().x()-x;
int h = cutScreen->getRightDown().y()-y;
areaScreen=new QPixmap(fullScreen->copy(x,y,w,h));
emit(fullshot(areaScreen));
this->close();
}
| 27.342657
| 132
| 0.558568
|
yushuiqiang
|
474290984179c1266a1f6ab5dc90f268beb25e07
| 2,216
|
cpp
|
C++
|
Client/localPlayerCam.cpp
|
WuskieFTW1113/IV-MP-T4
|
ec4f193c90d23e07e6200dcb061ec8773be6bedc
|
[
"MIT"
] | 2
|
2021-07-18T17:37:32.000Z
|
2021-08-04T12:33:51.000Z
|
Client/localPlayerCam.cpp
|
VittorioC97/IV-MP-T4
|
ec4f193c90d23e07e6200dcb061ec8773be6bedc
|
[
"MIT"
] | 1
|
2022-02-22T03:26:50.000Z
|
2022-02-22T03:26:50.000Z
|
Client/localPlayerCam.cpp
|
WuskieFTW1113/IV-MP-T4
|
ec4f193c90d23e07e6200dcb061ec8773be6bedc
|
[
"MIT"
] | 5
|
2021-06-17T06:41:00.000Z
|
2022-02-17T09:37:40.000Z
|
#include "players.h"
#include "easylogging++.h"
#include "cameraMemory.h"
void cameraMemory::getTarget(float ax, float az, float &x, float &y, float &z, float range)
{
/*
//c = (float)(Scripting::Sqrt((float)2.8 * 2.0) * (range * 0.15) * 3);
float c = range * 1.0647f;
//LINFO << c << " : " << (float)(Scripting::Sqrt((float)2.8 * 2.0) * (range * 0.15) * 3);
float s = c * Scripting::Cos(ax);
float b = s * Scripting::Cos(az);
float a = Scripting::Sqrt( (b*b) + (s*s) - ( 2 * b * s * Scripting::Cos(az) ) );
c = Scripting::Sqrt( ((s * s) / (Scripting::Cos(ax) * Scripting::Cos(ax))) - (s*s) );
if(ax < 0 || ax >= 180)
{
c = c * -1;
}
if(((az >= 90 && az <= 270) || az <= -90) && b > 0)
{
b = b * -1;
}
if(((az >= 0 && az <= 180) || az <= - 180) && az > 0)
{
a = a * -1;
}
x = a;
y = b;
z = c;*/
}
void cameraMemory::getCamTargetedCoords(float &x, float &y, float &z, float range)
{
/*Scripting::Camera cam;
float cx, cy, cz;
float ax, ay, az;
float a, b, c;
Scripting::GetGameCam(&cam);
Scripting::GetCamPos(cam, &cx, &cy, &cz);
Scripting::GetCamRot(cam, &ax, &ay, &az);
getTarget(ax, az, a, b, c, range);
x = a + cx;
y = b + cy;
z = c + cz;*/
Scripting::Camera cam;
float cx, cy, cz;
float ax, ay, az;
//float a, b, c;
Scripting::GetGameCam(&cam);
Scripting::GetCamPos(cam, &cx, &cy, &cz);
Scripting::GetCamRot(cam, &ax, &ay, &az);
float tZ = az * 0.01745f;
float tX = ax * 0.01745f;
float absX = abs(cos(tX));
x = cx + (-sin(tZ) * absX) * range;
y = cy + (cos(tZ) * absX) * range;
z = cz + (sin(tX) * range);
}
void cameraMemory::populateCamera(std::vector<simpleMath::Vector3>& vec, size_t range)
{
Scripting::Camera cam;
float cx, cy, cz;
float ax, ay, az;
//float a, b, c;
Scripting::GetGameCam(&cam);
Scripting::GetCamPos(cam, &cx, &cy, &cz);
Scripting::GetCamRot(cam, &ax, &ay, &az);
float tZ = az * 0.01745f;
float tX = ax * 0.01745f;
float absX = abs(cos(tX));
for(size_t k = 1; k < range + 5; k++)
{
//getTarget(ax, az, a, b, c, (float)range);
//vec.push_back(simpleMath::Vector3(a + cx, b + cy, c + cz));
vec.push_back(simpleMath::Vector3(cx + (-sin(tZ) * absX) * k, cy + (cos(tZ) * absX) * k, cz + (sin(tX)) * k));
}
}
| 24.351648
| 112
| 0.556408
|
WuskieFTW1113
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.