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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
952a3563cf948c4b22142babed8fe5ecfe16cd60
| 341
|
cpp
|
C++
|
src/frontg8/error.cpp
|
frontg8/frontg8lib
|
c1c6a436ae6ddd6ad15b0270ac233cd9d19f33d8
|
[
"BSD-3-Clause"
] | 3
|
2016-08-29T09:17:57.000Z
|
2016-10-18T05:01:25.000Z
|
src/frontg8/error.cpp
|
frontg8/frontg8lib
|
c1c6a436ae6ddd6ad15b0270ac233cd9d19f33d8
|
[
"BSD-3-Clause"
] | null | null | null |
src/frontg8/error.cpp
|
frontg8/frontg8lib
|
c1c6a436ae6ddd6ad15b0270ac233cd9d19f33d8
|
[
"BSD-3-Clause"
] | null | null | null |
#include "impl/error.hpp"
#include "frontg8/error.h"
extern "C"
{
FG8_DLL_EXPORT char const * fg8_error_message(fg8_error_t const error)
{
if(error)
{
return error->message.c_str();
}
return NULL;
}
FG8_DLL_EXPORT void fg8_error_destroy(fg8_error_t const error)
{
delete error;
}
}
| 14.826087
| 72
| 0.627566
|
frontg8
|
952cbc7eb26169d59db76921164bf6e0e80be9be
| 9,238
|
cpp
|
C++
|
test/decompiler/test_FormExpressionBuild2.cpp
|
joegoldin/jak-project
|
9969445cf78b43745b5910a2b09dbe6672f0ec92
|
[
"0BSD"
] | null | null | null |
test/decompiler/test_FormExpressionBuild2.cpp
|
joegoldin/jak-project
|
9969445cf78b43745b5910a2b09dbe6672f0ec92
|
[
"0BSD"
] | null | null | null |
test/decompiler/test_FormExpressionBuild2.cpp
|
joegoldin/jak-project
|
9969445cf78b43745b5910a2b09dbe6672f0ec92
|
[
"0BSD"
] | null | null | null |
#include "gtest/gtest.h"
#include "FormRegressionTest.h"
using namespace decompiler;
// tests stack variables
TEST_F(FormRegressionTest, MatrixPMult) {
std::string func =
"sll r0, r0, 0\n"
" daddiu sp, sp, -112\n"
" sd ra, 0(sp)\n"
" sq s5, 80(sp)\n"
" sq gp, 96(sp)\n"
" or gp, a0, r0\n"
" daddiu s5, sp, 16\n"
" sq r0, 0(s5)\n"
" sq r0, 16(s5)\n"
" sq r0, 32(s5)\n"
" sq r0, 48(s5)\n"
" lw t9, matrix*!(s7)\n"
" or a0, s5, r0\n"
" jalr ra, t9\n"
" sll v0, ra, 0\n"
" lq v1, 0(s5)\n"
" sq v1, 0(gp)\n"
" lq v1, 16(s5)\n"
" sq v1, 16(gp)\n"
" lq v1, 32(s5)\n"
" sq v1, 32(gp)\n"
" lq v1, 48(s5)\n"
" sq v1, 48(gp)\n"
" or v0, gp, r0\n"
" ld ra, 0(sp)\n"
" lq gp, 96(sp)\n"
" lq s5, 80(sp)\n"
" jr ra\n"
" daddiu sp, sp, 112";
std::string type = "(function matrix matrix matrix matrix)";
std::string expected =
"(begin\n"
" (let ((s5-0 (new (quote stack) (quote matrix))))\n"
" (set! (-> s5-0 vector 0 quad) (the-as uint128 0))\n"
" (set! (-> s5-0 vector 1 quad) (the-as uint128 0))\n"
" (set! (-> s5-0 vector 2 quad) (the-as uint128 0))\n"
" (set! (-> s5-0 vector 3 quad) (the-as uint128 0))\n"
" (matrix*! s5-0 arg1 arg2)\n"
" (set! (-> arg0 vector 0 quad) (-> s5-0 vector 0 quad))\n"
" (set! (-> arg0 vector 1 quad) (-> s5-0 vector 1 quad))\n"
" (set! (-> arg0 vector 2 quad) (-> s5-0 vector 2 quad))\n"
" (set! (-> arg0 vector 3 quad) (-> s5-0 vector 3 quad))\n"
" )\n"
" arg0\n"
" )";
test_with_stack_vars(func, type, expected,
"[\n"
" [16, \"matrix\"]\n"
" ]");
}
// TODO- this should also work without the cast, but be uglier.
TEST_F(FormRegressionTest, VectorXQuaternionWithCast) {
std::string func =
"sll r0, r0, 0\n"
" daddiu sp, sp, -112\n"
" sd ra, 0(sp)\n"
" sq s5, 80(sp)\n"
" sq gp, 96(sp)\n"
" or gp, a0, r0\n"
" daddiu s5, sp, 16\n"
" sq r0, 0(s5)\n"
" sq r0, 16(s5)\n"
" sq r0, 32(s5)\n"
" sq r0, 48(s5)\n"
" lw t9, quaternion->matrix(s7)\n"
" or a0, s5, r0\n"
" jalr ra, t9\n"
" sll v0, ra, 0\n"
" daddu v1, r0, s5\n"
" lq v1, 0(v1)\n"
" sq v1, 0(gp)\n"
" or v0, gp, r0\n"
" ld ra, 0(sp)\n"
" lq gp, 96(sp)\n"
" lq s5, 80(sp)\n"
" jr ra\n"
" daddiu sp, sp, 112";
std::string type = "(function quaternion quaternion quaternion)";
std::string expected =
"(begin\n"
" (let ((s5-0 (new (quote stack) (quote matrix))))\n"
" (set! (-> s5-0 vector 0 quad) (the-as uint128 0))\n"
" (set! (-> s5-0 vector 1 quad) (the-as uint128 0))\n"
" (set! (-> s5-0 vector 2 quad) (the-as uint128 0))\n"
" (set! (-> s5-0 vector 3 quad) (the-as uint128 0))\n"
" (quaternion->matrix s5-0 arg1)\n"
" (set! (-> arg0 vec quad) (-> (the-as (pointer uint128) (-> s5-0 data)) 0))\n"
" )\n"
" arg0\n"
" )";
test_with_stack_vars(func, type, expected,
"[\n"
" [16, \"matrix\"]\n"
" ]",
"[[10, \"v1\", \"(pointer uint128)\"]]");
}
TEST_F(FormRegressionTest, EliminateFloatDeadSet) {
std::string func =
"sll r0, r0, 0\n"
"L32:\n"
" daddiu sp, sp, -16\n"
" sd fp, 8(sp)\n"
" or fp, t9, r0\n"
" lwu v1, 4(a0)\n"
" mtc1 f0, v1\n"
" cvt.s.w f1, f0\n"
//" lwc1 f0, L83(fp)\n"
" mtc1 f0, r0\n"
" lw a1, *display*(s7)\n"
" ld a1, 780(a1)\n"
" divu a1, v1\n"
" mfhi v1\n"
" mtc1 f2, v1\n"
" cvt.s.w f2, f2\n"
" lwc1 f3, 0(a0)\n"
" add.s f2, f2, f3\n"
" div.s f3, f2, f1\n"
" cvt.w.s f3, f3\n"
" cvt.s.w f3, f3\n"
" mul.s f3, f3, f1\n"
" sub.s f2, f2, f3\n"
" div.s f1, f2, f1\n"
" mul.s f0, f0, f1\n"
//" lwc1 f1, L84(fp)\n"
" mtc1 f1, r0\n"
//" lwc1 f2, L83(fp)\n"
" mtc1 f2, r0\n"
" lwc1 f3, 12(a0)\n"
" mul.s f2, f2, f3\n"
" sub.s f1, f1, f2\n"
//" lwc1 f2, L84(fp)\n"
" mtc1 f2, r0\n"
//" lwc1 f3, L83(fp)\n"
" mtc1 f3, r0\n"
" lwc1 f4, 8(a0)\n"
" mul.s f3, f3, f4\n"
" sub.s f2, f2, f3\n"
//" lwc1 f3, L84(fp)\n"
" mtc1 f3, r0\n"
" add.s f3, f3, f1\n"
" c.lt.s f0, f3\n"
" bc1t L33\n"
" sll r0, r0, 0\n"
" mtc1 f0, r0\n"
" mfc1 v1, f0\n"
" beq r0, r0, L36\n"
" sll r0, r0, 0\n"
"L33:\n"
//" lwc1 f3, L84(fp)\n"e
" mtc1 f3, r0\n"
" c.lt.s f3, f0\n"
" bc1f L34\n"
" sll r0, r0, 0\n"
//" lwc1 f2, L84(fp)\n"
" mtc1 f2, r0\n"
//" lwc1 f3, L82(fp)\n"
" mtc1 f3, r0\n"
" add.s f0, f3, f0\n"
" div.s f0, f0, f1\n"
" sub.s f0, f2, f0\n"
" mfc1 v1, f0\n"
" beq r0, r0, L36\n"
" sll r0, r0, 0\n"
"L34:\n"
" c.lt.s f0, f2\n"
" bc1t L35\n"
" sll r0, r0, 0\n"
//" lwc1 f0, L84(fp)\n"
" mtc1 f0, r0\n"
" mfc1 v1, f0\n"
" beq r0, r0, L36\n"
" sll r0, r0, 0\n"
"L35:\n"
" div.s f0, f0, f2\n"
" mfc1 v1, f0\n"
"L36:\n"
" mfc1 v0, f0\n"
" ld fp, 8(sp)\n"
" jr ra\n"
" daddiu sp, sp, 16";
std::string type = "(function sync-info-paused float)";
std::string expected =
"(let* ((v1-0 (-> arg0 period))\n"
" (f1-0 (the float v1-0))\n"
" (f0-1 0.0)\n"
" (f2-2\n"
" (+\n"
" (the float (mod (-> *display* base-frame-counter) v1-0))\n"
" (-> arg0 offset)\n"
" )\n"
" )\n"
" (f0-2\n"
" (* f0-1 (/ (- f2-2 (* (the float (the int (/ f2-2 f1-0))) f1-0)) f1-0))\n"
" )\n"
" (f1-3 (- 0.0 (* 0.0 (-> arg0 pause-after-in))))\n"
" (f2-7 (- 0.0 (* 0.0 (-> arg0 pause-after-out))))\n"
" )\n"
" (cond\n"
" ((>= f0-2 (+ 0.0 f1-3))\n"
" 0.0\n"
" )\n"
" ((< 0.0 f0-2)\n"
" (- 0.0 (/ (+ 0.0 f0-2) f1-3))\n"
" )\n"
" ((>= f0-2 f2-7)\n"
" 0.0\n"
" )\n"
" (else\n"
" (/ f0-2 f2-7)\n"
" )\n"
" )\n"
" )";
test_with_stack_vars(func, type, expected, "[]");
}
TEST_F(FormRegressionTest, IterateProcessTree) {
std::string func =
"sll r0, r0, 0\n"
" daddiu sp, sp, -80\n"
" sd ra, 0(sp)\n"
" sq s3, 16(sp)\n"
" sq s4, 32(sp)\n"
" sq s5, 48(sp)\n"
" sq gp, 64(sp)\n"
" or s3, a0, r0\n"
" or gp, a1, r0\n"
" or s5, a2, r0\n"
" lwu v1, 4(s3)\n"
" andi v1, v1, 256\n"
" bnel v1, r0, L113\n"
" daddiu s4, s7, 8\n"
" or t9, gp, r0\n"
" or a0, s3, r0\n"
" jalr ra, t9\n"
" sll v0, ra, 0\n"
" or s4, v0, r0\n"
"L113:\n"
" daddiu v1, s7, dead\n"
" bne s4, v1, L114\n"
" sll r0, r0, 0\n"
" or v1, s7, r0\n"
" beq r0, r0, L117\n"
" sll r0, r0, 0\n"
"L114:\n"
" lwu v1, 16(s3)\n"
" beq r0, r0, L116\n"
" sll r0, r0, 0\n"
"L115:\n"
" lwu a0, 0(v1)\n"
" lwu s3, 12(a0)\n"
" lw t9, iterate-process-tree(s7)\n"
" lwu a0, 0(v1)\n"
" or a1, gp, r0\n"
" or a2, s5, r0\n"
" jalr ra, t9\n"
" sll v0, ra, 0\n"
" or v1, s3, r0\n"
" or a0, v1, r0\n"
"L116:\n"
" bne s7, v1, L115\n"
" sll r0, r0, 0\n"
" or v1, s7, r0\n"
"L117:\n"
" or v0, s4, r0\n"
" ld ra, 0(sp)\n"
" lq gp, 64(sp)\n"
" lq s5, 48(sp)\n"
" lq s4, 32(sp)\n"
" lq s3, 16(sp)\n"
" jr ra\n"
" daddiu sp, sp, 80";
std::string type = "(function process-tree (function object object) kernel-context object)";
std::string expected =
"(let ((s4-0 (or (nonzero? (logand (-> arg0 mask) 256)) (arg1 arg0))))\n"
" (cond\n"
" ((= s4-0 (quote dead))\n"
" )\n"
" (else\n"
" (let ((v1-4 (-> arg0 child)))\n"
" (while v1-4\n"
" (let ((s3-1 (-> v1-4 0 brother)))\n"
" (iterate-process-tree (-> v1-4 0) arg1 arg2)\n"
" (set! v1-4 s3-1)\n"
" )\n"
" )\n"
" )\n"
" )\n"
" )\n"
" s4-0\n"
" )";
test_with_stack_vars(func, type, expected, "[]");
}
| 28.164634
| 94
| 0.38688
|
joegoldin
|
95327f0344b50e233bd4726c36c37b26d2e6fe74
| 5,608
|
cc
|
C++
|
tests/client.cc
|
kborkows/libiqxmlrpc
|
046ac8a55b1b674f7406442dee533e1ecbfbb88d
|
[
"BSD-2-Clause"
] | null | null | null |
tests/client.cc
|
kborkows/libiqxmlrpc
|
046ac8a55b1b674f7406442dee533e1ecbfbb88d
|
[
"BSD-2-Clause"
] | null | null | null |
tests/client.cc
|
kborkows/libiqxmlrpc
|
046ac8a55b1b674f7406442dee533e1ecbfbb88d
|
[
"BSD-2-Clause"
] | null | null | null |
#define BOOST_TEST_MODULE test_client
#include <stdlib.h>
#include <openssl/md5.h>
#include <iostream>
#include <memory>
#include <boost/test/test_tools.hpp>
#include <boost/test/unit_test.hpp>
#include "libiqxmlrpc/libiqxmlrpc.h"
#include "libiqxmlrpc/http_client.h"
#include "libiqxmlrpc/http_errors.h"
#include "client_common.h"
#include "client_opts.h"
#if defined(WIN32)
#include <winsock2.h>
#endif
using namespace boost::unit_test;
using namespace iqxmlrpc;
// Global
Client_opts test_config;
Client_base* test_client = 0;
class ClientFixture {
public:
ClientFixture()
{
#if defined(WIN32)
WORD wVersionRequested;
WSADATA wsaData;
wVersionRequested = MAKEWORD(2, 2);
WSAStartup(wVersionRequested, &wsaData);
#endif
int argc = boost::unit_test::framework::master_test_suite().argc;
char** argv = boost::unit_test::framework::master_test_suite().argv;
test_config.configure(argc, argv);
test_client = test_config.create_instance();
}
};
BOOST_GLOBAL_FIXTURE( ClientFixture );
BOOST_AUTO_TEST_CASE( introspection_test )
{
BOOST_REQUIRE(test_client);
Introspection_proxy introspect(test_client);
Response retval( introspect() );
BOOST_REQUIRE_MESSAGE(!retval.is_fault(), retval.fault_string());
BOOST_TEST_MESSAGE("system.listMethods output:");
const Value& v = retval.value();
for (Array::const_iterator i = v.arr_begin(); i != v.arr_end(); ++i)
{
BOOST_TEST_MESSAGE("\t" + i->get_string());
}
}
BOOST_AUTO_TEST_CASE( auth_test )
{
BOOST_REQUIRE(test_client);
BOOST_CHECKPOINT("Successful authorization");
test_client->set_authinfo("goodman", "loooooooooooooooooongpaaaaaaaaaaaassssswwwwwwoooooord");
Response retval( test_client->execute("echo_user", 0) );
BOOST_CHECK( !retval.is_fault() );
BOOST_CHECK_EQUAL( retval.value().get_string(), "goodman" );
try {
BOOST_CHECKPOINT("Unsuccessful authorization");
test_client->set_authinfo("badman", "");
retval = test_client->execute("echo_user", 0);
} catch (const iqxmlrpc::http::Error_response& e) {
BOOST_CHECK_EQUAL(e.response_header()->code(), 401);
test_client->set_authinfo("", "");
return;
}
test_client->set_authinfo("", "");
BOOST_ERROR("'401 Unauthrozied' required");
}
BOOST_AUTO_TEST_CASE( echo_test )
{
BOOST_REQUIRE(test_client);
Echo_proxy echo(test_client);
Response retval(echo("Hello"));
BOOST_CHECK(retval.value().get_string() == "Hello");
}
BOOST_AUTO_TEST_CASE( error_method_test )
{
BOOST_REQUIRE(test_client);
Error_proxy err(test_client);
Response retval(err(""));
BOOST_CHECK(retval.is_fault());
BOOST_CHECK(retval.fault_code() == 123 && retval.fault_string() == "My fault");
}
BOOST_AUTO_TEST_CASE( get_file_test )
{
BOOST_REQUIRE(test_client);
Get_file_proxy get_file(test_client);
Response retval( get_file(1024*1024*10) ); // request 10Mb
const Value& v = retval.value();
const Binary_data& d = v["data"];
const Binary_data& m = v["md5"];
typedef const unsigned char md5char;
typedef const char strchar;
unsigned char md5[16];
MD5(reinterpret_cast<md5char*>(d.get_data().data()),
d.get_data().length(), md5);
std::auto_ptr<Binary_data> gen_md5( Binary_data::from_data(
reinterpret_cast<strchar*>(md5), sizeof(md5)) );
BOOST_TEST_MESSAGE("Recieved MD5: " + m.get_base64());
BOOST_TEST_MESSAGE("Calculated MD5: " + gen_md5->get_base64());
// "TODO: Binary_data::operator ==(const Binary_data&)");
BOOST_CHECK(gen_md5->get_base64() == m.get_base64());
}
BOOST_AUTO_TEST_CASE( stop_server )
{
if (!test_config.stop_server())
return;
BOOST_REQUIRE(test_client);
Stop_server_proxy stop(test_client);
try {
stop();
} catch (const iqnet::network_error&) {}
}
BOOST_AUTO_TEST_CASE( trace_all ) {
BOOST_REQUIRE(test_client);
XHeaders h;
h["X-Correlation-ID"] = "123";
h["X-Span-ID"] = "456";
test_client->set_xheaders(h);
Trace_proxy trace(test_client);
Response retval(trace(""));
BOOST_CHECK(retval.value().get_string() == "123456");
}
BOOST_AUTO_TEST_CASE( trace_all_exec ) {
BOOST_REQUIRE(test_client);
XHeaders h;
h["X-Correlation-ID"] = "580";
h["X-Span-ID"] = "111";
Trace_proxy trace(test_client);
Response retval(trace("", h));
BOOST_CHECK(retval.value().get_string() == "580111");
}
BOOST_AUTO_TEST_CASE( trace_all_exec_override ) {
BOOST_REQUIRE(test_client);
XHeaders gh;
gh["X-Correlation-ID"] = "123";
gh["X-Span-ID"] = "456";
test_client->set_xheaders(gh);
XHeaders h;
h["X-Span-ID"] = "111";
Trace_proxy trace(test_client);
Response retval(trace("", h));
BOOST_CHECK(retval.value().get_string() == "123111");
}
BOOST_AUTO_TEST_CASE( trace_corr ) {
BOOST_REQUIRE(test_client);
XHeaders h;
h["X-Correlation-ID"] = "123";
test_client->set_xheaders(h);
Trace_proxy trace(test_client);
Response retval(trace(""));
BOOST_CHECK(retval.value().get_string() == "123");
}
BOOST_AUTO_TEST_CASE( trace_span ) {
BOOST_REQUIRE(test_client);
XHeaders h;
h["X-Span-ID"] = "456";
test_client->set_xheaders(h);
Trace_proxy trace(test_client);
Response retval(trace(""));
BOOST_CHECK(retval.value().get_string() == "456");
}
BOOST_AUTO_TEST_CASE( trace_no ) {
BOOST_REQUIRE(test_client);
test_client->set_xheaders(XHeaders());
Trace_proxy trace(test_client);
Response retval(trace(""));
BOOST_CHECK(retval.value().get_string() == "");
}
BOOST_AUTO_TEST_CASE( trace_empty ) {
BOOST_REQUIRE(test_client);
Trace_proxy trace(test_client);
Response retval(trace(""));
BOOST_CHECK(retval.value().get_string() == "");
}
// vim:ts=2:sw=2:et
| 26.832536
| 96
| 0.709522
|
kborkows
|
953511a713690c1077b6f8891cdbe53b0f124127
| 9,760
|
cpp
|
C++
|
jme3-bullet-native/src/native/cpp/jmePhysicsSpace.cpp
|
MeFisto94/test-bot-1
|
c761210e199fc2e3cae5db0b2fbf13043d8d4b48
|
[
"BSD-3-Clause"
] | 3
|
2020-11-08T14:55:48.000Z
|
2021-09-28T08:33:26.000Z
|
jme3-bullet-native/src/native/cpp/jmePhysicsSpace.cpp
|
MeFisto94/test-bot-1
|
c761210e199fc2e3cae5db0b2fbf13043d8d4b48
|
[
"BSD-3-Clause"
] | 2
|
2020-09-24T22:09:36.000Z
|
2020-09-24T22:29:30.000Z
|
jme3-bullet-native/src/native/cpp/jmePhysicsSpace.cpp
|
Akshita-tewatia/jmonkeyengine
|
ff4b8d6a3b953a6899e31b787cb91094bced9ae6
|
[
"BSD-3-Clause"
] | 1
|
2017-08-31T15:17:31.000Z
|
2017-08-31T15:17:31.000Z
|
/*
* Copyright (c) 2009-2019 jMonkeyEngine
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'jMonkeyEngine' nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "jmePhysicsSpace.h"
#include "jmeBulletUtil.h"
/**
* Author: Normen Hansen
*/
jmePhysicsSpace::jmePhysicsSpace(JNIEnv* env, jobject javaSpace) {
//TODO: global ref? maybe not -> cleaning, rather callback class?
this->javaPhysicsSpace = env->NewWeakGlobalRef(javaSpace);
this->env = env;
env->GetJavaVM(&vm);
if (env->ExceptionCheck()) {
env->Throw(env->ExceptionOccurred());
return;
}
}
void jmePhysicsSpace::attachThread() {
#ifdef ANDROID
vm->AttachCurrentThread((JNIEnv**) &env, NULL);
#elif defined (JNI_VERSION_1_2)
vm->AttachCurrentThread((void**) &env, NULL);
#else
vm->AttachCurrentThread(&env, NULL);
#endif
}
JNIEnv* jmePhysicsSpace::getEnv() {
attachThread();
return this->env;
}
void jmePhysicsSpace::stepSimulation(jfloat tpf, jint maxSteps, jfloat accuracy) {
dynamicsWorld->stepSimulation(tpf, maxSteps, accuracy);
}
void jmePhysicsSpace::createPhysicsSpace(jfloat minX, jfloat minY, jfloat minZ, jfloat maxX, jfloat maxY, jfloat maxZ, jint broadphaseId, jboolean threading /*unused*/) {
btCollisionConfiguration* collisionConfiguration = new btDefaultCollisionConfiguration();
btVector3 min = btVector3(minX, minY, minZ);
btVector3 max = btVector3(maxX, maxY, maxZ);
btBroadphaseInterface* broadphase;
switch (broadphaseId) {
case 0: // SIMPLE
broadphase = new btSimpleBroadphase();
break;
case 1: // AXIS_SWEEP_3
broadphase = new btAxisSweep3(min, max);
break;
case 2: // AXIS_SWEEP_3_32
broadphase = new bt32BitAxisSweep3(min, max);
break;
case 3: // DBVT
broadphase = new btDbvtBroadphase();
break;
}
btCollisionDispatcher* dispatcher = new btCollisionDispatcher(collisionConfiguration);
btGImpactCollisionAlgorithm::registerAlgorithm(dispatcher);
btConstraintSolver* solver = new btSequentialImpulseConstraintSolver();
//create dynamics world
btDiscreteDynamicsWorld* world = new btDiscreteDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration);
dynamicsWorld = world;
dynamicsWorld->setWorldUserInfo(this);
broadphase->getOverlappingPairCache()->setInternalGhostPairCallback(new btGhostPairCallback());
dynamicsWorld->setGravity(btVector3(0, -9.81f, 0));
struct jmeFilterCallback : public btOverlapFilterCallback {
// return true when pairs need collision
virtual bool needBroadphaseCollision(btBroadphaseProxy* proxy0, btBroadphaseProxy * proxy1) const {
// bool collides = (proxy0->m_collisionFilterGroup & proxy1->m_collisionFilterMask) != 0;
// collides = collides && (proxy1->m_collisionFilterGroup & proxy0->m_collisionFilterMask);
bool collides = (proxy0->m_collisionFilterGroup & proxy1->m_collisionFilterMask) != 0;
collides = collides && (proxy1->m_collisionFilterGroup & proxy0->m_collisionFilterMask);
if (collides) {
btCollisionObject* co0 = (btCollisionObject*) proxy0->m_clientObject;
btCollisionObject* co1 = (btCollisionObject*) proxy1->m_clientObject;
jmeUserPointer *up0 = (jmeUserPointer*) co0 -> getUserPointer();
jmeUserPointer *up1 = (jmeUserPointer*) co1 -> getUserPointer();
if (up0 != NULL && up1 != NULL) {
collides = (up0->group & up1->groups) != 0 || (up1->group & up0->groups) != 0;
if(collides){
jmePhysicsSpace *dynamicsWorld = (jmePhysicsSpace *)up0->space;
JNIEnv* env = dynamicsWorld->getEnv();
jobject javaPhysicsSpace = env->NewLocalRef(dynamicsWorld->getJavaPhysicsSpace());
jobject javaCollisionObject0 = env->NewLocalRef(up0->javaCollisionObject);
jobject javaCollisionObject1 = env->NewLocalRef(up1->javaCollisionObject);
jboolean notifyResult = env->CallBooleanMethod(javaPhysicsSpace, jmeClasses::PhysicsSpace_notifyCollisionGroupListeners, javaCollisionObject0, javaCollisionObject1);
env->DeleteLocalRef(javaPhysicsSpace);
env->DeleteLocalRef(javaCollisionObject0);
env->DeleteLocalRef(javaCollisionObject1);
if (env->ExceptionCheck()) {
env->Throw(env->ExceptionOccurred());
return collides;
}
collides = (bool) notifyResult;
}
//add some additional logic here that modified 'collides'
return collides;
}
return false;
}
return collides;
}
};
dynamicsWorld->getPairCache()->setOverlapFilterCallback(new jmeFilterCallback());
dynamicsWorld->setInternalTickCallback(&jmePhysicsSpace::preTickCallback, static_cast<void *> (this), true);
dynamicsWorld->setInternalTickCallback(&jmePhysicsSpace::postTickCallback, static_cast<void *> (this));
if (gContactStartedCallback == NULL) {
gContactStartedCallback = &jmePhysicsSpace::contactStartedCallback;
}
}
void jmePhysicsSpace::preTickCallback(btDynamicsWorld *world, btScalar timeStep) {
jmePhysicsSpace* dynamicsWorld = (jmePhysicsSpace*) world->getWorldUserInfo();
JNIEnv* env = dynamicsWorld->getEnv();
jobject javaPhysicsSpace = env->NewLocalRef(dynamicsWorld->getJavaPhysicsSpace());
if (javaPhysicsSpace != NULL) {
env->CallVoidMethod(javaPhysicsSpace, jmeClasses::PhysicsSpace_preTick, timeStep);
env->DeleteLocalRef(javaPhysicsSpace);
if (env->ExceptionCheck()) {
env->Throw(env->ExceptionOccurred());
return;
}
}
}
void jmePhysicsSpace::postTickCallback(btDynamicsWorld *world, btScalar timeStep) {
jmePhysicsSpace* dynamicsWorld = (jmePhysicsSpace*) world->getWorldUserInfo();
JNIEnv* env = dynamicsWorld->getEnv();
jobject javaPhysicsSpace = env->NewLocalRef(dynamicsWorld->getJavaPhysicsSpace());
if (javaPhysicsSpace != NULL) {
env->CallVoidMethod(javaPhysicsSpace, jmeClasses::PhysicsSpace_postTick, timeStep);
env->DeleteLocalRef(javaPhysicsSpace);
if (env->ExceptionCheck()) {
env->Throw(env->ExceptionOccurred());
return;
}
}
}
void jmePhysicsSpace::contactStartedCallback(btPersistentManifold* const &pm) {
const btCollisionObject* co0 = pm->getBody0();
const btCollisionObject* co1 = pm->getBody1();
jmeUserPointer *up0 = (jmeUserPointer*) co0 -> getUserPointer();
jmeUserPointer *up1 = (jmeUserPointer*) co1 -> getUserPointer();
if (up0 != NULL) {
jmePhysicsSpace *dynamicsWorld = (jmePhysicsSpace *)up0->space;
if (dynamicsWorld != NULL) {
JNIEnv* env = dynamicsWorld->getEnv();
jobject javaPhysicsSpace = env->NewLocalRef(dynamicsWorld->getJavaPhysicsSpace());
if (javaPhysicsSpace != NULL) {
jobject javaCollisionObject0 = env->NewLocalRef(up0->javaCollisionObject);
jobject javaCollisionObject1 = env->NewLocalRef(up1->javaCollisionObject);
for(int i=0;i<pm->getNumContacts();i++){
env->CallVoidMethod(javaPhysicsSpace, jmeClasses::PhysicsSpace_addCollisionEvent, javaCollisionObject0, javaCollisionObject1, (jlong) & pm->getContactPoint(i));
if (env->ExceptionCheck()) {
env->Throw(env->ExceptionOccurred());
}
}
env->DeleteLocalRef(javaPhysicsSpace);
env->DeleteLocalRef(javaCollisionObject0);
env->DeleteLocalRef(javaCollisionObject1);
}
}
}
}
btDynamicsWorld* jmePhysicsSpace::getDynamicsWorld() {
return dynamicsWorld;
}
jobject jmePhysicsSpace::getJavaPhysicsSpace() {
return javaPhysicsSpace;
}
jmePhysicsSpace::~jmePhysicsSpace() {
delete(dynamicsWorld);
}
| 43.766816
| 189
| 0.665984
|
MeFisto94
|
95388ef254ece677e4b85484eb47258c1b9b592a
| 931
|
cpp
|
C++
|
codes/TEAMSCODE/2020/TC_MOCK/2/9.cpp
|
chessbot108/solved-problems
|
0945be829a8ea9f0d5896c89331460d70d076691
|
[
"MIT"
] | 2
|
2021-03-07T03:34:02.000Z
|
2021-03-09T01:22:21.000Z
|
codes/TEAMSCODE/2020/TC_MOCK/2/9.cpp
|
chessbot108/solved-problems
|
0945be829a8ea9f0d5896c89331460d70d076691
|
[
"MIT"
] | 1
|
2021-03-27T15:01:23.000Z
|
2021-03-27T15:55:34.000Z
|
codes/TEAMSCODE/2020/TC_MOCK/2/9.cpp
|
chessbot108/solved-problems
|
0945be829a8ea9f0d5896c89331460d70d076691
|
[
"MIT"
] | 1
|
2021-03-27T05:02:33.000Z
|
2021-03-27T05:02:33.000Z
|
//code by daniel. aaron worked on this, but daniel's code was much cleaner
#include <iostream>
#include <vector>
using namespace std;
string s1, s2;
string multiply(){
int len1 = s1.length();
int len2 = s2.length();
if (len1 == 0 || len2 == 0){
return "0";
}
vector<int> v(len1 + len2, 0);
int i1 = 0;
int i2 = 0;
for (int i = len1 - 1; i >= 0; i--){
int carry = 0;
int n1 = s1[i] - '0';
i2 = 0;
for (int j = len2 - 1; j >= 0; j--){
int n2 = s2[j] - '0';
int sum = n1*n2 + v[i1 + i2] + carry;
carry = sum/10;
v[i1 + i2] = sum % 10;
i2++;
}
v[i1 + i2] += carry;
i1++;
}
int i = v.size() - 1;
while (i >= 0 && v[i] == 0){
i--;
}
if (i == -1){
return "0";
}
string ret = "";
while (i >= 0){
ret += to_string(v[i--]);
}
return ret;
}
int main(){
cin >> s1 >> s2;
cout << multiply() << endl;
return 0;
}
| 14.777778
| 74
| 0.459721
|
chessbot108
|
9541c1871a6635bb284608e103d81e3fd8c2e37a
| 3,316
|
cc
|
C++
|
code/SuffixArray_new.cc
|
tulsyan/ACM-ICPC-Handbook
|
fbadfd66017991d264071af3f2fa8e050e4f8e40
|
[
"MIT"
] | 32
|
2017-12-24T20:00:47.000Z
|
2021-04-09T14:53:25.000Z
|
code/SuffixArray_new.cc
|
Zindastart/ACM-ICPC-Handbook
|
fbadfd66017991d264071af3f2fa8e050e4f8e40
|
[
"MIT"
] | null | null | null |
code/SuffixArray_new.cc
|
Zindastart/ACM-ICPC-Handbook
|
fbadfd66017991d264071af3f2fa8e050e4f8e40
|
[
"MIT"
] | 16
|
2017-12-13T14:35:27.000Z
|
2021-12-24T04:40:32.000Z
|
// Begins Suffix Arrays implementation
// O(n log n) - Manber and Myers algorithm
// SA = The suffix array. Contains the n suffixes of txt sorted in lexicographical order.
// Each suffix is represented as a single integer (the SAition of txt where it starts).
// iSA = The inverse of the suffix array. iSA[i] = the index of the suffix txt[i..n)
// in the SA array. (In other words, SA[i] = k <==> iSA[k] = i)
// With this array, you can compare two suffixes in O(1): Suffix txt[i..n) is smaller
// than txt[j..n) if and only if iSA[i] < iSA[j]
const int MAX = 1000100;
char txt[MAX]; //input
int iSA[MAX], SA[MAX]; //output
int cnt[MAX];
int nex[MAX]; //internal
bool bh[MAX], b2h[MAX];
// Compares two suffixes according to their first characters
bool smaller_first_char(int a, int b){
return txt[a] < txt[b];
}
void suffixSort(int n){
//sort suffixes according to their first characters
for (int i=0; i<n; ++i){
SA[i] = i;
}
sort(SA, SA + n, smaller_first_char);
//{SA contains the list of suffixes sorted by their first character}
for (int i=0; i<n; ++i){
bh[i] = i == 0 || txt[SA[i]] != txt[SA[i-1]];
b2h[i] = false;
}
for (int h = 1; h < n; h <<= 1){
//{bh[i] == false if the first h characters of SA[i-1] == the first h characters of SA[i]}
int buckets = 0;
for (int i=0, j; i < n; i = j){
j = i + 1;
while (j < n && !bh[j]) j++;
nex[i] = j; buckets++;
}
if (buckets == n) break; // We are done! Lucky bastards!
//{suffixes are separted in buckets containing txtings starting with the same h characters}
for (int i = 0; i < n; i = nex[i]){
cnt[i] = 0;
for (int j = i; j < nex[i]; ++j){
iSA[SA[j]] = i;
}
}
cnt[iSA[n - h]]++;
b2h[iSA[n - h]] = true;
for (int i = 0; i < n; i = nex[i]){
for (int j = i; j < nex[i]; ++j){
int s = SA[j] - h;
if (s >= 0){
int head = iSA[s];
iSA[s] = head + cnt[head]++; b2h[iSA[s]] = true;
}
}
for (int j = i; j < nex[i]; ++j){
int s = SA[j] - h;
if (s >= 0 && b2h[iSA[s]]){
for (int k = iSA[s]+1; !bh[k] && b2h[k]; k++) b2h[k] = false;
}
}
}
for (int i=0; i<n; ++i){
SA[iSA[i]] = i; bh[i] |= b2h[i];
}
}
for (int i=0; i<n; ++i)
iSA[SA[i]] = i;
}
// End of suffix array algorithm
// Begin of the O(n) longest common prefix algorithm
// Refer to "Linear-Time Longest-Common-Prefix Computation in Suffix
// Arrays and Its Applications" by Toru Kasai, Gunho Lee, Hiroki
// Arimura, Setsuo Arikawa, and Kunsoo Park.
int lcp[MAX];
// lcp[i] = length of the longest common prefix of suffix SA[i] and suffix SA[i-1]
// lcp[0] = 0
void getlcp(int n)
{
for (int i=0; i<n; ++i)
iSA[SA[i]] = i;
lcp[0] = 0;
for (int i=0, h=0; i<n; ++i) {
if (iSA[i] > 0) {
int j = SA[iSA[i]-1];
while (i + h < n && j + h < n && txt[i+h] == txt[j+h])
h++;
lcp[iSA[i]] = h;
if (h > 0) h--;
}
}
}
// End of longest common prefixes algorithm
int main() {
int len;
// gets(txt);
for(int i = 0; i < 1000000; i++)
txt[i] = 'a';
txt[1000000] = '\0';
len = strlen(txt);
printf("%d",len);
suffixSort(len);
getlcp(len);
return 0;
}
| 28.834783
| 95
| 0.528347
|
tulsyan
|
9542f2fa62e1c13870b3484a6ff2e59dd95a364b
| 1,939
|
cpp
|
C++
|
module04/ex03/main.cpp
|
mathias-mrsn/CPP_modules
|
726bb5bd25f5e366550c79e5f01aed1d3d95c7fc
|
[
"MIT"
] | null | null | null |
module04/ex03/main.cpp
|
mathias-mrsn/CPP_modules
|
726bb5bd25f5e366550c79e5f01aed1d3d95c7fc
|
[
"MIT"
] | null | null | null |
module04/ex03/main.cpp
|
mathias-mrsn/CPP_modules
|
726bb5bd25f5e366550c79e5f01aed1d3d95c7fc
|
[
"MIT"
] | null | null | null |
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mamaurai <mamaurai@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/05/03 10:02:00 by mamaurai #+# #+# */
/* Updated: 2022/05/11 14:06:41 by mamaurai ### ########.fr */
/* */
/* ************************************************************************** */
#include "ICharacter.hpp"
#include "Character.hpp"
#include "AMateria.hpp"
#include "IMateriaSource.hpp"
#include "MateriaSource.hpp"
#include "Ice.hpp"
#include "Cure.hpp"
int main()
{
IMateriaSource* src = new MateriaSource();
src->learnMateria(new Ice());
src->learnMateria(new Cure());
ICharacter* me = new Character("me");
ICharacter* ennemi = new Character("ennemi");
AMateria* tmp;
tmp = src->createMateria("ice");
me->equip(tmp);
me->use(0, *ennemi);
tmp = src->createMateria("cure");
me->equip(tmp);
me->use(1, *ennemi);
tmp = src->createMateria("unknown materia");
me->equip(tmp);
me->use(2, *ennemi);
me->unequip(1);
me->use(1, *ennemi);
IMateriaSource* src2 = new MateriaSource();
src2->learnMateria(new Cure());
src2->learnMateria(new Ice());
me->equip(src2->createMateria("cure"));
me->equip(src2->createMateria("ice"));
std::cout << std::endl;
for (int i = 0; i < NBR_MATERIA; i++)
me->use(i, *ennemi);
delete src2;
delete me;
delete src;
delete ennemi;
AMateria::clean();
return 0;
}
| 29.830769
| 80
| 0.407942
|
mathias-mrsn
|
95454efe95736a10e0c0eb54ae565a60cf4f32a5
| 5,442
|
hpp
|
C++
|
src/ivorium_core/Instancing/Instance.hpp
|
ivorne/ivorium
|
1d876b6dcabe29b3110d3058f997e59c40cd6a2b
|
[
"Apache-2.0"
] | 3
|
2021-02-26T02:59:09.000Z
|
2022-02-08T16:44:21.000Z
|
src/ivorium_core/Instancing/Instance.hpp
|
ivorne/ivorium
|
1d876b6dcabe29b3110d3058f997e59c40cd6a2b
|
[
"Apache-2.0"
] | null | null | null |
src/ivorium_core/Instancing/Instance.hpp
|
ivorne/ivorium
|
1d876b6dcabe29b3110d3058f997e59c40cd6a2b
|
[
"Apache-2.0"
] | null | null | null |
#pragma once
#include "../Basics/LogId.hpp"
#include "../Basics/SrcInfo.hpp"
#include "../Basics/volatile_set.hpp"
#include "../Basics/StringIO_defs.hpp"
#include <unordered_set>
#include <string>
#include <sstream>
#include <type_traits>
#include <vector>
#include <functional>
#include <typeindex>
#include <list>
#include <type_traits>
namespace iv
{
class InstanceSystem;
class DebugInstanceListener;
class SystemContainer;
class instance_ptr_interface;
class ClientMarker;
class TextDebugView;
/**
*/
class Instance
{
public:
//------------------------- structors ------------------------------
Instance( const SystemContainer * sc );
virtual ~Instance( );
Instance * instance(){ return this; }
//------------------------- SystemContainer manipulation -----------
/**
* Returns SystemContainer given in constructor.
* Do not use it directly, only Properties and Components should use this to communicate with systems.
*/
SystemContainer const * getSystemContainer() const;
/**
* SystemContainer of this Instance will be duplicated (to contain the same systems as the original SystemContainer).
* From now on, all children of this Instance will receive the new SystemContainer in the constructor.
* This Instance will still use the old SystemContainer.
* If the SystemContainer is already duplicated, this will just return pointer to it.
* Instance can change which systems are contained in the new SystemContainer (using the pointer returned from this method).
*
* Call SystemContainer::createProxies after/if you create new systems in that SystemContainer.
*/
SystemContainer * duplicateSystemContainer();
/**
Shortcut for getSystemContainer()->getSystem< TypedSystem >().
*/
template< class TypedSystem >
TypedSystem * getSystem() const;
/**
*/
unsigned frame_id() const;
//------------------------- instance introspection --------------------------
/**
Name for introspection purposes.
*/
std::string const & instance_name();
/**
Creates two way relation that is automaticaly cleaned when either Instance is destroyed.
Instance can has only one parent, can be nullptr to clear existing relation.
*/
void instance_parent( Instance * parent );
/**
Usually assigned right after instantiation.
Can be called only once.
This finalizes the Instance instanciation, so the instance is registered to InstanceSystem and debug listeners from this method.
*/
void instance_finalize( std::string const & inst_name, ClientMarker const * root_client );
/**
Called automatically from ClientMarker.
*/
void client_register( ClientMarker const * marker );
void client_unregister( ClientMarker const * marker );
//------------------------- logging --------------------------------
void client_log( ClientMarker const * cm, SrcInfo const & info, LogId id, std::string const & message );
bool client_log_enabled( ClientMarker const * cm, LogId id );
//------------------------- debug access ---------------------------------
void debug_print_clients( TextDebugView * view );
/**
*/
Instance * Debug_Parent();
std::unordered_set< Instance * > const & Debug_Children();
ClientMarker const * Debug_RootClient();
std::unordered_set< ClientMarker const * > const & Debug_Clients();
/**
Helper method, iterates over set returned by DebugClientMarkers(), checks type and casts client if type is equal.
NOTE - currently unsafe - changes to Instance clients (adding or removing) may corrupt iterators used in this method and cause segfault
- should be refactored in future to support some kind of safe listener based approach
*/
template< class TypedClient >
void Debug_ForeachClient( std::function< void( TypedClient * ) > const & lambda );
private:
InstanceSystem * getOS();
private:
//------------------ systems -------------------------------
SystemContainer const * sc;
SystemContainer * sc_dup;
InstanceSystem * os;
//----------------- structure introspection -------------------------------
std::string _instance_name;
Instance * _parent;
std::unordered_set< Instance * > _children;
ClientMarker const * _root_client;
std::unordered_set< ClientMarker const * > _clients;
//------------- debug ----------------------
int _logging_cnt;
//------------- weak pointer impl ----------
friend class instance_ptr_interface;
std::unordered_set< instance_ptr_interface * > instance_pointers;
};
}
#include "SystemContainer.hpp"
#include "InstanceSystem.hpp"
#include "ClientMarker.hpp"
#include "Instance.inl"
| 36.52349
| 143
| 0.564866
|
ivorne
|
954c6b17697851a69064cb4947dde42d3c6fb6ad
| 2,094
|
cpp
|
C++
|
DlgDocGe.cpp
|
RDamman/SpeakerWorkshop
|
87a38d04197a07a9a7878b3f60d5e0706782163c
|
[
"OML"
] | 12
|
2019-06-07T10:06:41.000Z
|
2021-03-22T22:13:59.000Z
|
DlgDocGe.cpp
|
RDamman/SpeakerWorkshop
|
87a38d04197a07a9a7878b3f60d5e0706782163c
|
[
"OML"
] | 1
|
2019-05-09T07:38:12.000Z
|
2019-07-10T04:20:55.000Z
|
DlgDocGe.cpp
|
RDamman/SpeakerWorkshop
|
87a38d04197a07a9a7878b3f60d5e0706782163c
|
[
"OML"
] | 3
|
2020-09-08T08:27:33.000Z
|
2021-05-13T09:25:43.000Z
|
// DlgDocGe.cpp : implementation file
//
#include "stdafx.h"
#include "audtest.h"
#include "DlgDocGe.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CDlgDocGeneral property page
IMPLEMENT_DYNCREATE(CDlgDocGeneral, CPropertyPage)
CDlgDocGeneral::CDlgDocGeneral() : CPropertyPage(CDlgDocGeneral::IDD)
{
//{{AFX_DATA_INIT(CDlgDocGeneral)
m_csDate = _T("");
m_csDescript = _T("");
m_csLastEdit = _T("");
//}}AFX_DATA_INIT
m_pDocument = NULL;
}
CDlgDocGeneral::~CDlgDocGeneral()
{
}
void CDlgDocGeneral::DoDataExchange(CDataExchange* pDX)
{
CPropertyPage::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CDlgDocGeneral)
DDX_Text(pDX, IDC_DATE, m_csDate);
DDX_Text(pDX, IDC_DESCRIPT, m_csDescript);
DDX_Text(pDX, IDC_LASTEDIT, m_csLastEdit);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CDlgDocGeneral, CPropertyPage)
//{{AFX_MSG_MAP(CDlgDocGeneral)
ON_EN_CHANGE(IDC_DESCRIPT, OnChangeDescript)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CDlgDocGeneral message handlers
void CDlgDocGeneral::PostDialog(CAudtestDoc *pDoc)
{
CFolder *proot = pDoc->GetRoot();
if ( proot)
{
CString csold = proot->GetDescription();
if ( csold.Compare( m_csDescript)) // has it changed???
{
proot->SetDescription( m_csDescript);
proot->SetLastEdit();
pDoc->SetModifiedFlag( TRUE);
}
}
}
void CDlgDocGeneral::PreDialog(CAudtestDoc *pDoc)
{
CFolder *proot = pDoc->GetRoot();
m_pDocument = pDoc;
if ( proot)
{
proot->SetDateStrings( m_csDate, m_csLastEdit);
m_csDescript = proot->GetDescription();
}
SetModified( FALSE);
}
void CDlgDocGeneral::OnChangeDescript()
{
SetModified( TRUE);
}
BOOL CDlgDocGeneral::OnApply()
{
// TODO: Add your specialized code here and/or call the base class
if ( m_pDocument)
{
ASSERT( m_pDocument->IsKindOf( RUNTIME_CLASS( CAudtestDoc)));
PostDialog( m_pDocument);
SetModified( FALSE);
}
return CPropertyPage::OnApply();
}
| 19.942857
| 77
| 0.674308
|
RDamman
|
9553172cdf814db84af12100ee8324f8ba0d0472
| 1,879
|
cpp
|
C++
|
Src/MapEditor/vehiclepath.cpp
|
vox-1/MapEditor
|
f1b8a3df64c91e9c3aef7ee21e997f4f1163fa0e
|
[
"MIT"
] | null | null | null |
Src/MapEditor/vehiclepath.cpp
|
vox-1/MapEditor
|
f1b8a3df64c91e9c3aef7ee21e997f4f1163fa0e
|
[
"MIT"
] | null | null | null |
Src/MapEditor/vehiclepath.cpp
|
vox-1/MapEditor
|
f1b8a3df64c91e9c3aef7ee21e997f4f1163fa0e
|
[
"MIT"
] | null | null | null |
#include "stdafx.h"
#include "vehiclepath.h"
using namespace graphic;
using namespace tms;
cVehiclePath::cVehiclePath()
: m_idx(0)
, m_velocity(10)
, m_incTime(0)
, m_initialDirection(0,0,1)
, m_rotTime(0.333f)
{
m_path.reserve(32);
}
cVehiclePath::~cVehiclePath()
{
}
bool cVehiclePath::SetPath(const vector<Vector3> &path, const Vector3 &direction)
{
m_initialDirection = direction;
m_path.resize(path.size());
for (u_int i=0; i < path.size(); ++i)
m_path[i] = path[i];
if (!m_path.empty())
{
m_idx = -1;
NextMove();
}
return true;
}
// If Finish Path, return true
bool cVehiclePath::Update(const float deltaSeconds)
{
if (m_idx >= (int)(m_path.size() - 1))
{
m_idx = -1;
//NextMove();
return true;
}
m_incTime += deltaSeconds;
if (m_elapsedTime < m_incTime)
{
NextMove();
}
else
{
common::lerp(m_pos, m_path[m_idx], m_path[m_idx + 1], m_incTime / m_elapsedTime);
if (m_incTime < m_rotTime)
m_rot = m_rot.Interpolate(m_nextRot, m_incTime / m_rotTime);
else
m_rot = m_nextRot;
if (m_pos.LengthRoughly(m_path[m_idx + 1]) < 0.01f)
NextMove();
}
return false;
}
bool cVehiclePath::IsEmpty()
{
return m_path.empty();
}
void cVehiclePath::NextMove()
{
++m_idx;
m_incTime = 0;
m_pos = m_path[m_idx];
if ((int)m_path.size() > (m_idx+1))
{
Vector3 dir = m_path[m_idx+1] - m_path[m_idx];
m_elapsedTime = dir.Length() / m_velocity;
dir.Normalize();
if (m_elapsedTime > 0)
{
// initial direction is Vector3(1,0,0)
// but Camera initial direction is Vector3(0,0,1)
// so rotation y
Matrix44 rot;
rot.SetRotationY(-MATH_PI / 2.f);
Vector3 newDir = dir * rot;
Matrix44 mDir;
mDir.SetView(Vector3(0, 0, 0), newDir, Vector3(0, 1, 0));
mDir.Inverse2();
m_nextRot = mDir.GetQuaternion();
//m_nextRot.SetRotationArc(m_initialDirection, dir, Vector3(0, 1, 0));
}
}
}
| 17.398148
| 83
| 0.653539
|
vox-1
|
9554eeba67fee4a1c1a7e99ea09a32575706a32e
| 539
|
cpp
|
C++
|
Samsung SW Expert Academy/2071.cpp
|
SiverPineValley/algo
|
29c75c6b226fdb15a3b6695e763ee49d4871094e
|
[
"Apache-2.0"
] | null | null | null |
Samsung SW Expert Academy/2071.cpp
|
SiverPineValley/algo
|
29c75c6b226fdb15a3b6695e763ee49d4871094e
|
[
"Apache-2.0"
] | null | null | null |
Samsung SW Expert Academy/2071.cpp
|
SiverPineValley/algo
|
29c75c6b226fdb15a3b6695e763ee49d4871094e
|
[
"Apache-2.0"
] | null | null | null |
// 2071. 평균값 구하기
#include <iostream>
#include <cmath>
using namespace std;
int main(void)
{
int n;
cin >> n;
for(int t = 1; t <= n; t++)
{
float temp2;
int ans, temp;
float sum = 0;
for(int i = 0; i < 10; i++)
{
cin >> temp;
sum += temp;
}
temp2 = sum/10;
temp = (int) temp2;
temp2 -= temp;
if(temp2 >= 0.5) ans = temp+1;
else ans = temp;
cout << "#" << t << " " << ans << "\n";
}
return 0;
}
| 19.962963
| 47
| 0.397032
|
SiverPineValley
|
95585e6b406ae394657489a38412eb01de9cfdae
| 2,316
|
cc
|
C++
|
src/codegen/codegen_function.cc
|
nitnelave/hopper
|
2d71fe2c9944b9cc8bc29ef8c4b9e068e7a54881
|
[
"BSD-3-Clause"
] | 2
|
2017-07-27T14:08:43.000Z
|
2021-11-12T17:30:58.000Z
|
src/codegen/codegen_function.cc
|
nitnelave/hopper
|
2d71fe2c9944b9cc8bc29ef8c4b9e068e7a54881
|
[
"BSD-3-Clause"
] | 61
|
2017-05-22T12:38:28.000Z
|
2017-09-21T08:10:46.000Z
|
src/codegen/codegen_function.cc
|
nitnelave/hopper
|
2d71fe2c9944b9cc8bc29ef8c4b9e068e7a54881
|
[
"BSD-3-Clause"
] | null | null | null |
#include "codegen/codegen.h"
#include "llvm/IR/CallingConv.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "ast/block_statement.h"
#include "ast/function_call.h"
#include "ast/function_declaration.h"
#include "ast/return_statement.h"
#include "ast/value.h"
#include "ast/value_statement.h"
#include "ast/variable_declaration.h"
#include "ast/variable_reference.h"
#include "util/logging.h"
namespace codegen {
using namespace llvm; // NOLINT
void CodeGenerator::visit(ast::ValueStatement* node) {
node->value()->accept(*this);
CHECK(gen_value_.is_ok()) << "No value generated by the visitor";
}
void CodeGenerator::visit(ast::FunctionDeclaration* node) {
std::vector<Type*> param_types; // fill by visiting.
for (std::size_t i = 0; i < node->arguments().size(); ++i) {
// TODO: put real type here.
param_types.push_back(IntegerType::get(context_, 32));
}
ArrayRef<Type*> param_types_array(param_types);
// TODO: put real return type here.
FunctionType* t = FunctionType::get(IntegerType::get(context_, 32),
param_types_array, /*isVarArg=*/false);
Constant* c = module_->getOrInsertFunction(node->id().short_name(), t);
Function* llvm_function = cast<Function>(c);
current_function_ = llvm_function;
llvm_function->setCallingConv(CallingConv::C);
functions_[node] = llvm_function;
// Name the parameters.
CHECK(llvm_function->arg_size() == node->arguments().size())
<< "There should be as much arguments in the llvm function as in the "
"ASTNode object";
auto llvm_arg = llvm_function->arg_begin();
auto gh_arg = std::begin(node->arguments());
for (; llvm_arg != llvm_function->arg_end(); llvm_arg++, gh_arg++) {
llvm_arg->setName((*gh_arg)->id().to_string());
functions_args_[(*gh_arg).get()] = &*llvm_arg;
}
// Create body of the function.
CHECK(node->body().is<ast::FunctionDeclaration::StatementsBody>())
<< "FunctionDeclaration body was not transformed, still a value";
BasicBlock* body_block = BasicBlock::Create(context_, node->id().to_string(),
current_function_.value_or_die());
ir_builder_.SetInsertPoint(body_block);
node->accept_body(*this);
consume_return_value();
}
} // namespace codegen
| 34.567164
| 80
| 0.685233
|
nitnelave
|
955c5571cb638173671c0632373109fd6717acb1
| 10,020
|
cpp
|
C++
|
src/main.cpp
|
lishi0927/BRDF
|
d9d2fc44b3d70d57a375dd85cb3624462874326a
|
[
"MIT"
] | null | null | null |
src/main.cpp
|
lishi0927/BRDF
|
d9d2fc44b3d70d57a375dd85cb3624462874326a
|
[
"MIT"
] | null | null | null |
src/main.cpp
|
lishi0927/BRDF
|
d9d2fc44b3d70d57a375dd85cb3624462874326a
|
[
"MIT"
] | null | null | null |
// Include standard headers
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <vector>
// Include GLEW
#include <GL/glew.h>
// Include GLFW
#include <glfw3.h>
GLFWwindow* window;
// Include GLM
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
using namespace glm;
#include "ground.h"
#include "shader.hpp"
#include "texture.hpp"
#include "controls.hpp"
#include "objloader.hpp"
#define WINDOW_WIDTH 1024
#define WINDOW_HEIGHT 768
#define COOK_Torrance
#ifdef DIFFUSE_LIGHT
#include "diffuselight.h"
#endif
#ifdef SPECULAR_LIGHT
#include "specularlight.h"
#endif
#ifdef COOK_Torrance
#include "brdf_cooktorrance.h"
float m_scale;
#endif
Texture* m_pTexture;
GLuint VertexArrayID;
GLuint vertexbuffer;
GLuint uvbuffer;
GLuint normalbuffer;
int verticenumber;
static const float FieldDepth = 20.0f;
static const float FieldWidth = 10.0f;
GLuint m_VBO;
void CreateVertexBuffer()
{
const glm::vec3 Normal = glm::vec3(0.0, 1.0f, 0.0f);
Vertex Vertices[6] = {
Vertex(glm::vec3(0.0f, 0.0f, 0.0f), glm::vec2(0.0f, 0.0f), Normal),
Vertex(glm::vec3(0.0f, 0.0f, FieldDepth), glm::vec2(0.0f, 1.0f), Normal),
Vertex(glm::vec3(FieldWidth, 0.0f, 0.0f), glm::vec2(1.0f, 0.0f), Normal),
Vertex(glm::vec3(FieldWidth, 0.0f, 0.0f), glm::vec2(1.0f, 0.0f), Normal),
Vertex(glm::vec3(0.0f, 0.0f, FieldDepth), glm::vec2(0.0f, 1.0f), Normal),
Vertex(glm::vec3(FieldWidth, 0.0f, FieldDepth), glm::vec2(1.0f, 1.0f), Normal)
};
glGenBuffers(1, &m_VBO);
glBindBuffer(GL_ARRAY_BUFFER, m_VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(Vertices), Vertices, GL_STATIC_DRAW);
}
void init()
{
LightInit();
// Enable depth test
glEnable(GL_DEPTH_TEST);
// Accept fragment if it closer to the camera than the former one
glDepthFunc(GL_LESS);
// Cull triangles which normal is not towards the camera
glEnable(GL_CULL_FACE);
CreateVertexBuffer();
glGenVertexArrays(1, &VertexArrayID);
glBindVertexArray(VertexArrayID);
/*
// Load the texture
// TextureI = loadDDS("uvmap.DDS");
// Read our .obj file
std::vector<glm::vec3> vertices;
std::vector<glm::vec2> uvs;
std::vector<glm::vec3> normals;
bool res = loadOBJ("suzanne.obj", vertices, uvs, normals);
// Load it into a VBO
verticenumber = vertices.size();
glGenBuffers(1, &vertexbuffer);
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(glm::vec3), &vertices[0], GL_STATIC_DRAW);
glGenBuffers(1, &uvbuffer);
glBindBuffer(GL_ARRAY_BUFFER, uvbuffer);
glBufferData(GL_ARRAY_BUFFER, uvs.size() * sizeof(glm::vec2), &uvs[0], GL_STATIC_DRAW);
glGenBuffers(1, &normalbuffer);
glBindBuffer(GL_ARRAY_BUFFER, normalbuffer);
glBufferData(GL_ARRAY_BUFFER, normals.size() * sizeof(glm::vec3), &normals[0], GL_STATIC_DRAW);
vertices.clear();
uvs.clear();
normals.clear();
*/
#ifdef DIFFUSE_LIGHT
Diffuseshader.shader = LoadShaders("shader/diffuse_vert.glsl", "shader/diffuse_fragment.glsl");
if (!Diffuseshader.Init())
{
std::cout << "DiffuseShader ERROR!" << std::endl;
exit(-1);
}
Diffuseshader.Enable();
Diffuseshader.SetTextureUnit(0);
#endif
#ifdef SPECULAR_LIGHT
SpecularShader.shader = LoadShaders("shader/specular_vert.glsl", "shader/specular_fragment.glsl");
if (!SpecularShader.Init())
{
std::cout << "SpecularShader ERROR!" << std::endl;
exit(-1);
}
SpecularShader.Enable();
SpecularShader.SetTextureUnit(0);
#endif
#ifdef COOK_Torrance
m_scale = 0;
CookShader.shader = LoadShaders("shader/cooktorrance_vert.glsl", "shader/cooktorrance_fragment.glsl");
if (!CookShader.Init())
{
std::cout << "CookTorrance Error!" << std::endl;
exit(-1);
}
CookShader.Enable();
CookShader.SetTextureUnit(0);
#endif
m_pTexture = new Texture(GL_TEXTURE_2D, "test.png");
if (!m_pTexture->Load()) {
std::cout << "Texture ERROR!" << std::endl;
exit(-1);
}
}
void render()
{
// Clear the screen
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Compute the MVP matrix from keyboard and mouse input
computeMatricesFromInputs();
glm::mat4 ProjectionMatrix = getProjectionMatrix();
glm::mat4 ViewMatrix = getViewMatrix();
glm::mat4 ModelMatrix = glm::mat4(1.0);
glm::mat4 MVP = ProjectionMatrix * ViewMatrix * ModelMatrix;
glm::vec3 camerapos = getCameraPosition();
#ifdef DIFFUSE_LIGHT
Diffuseshader.Enable();
Diffuseshader.SetWVP(MVP);
Diffuseshader.SetWorldMatrix(ModelMatrix);
Diffuseshader.SetDirectionalLight(m_directionalLight);
#endif
#ifdef SPECULAR_LIGHT
SpecularShader.Enable();
SpecularShader.SetWVP(MVP);
SpecularShader.SetWorldMatrix(ModelMatrix);
SpecularShader.SetDirectionalLight(m_directionalLight);
SpecularShader.SetEyeWorldPos(camerapos);
SpecularShader.SetMatSpecularIntensity(1.0f);
SpecularShader.SetMatSpecularPower(32);
#endif
#ifdef COOK_Torrance
m_scale += 0.0057f;
PointLight pl[2];
pl[0].DiffuseIntensity = 0.5f;
pl[0].Color = glm::vec3(1.0f, 0.5f, 0.0f);
pl[0].Position = glm::vec3(3.0f, 1.0f, 20 * (cosf(m_scale) + 1.0f) / 2.0f);
pl[0].Attenuation.Linear = 0.1f;
pl[1].DiffuseIntensity = 0.5f;
pl[1].Color = glm::vec3(0.0f, 0.5f, 1.0f);
pl[1].Position = glm::vec3(7.0f, 1.0f, 20 * (sinf(m_scale) + 1.0f) / 2.0f);
pl[1].Attenuation.Linear = 0.1f;
// CookShader.Enable();
CookShader.SetPointLights(2, pl);
CookShader.SetWVP(MVP);
CookShader.SetWorldMatrix(ModelMatrix);
CookShader.SetDirectionalLight(m_directionalLight);
CookShader.SetEyeWorldPos(camerapos);
CookShader.SetRoughness(0.3);
CookShader.SetFresnel(0.8);
CookShader.SetGK(0.2);
#endif
// m_pTexture->Bind(GL_TEXTURE0);
/*
// 1rst attribute buffer : vertices
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
glVertexAttribPointer(
0, // attribute
3, // size
GL_FLOAT, // type
GL_FALSE, // normalized?
0, // stride
(void*)0 // array buffer offset
);
// 2nd attribute buffer : UVs
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER, uvbuffer);
glVertexAttribPointer(
1, // attribute
2, // size
GL_FLOAT, // type
GL_FALSE, // normalized?
0, // stride
(void*)0 // array buffer offset
);
// 3rd attribute buffer : normals
glEnableVertexAttribArray(2);
glBindBuffer(GL_ARRAY_BUFFER, normalbuffer);
glVertexAttribPointer(
2, // attribute
3, // size
GL_FLOAT, // type
GL_FALSE, // normalized?
0, // stride
(void*)0 // array buffer offset
);
// Draw the triangles !
glDrawArrays(GL_TRIANGLES, 0, verticenumber);
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
glDisableVertexAttribArray(2);
*/
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glEnableVertexAttribArray(2);
glBindBuffer(GL_ARRAY_BUFFER, m_VBO);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), 0);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid*)12);
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid*)20);
m_pTexture->Bind(GL_TEXTURE0);
glDrawArrays(GL_TRIANGLES, 0, 6);
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
glDisableVertexAttribArray(2);
}
void keyCallback(GLFWwindow *window, int key, int scancode, int action, int mods) {
if (action != GLFW_PRESS) return;
switch (key) {
case GLFW_KEY_ESCAPE:
glfwSetWindowShouldClose(window, GL_TRUE);
break;
case GLFW_KEY_A:
m_directionalLight.AmbientIntensity += 0.05f;
break;
case GLFW_KEY_S:
m_directionalLight.AmbientIntensity -= 0.05f;
break;
case GLFW_KEY_Z:
m_directionalLight.DiffuseIntensity += 0.05f;
break;
case GLFW_KEY_X:
m_directionalLight.DiffuseIntensity -= 0.05f;
break;
}
}
int main(void)
{
// Initialise GLFW
if (!glfwInit())
{
fprintf(stderr, "Failed to initialize GLFW\n");
getchar();
return -1;
}
glfwWindowHint(GLFW_SAMPLES, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // To make MacOS happy; should not be needed
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
// Open a window and create its OpenGL context
window = glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT, "Tutorial 01", NULL, NULL);
if (window == NULL) {
fprintf(stderr, "Failed to open GLFW window. If you have an Intel GPU, they are not 3.3 compatible. Try the 2.1 version of the tutorials.\n");
getchar();
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
// Initialize GLEW
glewExperimental = true; // Needed for core profile
// Initialize GLEW
if (glewInit() != GLEW_OK) {
fprintf(stderr, "Failed to initialize GLEW\n");
getchar();
glfwTerminate();
return -1;
}
// Hide the mouse and enable unlimited mouvement
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
glfwSetKeyCallback(window, keyCallback);
// Set the mouse at the center of the screen
glfwPollEvents();
glfwSetCursorPos(window, 1024 / 2, 768 / 2);
// Dark blue background
glClearColor(0.0f, 0.0f, 0.4f, 0.0f);
init();
do {
// Clear the screen. It's not mentioned before Tutorial 02, but it can cause flickering, so it's there nonetheless.
glClear(GL_COLOR_BUFFER_BIT);
// Draw nothing, see you in tutorial 2 !
render();
// Swap buffers
glfwSwapBuffers(window);
glfwPollEvents();
} // Check if the ESC key was pressed or the window was closed
while (glfwWindowShouldClose(window) == 0);
glDeleteBuffers(1, &vertexbuffer);
glDeleteBuffers(1, &uvbuffer);
glDeleteBuffers(1, &normalbuffer);
delete m_pTexture;
// Close OpenGL window and terminate GLFW
glfwTerminate();
return 0;
}
| 25.561224
| 144
| 0.694511
|
lishi0927
|
95637a52191c30ceb46b0bb053029d76d08f1ef3
| 1,709
|
cpp
|
C++
|
src/etc/subclassing.cpp
|
rosasurfer/mt4-expander
|
dc2fb04aaaa62f4ba575d7c16a266169daac417a
|
[
"WTFPL"
] | 25
|
2017-02-16T16:58:18.000Z
|
2021-12-06T06:42:54.000Z
|
src/etc/subclassing.cpp
|
rosasurfer/mt4-expander
|
dc2fb04aaaa62f4ba575d7c16a266169daac417a
|
[
"WTFPL"
] | 5
|
2016-12-13T05:58:11.000Z
|
2020-09-23T17:49:33.000Z
|
src/etc/subclassing.cpp
|
rosasurfer/mt4-expander
|
dc2fb04aaaa62f4ba575d7c16a266169daac417a
|
[
"WTFPL"
] | 26
|
2017-02-08T13:34:28.000Z
|
2022-03-12T10:53:41.000Z
|
#include "expander.h"
HWND last_hWnd;
WNDPROC origWndProc;
/**
* Custom window procedure
*/
LRESULT WINAPI CustomWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
debug("hWnd=%d, msg=%d, wParam=%p, lParam=%p", hWnd, msg, wParam, lParam);
return(CallWindowProc(origWndProc, hWnd, msg, wParam, lParam));
}
/**
* There is already a macro SubclassWindow in windowsx.h
*/
BOOL WINAPI _SubclassWindow(HWND hWnd) {
if (!IsWindow(hWnd)) return(error(ERR_INVALID_PARAMETER, "invalid parameter hWnd: %d (not a window)", hWnd));
DWORD processId; GetWindowThreadProcessId(hWnd, &processId);
if (processId != GetCurrentProcessId()) return(error(ERR_INVALID_PARAMETER, "window hWnd=%d not owned by the current process", hWnd));
origWndProc = (WNDPROC)SetWindowLong(hWnd, GWL_WNDPROC, (LONG)CustomWndProc);
if (!origWndProc) return(error(ERR_WIN32_ERROR+GetLastError(), "SetWindowLong()"));
last_hWnd = hWnd;
debug("replaced window procedure 0x%p with 0x%p", origWndProc, CustomWndProc);
return(TRUE);
#pragma EXPANDER_EXPORT
}
/**
*
*/
BOOL WINAPI UnsubclassWindow(HWND hWnd) {
if (!hWnd) return(error(ERR_INVALID_PARAMETER, "invalid parameter hWnd: %d (not a window)", hWnd));
if (hWnd != last_hWnd) return(error(ERR_INVALID_PARAMETER, "invalid parameter hWnd: %d (not a subclassed window)", hWnd));
if (!SetWindowLong(hWnd, GWL_WNDPROC, (LONG)origWndProc))
return(error(ERR_WIN32_ERROR+GetLastError(), "SetWindowLong() failed to restore original window procedure"));
last_hWnd = NULL;
origWndProc = NULL;
debug("original window procedure restored");
return(TRUE);
#pragma EXPANDER_EXPORT
}
| 31.648148
| 137
| 0.705091
|
rosasurfer
|
956a84f757664515ab460661f16b9a12aafdd4cd
| 1,476
|
cpp
|
C++
|
tests.boost/write_xml_with_property_tree.cpp
|
virgiliosanz/Tests
|
f24f210b7ef3ef8c8a6b3e915c33ce4f9cf26694
|
[
"Unlicense"
] | null | null | null |
tests.boost/write_xml_with_property_tree.cpp
|
virgiliosanz/Tests
|
f24f210b7ef3ef8c8a6b3e915c33ce4f9cf26694
|
[
"Unlicense"
] | null | null | null |
tests.boost/write_xml_with_property_tree.cpp
|
virgiliosanz/Tests
|
f24f210b7ef3ef8c8a6b3e915c33ce4f9cf26694
|
[
"Unlicense"
] | null | null | null |
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
//<Root>
// <Set Name="1">
// <Field Name="Hello 1"/>
// <Field Name="World 1"/>
// </Set>
// <Set Name="2">
// <Field Name="Hello 2"/>
// <Field Name="World 2"/>
// </Set>
//</Root>
int main(int argc, char* argv[])
{
using boost::property_tree::ptree;
ptree pt;
boost::property_tree::ptree rootNode;
boost::property_tree::ptree setNode1;
boost::property_tree::ptree setNode2;
boost::property_tree::ptree fieldNode1;
boost::property_tree::ptree fieldNode2;
boost::property_tree::ptree fieldNode3;
boost::property_tree::ptree fieldNode4;
fieldNode1.put("<xmlattr>.Name", "Hello 1");
fieldNode2.put("<xmlattr>.Name", "World 1");
fieldNode3.put("<xmlattr>.Name", "Hello 2");
fieldNode4.put("<xmlattr>.Name", "World 2");
setNode1.add_child("Field", fieldNode1);
setNode1.add_child("Field", fieldNode2);
setNode2.add_child("Field", fieldNode3);
setNode2.add_child("Field", fieldNode4);
setNode1.put("<xmlattr>.Name", "1");
setNode2.put("<xmlattr>.Name", "2");
rootNode.add_child("Set", setNode1);
rootNode.add_child("Set", setNode2);
pt.add_child("Root", rootNode);
// boost::property_tree::xml_writer_settings<char> settings('\t', 1);
// write_xml("testXml.xml", pt, std::locale(), settings);
write_xml("testXml.xml", pt, std::locale());
return 0;
}
| 28.941176
| 76
| 0.638211
|
virgiliosanz
|
956f75011ae92a722898e80f4d7008a1d951494b
| 382
|
cpp
|
C++
|
VeshApiBattle/battle.cpp
|
FireAlfa/VeshApi-BattleSystem
|
03356f77a61b69597870d7f4773f6744fd78c360
|
[
"MIT"
] | null | null | null |
VeshApiBattle/battle.cpp
|
FireAlfa/VeshApi-BattleSystem
|
03356f77a61b69597870d7f4773f6744fd78c360
|
[
"MIT"
] | null | null | null |
VeshApiBattle/battle.cpp
|
FireAlfa/VeshApi-BattleSystem
|
03356f77a61b69597870d7f4773f6744fd78c360
|
[
"MIT"
] | null | null | null |
#include "battle.h"
Battle::Battle(std::string _name) : name(_name)
{
}
Battle::~Battle()
{
}
void Battle::AddPlayer(Player* p)
{
if (!playerCreated)
{
players.insert(players.begin(), p);
}
playerCreated = true;
}
void Battle::CreateEnemy(std::string _name)
{
Player* p = new Player(_name);
AddEnemy(p);
}
void Battle::AddEnemy(Player* p)
{
players.push_back(p);
}
| 11.575758
| 47
| 0.659686
|
FireAlfa
|
9570cc112d93525ede31d9eddaa9df7c358de5f0
| 433
|
cpp
|
C++
|
SOCTestProject/SOCTestProject/Code/main.cpp
|
Jin02/SOCEngine
|
7a04d914149783f54aecf2fbbc4e78a7325f0fbd
|
[
"MIT"
] | 14
|
2015-12-24T03:08:59.000Z
|
2021-12-13T13:29:07.000Z
|
SOCTestProject/SOCTestProject/Code/main.cpp
|
Jin02/SOCEngine
|
7a04d914149783f54aecf2fbbc4e78a7325f0fbd
|
[
"MIT"
] | 106
|
2015-08-16T10:32:47.000Z
|
2018-10-08T19:01:44.000Z
|
SOCTestProject/SOCTestProject/Code/main.cpp
|
Jin02/SOCEngine
|
7a04d914149783f54aecf2fbbc4e78a7325f0fbd
|
[
"MIT"
] | 2
|
2018-03-02T06:17:08.000Z
|
2020-02-11T11:19:41.000Z
|
#include "Launcher.h"
#include "TestScene.h"
using namespace Core;
using namespace Device;
INT WINAPI wWinMain( HINSTANCE hInst, HINSTANCE, LPWSTR, INT )
{
WinApp::Desc desc;
{
desc.rect = Rect<uint>(0, 0, 800, 600);
desc.instance = hInst;
desc.name = "Refactoring";
desc.windowMode = true;
desc.isChild = false;
desc.parentHandle = NULL;
}
Launcher::Run(desc, desc.rect, false, new TestScene);
return 0;
}
| 20.619048
| 62
| 0.681293
|
Jin02
|
9577a841090e2aca4c6844b31c2bee77695e9685
| 223
|
cpp
|
C++
|
src/kasm/externalLoaders.cpp
|
knoxaramav2/KASM
|
e678374e579768cc2c9654ee53225684198b00ad
|
[
"MIT"
] | null | null | null |
src/kasm/externalLoaders.cpp
|
knoxaramav2/KASM
|
e678374e579768cc2c9654ee53225684198b00ad
|
[
"MIT"
] | null | null | null |
src/kasm/externalLoaders.cpp
|
knoxaramav2/KASM
|
e678374e579768cc2c9654ee53225684198b00ad
|
[
"MIT"
] | null | null | null |
#include "externalLoaders.hpp"
#include "instructionRegistery.hpp"
#include "controller.hpp"
#include "graphics.hpp"
void KASM::LoadGraphics(KASM::AsmController&ctrl){
KASM::GRAPHICS::InitGraphics(ctrl);
}
| 24.777778
| 51
| 0.726457
|
knoxaramav2
|
9579502c15e235c8d916c537e50edde00da63ec2
| 419
|
cpp
|
C++
|
Plugins/VisCreationHelper/Source/VisCreationHelper/Private/PerfomanceStats/VCHTimerCounter.cpp
|
Mihalo15z/VisCreationHelper
|
dcac82b304542a7d4768b2a292cc2408118bf4aa
|
[
"MIT"
] | null | null | null |
Plugins/VisCreationHelper/Source/VisCreationHelper/Private/PerfomanceStats/VCHTimerCounter.cpp
|
Mihalo15z/VisCreationHelper
|
dcac82b304542a7d4768b2a292cc2408118bf4aa
|
[
"MIT"
] | null | null | null |
Plugins/VisCreationHelper/Source/VisCreationHelper/Private/PerfomanceStats/VCHTimerCounter.cpp
|
Mihalo15z/VisCreationHelper
|
dcac82b304542a7d4768b2a292cc2408118bf4aa
|
[
"MIT"
] | 1
|
2022-01-17T10:07:17.000Z
|
2022-01-17T10:07:17.000Z
|
#include "PerfomanceStats/VCHTimerCounter.h"
DECLARE_LOG_CATEGORY_CLASS(VCH_PerfomansceLog, Log, All);
FVCHTimeConter::FVCHTimeConter(const FString & InCounterInfo) :CounterInfo(InCounterInfo)
{
StartCicles = FPlatformTime::Cycles();
}
FVCHTimeConter::~FVCHTimeConter()
{
UE_LOG(VCH_PerfomansceLog, Log, TEXT("%s: time = %f"), *CounterInfo, FPlatformTime::ToMilliseconds(FPlatformTime::Cycles() - StartCicles));
}
| 29.928571
| 140
| 0.782816
|
Mihalo15z
|
957d6b554cc3aabcff4165c63897e11974d3a6fc
| 250
|
hpp
|
C++
|
dali/sasha/saxref.hpp
|
miguelvazq/HPCC-Platform
|
22ad8e5fcb59626abfd8febecbdfccb1e9fb0aa5
|
[
"Apache-2.0"
] | 286
|
2015-01-03T12:45:17.000Z
|
2022-03-25T18:12:57.000Z
|
dali/sasha/saxref.hpp
|
miguelvazq/HPCC-Platform
|
22ad8e5fcb59626abfd8febecbdfccb1e9fb0aa5
|
[
"Apache-2.0"
] | 9,034
|
2015-01-02T08:49:19.000Z
|
2022-03-31T20:34:44.000Z
|
dali/sasha/saxref.hpp
|
cloLN/HPCC-Platform
|
42ffb763a1cdcf611d3900831973d0a68e722bbe
|
[
"Apache-2.0"
] | 208
|
2015-01-02T03:27:28.000Z
|
2022-02-11T05:54:52.000Z
|
#ifndef SAXREFIF_HPP
#define SAXREFIF_HPP
interface ISashaServer;
interface ISashaCommand;
extern ISashaServer *createSashaXrefServer();
extern void processXRefRequest(ISashaCommand *cmd);
extern ISashaServer *createSashaFileExpiryServer();
#endif
| 22.727273
| 51
| 0.848
|
miguelvazq
|
9582a7a99cc88a427c7710ab064a6b9116c05ba3
| 428
|
hpp
|
C++
|
Source/Shader.hpp
|
claytonkanderson/Fractus
|
c4012cc40ee81ac042edcc5461c48e02456bcbd0
|
[
"MIT"
] | null | null | null |
Source/Shader.hpp
|
claytonkanderson/Fractus
|
c4012cc40ee81ac042edcc5461c48e02456bcbd0
|
[
"MIT"
] | null | null | null |
Source/Shader.hpp
|
claytonkanderson/Fractus
|
c4012cc40ee81ac042edcc5461c48e02456bcbd0
|
[
"MIT"
] | null | null | null |
//
// Shader.hpp
// Fracturing
//
// Created by Clayton Anderson on 4/16/17.
// Copyright © 2017 Clayton Anderson. All rights reserved.
//
#pragma once
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <glm/mat4x4.hpp>
#include <glm/gtc/matrix_transform.hpp>
GLuint LoadShaders(const char * vertex_file_path,const char * fragment_file_path);
| 20.380952
| 82
| 0.726636
|
claytonkanderson
|
9582df70e25512b93c6c1d0601032a3c4562f57f
| 14,410
|
cpp
|
C++
|
tools/quantization/opttools/quantized_model_optimize.cpp
|
JujuDel/MNN
|
8a82f5c5a7ae37192784c2dbd6dfc8ca8833565a
|
[
"Apache-2.0"
] | 2
|
2020-12-15T13:56:31.000Z
|
2022-01-26T03:20:28.000Z
|
tools/quantization/opttools/quantized_model_optimize.cpp
|
JujuDel/MNN
|
8a82f5c5a7ae37192784c2dbd6dfc8ca8833565a
|
[
"Apache-2.0"
] | null | null | null |
tools/quantization/opttools/quantized_model_optimize.cpp
|
JujuDel/MNN
|
8a82f5c5a7ae37192784c2dbd6dfc8ca8833565a
|
[
"Apache-2.0"
] | 1
|
2021-11-24T06:26:27.000Z
|
2021-11-24T06:26:27.000Z
|
#include "MNN_generated.h"
#include <MNN/MNNDefine.h>
#include <fstream>
#include <sstream>
#include <memory>
#include <map>
#include <queue>
#include <set>
using namespace MNN;
//#define OPT_SHAPE_TRANSFORM
static bool reIndex(MNN::NetT* mNet) {
std::map<int, int> usefulTensorIndexMap;
std::vector<std::string> usefulTensorName;
std::vector<bool> tensorValid(mNet->tensorName.size(), false);
for (auto& op : mNet->oplists) {
for (auto index : op->inputIndexes) {
tensorValid[index] = true;
}
for (auto index : op->outputIndexes) {
tensorValid[index] = true;
}
}
for (int i = 0; i < tensorValid.size(); ++i) {
if (tensorValid[i]) {
usefulTensorIndexMap.insert(std::make_pair(i, usefulTensorName.size()));
usefulTensorName.push_back(mNet->tensorName[i]);
}
}
// Re index
for (auto& op : mNet->oplists) {
for (int i = 0; i < op->inputIndexes.size(); ++i) {
auto iter = usefulTensorIndexMap.find(op->inputIndexes[i]);
op->inputIndexes[i] = iter->second;
}
for (int i = 0; i < op->outputIndexes.size(); ++i) {
auto iter = usefulTensorIndexMap.find(op->outputIndexes[i]);
op->outputIndexes[i] = iter->second;
}
}
mNet->tensorName = usefulTensorName;
for (auto iter = mNet->extraTensorDescribe.begin(); iter != mNet->extraTensorDescribe.end();) {
auto index = (*iter)->index;
if (usefulTensorIndexMap.find(index) == usefulTensorIndexMap.end()) {
iter = mNet->extraTensorDescribe.erase(iter);
continue;
}
(*iter)->index = usefulTensorIndexMap.find(index)->second;
iter++;
}
// Check dup name and modify
std::set<std::string> names;
std::set<std::string> tensorNames;
for (int i = 0; i < mNet->oplists.size(); ++i) {
auto& op = mNet->oplists[i];
auto opName = op->name;
if (opName.empty() || names.find(opName) != names.end()) {
std::ostringstream defaultName;
defaultName << EnumNameOpType(op->type);
defaultName << i;
op->name = defaultName.str();
MNN_PRINT("%d op name is empty or dup, set to %s\n", i, op->name.c_str());
opName = op->name;
}
names.insert(opName);
for (auto output : op->outputIndexes) {
auto origin = mNet->tensorName[output];
if (origin.empty() || tensorNames.find(origin) != tensorNames.end()) {
std::ostringstream defaultName;
defaultName << output;
origin = defaultName.str();
mNet->tensorName[output] = origin;
}
tensorNames.insert(origin);
}
}
return true;
}
static std::set<OpType> gShapeTransformType {
OpType_BatchToSpaceND,
OpType_Crop,
OpType_DepthToSpace,
OpType_ExpandDims,
OpType_Flatten,
OpType_Gather,
OpType_GatherV2,
OpType_GatherND,
OpType_Padding,
OpType_Permute,
OpType_Reshape,
OpType_Slice,
OpType_SliceTf,
OpType_StridedSlice,
OpType_Squeeze,
OpType_SpaceToDepth,
OpType_SpaceToBatchND,
OpType_Tile,
OpType_Unsqueeze,
OpType_ConvertTensor,
OpType_Broastcast,
};
static std::set<OpType> gInt8Ops {
OpType_ConvInt8,
OpType_DepthwiseConvInt8,
OpType_PoolInt8,
OpType_EltwiseInt8
};
static void onlyTurnScaleToSingle(const std::vector<std::unique_ptr<OpT>>& sourceOplists) {
for (int i=0; i<sourceOplists.size(); ++i) {
auto op = sourceOplists[i].get();
if (op->type == OpType_Int8ToFloat || op->type == OpType_FloatToInt8) {
auto quanParam = op->main.AsQuantizedFloatParam();
auto tensorScale = quanParam->tensorScale[0];
quanParam->tensorScale = {tensorScale};
}
}
}
int main(int argc, const char* argv[]) {
MNN_PRINT("Optimize quantize model for smaller and faster, only valid to run after MNN 1.1.2\n");
MNN_PRINT("The tool is just for temporary usage, in laster version may be depercerate\n");
if (argc < 3) {
MNN_ERROR("Usage: ./quantized_model_optimize.out origin_quan.mnn optimized_quan.mnn\n");
return 0;
}
auto srcFile = argv[1];
auto dstFile = argv[2];
FUNC_PRINT_ALL(srcFile, s);
FUNC_PRINT_ALL(dstFile, s);
std::unique_ptr<NetT> source;
{
std::ifstream sourceFile(srcFile);
if (sourceFile.fail()) {
MNN_ERROR("Can't open source file\n");
return 0;
}
std::ostringstream tempOs;
tempOs << sourceFile.rdbuf();
auto tempS = tempOs.str();
source = std::move(UnPackNet((void*)tempS.c_str()));
}
if (nullptr == source) {
MNN_ERROR("Source net invalid\n");
return 0;
}
#ifdef OPT_SHAPE_TRANSFORM
// Compute the quan info for model
struct ValueMapInfo {
float scale = 0.0f;
float bias = 0.0f;
float minValue = -128.0f;
float maxValue = 127.0f;
bool valid = false;
};
std::vector<ValueMapInfo> quanInfos(source->tensorName.size());
int beforeConvert = 0;
// First Load info from convert op
for (int i=0; i<source->oplists.size(); ++i) {
auto op = source->oplists[i].get();
if (op->type == OpType_Int8ToFloat || op->type == OpType_FloatToInt8) {
auto quanParam = op->main.AsQuantizedFloatParam();
auto tensorScale = quanParam->tensorScale[0];
beforeConvert++;
if (op->type == OpType_FloatToInt8) {
if (tensorScale > 0.000001f) {
tensorScale = 1.0f / tensorScale;
}
}
for (auto index : op->inputIndexes) {
auto& info = quanInfos[index];
info.valid = true;
info.scale = tensorScale;
}
for (auto index : op->outputIndexes) {
auto& info = quanInfos[index];
info.valid = true;
info.scale = tensorScale;
}
continue;
}
if (OpType_EltwiseInt8 == op->type) {
auto quanParameters = op->main.AsEltwiseInt8();
quanInfos[op->inputIndexes[0]].valid = true;
quanInfos[op->inputIndexes[0]].scale = quanParameters->inputQuan0->tensorScale[0];
quanInfos[op->inputIndexes[1]].valid = true;
quanInfos[op->inputIndexes[1]].scale = quanParameters->inputQuan1->tensorScale[0];
quanInfos[op->outputIndexes[0]].valid = true;
quanInfos[op->outputIndexes[0]].scale = 1.0f / quanParameters->outputQuan->tensorScale[0];
continue;
}
}
// Compute indirect quan infos by shape transform
std::vector<ValueMapInfo> quanInfoIndirects = quanInfos;
for (int i=0; i<source->oplists.size(); ++i) {
auto op = source->oplists[i].get();
if (op->type == OpType_Int8ToFloat || op->type == OpType_FloatToInt8) {
auto& info = quanInfoIndirects[op->inputIndexes[0]];
if (info.valid) {
for (auto index : op->outputIndexes) {
quanInfoIndirects[index] = info;
}
}
}
if (gShapeTransformType.find(op->type) != gShapeTransformType.end()) {
auto& info = quanInfoIndirects[op->inputIndexes[0]];
if (info.valid) {
for (auto index : op->outputIndexes) {
quanInfoIndirects[index] = info;
}
}
continue;
}
}
// Reset Quan op's parameter by new quanInfoIndirects info
for (int i=0; i<source->oplists.size(); ++i) {
auto op = source->oplists[i].get();
if (OpType_ConvInt8 == op->type || OpType_DepthwiseConvInt8 == op->type) {
auto quanParameters = op->main.AsConvolution2D()->symmetricQuan.get();
if (quanInfoIndirects[op->inputIndexes[0]].scale != quanInfos[op->inputIndexes[0]].scale) {
// s0 * A1 = F, s1 * A2 = F, C = f(A1) * p0 = f(A2) * s1 / s0 * p0
auto adjustScale = quanInfoIndirects[op->inputIndexes[0]].scale / quanInfos[op->inputIndexes[0]].scale;
for (auto& s : quanParameters->scale) {
s = s * adjustScale;
}
}
MNN_ASSERT(quanInfos[op->outputIndexes[0]].scale == quanInfoIndirects[op->outputIndexes[0]].scale);
continue;
}
if (OpType_EltwiseInt8 == op->type) {
auto quanParameters = op->main.AsEltwiseInt8();
for (auto& s : quanParameters->inputQuan0->scale) {
s = quanInfoIndirects[op->inputIndexes[0]].scale;
}
for (auto& s : quanParameters->inputQuan1->scale) {
s = quanInfoIndirects[op->inputIndexes[1]].scale;
}
for (auto& s : quanParameters->outputQuan->scale) {
s = 1.0f / quanInfoIndirects[op->outputIndexes[0]].scale;
}
}
}
quanInfos = std::move(quanInfoIndirects);
// Remove Int8ToFloat and Float2Int8
std::queue<int> unusedIndexes;
{
std::map<int, int> indexMap;
auto oplists = std::move(source->oplists);
for (int i=0; i<oplists.size(); ++i) {
auto op = oplists[i].get();
if (op->type == OpType_FloatToInt8 || op->type == OpType_Int8ToFloat) {
auto inputIndex = op->inputIndexes[0];
auto outputIndex = op->outputIndexes[0];
auto iter = indexMap.find(inputIndex);
if (iter == indexMap.end()) {
indexMap.insert(std::make_pair(outputIndex, inputIndex));
} else {
indexMap.insert(std::make_pair(outputIndex, iter->second));
}
continue;
}
for (int j=0; j<op->inputIndexes.size(); ++j) {
auto iter = indexMap.find(op->inputIndexes[j]);
if (iter != indexMap.end()) {
op->inputIndexes[j] = iter->second;
}
}
source->oplists.emplace_back(std::move(oplists[i]));
}
for (auto& iter : indexMap) {
unusedIndexes.push(iter.first);
}
}
// Add Float2Int8 and Int8ToFloat Back
int afterConvert = 0;
{
// 0: float, 1: int
enum DataType {
FLOAT = 0,
INT8 = 1
};
std::vector<DataType> tensorType(source->tensorName.size(), FLOAT);
std::map<int, int> indexMap;
auto oplists = std::move(source->oplists);
for (int opIndex = 0; opIndex < oplists.size(); ++opIndex) {
auto op = oplists[opIndex].get();
DataType dataType = FLOAT;
if (gInt8Ops.find(op->type) != gInt8Ops.end()) {
dataType = INT8;
} else if (gShapeTransformType.find(op->type) != gShapeTransformType.end()) {
dataType = tensorType[op->inputIndexes[0]];
}
for (int i = 0; i < op->outputIndexes.size(); ++i) {
tensorType[op->outputIndexes[i]] = dataType;
}
for (int i = 0; i < op->inputIndexes.size(); ++i) {
auto index = op->inputIndexes[i];
if (tensorType[index] != dataType) {
auto replaceIter = indexMap.find(index);
if (replaceIter != indexMap.end()) {
op->inputIndexes[i] = replaceIter->second;
} else if (quanInfos[index].valid) {
afterConvert++;
// Create Op
// construct new op
std::unique_ptr<OpT> convertType(new MNN::OpT);
convertType->main.type = MNN::OpParameter_QuantizedFloatParam;
std::ostringstream opName;
opName << "Convert_" << index << "_" << (int)dataType;
convertType->name = opName.str();
auto dequantizationParam = new MNN::QuantizedFloatParamT;
convertType->main.value = dequantizationParam;
if (dataType == FLOAT) {
convertType->type = MNN::OpType_Int8ToFloat;
dequantizationParam->tensorScale = {quanInfos[index].scale};
} else {
convertType->type = MNN::OpType_FloatToInt8;
if (quanInfos[index].scale > 0.0f) {
dequantizationParam->tensorScale = {1.0f / quanInfos[index].scale};
} else {
dequantizationParam->tensorScale = {0.0f};
}
}
convertType->inputIndexes = {index};
convertType->outputIndexes = {(int)source->tensorName.size()};
source->tensorName.push_back(convertType->name);
// reset current op's input index at i
op->inputIndexes[i] = convertType->outputIndexes[0];
indexMap[index] = convertType->outputIndexes[0];
source->oplists.emplace_back(std::move(convertType));
}
}
}
source->oplists.emplace_back(std::move(oplists[opIndex]));
}
}
MNN_PRINT("From %d Convert to %d Convert\n", beforeConvert, afterConvert);
reIndex(source.get());
#else
onlyTurnScaleToSingle(source->oplists);
for (auto& subGraph : source->subgraphs) {
onlyTurnScaleToSingle(subGraph->nodes);
}
#endif
{
flatbuffers::FlatBufferBuilder builderOutput(1024);
auto len = MNN::Net::Pack(builderOutput, source.get());
builderOutput.Finish(len);
int sizeOutput = builderOutput.GetSize();
auto bufferOutput = builderOutput.GetBufferPointer();
std::ofstream output(dstFile);
output.write((const char*)bufferOutput, sizeOutput);
}
return 0;
}
| 39.264305
| 119
| 0.540389
|
JujuDel
|
9585b39d1666335cf42c47767b455d9ffda41564
| 3,525
|
cpp
|
C++
|
DeferredShading/DeferredShading/Renderer.cpp
|
yanghyunchan/2014_OperationBluehole
|
188b61dea134d4f8e37aff514cda3601f5f2a294
|
[
"MIT"
] | null | null | null |
DeferredShading/DeferredShading/Renderer.cpp
|
yanghyunchan/2014_OperationBluehole
|
188b61dea134d4f8e37aff514cda3601f5f2a294
|
[
"MIT"
] | null | null | null |
DeferredShading/DeferredShading/Renderer.cpp
|
yanghyunchan/2014_OperationBluehole
|
188b61dea134d4f8e37aff514cda3601f5f2a294
|
[
"MIT"
] | null | null | null |
#include "stdafx.h"
#include "Renderer.h"
#include "App.h"
#include "Logger.h"
#include "RSManager.h"
#include "LightManager.h"
Renderer::Renderer()
{
}
Renderer::~Renderer()
{
DestroyDevice();
}
BOOL Renderer::Init()
{
HWND hWnd = App::GetInstance()->GetHandleMainWindow();
if (!CreateDevice(hWnd))
{
MessageBox(hWnd, L"CreateDevice Error!", L"Error!", MB_ICONINFORMATION | MB_OK);
DestroyDevice();
return FALSE;
}
if (!mElin.Init())
{
MessageBox(hWnd, L"mElin Init Error!", L"Error!", MB_ICONINFORMATION | MB_OK);
DestroyDevice();
return FALSE;
}
if (!mRoom.Init())
{
MessageBox(hWnd, L"mRoom Init Error!", L"Error!", MB_ICONINFORMATION | MB_OK);
DestroyDevice();
return FALSE;
}
return TRUE;
}
void Renderer::Render()
{
// om - output merge
mD3DDeviceContext->OMSetDepthStencilState(RenderStateManager::GetInstance()->GetDepthState(), 0);
mElin.RenderAll();
mRoom.RenderAll(mD3DDeviceContext);
}
BOOL Renderer::CreateDevice(HWND hWnd)
{
UINT createDeviceFlags = 0;
#ifdef _DEBUG
createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif
D3D_DRIVER_TYPE driverTypes[] =
{
D3D_DRIVER_TYPE_HARDWARE,
D3D_DRIVER_TYPE_WARP,
D3D_DRIVER_TYPE_REFERENCE,
};
UINT numDriverTypes = ARRAYSIZE(driverTypes);
D3D_FEATURE_LEVEL featureLevels[] =
{
D3D_FEATURE_LEVEL_11_0,
D3D_FEATURE_LEVEL_10_1,
D3D_FEATURE_LEVEL_10_0,
};
UINT numFeatureLevels = ARRAYSIZE(featureLevels);
DXGI_SWAP_CHAIN_DESC sd;
ZeroMemory(&sd, sizeof(sd));
sd.BufferCount = 1;
sd.BufferDesc.Width = App::GetInstance()->GetWindowWidth();
sd.BufferDesc.Height = App::GetInstance()->GetWindowHeight();
sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
sd.BufferDesc.RefreshRate.Numerator = 60;
sd.BufferDesc.RefreshRate.Denominator = 1;
sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
sd.OutputWindow = hWnd;
sd.SampleDesc.Count = 1;
sd.SampleDesc.Quality = 0;
sd.Windowed = TRUE;
for (UINT driverTypeIndex = 0; driverTypeIndex < numDriverTypes; driverTypeIndex++)
{
mDriverType = driverTypes[driverTypeIndex];
hr = D3D11CreateDeviceAndSwapChain(NULL, mDriverType, NULL, createDeviceFlags, featureLevels, numFeatureLevels,
D3D11_SDK_VERSION, &sd, &mSwapChain, &mD3DDevice, &mFeatureLevel, &mD3DDeviceContext);
if (SUCCEEDED(hr))
break;
}
if (FAILED(hr))
return FALSE;
// Create a render target view
ID3D11Texture2D* pBackBuffer = NULL;
hr = mSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&pBackBuffer);
if (FAILED(hr))
return FALSE;
hr = mD3DDevice->CreateRenderTargetView(pBackBuffer, NULL, &mRenderTargetView);
pBackBuffer->Release();
if (FAILED(hr))
return FALSE;
return TRUE;
}
void Renderer::DestroyDevice()
{
if (mD3DDeviceContext)
mD3DDeviceContext->ClearState();
SafeRelease(mRenderTargetView);
SafeRelease(mSwapChain);
SafeRelease(mD3DDeviceContext);
SafeRelease(mD3DDevice);
}
void Renderer::SetupViewPort()
{
// Setup the viewport
D3D11_VIEWPORT vp;
vp.Width = (FLOAT)App::GetInstance()->GetWindowWidth();
vp.Height = (FLOAT)App::GetInstance()->GetWindowHeight();
vp.MinDepth = 0.0f;
vp.MaxDepth = 1.0f;
vp.TopLeftX = 0;
vp.TopLeftY = 0;
mD3DDeviceContext->RSSetViewports(1, &vp);
}
void Renderer::ClearBackBuff()
{
//clear
float ClearColor[4] = { 0.0f, 0.125f, 0.3f, 1.0f };
mD3DDeviceContext->ClearRenderTargetView(mRenderTargetView, ClearColor);
}
| 23.344371
| 114
| 0.704397
|
yanghyunchan
|
9587752c5a95185648b09b1a5feef0e5bc73ee54
| 8,501
|
cpp
|
C++
|
Chapter3/GL01_APIWrapping/src/GLAPITrace.cpp
|
adoug/3D-Graphics-Rendering-Cookbook
|
dabffed670b8be5a619f0f62b10e0cc8ccdd5a36
|
[
"MIT"
] | 399
|
2021-06-03T02:42:20.000Z
|
2022-03-27T23:23:15.000Z
|
Chapter3/GL01_APIWrapping/src/GLAPITrace.cpp
|
adoug/3D-Graphics-Rendering-Cookbook
|
dabffed670b8be5a619f0f62b10e0cc8ccdd5a36
|
[
"MIT"
] | 7
|
2021-07-13T02:36:01.000Z
|
2022-03-26T03:46:37.000Z
|
Chapter3/GL01_APIWrapping/src/GLAPITrace.cpp
|
adoug/3D-Graphics-Rendering-Cookbook
|
dabffed670b8be5a619f0f62b10e0cc8ccdd5a36
|
[
"MIT"
] | 53
|
2021-06-02T20:02:24.000Z
|
2022-03-29T15:36:30.000Z
|
#include <assert.h>
#include "GL.h"
#include "GLAPITrace.h"
#define W( en ) if ( e == en ) return #en;
std::string Enum2String(GLenum e)
{
/* BeginMode */
W(GL_POINTS);
W(GL_LINES);
W(GL_LINE_LOOP);
W(GL_LINE_STRIP);
W(GL_TRIANGLES);
W(GL_TRIANGLE_STRIP);
W(GL_TRIANGLE_FAN);
/* BlendingFactorDest */
W(GL_SRC_COLOR);
W(GL_ONE_MINUS_SRC_COLOR);
W(GL_SRC_ALPHA);
W(GL_ONE_MINUS_SRC_ALPHA);
W(GL_DST_ALPHA);
W(GL_ONE_MINUS_DST_ALPHA);
/* BlendingFactorSrc */
W(GL_DST_COLOR);
W(GL_ONE_MINUS_DST_COLOR);
W(GL_SRC_ALPHA_SATURATE);
/* BlendEquationSeparate */
W(GL_FUNC_ADD);
W(GL_BLEND_EQUATION);
W(GL_BLEND_EQUATION_RGB);
W(GL_BLEND_EQUATION_ALPHA);
/* BlendSubtract */
W(GL_FUNC_SUBTRACT);
W(GL_FUNC_REVERSE_SUBTRACT);
/* Separate Blend Functions */
W(GL_BLEND_DST_RGB);
W(GL_BLEND_SRC_RGB);
W(GL_BLEND_DST_ALPHA);
W(GL_BLEND_SRC_ALPHA);
W(GL_CONSTANT_COLOR);
W(GL_ONE_MINUS_CONSTANT_COLOR);
W(GL_CONSTANT_ALPHA);
W(GL_ONE_MINUS_CONSTANT_ALPHA);
W(GL_BLEND_COLOR);
/* Buffer Objects */
W(GL_ARRAY_BUFFER);
W(GL_ELEMENT_ARRAY_BUFFER);
W(GL_ARRAY_BUFFER_BINDING);
W(GL_ELEMENT_ARRAY_BUFFER_BINDING);
W(GL_STREAM_DRAW);
W(GL_STATIC_DRAW);
W(GL_DYNAMIC_DRAW);
W(GL_BUFFER_SIZE);
W(GL_BUFFER_USAGE);
W(GL_CURRENT_VERTEX_ATTRIB);
/* CullFaceMode */
W(GL_FRONT);
W(GL_BACK);
W(GL_FRONT_AND_BACK);
/* EnableCap */
W(GL_TEXTURE_2D);
W(GL_CULL_FACE);
W(GL_BLEND);
W(GL_DITHER);
W(GL_STENCIL_TEST);
W(GL_DEPTH_TEST);
W(GL_SCISSOR_TEST);
W(GL_POLYGON_OFFSET_FILL);
W(GL_SAMPLE_ALPHA_TO_COVERAGE);
W(GL_SAMPLE_COVERAGE);
/* ErrorCode */
W(GL_INVALID_ENUM);
W(GL_INVALID_VALUE);
W(GL_INVALID_OPERATION);
W(GL_OUT_OF_MEMORY);
/* FrontFaceDirection */
W(GL_CW);
W(GL_CCW);
/* GetPName */
W(GL_LINE_WIDTH);
W(GL_ALIASED_LINE_WIDTH_RANGE);
W(GL_CULL_FACE_MODE);
W(GL_FRONT_FACE);
W(GL_DEPTH_RANGE);
W(GL_DEPTH_WRITEMASK);
W(GL_DEPTH_CLEAR_VALUE);
W(GL_DEPTH_FUNC);
W(GL_STENCIL_CLEAR_VALUE);
W(GL_STENCIL_FUNC);
W(GL_STENCIL_FAIL);
W(GL_STENCIL_PASS_DEPTH_FAIL);
W(GL_STENCIL_PASS_DEPTH_PASS);
W(GL_STENCIL_REF);
W(GL_STENCIL_VALUE_MASK);
W(GL_STENCIL_WRITEMASK);
W(GL_STENCIL_BACK_FUNC);
W(GL_STENCIL_BACK_FAIL);
W(GL_STENCIL_BACK_PASS_DEPTH_FAIL);
W(GL_STENCIL_BACK_PASS_DEPTH_PASS);
W(GL_STENCIL_BACK_REF);
W(GL_STENCIL_BACK_VALUE_MASK);
W(GL_STENCIL_BACK_WRITEMASK);
W(GL_VIEWPORT);
W(GL_SCISSOR_BOX);
/* GL_SCISSOR_TEST */
W(GL_COLOR_CLEAR_VALUE);
W(GL_COLOR_WRITEMASK);
W(GL_UNPACK_ALIGNMENT);
W(GL_PACK_ALIGNMENT);
W(GL_MAX_TEXTURE_SIZE);
W(GL_MAX_VIEWPORT_DIMS);
W(GL_SUBPIXEL_BITS);
W(GL_POLYGON_OFFSET_UNITS);
/* GL_POLYGON_OFFSET_FILL */
W(GL_POLYGON_OFFSET_FACTOR);
W(GL_TEXTURE_BINDING_2D);
W(GL_SAMPLE_BUFFERS);
W(GL_SAMPLES);
W(GL_SAMPLE_COVERAGE_VALUE);
W(GL_SAMPLE_COVERAGE_INVERT);
W(GL_NUM_COMPRESSED_TEXTURE_FORMATS);
W(GL_COMPRESSED_TEXTURE_FORMATS);
/* HintMode */
W(GL_DONT_CARE);
W(GL_FASTEST);
W(GL_NICEST);
/* DataType */
W(GL_BYTE);
W(GL_UNSIGNED_BYTE);
W(GL_SHORT);
W(GL_UNSIGNED_SHORT);
W(GL_INT);
W(GL_UNSIGNED_INT);
W(GL_FLOAT);
W(GL_FIXED);
/* PixelFormat */
W(GL_DEPTH_COMPONENT);
W(GL_ALPHA);
W(GL_RGB);
W(GL_RGBA);
W(GL_COMPRESSED_RGB8_ETC2);
W(GL_COMPRESSED_RGBA8_ETC2_EAC);
/* PixelType */
W(GL_UNSIGNED_SHORT_4_4_4_4);
W(GL_UNSIGNED_SHORT_5_5_5_1);
W(GL_UNSIGNED_SHORT_5_6_5);
/* Shaders */
W(GL_FRAGMENT_SHADER);
W(GL_VERTEX_SHADER);
W(GL_MAX_VERTEX_ATTRIBS);
W(GL_MAX_VERTEX_UNIFORM_VECTORS);
W(GL_MAX_FRAGMENT_UNIFORM_VECTORS);
W(GL_MAX_VARYING_VECTORS);
W(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS);
W(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS);
W(GL_MAX_TEXTURE_IMAGE_UNITS);
W(GL_SHADER_TYPE);
W(GL_DELETE_STATUS);
W(GL_LINK_STATUS);
W(GL_VALIDATE_STATUS);
W(GL_ATTACHED_SHADERS);
W(GL_ACTIVE_UNIFORMS);
W(GL_ACTIVE_UNIFORM_MAX_LENGTH);
W(GL_ACTIVE_ATTRIBUTES);
W(GL_ACTIVE_ATTRIBUTE_MAX_LENGTH);
W(GL_SHADING_LANGUAGE_VERSION);
W(GL_CURRENT_PROGRAM);
/* StencilFunction */
W(GL_NEVER);
W(GL_LESS);
W(GL_EQUAL);
W(GL_LEQUAL);
W(GL_GREATER);
W(GL_NOTEQUAL);
W(GL_GEQUAL);
W(GL_ALWAYS);
/* StencilOp */
W(GL_KEEP);
W(GL_REPLACE);
W(GL_INCR);
W(GL_DECR);
W(GL_INVERT);
W(GL_INCR_WRAP);
W(GL_DECR_WRAP);
/* StringName */
W(GL_VENDOR);
W(GL_RENDERER);
W(GL_VERSION);
W(GL_EXTENSIONS);
/* TextureMagFilter */
W(GL_NEAREST);
W(GL_LINEAR);
/* TextureMinFilter */
W(GL_NEAREST_MIPMAP_NEAREST);
W(GL_LINEAR_MIPMAP_NEAREST);
W(GL_NEAREST_MIPMAP_LINEAR);
W(GL_LINEAR_MIPMAP_LINEAR);
/* TextureParameterName */
W(GL_TEXTURE_MAG_FILTER);
W(GL_TEXTURE_MIN_FILTER);
W(GL_TEXTURE_WRAP_S);
W(GL_TEXTURE_WRAP_T);
/* TextureTarget */
W(GL_TEXTURE);
W(GL_TEXTURE_CUBE_MAP);
W(GL_TEXTURE_BINDING_CUBE_MAP);
W(GL_TEXTURE_CUBE_MAP_POSITIVE_X);
W(GL_TEXTURE_CUBE_MAP_NEGATIVE_X);
W(GL_TEXTURE_CUBE_MAP_POSITIVE_Y);
W(GL_TEXTURE_CUBE_MAP_NEGATIVE_Y);
W(GL_TEXTURE_CUBE_MAP_POSITIVE_Z);
W(GL_TEXTURE_CUBE_MAP_NEGATIVE_Z);
W(GL_MAX_CUBE_MAP_TEXTURE_SIZE);
/* TextureUnit */
W(GL_TEXTURE0);
W(GL_TEXTURE1);
W(GL_TEXTURE2);
W(GL_TEXTURE3);
W(GL_TEXTURE4);
W(GL_TEXTURE5);
W(GL_TEXTURE6);
W(GL_TEXTURE7);
W(GL_TEXTURE8);
W(GL_TEXTURE9);
W(GL_TEXTURE10);
W(GL_TEXTURE11);
W(GL_TEXTURE12);
W(GL_TEXTURE13);
W(GL_TEXTURE14);
W(GL_TEXTURE15);
W(GL_TEXTURE16);
W(GL_TEXTURE17);
W(GL_TEXTURE18);
W(GL_TEXTURE19);
W(GL_TEXTURE20);
W(GL_TEXTURE21);
W(GL_TEXTURE22);
W(GL_TEXTURE23);
W(GL_TEXTURE24);
W(GL_TEXTURE25);
W(GL_TEXTURE26);
W(GL_TEXTURE27);
W(GL_TEXTURE28);
W(GL_TEXTURE29);
W(GL_TEXTURE30);
W(GL_TEXTURE31);
W(GL_ACTIVE_TEXTURE);
/* TextureWrapMode */
W(GL_REPEAT);
W(GL_CLAMP_TO_EDGE);
W(GL_MIRRORED_REPEAT);
/* Uniform Types */
W(GL_FLOAT_VEC2);
W(GL_FLOAT_VEC3);
W(GL_FLOAT_VEC4);
W(GL_INT_VEC2);
W(GL_INT_VEC3);
W(GL_INT_VEC4);
W(GL_BOOL);
W(GL_BOOL_VEC2);
W(GL_BOOL_VEC3);
W(GL_BOOL_VEC4);
W(GL_FLOAT_MAT2);
W(GL_FLOAT_MAT3);
W(GL_FLOAT_MAT4);
W(GL_SAMPLER_2D);
W(GL_SAMPLER_CUBE);
/* Vertex Arrays */
W(GL_VERTEX_ATTRIB_ARRAY_ENABLED);
W(GL_VERTEX_ATTRIB_ARRAY_SIZE);
W(GL_VERTEX_ATTRIB_ARRAY_STRIDE);
W(GL_VERTEX_ATTRIB_ARRAY_TYPE);
W(GL_VERTEX_ATTRIB_ARRAY_NORMALIZED);
W(GL_VERTEX_ATTRIB_ARRAY_POINTER);
W(GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING);
/* Read Format */
W(GL_IMPLEMENTATION_COLOR_READ_TYPE);
W(GL_IMPLEMENTATION_COLOR_READ_FORMAT);
/* Shader Source */
W(GL_COMPILE_STATUS);
W(GL_INFO_LOG_LENGTH);
W(GL_SHADER_SOURCE_LENGTH);
W(GL_SHADER_COMPILER);
/* Shader Binary */
W(GL_SHADER_BINARY_FORMATS);
W(GL_NUM_SHADER_BINARY_FORMATS);
/* Shader Precision-Specified Types */
W(GL_LOW_FLOAT);
W(GL_MEDIUM_FLOAT);
W(GL_HIGH_FLOAT);
W(GL_LOW_INT);
W(GL_MEDIUM_INT);
W(GL_HIGH_INT);
/* Framebuffer Object. */
W(GL_FRAMEBUFFER);
W(GL_RENDERBUFFER);
W(GL_RGBA4);
W(GL_RGB5_A1);
W(GL_RGB565);
W(GL_DEPTH_COMPONENT16);
W(GL_STENCIL_INDEX);
W(GL_STENCIL_INDEX8);
W(GL_RENDERBUFFER_WIDTH);
W(GL_RENDERBUFFER_HEIGHT);
W(GL_RENDERBUFFER_INTERNAL_FORMAT);
W(GL_RENDERBUFFER_RED_SIZE);
W(GL_RENDERBUFFER_GREEN_SIZE);
W(GL_RENDERBUFFER_BLUE_SIZE);
W(GL_RENDERBUFFER_ALPHA_SIZE);
W(GL_RENDERBUFFER_DEPTH_SIZE);
W(GL_RENDERBUFFER_STENCIL_SIZE);
W(GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE);
W(GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME);
W(GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL);
W(GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE);
W(GL_COLOR_ATTACHMENT0);
W(GL_DEPTH_ATTACHMENT);
W(GL_STENCIL_ATTACHMENT);
W(GL_FRAMEBUFFER_COMPLETE);
W(GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT);
W(GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT);
W(GL_FRAMEBUFFER_UNSUPPORTED);
W(GL_FRAMEBUFFER_BINDING);
W(GL_RENDERBUFFER_BINDING);
W(GL_MAX_RENDERBUFFER_SIZE);
W(GL_INVALID_FRAMEBUFFER_OPERATION);
W(GL_TEXTURE_WIDTH);
W(GL_TEXTURE_HEIGHT);
W(GL_TEXTURE_INTERNAL_FORMAT);
W(GL_LINE);
W(GL_FILL);
W(GL_UNIFORM_BUFFER);
W(GL_RGBA32F);
W(GL_RGB32F);
W(GL_RGBA16F);
W(GL_COMPRESSED_RED);
W(GL_COMPRESSED_RGB);
W(GL_COMPRESSED_RGBA);
W(GL_RED);
W(GL_R16);
W(GL_R32F);
W(GL_RGB16F);
W(GL_TEXTURE_3D);
W(GL_DEPTH_COMPONENT24);
W(GL_BGR);
W(GL_BGRA);
W(GL_TEXTURE_COMPRESSED_IMAGE_SIZE);
W(GL_TEXTURE_COMPRESSED);
W(GL_TIME_ELAPSED);
W(GL_TIMESTAMP);
W(GL_QUERY_RESULT);
W(GL_QUERY_RESULT_AVAILABLE);
W(GL_PROGRAM_BINARY_LENGTH);
W(GL_PROGRAM_BINARY_RETRIEVABLE_HINT);
W(GL_UNIFORM_BLOCK_DATA_SIZE);
W(GL_GEOMETRY_SHADER);
W(GL_PATCHES);
W(GL_PATCH_VERTICES);
W(GL_TESS_EVALUATION_SHADER);
W(GL_TESS_CONTROL_SHADER);
return std::to_string(e);
}
| 20.683698
| 52
| 0.764616
|
adoug
|
9590f35960698ec5baec6d3f40b7936858cd28b8
| 1,683
|
cpp
|
C++
|
enshellcode.cpp
|
3gstudent/Shellcode-Generater
|
ca992ef1a5493e908bce18327c3efc1aeeb4c5f4
|
[
"BSD-3-Clause"
] | 61
|
2017-01-19T07:40:24.000Z
|
2022-03-14T18:56:27.000Z
|
enshellcode.cpp
|
3gstudent/Shellcode-Generater
|
ca992ef1a5493e908bce18327c3efc1aeeb4c5f4
|
[
"BSD-3-Clause"
] | null | null | null |
enshellcode.cpp
|
3gstudent/Shellcode-Generater
|
ca992ef1a5493e908bce18327c3efc1aeeb4c5f4
|
[
"BSD-3-Clause"
] | 35
|
2017-01-19T07:40:30.000Z
|
2022-03-14T18:56:30.000Z
|
#include <windows.h>
size_t GetSize(char * szFilePath)
{
size_t size;
FILE* f = fopen(szFilePath, "rb");
fseek(f, 0, SEEK_END);
size = ftell(f);
rewind(f);
fclose(f);
return size;
}
unsigned char* ReadBinaryFile(char *szFilePath, size_t *size)
{
unsigned char *p = NULL;
FILE* f = NULL;
size_t res = 0;
*size = GetSize(szFilePath);
if (*size == 0) return NULL;
f = fopen(szFilePath, "rb");
if (f == NULL)
{
printf("Binary file does not exists!\n");
return 0;
}
p = new unsigned char[*size];
rewind(f);
res = fread(p, sizeof(unsigned char), *size, f);
fclose(f);
if (res == 0)
{
delete[] p;
return NULL;
}
return p;
}
int main(int argc, char* argv[])
{
char *szFilePath="c:\\test\\shellcode.bin";
char *szFilePath2="c:\\test\\shellcode2.bin";
unsigned char *BinData = NULL;
size_t size = 0;
BinData = ReadBinaryFile(szFilePath, &size);
for(int i=0;i<size;i++)
{
BinData[i]=BinData[i]^0x44;
}
FILE* f = NULL;
f = fopen(szFilePath2, "wb");
if (f == NULL)
{
printf("Create error\n");
return 0;
}
char decode[]="\x83\xC0\x14\x33\xC9\x8A\x1C\x08\x80\xF3\x44\x88\x1C\x08\x41\x80\xFB\x91\x75\xF1";
char end[]="\xD5";
fwrite(decode,20,1,f);
fwrite(BinData,size,1,f);
fwrite(end,1,1,f);
fclose(f);
f = fopen(szFilePath2, "rb");
if (f == NULL)
{
printf("Create error\n");
return 0;
}
unsigned char *BinData2 = NULL;
size_t size2 = 0;
BinData2 = ReadBinaryFile(szFilePath2, &size2);
printf("\"");
for (int j=0;j<size2;j++)
{
printf("\\x%02x",BinData2[j]);
if((j+1)%16==0)
printf("\"\n\"");
}
printf("\"");
fclose(f);
return 0;
}
| 21.0375
| 99
| 0.586453
|
3gstudent
|
d2e60056a68e23bf365edb4411447e7794d5552f
| 6,434
|
cpp
|
C++
|
tests/test_vec3.cpp
|
stephen-sorley/obvi
|
ead96e23dfd9ffba35590b3a035556eeb093d9a8
|
[
"MIT"
] | null | null | null |
tests/test_vec3.cpp
|
stephen-sorley/obvi
|
ead96e23dfd9ffba35590b3a035556eeb093d9a8
|
[
"MIT"
] | null | null | null |
tests/test_vec3.cpp
|
stephen-sorley/obvi
|
ead96e23dfd9ffba35590b3a035556eeb093d9a8
|
[
"MIT"
] | null | null | null |
/* Unit tests for vec3 (util library).
*
* * * * * * * * * * * *
* The MIT License (MIT)
*
* Copyright (c) 2019 Stephen Sorley
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
* * * * * * * * * * * *
*/
#include <catch2/catch.hpp>
#include <obvi/util/vec3.hpp>
using obvi::vec3;
using namespace Catch::literals; // To get "_a" UDL for approximate floating-point values.
#define VEC3_EQUAL(v, v0, v1, v2) \
REQUIRE( v.pt[0] == v0 ); \
REQUIRE( v.pt[1] == v1 ); \
REQUIRE( v.pt[2] == v2 );
TEMPLATE_TEST_CASE("vec3 set and get", "[vec3]", float, double) {
vec3<TestType> v;
VEC3_EQUAL(v, 0, 0, 0);
SECTION( "array and named element access are the same" ) {
v.pt[0] = TestType(1.1);
v.pt[1] = TestType(2.2);
v.pt[2] = TestType(3.3);
VEC3_EQUAL(v, v.x(), v.y(), v.z());
}
SECTION( "array and index element access are the same" ) {
v.pt[0] = TestType(1.1);
v.pt[1] = TestType(2.2);
v.pt[2] = TestType(3.3);
VEC3_EQUAL(v, v[0], v[1], v[2]);
const vec3<TestType> &vref = v;
VEC3_EQUAL(v, vref[0], vref[1], vref[2]);
}
SECTION( "set method works" ) {
v.set(TestType(4.4), TestType(5.5), TestType(6.6));
VEC3_EQUAL(v, TestType(4.4), TestType(5.5), TestType(6.6));
}
SECTION( "initialization from different type works" ) {
vec3<long double> w(1.0L,2.0L,3.6L);
v = vec3<TestType>(w);
VEC3_EQUAL(v, TestType(w.x()), TestType(w.y()), TestType(w.z()))
}
}
TEMPLATE_TEST_CASE("vec3 math", "[vec3]", float, double) {
vec3<TestType> v(1,2,3);
vec3<TestType> w(4,5,6);
TestType s = 2.5;
SECTION( "negate" ) {
w = -v;
VEC3_EQUAL(w, -1.0_a, -2.0_a, -3.0_a);
}
SECTION( "add" ) {
SECTION( "vector in-place" ) {
v += w;
VEC3_EQUAL(v, 5.0_a, 7.0_a, 9.0_a);
}
SECTION( "vector separate" ) {
v = v + w;
VEC3_EQUAL(v, 5.0_a, 7.0_a, 9.0_a);
}
SECTION( "scalar in-place" ) {
v += s;
VEC3_EQUAL(v, 3.5_a, 4.5_a, 5.5_a);
}
SECTION( "scalar separate right" ) {
v = v + s;
VEC3_EQUAL(v, 3.5_a, 4.5_a, 5.5_a);
}
SECTION( "scalar separate left" ) {
v = s + v;
VEC3_EQUAL(v, 3.5_a, 4.5_a, 5.5_a);
}
}
SECTION( "subtract" ) {
SECTION( "vector in-place" ) {
v -= w;
VEC3_EQUAL(v, -3.0_a, -3.0_a, -3.0_a);
}
SECTION( "vector separate" ) {
v = v - w;
VEC3_EQUAL(v, -3.0_a, -3.0_a, -3.0_a);
}
SECTION( "scalar in-place" ) {
v -= s;
VEC3_EQUAL(v, -1.5_a, -0.5_a, 0.5_a);
}
SECTION( "scalar separate" ) {
v = v - s;
VEC3_EQUAL(v, -1.5_a, -0.5_a, 0.5_a);
}
}
SECTION( "multiply" ) {
SECTION( "scalar in-place" ) {
v *= s;
VEC3_EQUAL(v, 2.5_a, 5.0_a, 7.5_a);
}
SECTION( "scalar separate right" ) {
v = v * s;
VEC3_EQUAL(v, 2.5_a, 5.0_a, 7.5_a);
}
SECTION( "scalar separate left" ) {
v = s * v;
VEC3_EQUAL(v, 2.5_a, 5.0_a, 7.5_a);
}
SECTION( "vector in-place" ) {
v *= w;
VEC3_EQUAL(v, 4.0_a, 10.0_a, 18.0_a);
}
SECTION( "vector separate" ) {
v = v * w;
VEC3_EQUAL(v, 4.0_a, 10.0_a, 18.0_a);
}
}
SECTION( "divide" ) {
SECTION( "scalar in-place" ) {
v /= s;
VEC3_EQUAL(v, 0.4_a, 0.8_a, 1.2_a);
}
SECTION( "scalar separate right" ) {
v = v / s;
VEC3_EQUAL(v, 0.4_a, 0.8_a, 1.2_a);
}
SECTION( "scalar separate left" ) {
v = s / v;
VEC3_EQUAL(v, 2.5_a, 1.25_a, 0.8333333333333333_a);
}
SECTION( "vector in-place" ) {
v /= w;
VEC3_EQUAL(v, 0.25_a, 0.4_a, 0.5_a);
}
SECTION( "vector separate" ) {
v = v / w;
VEC3_EQUAL(v, 0.25_a, 0.4_a, 0.5_a);
}
}
SECTION( "dot product" ) {
REQUIRE( v.dot(w) == 32.0_a );
REQUIRE( v.dot(w.x(), w.y(), w.z()) == 32.0_a );
}
SECTION( "cross product" ) {
v = v.cross(w);
VEC3_EQUAL(v, -3.0_a, 6.0_a, -3.0_a);
}
SECTION( "2-norm" ) {
REQUIRE( v.normsqd() == 14.0_a );
w = v.normalized();
VEC3_EQUAL(w, 0.2672612_a, 0.5345225_a, 0.8017837_a);
}
SECTION( "min/max" ) {
using vec3t = vec3<TestType>;
REQUIRE( vec3t(1,5,7).min_component() == 1 );
REQUIRE( vec3t(7,1,5).min_component() == 1 );
REQUIRE( vec3t(5,7,1).min_component() == 1 );
REQUIRE( vec3t(1,5,7).max_component() == 7 );
REQUIRE( vec3t(7,1,5).max_component() == 7 );
REQUIRE( vec3t(5,7,1).max_component() == 7 );
v.set(1,5,7);
w.set(2,3,6);
VEC3_EQUAL(std::min(v,w), 1, 3, 6);
VEC3_EQUAL(std::max(v,w), 2, 5, 7);
}
}
| 28.981982
| 91
| 0.494871
|
stephen-sorley
|
d2e7346e5842d06158d5b731f4695a17f846f84c
| 1,080
|
cc
|
C++
|
src/commands/heapdump/heap_snapshot.cc
|
rickyes/xprofiler
|
536160b955daa36b6953f3856e11149218ef1390
|
[
"BSD-2-Clause"
] | 249
|
2020-05-22T14:25:36.000Z
|
2022-03-29T02:30:18.000Z
|
src/commands/heapdump/heap_snapshot.cc
|
rickyes/xprofiler
|
536160b955daa36b6953f3856e11149218ef1390
|
[
"BSD-2-Clause"
] | 97
|
2020-05-29T06:10:04.000Z
|
2022-03-31T10:14:59.000Z
|
src/commands/heapdump/heap_snapshot.cc
|
rickyes/xprofiler
|
536160b955daa36b6953f3856e11149218ef1390
|
[
"BSD-2-Clause"
] | 39
|
2020-06-11T08:45:35.000Z
|
2022-03-15T07:29:53.000Z
|
#include "heap_snapshot.h"
#include "../../library/writer.h"
#include "../../logger.h"
namespace xprofiler {
using v8::OutputStream;
class FileOutputStream : public OutputStream {
public:
FileOutputStream(FILE *stream) : stream_(stream) {}
virtual int GetChunkSize() {
return 65536; // big chunks == faster
}
virtual void EndOfStream() {}
virtual WriteResult WriteAsciiChunk(char *data, int size) {
const size_t len = static_cast<size_t>(size);
size_t off = 0;
while (off < len && !feof(stream_) && !ferror(stream_))
off += fwrite(data + off, 1, len - off, stream_);
return off == len ? kContinue : kAbort;
}
private:
FILE *stream_;
};
void Snapshot::Serialize(const HeapSnapshot *profile, string filename) {
FILE *fp = fopen(filename.c_str(), "w");
if (fp == NULL) {
Error("heapdump", "open file %s failed.", filename.c_str());
return;
}
FileOutputStream stream(fp);
profile->Serialize(&stream, HeapSnapshot::kJSON);
fclose(fp);
const_cast<HeapSnapshot *>(profile)->Delete();
}
} // namespace xprofiler
| 24
| 72
| 0.660185
|
rickyes
|
d2e7839d96e9324465863c5e0aeebbe4e48d3442
| 9,579
|
cpp
|
C++
|
build/moc/moc_VideoReceiver.cpp
|
UNIST-ESCL/UNIST_GCS
|
f61f0c12bbb028869e4494f507ea8ab52c8c79c2
|
[
"Apache-2.0"
] | 1
|
2018-11-07T06:10:53.000Z
|
2018-11-07T06:10:53.000Z
|
build/moc/moc_VideoReceiver.cpp
|
UNIST-ESCL/UNIST_GCS
|
f61f0c12bbb028869e4494f507ea8ab52c8c79c2
|
[
"Apache-2.0"
] | null | null | null |
build/moc/moc_VideoReceiver.cpp
|
UNIST-ESCL/UNIST_GCS
|
f61f0c12bbb028869e4494f507ea8ab52c8c79c2
|
[
"Apache-2.0"
] | 1
|
2018-11-07T06:10:47.000Z
|
2018-11-07T06:10:47.000Z
|
/****************************************************************************
** Meta object code from reading C++ file 'VideoReceiver.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.9.3)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../../src/VideoStreaming/VideoReceiver.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'VideoReceiver.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.9.3. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
struct qt_meta_stringdata_VideoReceiver_t {
QByteArrayData data[19];
char stringdata0[230];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_VideoReceiver_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_VideoReceiver_t qt_meta_stringdata_VideoReceiver = {
{
QT_MOC_LITERAL(0, 0, 13), // "VideoReceiver"
QT_MOC_LITERAL(1, 14, 19), // "videoRunningChanged"
QT_MOC_LITERAL(2, 34, 0), // ""
QT_MOC_LITERAL(3, 35, 16), // "imageFileChanged"
QT_MOC_LITERAL(4, 52, 16), // "videoFileChanged"
QT_MOC_LITERAL(5, 69, 21), // "showFullScreenChanged"
QT_MOC_LITERAL(6, 91, 5), // "start"
QT_MOC_LITERAL(7, 97, 4), // "stop"
QT_MOC_LITERAL(8, 102, 6), // "setUri"
QT_MOC_LITERAL(9, 109, 3), // "uri"
QT_MOC_LITERAL(10, 113, 13), // "stopRecording"
QT_MOC_LITERAL(11, 127, 14), // "startRecording"
QT_MOC_LITERAL(12, 142, 9), // "videoFile"
QT_MOC_LITERAL(13, 152, 12), // "_updateTimer"
QT_MOC_LITERAL(14, 165, 12), // "videoSurface"
QT_MOC_LITERAL(15, 178, 13), // "VideoSurface*"
QT_MOC_LITERAL(16, 192, 12), // "videoRunning"
QT_MOC_LITERAL(17, 205, 9), // "imageFile"
QT_MOC_LITERAL(18, 215, 14) // "showFullScreen"
},
"VideoReceiver\0videoRunningChanged\0\0"
"imageFileChanged\0videoFileChanged\0"
"showFullScreenChanged\0start\0stop\0"
"setUri\0uri\0stopRecording\0startRecording\0"
"videoFile\0_updateTimer\0videoSurface\0"
"VideoSurface*\0videoRunning\0imageFile\0"
"showFullScreen"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_VideoReceiver[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
11, 14, // methods
5, 84, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
4, // signalCount
// signals: name, argc, parameters, tag, flags
1, 0, 69, 2, 0x06 /* Public */,
3, 0, 70, 2, 0x06 /* Public */,
4, 0, 71, 2, 0x06 /* Public */,
5, 0, 72, 2, 0x06 /* Public */,
// slots: name, argc, parameters, tag, flags
6, 0, 73, 2, 0x0a /* Public */,
7, 0, 74, 2, 0x0a /* Public */,
8, 1, 75, 2, 0x0a /* Public */,
10, 0, 78, 2, 0x0a /* Public */,
11, 1, 79, 2, 0x0a /* Public */,
11, 0, 82, 2, 0x2a /* Public | MethodCloned */,
13, 0, 83, 2, 0x08 /* Private */,
// signals: parameters
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
// slots: parameters
QMetaType::Void,
QMetaType::Void,
QMetaType::Void, QMetaType::QString, 9,
QMetaType::Void,
QMetaType::Void, QMetaType::QString, 12,
QMetaType::Void,
QMetaType::Void,
// properties: name, type, flags
14, 0x80000000 | 15, 0x00095409,
16, QMetaType::Bool, 0x00495001,
17, QMetaType::QString, 0x00495001,
12, QMetaType::QString, 0x00495001,
18, QMetaType::Bool, 0x00495103,
// properties: notify_signal_id
0,
0,
1,
2,
3,
0 // eod
};
void VideoReceiver::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
VideoReceiver *_t = static_cast<VideoReceiver *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->videoRunningChanged(); break;
case 1: _t->imageFileChanged(); break;
case 2: _t->videoFileChanged(); break;
case 3: _t->showFullScreenChanged(); break;
case 4: _t->start(); break;
case 5: _t->stop(); break;
case 6: _t->setUri((*reinterpret_cast< const QString(*)>(_a[1]))); break;
case 7: _t->stopRecording(); break;
case 8: _t->startRecording((*reinterpret_cast< const QString(*)>(_a[1]))); break;
case 9: _t->startRecording(); break;
case 10: _t->_updateTimer(); break;
default: ;
}
} else if (_c == QMetaObject::IndexOfMethod) {
int *result = reinterpret_cast<int *>(_a[0]);
{
typedef void (VideoReceiver::*_t)();
if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&VideoReceiver::videoRunningChanged)) {
*result = 0;
return;
}
}
{
typedef void (VideoReceiver::*_t)();
if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&VideoReceiver::imageFileChanged)) {
*result = 1;
return;
}
}
{
typedef void (VideoReceiver::*_t)();
if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&VideoReceiver::videoFileChanged)) {
*result = 2;
return;
}
}
{
typedef void (VideoReceiver::*_t)();
if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&VideoReceiver::showFullScreenChanged)) {
*result = 3;
return;
}
}
} else if (_c == QMetaObject::RegisterPropertyMetaType) {
switch (_id) {
default: *reinterpret_cast<int*>(_a[0]) = -1; break;
case 0:
*reinterpret_cast<int*>(_a[0]) = qRegisterMetaType< VideoSurface* >(); break;
}
}
#ifndef QT_NO_PROPERTIES
else if (_c == QMetaObject::ReadProperty) {
VideoReceiver *_t = static_cast<VideoReceiver *>(_o);
Q_UNUSED(_t)
void *_v = _a[0];
switch (_id) {
case 0: *reinterpret_cast< VideoSurface**>(_v) = _t->videoSurface(); break;
case 1: *reinterpret_cast< bool*>(_v) = _t->videoRunning(); break;
case 2: *reinterpret_cast< QString*>(_v) = _t->imageFile(); break;
case 3: *reinterpret_cast< QString*>(_v) = _t->videoFile(); break;
case 4: *reinterpret_cast< bool*>(_v) = _t->showFullScreen(); break;
default: break;
}
} else if (_c == QMetaObject::WriteProperty) {
VideoReceiver *_t = static_cast<VideoReceiver *>(_o);
Q_UNUSED(_t)
void *_v = _a[0];
switch (_id) {
case 4: _t->setShowFullScreen(*reinterpret_cast< bool*>(_v)); break;
default: break;
}
} else if (_c == QMetaObject::ResetProperty) {
}
#endif // QT_NO_PROPERTIES
}
const QMetaObject VideoReceiver::staticMetaObject = {
{ &QObject::staticMetaObject, qt_meta_stringdata_VideoReceiver.data,
qt_meta_data_VideoReceiver, qt_static_metacall, nullptr, nullptr}
};
const QMetaObject *VideoReceiver::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *VideoReceiver::qt_metacast(const char *_clname)
{
if (!_clname) return nullptr;
if (!strcmp(_clname, qt_meta_stringdata_VideoReceiver.stringdata0))
return static_cast<void*>(this);
return QObject::qt_metacast(_clname);
}
int VideoReceiver::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QObject::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 11)
qt_static_metacall(this, _c, _id, _a);
_id -= 11;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 11)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 11;
}
#ifndef QT_NO_PROPERTIES
else if (_c == QMetaObject::ReadProperty || _c == QMetaObject::WriteProperty
|| _c == QMetaObject::ResetProperty || _c == QMetaObject::RegisterPropertyMetaType) {
qt_static_metacall(this, _c, _id, _a);
_id -= 5;
} else if (_c == QMetaObject::QueryPropertyDesignable) {
_id -= 5;
} else if (_c == QMetaObject::QueryPropertyScriptable) {
_id -= 5;
} else if (_c == QMetaObject::QueryPropertyStored) {
_id -= 5;
} else if (_c == QMetaObject::QueryPropertyEditable) {
_id -= 5;
} else if (_c == QMetaObject::QueryPropertyUser) {
_id -= 5;
}
#endif // QT_NO_PROPERTIES
return _id;
}
// SIGNAL 0
void VideoReceiver::videoRunningChanged()
{
QMetaObject::activate(this, &staticMetaObject, 0, nullptr);
}
// SIGNAL 1
void VideoReceiver::imageFileChanged()
{
QMetaObject::activate(this, &staticMetaObject, 1, nullptr);
}
// SIGNAL 2
void VideoReceiver::videoFileChanged()
{
QMetaObject::activate(this, &staticMetaObject, 2, nullptr);
}
// SIGNAL 3
void VideoReceiver::showFullScreenChanged()
{
QMetaObject::activate(this, &staticMetaObject, 3, nullptr);
}
QT_WARNING_POP
QT_END_MOC_NAMESPACE
| 33.493007
| 107
| 0.598288
|
UNIST-ESCL
|
d2e91391e42c5312372509b2bb141c1a7d383ec3
| 4,090
|
cpp
|
C++
|
src/gdb_server.cpp
|
Cytosine2020/neutron
|
1c3db597d8a4027a03f1201c0ffb255a831a246c
|
[
"MIT"
] | 2
|
2020-09-03T13:36:55.000Z
|
2022-03-19T17:54:36.000Z
|
src/gdb_server.cpp
|
Cytosine2020/neutron
|
1c3db597d8a4027a03f1201c0ffb255a831a246c
|
[
"MIT"
] | null | null | null |
src/gdb_server.cpp
|
Cytosine2020/neutron
|
1c3db597d8a4027a03f1201c0ffb255a831a246c
|
[
"MIT"
] | null | null | null |
#include "gdb_server.hpp"
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <ostream>
#include "neutron_utility.hpp"
namespace neutron {
bool GDBServer::Buffer::receive(int socket) {
if (begin_ < end_ && begin_ > 0) {
for (usize i = begin_; i < end_; ++i) {
array[i - begin_] = array[i];
}
}
usize remain = end_ - begin_;
isize ret = recv(socket, array.begin() + remain, array.size() - remain, 0);
begin_ = 0;
end_ = remain + ret;
if (debug) {
if (ret > 0) {
*debug_stream << "[receive] ";
(*debug_stream).write(reinterpret_cast<const char *>(array.begin() + remain), end_);
*debug_stream << std::endl;
} else {
*debug_stream << "recv failed!" << std::endl;
}
}
return ret > 0;
}
bool GDBServer::Buffer::receive_message(int socket, GDBServer::Buffer &buf) {
if (!seek_message(socket)) return false;
u8 sum = 0;
while (true) {
i32 a = pop_socket(socket), b;
switch (a) {
case -1:
goto error;
case '$':
if (debug) { *debug_stream << "unexpected character `$`!" << std::endl; }
goto error;
case '#':
if (sum != pop_hex_byte_socket(socket)) { goto error; }
return true;
case '}':
b = pop_socket(socket);
if (b == -1) { goto error; }
sum += a + b;
buf.push(static_cast<u8>(b) ^ ESCAPE);
break;
default:
sum += a;
buf.push(a);
}
}
error:
buf.clear();
clear();
return false;
}
bool GDBServer::gdb_connect(u32 port) {
int socket_fd = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in local{};
struct sockaddr_in gdb_addr{};
local.sin_family = AF_INET;
local.sin_port = htons(port);
local.sin_addr = in_addr{.s_addr = INADDR_ANY};
socklen_t len = sizeof(gdb_addr);
if (socket_fd == -1) {
neutron_warn("socket creation failed!");
goto error;
}
if (bind(socket_fd, reinterpret_cast<struct sockaddr *>(&local), sizeof(local)) == -1) {
neutron_warn("socket bind failed!");
goto error;
}
if (listen(socket_fd, 1) == -1) {
neutron_warn("socket listen failed!");
goto error;
}
gdb = ::accept(socket_fd, reinterpret_cast<struct sockaddr *>(&gdb_addr), &len);
if (gdb == -1) {
neutron_warn("accept failed!");
goto error;
}
if (debug) {
char *in_addr = reinterpret_cast<char *>(&gdb_addr.sin_addr);
*debug_stream << static_cast<u32>(in_addr[0]) << '.'
<< static_cast<u32>(in_addr[1]) << '.'
<< static_cast<u32>(in_addr[2]) << '.'
<< static_cast<u32>(in_addr[3]) << ':'
<< gdb_addr.sin_port << std::endl;
}
close(socket_fd);
if (recv_buffer.pop_socket(gdb) != '+') {
if (debug) { *debug_stream << "the first character received is not `+`!" << std::endl; }
gdb_close();
}
send_buffer.push('$');
return true;
error:
if (socket_fd != -1) { close(socket_fd); }
return false;
}
bool GDBServer::send() {
u8 sum = 0;
for (auto *ptr = send_buffer.begin() + 1, *end = send_buffer.end(); ptr < end; ++ptr) {
sum += *ptr;
}
if (!send_buffer.push('#') || !send_buffer.push_hex_byte(sum)) return false;
for (usize retry = 0; retry < RETRY; ++retry) {
isize byte = send_message(reinterpret_cast<const char *>(send_buffer.begin()),
send_buffer.size());
if (static_cast<usize>(byte) == send_buffer.size()) {
recv_buffer.clear();
if (recv_buffer.pop_socket(gdb) == '+') {
send_buffer.clear();
send_buffer.push('$');
return true;
}
}
}
return false;
}
}
| 25.72327
| 96
| 0.51198
|
Cytosine2020
|
d2ea4e3b00573bdd4382469a615e62247c72b75d
| 645
|
hpp
|
C++
|
modules/procedural/source/blub/procedural/log/global.hpp
|
qwertzui11/voxelTerrain
|
05038fb261893dd044ae82fab96b7708ea5ed623
|
[
"MIT"
] | 96
|
2015-02-02T20:01:24.000Z
|
2021-11-14T20:33:29.000Z
|
modules/procedural/source/blub/procedural/log/global.hpp
|
qwertzui11/voxelTerrain
|
05038fb261893dd044ae82fab96b7708ea5ed623
|
[
"MIT"
] | 12
|
2016-06-04T15:45:30.000Z
|
2020-02-04T11:10:51.000Z
|
modules/procedural/source/blub/procedural/log/global.hpp
|
qwertzui11/voxelTerrain
|
05038fb261893dd044ae82fab96b7708ea5ed623
|
[
"MIT"
] | 19
|
2015-09-22T01:21:45.000Z
|
2020-09-30T09:52:27.000Z
|
#ifndef BLUB_PROCEDURAL_LOG_GLOBAL_HPP
#define BLUB_PROCEDURAL_LOG_GLOBAL_HPP
#include "blub/log/global.hpp"
#include "blub/log/globalLogger.hpp"
#include "blub/log/logger.hpp"
#include "blub/log/predecl.hpp"
namespace blub
{
namespace procedural
{
namespace log
{
BLUB_LOG_GLOBAL_LOGGER(global, blub::log::logger)
}
}
}
#define BLUB_PROCEDURAL_LOG_OUT() BLUB_LOG_OUT_TO(blub::procedural::log::global::get())
#define BLUB_PROCEDURAL_LOG_WARNING() BLUB_LOG_WARNING_TO(blub::procedural::log::global::get())
#define BLUB_PROCEDURAL_LOG_ERROR() BLUB_LOG_ERROR_TO(blub::procedural::log::global::get())
#endif // BLUB_PROCEDURAL_LOG_GLOBAL_HPP
| 23.035714
| 95
| 0.795349
|
qwertzui11
|
d2ee01391bcdf7ee82c7a630fc56fcefc34731e7
| 7,327
|
cpp
|
C++
|
tester/g_ult/unit_tests/cpu/test_cases/cpu_layer_softmax.cpp
|
davenso/idlf
|
df34a6b88c1ff1880fbb2b58caccd6075dd414a5
|
[
"BSD-3-Clause"
] | 1
|
2015-12-04T21:01:27.000Z
|
2015-12-04T21:01:27.000Z
|
tester/g_ult/unit_tests/cpu/test_cases/cpu_layer_softmax.cpp
|
davenso/idlf
|
df34a6b88c1ff1880fbb2b58caccd6075dd414a5
|
[
"BSD-3-Clause"
] | null | null | null |
tester/g_ult/unit_tests/cpu/test_cases/cpu_layer_softmax.cpp
|
davenso/idlf
|
df34a6b88c1ff1880fbb2b58caccd6075dd414a5
|
[
"BSD-3-Clause"
] | null | null | null |
/*
Copyright (c) 2014, Intel Corporation
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Intel Corporation nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <cfloat>
#include "tester/g_ult/unit_tests/cpu/naive_implementations.h"
namespace
{
///////////////////////////////////////////////////////////////////////////////////////////////////
// Helper classess and functions.
bool compare_work_items(
nn_workload_item* &work_item,
nn_workload_item* &work_item_ref)
{
for (uint32_t batch = 0; batch < work_item->output[0]->parent->lengths.t[NN_DATA_COORD_n]; ++batch)
{
for (uint32_t output_element = 0; output_element < work_item->output[0]->parent->lengths.t[NN_DATA_COORD_x]; ++output_element)
{
float value = nn_workload_data_get<float>(work_item->output[0], batch, output_element, 0, 0, 0, 0);
float value_ref = nn_workload_data_get<float>(work_item_ref->output[0], batch, output_element, 0, 0, 0, 0);
float diff = fabs(value_ref - value);
if (value_ref == 0.0f || value == 0.0f || diff < FLT_MIN)
{
if (diff > FLT_MIN)
{
return false;
}
}
else
{
if (fabs(diff / value_ref) > 5.2e-05F)
{
return false;
}
}
}
}
return true;
}
bool run_work_item(
nn_workload_item* &work_item,
bool is_ref,
nn_device_t *device)
{
if (is_ref)
{
// Naive implementation.
cpu_layer_softmax( //definition in naive_implementations.cpp
work_item,
is_ref,
device);
}
else
{
// Use optimized routine.
work_item->primitive->forward({work_item->input[0].get_data_view()}, {}, work_item->output);
}
return true;
}
void destroy_work_item(
nn_workload_item* &work_item)
{
work_item->input.clear();
delete reinterpret_cast<nn::workload_data<float>*>(work_item->output[0]);
delete work_item;
work_item = nullptr;
}
void create_and_initialize_input_item(
nn_workload_item* &work_item,
uint32_t input_width,
uint32_t batch_size)
{
nn_workload_data_coords_t in_out_coords =
{
batch_size,
input_width,
1,
1,
1,
1
};
work_item = new nn_workload_item();
work_item->type = NN_WORK_ITEM_TYPE_INPUT;
work_item->arguments.input.index = 0;
nn_workload_data_layout_t inp_out_layout = nn::workload_data<float>::layout.nxyzpq;
work_item->output.push_back(new nn::workload_data<float>(in_out_coords, inp_out_layout));
for (uint32_t batch = 0; batch < batch_size; ++batch)
{
for (uint32_t input_element = 0; input_element < input_width; ++input_element)
{
float value = 0.03125f;
value *= pow(1.01f, input_element);
value *= pow(1.01f, batch);
if (input_element % 2) value *= -1.0f;
nn_workload_data_get<float>(work_item->output[0], batch, input_element, 0, 0, 0, 0) = value;
}
}
}
void create_and_initialize_work_item(
nn_workload_item* &work_item,
nn_workload_item* input_item,
uint32_t input_width,
uint32_t batch_size,
nn_device_t *device)
{
nn_workload_data_coords_t in_out_coords =
{
batch_size,
input_width,
1,
1,
1,
1
};
work_item = new nn_workload_item();
work_item->type = NN_WORK_ITEM_TYPE_SOFTMAX;
work_item->primitive =
new layer::softmax_f32(input_width, batch_size, reinterpret_cast<nn_device_internal *>(device));
work_item->input.push_back({ input_item, 0 });
nn_workload_data_layout_t inp_out_layout = nn::workload_data<float>::layout.nxyzpq;
work_item->output.push_back(new nn::workload_data<float>(in_out_coords, inp_out_layout));
for (uint32_t batch = 0; batch < batch_size; ++batch)
{
for (uint32_t output_element = 0; output_element < input_width; ++output_element)
{
nn_workload_data_get<float>(work_item->output[0], batch, output_element, 0, 0, 0, 0) = 0.0f;
}
}
}
bool ult_perform_test(
uint32_t input_width,
uint32_t batch_size)
{
bool return_value = true;
nn_device_description_t device_description;
nn_device_interface_0_t device_interface_0;
nn_device_load(&device_description);
nn_device_interface_open(0, &device_interface_0);
// Input item.
nn_workload_item* input_item = nullptr;
create_and_initialize_input_item(input_item, input_width, batch_size);
// Work item.
nn_workload_item* work_item = nullptr;
create_and_initialize_work_item(work_item, input_item, input_width, batch_size, device_interface_0.device);
// Reference workload item.
nn_workload_item* work_item_ref = nullptr;
create_and_initialize_work_item(work_item_ref, input_item, input_width, batch_size, nullptr);
// Run items.
return_value &= run_work_item(work_item, false, device_interface_0.device);
return_value &= run_work_item(work_item_ref, true, nullptr);
// Compare results.
return_value &= compare_work_items(work_item, work_item_ref);
// Cleanup.
destroy_work_item(work_item);
destroy_work_item(work_item_ref);
destroy_work_item(input_item);
nn_device_interface_close(&device_interface_0);
nn_device_unload();
return return_value;
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
// Tests.
TEST(cpu_softmax_artificial, cpu_softmax_base)
{
uint32_t batches[] = { 1, 8, 48 };
for (auto batch : batches)
for (uint32_t input_sizes = 1; input_sizes < 256; ++input_sizes)
EXPECT_EQ(true, ult_perform_test(
input_sizes, // input/output width
batch // batch size
));
}
| 31.718615
| 134
| 0.653746
|
davenso
|
d2f1e8a9a135b0da04a661fa80c256bcac7c48c1
| 9,611
|
cpp
|
C++
|
src/main.cpp
|
csc-std/routine
|
16e74628eb4815a816fb8eecbbe8e5fe2ad55daa
|
[
"MIT"
] | null | null | null |
src/main.cpp
|
csc-std/routine
|
16e74628eb4815a816fb8eecbbe8e5fe2ad55daa
|
[
"MIT"
] | null | null | null |
src/main.cpp
|
csc-std/routine
|
16e74628eb4815a816fb8eecbbe8e5fe2ad55daa
|
[
"MIT"
] | null | null | null |
#include "util.h"
using namespace UNITTEST ;
namespace UNITTEST {
template <class U>
struct GN_sqrt_mFirstY {
DOUBLE mFirstY ;
Scope<GN_sqrt_mFirstY> mHandle ;
explicit GN_sqrt_mFirstY (VREF<SyntaxTree> me) {
me.mark_as_iteration () ;
me.then (Function<void> ([&] () {
mFirstY = me.later (TYPEAS<DOUBLE>::expr) ;
Singleton<Console>::instance ().print (slice ("mFirstY = ") ,mFirstY) ;
})) ;
mHandle = Scope<GN_sqrt_mFirstY> (thiz) ;
}
void enter () {
Singleton<Console>::instance ().info (slice ("enter GN_sqrt_mFirstY[") ,U::expr ,slice ("]")) ;
}
void leave () {
Singleton<Console>::instance ().info (slice ("leave GN_sqrt_mFirstY[") ,U::expr ,slice ("]")) ;
}
} ;
template <class U>
struct GN_sqrt_mCurrX {
DOUBLE mCurrX ;
Scope<GN_sqrt_mCurrX> mHandle ;
explicit GN_sqrt_mCurrX (VREF<SyntaxTree> me) {
me.mark_as_iteration () ;
me.then (Function<void> ([&] () {
mCurrX = me.later (TYPEAS<DOUBLE>::expr) ;
})) ;
mHandle = Scope<GN_sqrt_mCurrX> (thiz) ;
}
void enter () {
Singleton<Console>::instance ().info (slice ("enter GN_sqrt_mCurrX[") ,U::expr ,slice ("]")) ;
}
void leave () {
Singleton<Console>::instance ().info (slice ("leave GN_sqrt_mCurrX[") ,U::expr ,slice ("]")) ;
}
} ;
template <class U>
struct GN_sqrt_mCurrY {
DOUBLE mCurrY ;
Scope<GN_sqrt_mCurrY> mHandle ;
explicit GN_sqrt_mCurrY (VREF<SyntaxTree> me) {
auto &mFirstY = me.stack (TYPEAS<GN_sqrt_mFirstY<U>>::expr).mFirstY ;
auto &mCurrX = me.stack (TYPEAS<GN_sqrt_mCurrX<U>>::expr).mCurrX ;
me.then (Function<void> ([&] () {
mCurrY = MathProc::square (mCurrX) - mFirstY ;
Singleton<Console>::instance ().print (slice ("mCurrY = ") ,mCurrY) ;
})) ;
mHandle = Scope<GN_sqrt_mCurrY> (thiz) ;
}
void enter () {
Singleton<Console>::instance ().info (slice ("enter GN_sqrt_mCurrY[") ,U::expr ,slice ("]")) ;
}
void leave () {
Singleton<Console>::instance ().info (slice ("leave GN_sqrt_mCurrY[") ,U::expr ,slice ("]")) ;
}
} ;
template <class U>
struct GN_sqrt_mCurrZ {
DOUBLE mCurrZ ;
Scope<GN_sqrt_mCurrZ> mHandle ;
explicit GN_sqrt_mCurrZ (VREF<SyntaxTree> me) {
auto &mCurrX = me.stack (TYPEAS<GN_sqrt_mCurrX<U>>::expr).mCurrX ;
me.then (Function<void> ([&] () {
mCurrZ = 2 * mCurrX ;
})) ;
mHandle = Scope<GN_sqrt_mCurrZ> (thiz) ;
}
void enter () {
Singleton<Console>::instance ().info (slice ("enter GN_sqrt_mCurrZ[") ,U::expr ,slice ("]")) ;
}
void leave () {
Singleton<Console>::instance ().info (slice ("leave GN_sqrt_mCurrZ[") ,U::expr ,slice ("]")) ;
}
} ;
template <class U>
struct GN_sqrt_mNextX {
DOUBLE mNextX ;
Scope<GN_sqrt_mNextX> mHandle ;
explicit GN_sqrt_mNextX (VREF<SyntaxTree> me) {
auto &mCurrX = me.stack (TYPEAS<GN_sqrt_mCurrX<U>>::expr).mCurrX ;
auto &mCurrY = me.stack (TYPEAS<GN_sqrt_mCurrY<U>>::expr).mCurrY ;
auto &mCurrZ = me.stack (TYPEAS<GN_sqrt_mCurrZ<U>>::expr).mCurrZ ;
me.then (Function<void> ([&] () {
mNextX = mCurrX - mCurrY * MathProc::inverse (mCurrZ) ;
})) ;
mHandle = Scope<GN_sqrt_mNextX> (thiz) ;
}
void enter () {
Singleton<Console>::instance ().info (slice ("enter GN_sqrt_mNextX[") ,U::expr ,slice ("]")) ;
}
void leave () {
Singleton<Console>::instance ().info (slice ("leave GN_sqrt_mNextX[") ,U::expr ,slice ("]")) ;
}
} ;
template <class U>
struct GN_sqrt_mCurrTimes {
LENGTH mCurrTimes ;
Scope<GN_sqrt_mCurrTimes> mHandle ;
explicit GN_sqrt_mCurrTimes (VREF<SyntaxTree> me) {
me.mark_as_iteration () ;
me.then (Function<void> ([&] () {
mCurrTimes = me.later (TYPEAS<LENGTH>::expr) ;
})) ;
mHandle = Scope<GN_sqrt_mCurrTimes> (thiz) ;
}
void enter () {
Singleton<Console>::instance ().info (slice ("enter GN_sqrt_mCurrTimes[") ,U::expr ,slice ("]")) ;
}
void leave () {
Singleton<Console>::instance ().info (slice ("leave GN_sqrt_mCurrTimes[") ,U::expr ,slice ("]")) ;
}
} ;
template <class U>
struct GN_sqrt_mNextTimes {
LENGTH mNextTimes ;
Scope<GN_sqrt_mNextTimes> mHandle ;
explicit GN_sqrt_mNextTimes (VREF<SyntaxTree> me) {
auto &mCurrTimes = me.stack (TYPEAS<GN_sqrt_mCurrTimes<U>>::expr).mCurrTimes ;
me.then (Function<void> ([&] () {
mNextTimes = mCurrTimes + 1 ;
})) ;
mHandle = Scope<GN_sqrt_mNextTimes> (thiz) ;
}
void enter () {
Singleton<Console>::instance ().info (slice ("enter GN_sqrt_mNextTimes[") ,U::expr ,slice ("]")) ;
}
void leave () {
Singleton<Console>::instance ().info (slice ("leave GN_sqrt_mNextTimes[") ,U::expr ,slice ("]")) ;
}
} ;
template <class U>
struct GN_sqrt_mFinalX {
DOUBLE mFinalX ;
LENGTH mFinalTimes ;
Scope<GN_sqrt_mFinalX> mHandle ;
explicit GN_sqrt_mFinalX (VREF<SyntaxTree> me) {
me.maybe (TYPEAS<GN_sqrt_mFirstY<U>>::expr) ;
me.maybe (TYPEAS<GN_sqrt_mCurrX<U>>::expr) ;
me.maybe (TYPEAS<GN_sqrt_mNextX<U>>::expr) ;
me.maybe (TYPEAS<GN_sqrt_mCurrY<U>>::expr) ;
me.maybe (TYPEAS<GN_sqrt_mCurrTimes<U>>::expr) ;
me.maybe (TYPEAS<GN_sqrt_mNextTimes<U>>::expr) ;
me.once (Function<void> ([&] () {
auto &mFirstY = me.stack (TYPEAS<GN_sqrt_mFirstY<U>>::expr).mFirstY ;
auto &mCurrX = me.stack (TYPEAS<GN_sqrt_mCurrX<U>>::expr).mCurrX ;
auto &mNextX = me.stack (TYPEAS<GN_sqrt_mNextX<U>>::expr).mNextX ;
auto &mCurrY = me.stack (TYPEAS<GN_sqrt_mCurrY<U>>::expr).mCurrY ;
auto &mCurrTimes = me.stack (TYPEAS<GN_sqrt_mCurrTimes<U>>::expr).mCurrTimes ;
auto &mNextTimes = me.stack (TYPEAS<GN_sqrt_mNextTimes<U>>::expr).mNextTimes ;
me.redo (TYPEAS<GN_sqrt_mCurrX<U>>::expr ,mFirstY) ;
me.redo (TYPEAS<GN_sqrt_mCurrTimes<U>>::expr ,ZERO) ;
while (TRUE) {
me.play () ;
if (MathProc::abs (mCurrY) < DOUBLE (SINGLE_EPS))
break ;
if (mCurrTimes >= 100)
break ;
me.undo (TYPEAS<GN_sqrt_mCurrX<U>>::expr) ;
me.undo (TYPEAS<GN_sqrt_mCurrTimes<U>>::expr) ;
me.redo (TYPEAS<GN_sqrt_mCurrX<U>>::expr ,mNextX) ;
me.redo (TYPEAS<GN_sqrt_mCurrTimes<U>>::expr ,mNextTimes) ;
}
me.then (Function<void> ([&] () {
mFinalX = mCurrX ;
mFinalTimes = mCurrTimes ;
Singleton<Console>::instance ().print (slice ("mFinalX = ") ,mFinalX) ;
Singleton<Console>::instance ().print (slice ("mFinalTimes = ") ,mFinalTimes) ;
})) ;
})) ;
mHandle = Scope<GN_sqrt_mFinalX> (thiz) ;
}
void enter () {
Singleton<Console>::instance ().info (slice ("enter GN_sqrt_mFinalX[") ,U::expr ,slice ("]")) ;
}
void leave () {
Singleton<Console>::instance ().info (slice ("leave GN_sqrt_mFinalX[") ,U::expr ,slice ("]")) ;
}
} ;
struct GN_sqrt_mFirstY_thread {
Array<DOUBLE> mFirstY ;
Scope<GN_sqrt_mFirstY_thread> mHandle ;
explicit GN_sqrt_mFirstY_thread (VREF<SyntaxTree> me) {
me.then (Function<void> ([&] () {
mFirstY = Array<DOUBLE> (10) ;
for (auto &&i : mFirstY) {
const auto r1x = Random::instance ().random_value (100 ,10000) ;
i = DOUBLE (r1x) ;
}
})) ;
mHandle = Scope<GN_sqrt_mFirstY_thread> (thiz) ;
}
void enter () {
Singleton<Console>::instance ().info (slice ("enter GN_sqrt_mFirstY_thread")) ;
}
void leave () {
Singleton<Console>::instance ().info (slice ("leave GN_sqrt_mFirstY_thread")) ;
}
} ;
struct GN_sqrt_mFinalX_thread {
Array<DOUBLE> mFinalX ;
Scope<GN_sqrt_mFinalX_thread> mHandle ;
explicit GN_sqrt_mFinalX_thread (VREF<SyntaxTree> me) {
auto &&mFirstY = me.stack (TYPEAS<GN_sqrt_mFirstY_thread>::expr).mFirstY ;
me.maybe (TYPEAS<GN_sqrt_mFinalX<RANK0>>::expr) ;
me.maybe (TYPEAS<GN_sqrt_mFinalX<RANK1>>::expr) ;
me.maybe (TYPEAS<GN_sqrt_mFinalX<RANK2>>::expr) ;
me.maybe (TYPEAS<GN_sqrt_mFinalX<RANK3>>::expr) ;
me.maybe (TYPEAS<GN_sqrt_mFinalX<RANK4>>::expr) ;
me.maybe (TYPEAS<GN_sqrt_mFinalX<RANK5>>::expr) ;
me.maybe (TYPEAS<GN_sqrt_mFinalX<RANK6>>::expr) ;
me.maybe (TYPEAS<GN_sqrt_mFinalX<RANK7>>::expr) ;
me.maybe (TYPEAS<GN_sqrt_mFinalX<RANK8>>::expr) ;
me.maybe (TYPEAS<GN_sqrt_mFinalX<RANK9>>::expr) ;
me.once (Function<void> ([&] () {
mFinalX = Array<DOUBLE> (mFirstY.length ()) ;
process<RANK0> (me ,mFirstY ,mFinalX) ;
process<RANK1> (me ,mFirstY ,mFinalX) ;
process<RANK2> (me ,mFirstY ,mFinalX) ;
process<RANK3> (me ,mFirstY ,mFinalX) ;
process<RANK4> (me ,mFirstY ,mFinalX) ;
process<RANK5> (me ,mFirstY ,mFinalX) ;
process<RANK6> (me ,mFirstY ,mFinalX) ;
process<RANK7> (me ,mFirstY ,mFinalX) ;
process<RANK8> (me ,mFirstY ,mFinalX) ;
process<RANK9> (me ,mFirstY ,mFinalX) ;
me.then (Function<void> ([&] () {
Singleton<Console>::instance ().print () ;
for (auto &&i : mFinalX.iter ()) {
Singleton<Console>::instance ().print (slice ("sqrt (") ,mFirstY[i] ,slice (") = ") ,mFinalX[i]) ;
}
Singleton<Console>::instance ().print () ;
})) ;
})) ;
mHandle = Scope<GN_sqrt_mFinalX_thread> (thiz) ;
}
void enter () {
Singleton<Console>::instance ().info (slice ("enter GN_sqrt_mFinalX_thread")) ;
}
void leave () {
Singleton<Console>::instance ().info (slice ("leave GN_sqrt_mFinalX_thread")) ;
}
template <class U>
imports void process (
VREF<SyntaxTree> me ,
CREF<Array<DOUBLE>> mFirstY_thread ,
VREF<Array<DOUBLE>> mFinalX_thread) {
auto &mFinalX = me.stack (TYPEAS<GN_sqrt_mFinalX<U>>::expr).mFinalX ;
me.redo (TYPEAS<GN_sqrt_mFirstY<U>>::expr ,mFirstY_thread[U::expr]) ;
me.play () ;
mFinalX_thread[U::expr] = mFinalX ;
}
} ;
} ;
exports void test_main () ;
#ifdef __CSC_TARGET_EXE__
exports int main () {
Singleton<Reporter>::instance ().detect_memory_leaks () ;
Singleton<Reporter>::instance ().detect_crash_signal () ;
Singleton<Console>::instance ().open () ;
Singleton<Console>::instance ().link (slice (".")) ;
test_main () ;
return 0 ;
}
#endif
| 30.511111
| 103
| 0.655499
|
csc-std
|
d2f25c92265d7d680c5b5fb7187d406c4b75d3d4
| 3,451
|
cpp
|
C++
|
Sources/engine/engine/private/engine/Engine.cpp
|
Zino2201/ZinoEngine
|
519d34a1d2b09412c8e2cba6b685b4556ec2c2ac
|
[
"MIT"
] | 20
|
2019-12-22T20:40:22.000Z
|
2021-07-06T00:23:45.000Z
|
Sources/engine/engine/private/engine/Engine.cpp
|
Zino2201/ZinoEngine
|
519d34a1d2b09412c8e2cba6b685b4556ec2c2ac
|
[
"MIT"
] | 32
|
2020-07-11T15:51:13.000Z
|
2021-06-07T10:25:07.000Z
|
Sources/engine/engine/private/engine/Engine.cpp
|
Zino2201/ZinoEngine
|
519d34a1d2b09412c8e2cba6b685b4556ec2c2ac
|
[
"MIT"
] | 3
|
2019-12-19T17:04:04.000Z
|
2021-05-17T01:49:59.000Z
|
#include "engine/Engine.h"
#include "module/Module.h"
#include "module/ModuleManager.h"
#include "engine/TickSystem.h"
#include "profiling/Profiling.h"
#include "console/Console.h"
#include <SDL.h>
#include "engine/InputSystem.h"
#include "module/Module.h"
#include "assetdatabase/AssetDatabase.h"
namespace ze
{
static ConVarRef<int32_t> cvar_maxfps("r_maxfps", 300,
"Max FPS when focused. 0 to disable.",
0,
300);
static ConVarRef<int32_t> cvar_unfocus_fps("r_unfocusfps", 15,
"Max FPS when unfocused",
1,
1000);
static ConVarRef<int32_t> CVarSimFPS("sim_fixed_dt", 20,
"Fixed simulation/Physics delta time",
1,
60);
bool bRun = true;
ZE_DEFINE_MODULE(ze::module::DefaultModule, engine)
/**
* Try to load a required module
* Crash if it fails
*/
ze::module::Module* LoadRequiredModule(const std::string_view& InName)
{
ze::module::Module* Ptr = ze::module::load_module(InName);
if (!Ptr)
ze::logger::fatal("Failed to load required module {} ! Exiting", InName);
return Ptr;
}
EngineApp::EngineApp() : should_run(false), focused(true), frame_count(0), err_code(0)
{
/** Load asset related modules */
LoadRequiredModule("asset");
LoadRequiredModule("assetdatabase");
previous = std::chrono::high_resolution_clock::now();
}
void EngineApp::process_event(const SDL_Event& in_event, const float in_delta_time)
{
if (in_event.type == SDL_QUIT)
exit(0);
if (in_event.type == SDL_KEYDOWN)
ze::input::on_key_pressed(in_event);
if (in_event.type == SDL_KEYUP)
ze::input::on_key_released(in_event);
if (in_event.type == SDL_MOUSEMOTION)
ze::input::set_mouse_delta(maths::Vector2f(in_event.motion.xrel, in_event.motion.yrel));
/*
if (in_event.type == SDL_WINDOWEVENT)
{
switch(in_event.window.event)
{
case SDL_WINDOWEVENT_FOCUS_GAINED:
focused = true;
break;
case SDL_WINDOWEVENT_FOCUS_LOST:
focused = false;
break;
}
}
*/
}
int EngineApp::run()
{
should_run = true;
focused = true;
while(should_run)
{
loop();
}
return err_code;
}
void EngineApp::exit(int in_err_code)
{
should_run = false;
err_code = in_err_code;
}
double engine_elapsed_time = 0.0;
double engine_delta_time = 0.0;
void EngineApp::loop()
{
auto current = std::chrono::high_resolution_clock::now();
std::chrono::duration<double, std::milli> delta_time = current - previous;
previous = current;
engine_delta_time = delta_time.count();
float delta_time_as_secs = static_cast<float>(engine_delta_time) * 0.001f;
engine_elapsed_time += delta_time_as_secs;
ze::input::clear();
/** Process events */
{
SDL_Event event;
while (SDL_PollEvent(&event))
{
process_event(event, delta_time_as_secs);
}
}
ticksystem::tick(ticksystem::TickFlagBits::Variable, delta_time_as_secs);
ticksystem::tick(ticksystem::TickFlagBits::Late, delta_time_as_secs);
post_tick(delta_time_as_secs);
/** Fps limiter */
if(cvar_maxfps.get() != 0)
{
using namespace std::chrono_literals;
focused = true;
const std::chrono::duration<double, std::milli> min_ms(focused ? (1000.0 / cvar_maxfps.get()) : (1000.0 / cvar_unfocus_fps.get()));
const auto target_sleep_time = current + min_ms;
std::this_thread::sleep_until(target_sleep_time - 1ms);
while(std::chrono::high_resolution_clock::now() < target_sleep_time) {}
}
frame_count++;
}
double EngineApp::get_elapsed_time()
{
return engine_elapsed_time;
}
double EngineApp::get_delta_time()
{
return engine_delta_time;
}
} /* namespace ze */
| 22.121795
| 133
| 0.722689
|
Zino2201
|
d2f2a2afd2e868f8c599c400ab9fbbe6f347e299
| 12,000
|
hpp
|
C++
|
src/utility.hpp
|
bkentel/boken-old
|
8967856be5f283989d0c10843bcb739728423152
|
[
"MIT"
] | null | null | null |
src/utility.hpp
|
bkentel/boken-old
|
8967856be5f283989d0c10843bcb739728423152
|
[
"MIT"
] | null | null | null |
src/utility.hpp
|
bkentel/boken-old
|
8967856be5f283989d0c10843bcb739728423152
|
[
"MIT"
] | 1
|
2020-04-11T12:20:00.000Z
|
2020-04-11T12:20:00.000Z
|
#pragma once
#include "config.hpp" //string_view
#include <bkassert/assert.hpp>
#include <type_traits>
#include <algorithm>
#include <array>
#include <functional>
#include <utility>
#include <memory>
#include <cstddef>
#include <cstdint>
namespace boken {
namespace detail {
template <typename Container, typename Compare>
void sort_impl(Container&& c, Compare comp) {
using std::sort;
using std::begin;
using std::end;
sort(begin(c), end(c), comp);
}
} //namespace detail
namespace container_algorithms {
template <typename Container, typename Compare>
void sort(Container&& c, Compare comp) {
detail::sort_impl(std::forward<Container>(c), comp);
}
template <typename Container, typename Predicate>
auto find_if(Container&& c, Predicate pred) {
using std::begin;
using std::end;
return std::find_if(begin(c), end(c), pred);
}
template <typename Container, typename Predicate>
auto* find_ptr_if(Container&& c, Predicate pred) {
using std::begin;
using std::end;
using result_t = decltype(std::addressof(*begin(c)));
auto const it = find_if(std::forward<Container>(c), pred);
return (it == end(c))
? static_cast<result_t>(nullptr)
: std::addressof(*it);
}
} // container_algorithms
template <size_t N, typename Predicate = std::less<>>
auto sort_by_nth_element(Predicate pred = Predicate {}) noexcept {
return [pred](auto const& a, auto const& b) noexcept {
return pred(std::get<N>(a), std::get<N>(b));
};
}
enum class convertion_type {
unchecked, clamp, fail, modulo
};
template <convertion_type T>
using convertion_t = std::integral_constant<convertion_type, T>;
template <typename T>
constexpr auto as_unsigned(T const n, convertion_t<convertion_type::clamp>) noexcept {
return static_cast<std::make_unsigned_t<T>>(n < 0 ? 0 : n);
}
template <typename T>
constexpr auto as_unsigned(T const n, convertion_type const type = convertion_type::clamp) noexcept {
static_assert(std::is_arithmetic<T>::value, "");
using ct = convertion_type;
return type == ct::clamp ? as_unsigned(n, convertion_t<ct::clamp> {})
: as_unsigned(n, convertion_t<ct::clamp> {});
}
template <typename T, typename U>
inline constexpr ptrdiff_t check_offsetof() noexcept {
static_assert(std::is_standard_layout<T>::value
, "Must be standard layout");
static_assert(!std::is_function<U>::value
, "Must not be a function");
static_assert(!std::is_member_function_pointer<std::add_pointer_t<U>>::value
, "Must not be a member function");
return 0;
}
#define BK_OFFSETOF(s, m) (check_offsetof<s, decltype(s::m)>() + offsetof(s, m))
template <typename T>
inline constexpr std::add_const_t<T>& as_const(T& t) noexcept {
return t;
}
template <typename T>
void as_const(T const&&) = delete;
template <typename T>
inline constexpr std::add_const_t<T>* as_const(T* const t) noexcept {
return t;
}
template <typename T>
inline constexpr void call_destructor(T& t)
noexcept(std::is_nothrow_destructible<T>::value)
{
t.~T();
(void)t; // spurious unused warning
}
template <size_t StackSize>
class basic_buffer {
public:
explicit basic_buffer(size_t const size)
: data_ {}
, size_ {size <= StackSize ? StackSize : size}
, first_ {init_storage_(data_, size_)}
{
}
basic_buffer() noexcept
: basic_buffer {StackSize}
{
}
~basic_buffer() {
size_ <= StackSize ? call_destructor(data_.s_)
: call_destructor(data_.d_);
}
auto size() const noexcept { return size_; }
auto data() const noexcept { return as_const(first_); }
auto begin() const noexcept { return data(); }
auto end() const noexcept { return begin() + size(); }
auto data() noexcept { return first_; }
auto begin() noexcept { return data(); }
auto end() noexcept { return begin() + size(); }
char operator[](size_t const i) const noexcept {
return *(begin() + i);
}
char& operator[](size_t const i) noexcept {
return *(begin() + i);
}
private:
using static_t = std::array<char, StackSize + 1>;
using dynamic_t = std::unique_ptr<char[]>;
union storage_t {
storage_t() noexcept {}
~storage_t() {}
static_t s_;
dynamic_t d_;
} data_;
static char* init_storage_(storage_t& data, size_t const size) {
if (size && size <= StackSize) {
new (&data.s_) static_t;
return data.s_.data();
} else {
new (&data.d_) dynamic_t {new char[size]};
return data.d_.get();
}
}
size_t size_;
char* first_;
};
using dynamic_buffer = basic_buffer<0>;
template <size_t Size>
using static_buffer = basic_buffer<Size>;
template <typename T>
class sub_region_iterator : public std::iterator_traits<T*> {
using this_t = sub_region_iterator<T>;
template <typename U> friend class sub_region_iterator;
public:
using reference = typename std::iterator_traits<T*>::reference;
using pointer = typename std::iterator_traits<T*>::pointer;
sub_region_iterator(
T* const p
, ptrdiff_t const off_x, ptrdiff_t const off_y
, ptrdiff_t const width_outer, ptrdiff_t const height_outer
, ptrdiff_t const width_inner, ptrdiff_t const height_inner
, ptrdiff_t const x = 0, ptrdiff_t const y = 0
) noexcept
: p_ {p + (off_x + x) + (off_y + y) * width_outer}
, off_x_ {off_x}
, off_y_ {off_y}
, width_outer_ {width_outer}
, width_inner_ {width_inner}
, height_inner_ {height_inner}
, x_ {x}
, y_ {y}
{
BK_ASSERT(!!p);
BK_ASSERT(off_x >= 0 && off_y >= 0);
BK_ASSERT(width_inner >= 0 && width_outer >= width_inner + off_x);
BK_ASSERT(height_inner >= 0 && height_outer >= height_inner + off_y);
BK_ASSERT(x_ <= width_inner && y_ <= height_inner);
}
// create a new iterator with the same properties as other, but with a
// different base pointer.
template <typename U>
sub_region_iterator(sub_region_iterator<U> it, T* const p) noexcept
: p_ {p + (it.off_x_ + it.x_) + (it.off_y_ + it.y_) * it.width_outer_}
, off_x_ {it.off_x_}
, off_y_ {it.off_y_}
, width_outer_ {it.width_outer_}
, width_inner_ {it.width_inner_}
, height_inner_ {it.height_inner_}
, x_ {it.x_}
, y_ {it.y_}
{
}
reference operator*() const noexcept {
return *p_;
}
pointer operator->() const noexcept {
return &**this;
}
void operator++() noexcept {
++p_;
if (++x_ < width_inner_) {
return;
}
if (++y_ < height_inner_) {
x_ = 0;
p_ += (width_outer_ - width_inner_);
}
}
sub_region_iterator operator++(int) noexcept {
auto result = *this;
++(*this);
return result;
}
bool operator<(this_t const& other) const noexcept {
return p_ < other.p_;
}
bool operator==(this_t const& other) const noexcept {
return (p_ == other.p_);
}
bool operator!=(this_t const& other) const noexcept {
return !(*this == other);
}
ptrdiff_t operator-(this_t const& other) const noexcept {
BK_ASSERT(is_compatible_(other));
return (x_ + y_ * width_inner_)
- (other.x_ + other.y_ * other.width_inner_);
}
ptrdiff_t x() const noexcept { return x_; }
ptrdiff_t y() const noexcept { return y_; }
ptrdiff_t off_x() const noexcept { return off_x_; }
ptrdiff_t off_y() const noexcept { return off_y_; }
ptrdiff_t width() const noexcept { return width_inner_; }
ptrdiff_t height() const noexcept { return height_inner_; }
ptrdiff_t stride() const noexcept { return width_outer_; }
private:
template <typename U>
bool is_compatible_(sub_region_iterator<U> const& it) const noexcept {
return off_x_ == it.off_x_
&& off_y_ == it.off_y_
&& width_outer_ == it.width_outer_
&& width_inner_ == it.width_inner_
&& height_inner_ == it.height_inner_;
}
T* p_ {};
ptrdiff_t off_x_ {};
ptrdiff_t off_y_ {};
ptrdiff_t width_outer_ {};
ptrdiff_t width_inner_ {};
ptrdiff_t height_inner_ {};
ptrdiff_t x_ {};
ptrdiff_t y_ {};
};
template <typename T>
using const_sub_region_iterator = sub_region_iterator<std::add_const_t<std::decay_t<T>>>;
template <typename T>
using sub_region_range = std::pair<
sub_region_iterator<T>, sub_region_iterator<T>>;
template <typename T>
using const_sub_region_range = sub_region_range<std::add_const_t<std::decay_t<T>>>;
template <typename T>
sub_region_range<T> make_sub_region_range(
T* const p
, ptrdiff_t const off_x, ptrdiff_t const off_y
, ptrdiff_t const width_outer, ptrdiff_t const height_outer
, ptrdiff_t const width_inner, ptrdiff_t const height_inner
) noexcept {
return {
sub_region_iterator<T> {
p
, off_x, off_y
, width_outer, height_outer
, width_inner, height_inner
}
, sub_region_iterator<T> {
p
, off_x, off_y
, width_outer, height_outer
, width_inner, height_inner
, width_inner, height_inner - 1
}
};
}
namespace detail {
template <typename It>
size_t weight_list_size(std::random_access_iterator_tag, It const first, It const last) noexcept {
return static_cast<size_t>(std::distance(first, last));
}
template <typename Tag, typename It>
size_t weight_list_size(Tag, It, It) noexcept {
return 0u;
}
} // namespace detail
template <typename Weight, typename Result>
class weight_list {
static_assert(std::is_arithmetic<Weight>::value, "");
using pair_t = std::pair<Weight, Result>;
public:
weight_list() = default;
template <typename InputIt1, typename InputIt2>
weight_list(InputIt1 const first_weight, InputIt1 const last_weight
, InputIt2 const first_result, InputIt2 const last_result
) {
using tag1_t = typename std::iterator_traits<InputIt1>::iterator_category;
using tag2_t = typename std::iterator_traits<InputIt2>::iterator_category;
size_t const s1 =
detail::weight_list_size(tag1_t {}, first_weight, last_weight);
size_t const s2 =
detail::weight_list_size(tag2_t {}, first_result, last_result);
size_t const reserve_size =
((s1 > 0u) && (s2 > 0u)) ? std::min(s1, s2)
: (s1 > 0u) ? s1
: (s2 > 0u) ? s2
: 0u;
data_.reserve(reserve_size);
auto it1 = first_weight;
auto it2 = first_result;
for (; it1 != last_weight && it2 != last_result; ++it1, ++it2) {
BK_ASSERT(*it1 > Weight {});
data_.push_back({sum_ += *it1, *it2});
}
}
weight_list(std::initializer_list<pair_t> const data) {
data_.reserve(data.size());
for (auto const& p : data) {
BK_ASSERT(p.first > 0);
data_.push_back({sum_ += p.first, p.second});
}
}
Weight max() const noexcept { return sum_; }
Result const& operator[](Weight const n) const noexcept {
BK_ASSERT(!data_.empty() && n >= Weight {} && n < sum_);
auto const first = begin(data_);
auto const last = end(data_);
auto const it = std::lower_bound(first, last, n
, [](pair_t const& p, Weight const w) noexcept {
return p.first <= w;
});
return (it != last)
? it->second
: data_.back().second;
}
private:
std::vector<pair_t> data_ {};
Weight sum_ {};
};
} //namespace boken
| 28.436019
| 101
| 0.6165
|
bkentel
|
d2f79d0ccf37336b91b25491691596d601dca514
| 49
|
cxx
|
C++
|
libs/cg_nui/surfel_container.cxx
|
IXDdev/IXD_engine
|
497c1fee90e486c19debc5347b740b56b1fef416
|
[
"BSD-3-Clause"
] | 11
|
2017-09-30T12:21:55.000Z
|
2021-04-29T21:31:57.000Z
|
libs/cg_nui/surfel_container.cxx
|
IXDdev/IXD_engine
|
497c1fee90e486c19debc5347b740b56b1fef416
|
[
"BSD-3-Clause"
] | 2
|
2017-07-11T11:20:08.000Z
|
2018-03-27T12:09:02.000Z
|
libs/cg_nui/surfel_container.cxx
|
IXDdev/IXD_engine
|
497c1fee90e486c19debc5347b740b56b1fef416
|
[
"BSD-3-Clause"
] | 24
|
2018-03-27T11:46:16.000Z
|
2021-05-01T20:28:34.000Z
|
#include "surfel_container.h"
// TODO: implement
| 16.333333
| 29
| 0.755102
|
IXDdev
|
d2f9e5afc7cd122b4ed8de4a0ecd19ae123b127a
| 1,416
|
cpp
|
C++
|
AlphaEngine/Source/Scripting/LuaVar.cpp
|
Sh1ft0/alpha
|
6726d366f0c8d2e1434b87f815b2644ebf170adf
|
[
"Apache-2.0"
] | null | null | null |
AlphaEngine/Source/Scripting/LuaVar.cpp
|
Sh1ft0/alpha
|
6726d366f0c8d2e1434b87f815b2644ebf170adf
|
[
"Apache-2.0"
] | null | null | null |
AlphaEngine/Source/Scripting/LuaVar.cpp
|
Sh1ft0/alpha
|
6726d366f0c8d2e1434b87f815b2644ebf170adf
|
[
"Apache-2.0"
] | null | null | null |
/**
Copyright 2014-2015 Jason R. Wendlandt
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 "Scripting/LuaVar.h"
namespace alpha
{
LuaTable::LuaTable(const std::string & name)
: LuaVar(name)
{ }
LuaTable::~LuaTable() { }
LUA_VARTYPE LuaTable::GetVarType() const { return VT_TABLE; }
void LuaTable::Push(std::string key, std::shared_ptr<LuaVar> value)
{
m_vars[key] = value;
}
/**
* Find the LuaVar with the given key, if it exists (shallow search)
*/
std::shared_ptr<LuaVar> LuaTable::Get(const std::string & key) const
{
auto search = m_vars.find(key);
if (search != m_vars.end())
{
return search->second;
}
return nullptr;
}
//! Get all variables that exist in this LUA table
const std::map<std::string, std::shared_ptr<LuaVar> > & LuaTable::GetAll() const
{
return m_vars;
}
}
| 27.230769
| 84
| 0.664548
|
Sh1ft0
|
d2fb38a80612a4f2ad85fa926c0fe4112c7295b9
| 716
|
hpp
|
C++
|
include/molecular.hpp
|
grasingerm/port-authority
|
51db6b09d6a1545eafeaf6be037a23d47313c490
|
[
"MIT"
] | null | null | null |
include/molecular.hpp
|
grasingerm/port-authority
|
51db6b09d6a1545eafeaf6be037a23d47313c490
|
[
"MIT"
] | null | null | null |
include/molecular.hpp
|
grasingerm/port-authority
|
51db6b09d6a1545eafeaf6be037a23d47313c490
|
[
"MIT"
] | null | null | null |
#ifndef __MOLECULAR_HPP__
#define __MOLECULAR_HPP__
#include "pauth_types.hpp"
#include "unordered_pair.hpp"
#include <unordered_map>
namespace pauth {
enum class molecular_id { Ar, Cu, H, O, C, Test, Test1, Test2 };
using molecular_name_map = std::unordered_map<std::string, molecular_id>;
extern const molecular_name_map molecular_names_to_ids;
struct molecular_pair_hash {
std::size_t operator()(const unordered_pair<molecular_id> &k) const {
return ((std::hash<int>()(static_cast<int>(k.first))) ^
(std::hash<int>()(static_cast<int>(k.second))));
}
};
using molecular_pair_interaction_map =
std::unordered_map<unordered_pair<molecular_id>, double, molecular_pair_hash>;
}
#endif
| 25.571429
| 82
| 0.74162
|
grasingerm
|
d2fe497101c59db89f5e757c5201f8312f339003
| 226
|
cpp
|
C++
|
acwing/0717.cpp
|
zyzisyz/OJ
|
55221a55515231182b6bd133edbdb55501a565fc
|
[
"Apache-2.0"
] | null | null | null |
acwing/0717.cpp
|
zyzisyz/OJ
|
55221a55515231182b6bd133edbdb55501a565fc
|
[
"Apache-2.0"
] | null | null | null |
acwing/0717.cpp
|
zyzisyz/OJ
|
55221a55515231182b6bd133edbdb55501a565fc
|
[
"Apache-2.0"
] | 2
|
2020-01-01T13:49:08.000Z
|
2021-03-06T06:54:26.000Z
|
#include<iostream>
using namespace std;
int f[50];
int main(void){
int n;
cin>>n;
f[0] = 0;
f[1] = 1;
for(int i=2; i<n; i++){
f[i] = f[i-1]+f[i-2];
}
for(int i=0; i<n; i++){
cout<<f[i]<<" ";
}
cout<<endl;
}
| 9.826087
| 24
| 0.473451
|
zyzisyz
|
9603f5ed110e157362f45ee4f58cb664d4919beb
| 3,149
|
cc
|
C++
|
src/automaton/tests/crypto/test_Keccak_256_cryptopp.cc
|
automaton-network/automaton
|
34f6df278dc71d11340084c3487564ab58b04c2e
|
[
"MIT"
] | 2
|
2018-12-19T18:01:14.000Z
|
2019-03-29T12:54:41.000Z
|
src/automaton/tests/crypto/test_Keccak_256_cryptopp.cc
|
automaton-network/automaton
|
34f6df278dc71d11340084c3487564ab58b04c2e
|
[
"MIT"
] | 3
|
2018-12-20T17:44:31.000Z
|
2020-03-25T16:45:04.000Z
|
src/automaton/tests/crypto/test_Keccak_256_cryptopp.cc
|
automaton-network/automaton
|
34f6df278dc71d11340084c3487564ab58b04c2e
|
[
"MIT"
] | 2
|
2020-03-12T13:33:10.000Z
|
2020-03-22T00:48:51.000Z
|
#include <cryptopp/cryptlib.h>
#include <cryptopp/keccak.h>
#include <cryptopp/hex.h>
#include <cryptopp/filters.h>
#include <string>
#include "automaton/core/crypto/cryptopp/Keccak_256_cryptopp.h"
#include "automaton/core/crypto/hash_transformation.h"
#include "automaton/core/io/io.h"
#include "gtest/gtest.h"
using automaton::core::crypto::cryptopp::Keccak_256_cryptopp;
using automaton::core::crypto::hash_transformation;
using automaton::core::io::bin2hex;
TEST(keccak_256_cryptopp, calculate_digest) {
Keccak_256_cryptopp hasher;
size_t digest_size = hasher.digest_size();
uint8_t* digest = new uint8_t[digest_size];
constexpr uint32_t test_cases = 6;
std::string test[test_cases][2] = {
{"a",
"3AC225168DF54212A25C1C01FD35BEBFEA408FDAC2E31DDD6F80A4BBF9A5F1CB"},
{"abc",
"4E03657AEA45A94FC7D47BA826C8D667C0D1E6E33A64A036EC44F58FA12D6C45"},
{"",
"C5D2460186F7233C927E7DB2DCC703C0E500B653CA82273B7BFAD8045D85A470"},
{"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
"45D3B367A6904E6E8D502EE04999A7C27647F91FA845D456525FD352AE3D7371"},
{"abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmno"
"ijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu",
"F519747ED599024F3882238E5AB43960132572B7345FBEB9A90769DAFD21AD67"},
{"testing",
"5F16F4C7F149AC4F9510D9CF8CF384038AD348B3BCDC01915F95DE12DF9D1B02"}
};
for (uint32_t i = 0; i < test_cases; i++) {
hasher.calculate_digest(reinterpret_cast<const uint8_t*>(test[i][0].data()),
test[i][0].length(), digest);
std::string result(reinterpret_cast<char*>(digest), digest_size);
EXPECT_EQ(bin2hex(result), test[i][1]);
}
delete[] digest;
}
TEST(keccak_256_cryptopp, update_and_finish) {
Keccak_256_cryptopp hasher;
size_t digest_size = hasher.digest_size();
uint8_t* digest = new uint8_t[digest_size];
std::string test_input(
"abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmno");
const std::string EXP1 =
"C8A625720D2C6221C09DB8A33A63FB936E628A0C10195768A206E7AD8D1E54DE";
const uint8_t* p_test_input = reinterpret_cast<const uint8_t*>(test_input.data());
size_t len = test_input.length();
for (uint32_t i = 0; i < 10; i++) {
hasher.update(p_test_input, len);
}
hasher.final(digest);
std::string result(reinterpret_cast<char*>(digest), digest_size);
EXPECT_EQ(bin2hex(result), EXP1);
// Try to hash a new string to see if everything restarted as intended
const uint8_t* a = reinterpret_cast<const uint8_t*>("a");
const uint8_t* b = reinterpret_cast<const uint8_t*>("b");
const uint8_t* c = reinterpret_cast<const uint8_t*>("c");
const std::string EXP2 =
"4E03657AEA45A94FC7D47BA826C8D667C0D1E6E33A64A036EC44F58FA12D6C45";
hasher.update(a, 1);
hasher.update(b, 1);
hasher.update(c, 1);
hasher.final(digest);
std::string result2(reinterpret_cast<char*>(digest), digest_size);
EXPECT_EQ(bin2hex(result2), EXP2);
delete[] digest;
}
TEST(keccak_256_cryptopp, digest_size) {
Keccak_256_cryptopp hasher;
EXPECT_EQ(hasher.digest_size(), static_cast<size_t>(CryptoPP::Keccak_256::DIGESTSIZE));
}
| 34.988889
| 89
| 0.755478
|
automaton-network
|
960634c731a2413e1e4df7fb0f6868ec71e19018
| 1,715
|
cxx
|
C++
|
Testing/selxDataManager.cxx
|
FBerendsen/SuperElastix-1
|
69d97589e34f6f2109621e917792ce18e32442fe
|
[
"Apache-2.0"
] | null | null | null |
Testing/selxDataManager.cxx
|
FBerendsen/SuperElastix-1
|
69d97589e34f6f2109621e917792ce18e32442fe
|
[
"Apache-2.0"
] | null | null | null |
Testing/selxDataManager.cxx
|
FBerendsen/SuperElastix-1
|
69d97589e34f6f2109621e917792ce18e32442fe
|
[
"Apache-2.0"
] | null | null | null |
/*=========================================================================
*
* Copyright Leiden University Medical Center, Erasmus University Medical
* Center and contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include <itkSimpleDataObjectDecorator.h>
#include "selxDataManager.h"
const std::string
DataManager
::GetInputFile( const std::string filename ) const
{
const std::string path = this->GetInputDirectory() + this->GetFolderSeparator() + filename;
return path;
}
const std::string
DataManager
::GetOutputFile( const std::string filename ) const
{
const std::string path = this->GetOutputDirectory() + this->GetFolderSeparator() + filename;
return path;
}
const std::string
DataManager
::GetBaselineFile( const std::string filename ) const
{
const std::string path = this->GetBaselineDirectory() + this->GetFolderSeparator() + filename;
return path;
}
const std::string
DataManager
::GetConfigurationFile( const std::string filename ) const
{
const std::string path = this->GetConfigurationDirectory() + this->GetFolderSeparator() + filename;
return path;
}
| 30.087719
| 101
| 0.674636
|
FBerendsen
|
9609b68b248bbcf6790467bdbacdb5302ab865da
| 1,396
|
cpp
|
C++
|
Chapter-6-Functions/Review Questions and Exercises/Programming Challenges/23.cpp
|
jesushilarioh/C-Plus-Plus
|
bbff921460ac4267af48558f040c7d82ccf42d5e
|
[
"MIT"
] | 3
|
2019-10-28T01:12:46.000Z
|
2021-10-16T09:16:31.000Z
|
Chapter-6-Functions/Review Questions and Exercises/Programming Challenges/23.cpp
|
jesushilarioh/C-Plus-Plus
|
bbff921460ac4267af48558f040c7d82ccf42d5e
|
[
"MIT"
] | null | null | null |
Chapter-6-Functions/Review Questions and Exercises/Programming Challenges/23.cpp
|
jesushilarioh/C-Plus-Plus
|
bbff921460ac4267af48558f040c7d82ccf42d5e
|
[
"MIT"
] | 4
|
2020-04-10T17:22:17.000Z
|
2021-11-04T14:34:00.000Z
|
/************************************************************
*
* 23. Prime Number List
*
* Use the isPrime function that you wrote in Programming
* Challenge 22 in a program that stores a list of all
* the prime numbers from 1 through 100 in a file.
*
* Jesus Hilario Hernandez
* December 27, 2018 --> "Merry Christmas!"
*
*************************************************************/
#include <iostream>
#include <fstream>
using namespace std;
// Function Prototypes
bool isPrime(int);
int main()
{
ofstream outputFile;
outputFile.open("primeNumbers.txt");
if (outputFile)
{
for (int i = 0; i <= 100; i++)
{
if(isPrime(i))
outputFile << i << endl;
}
outputFile.close();
}
else
{
cout << "Error opening the file.\n";
}
return 0;
}
/****************************************************
* Definition for isPrime(): ` *
* isPrime takes a integer as an argument and *
* returns true if the argument is a prime number, *
* or false otherwise. *
****************************************************/
bool isPrime(int number)
{
int isPrime = 0;
for (int i = 1; i <= number; i++)
{
if (number % i == 0)
isPrime++;
}
return isPrime == 2 ? 1 : 0;
}
| 22.885246
| 63
| 0.437679
|
jesushilarioh
|
960d1fd91f48fbeb3609a53dcb4c3fdb9b09bf4d
| 476
|
cc
|
C++
|
sieve2015/src/tst_sieve_bit_table.cc
|
mhdeleglise/Gh
|
21a0b9bd53ae9de17f8b99040cac95cd6e1897e4
|
[
"MIT"
] | null | null | null |
sieve2015/src/tst_sieve_bit_table.cc
|
mhdeleglise/Gh
|
21a0b9bd53ae9de17f8b99040cac95cd6e1897e4
|
[
"MIT"
] | null | null | null |
sieve2015/src/tst_sieve_bit_table.cc
|
mhdeleglise/Gh
|
21a0b9bd53ae9de17f8b99040cac95cd6e1897e4
|
[
"MIT"
] | null | null | null |
#include<mylib.h>
#include"../Include/sieve_slices.h"
int main(int argc, char* argv[]) {
long32 wsize = (argc==2)? atoi(argv[1]) : 100;
presieved_primes::init_prime_table(1000,3);
cout << "Sieve par tranche avec crible d'Eratosthène automatique\n";
sieve_by_slice<bit_table,long64> sl(2,1,wsize,0,6, AUTO_SIEVE);
for (int n=0; n < 3; n++) {
sl.display();
cout << "Shift_forward\n";
sl.shift_window_forward();
}
cout << "ok" << endl;
return 0;
}
| 25.052632
| 70
| 0.644958
|
mhdeleglise
|
961569204d83b05767f48e91acd8cd62dd6563b8
| 1,588
|
hpp
|
C++
|
include/mbgl/geometry/geometry.hpp
|
free1978/mapbox-gl-native
|
2a50fccd24e762d0de5a53bac358e5ddfea8d213
|
[
"BSD-2-Clause"
] | 2
|
2017-02-28T22:41:54.000Z
|
2020-02-13T20:54:55.000Z
|
include/mbgl/geometry/geometry.hpp
|
free1978/mapbox-gl-native
|
2a50fccd24e762d0de5a53bac358e5ddfea8d213
|
[
"BSD-2-Clause"
] | null | null | null |
include/mbgl/geometry/geometry.hpp
|
free1978/mapbox-gl-native
|
2a50fccd24e762d0de5a53bac358e5ddfea8d213
|
[
"BSD-2-Clause"
] | null | null | null |
#ifndef MBGL_GEOMETRY_GEOMETRY
#define MBGL_GEOMETRY_GEOMETRY
#include <mbgl/util/pbf.hpp>
#include <mbgl/util/noncopyable.hpp>
#include <cstdlib>
namespace mbgl {
class Geometry : private util::noncopyable {
public:
inline explicit Geometry(pbf& data);
enum command : uint8_t {
end = 0,
move_to = 1,
line_to = 2,
close = 7
};
inline command next(int32_t &rx, int32_t &ry);
private:
pbf& data;
uint8_t cmd;
uint32_t length;
int32_t x, y;
int32_t ox, oy;
};
Geometry::Geometry(pbf& data)
: data(data),
cmd(1),
length(0),
x(0), y(0),
ox(0), oy(0) {}
Geometry::command Geometry::next(int32_t &rx, int32_t &ry) {
if (data.data < data.end) {
if (length == 0) {
uint32_t cmd_length = static_cast<uint32_t>(data.varint());
cmd = cmd_length & 0x7;
length = cmd_length >> 3;
}
--length;
if (cmd == move_to || cmd == line_to) {
rx = (x += data.svarint());
ry = (y += data.svarint());
if (cmd == move_to) {
ox = x;
oy = y;
return move_to;
} else {
return line_to;
}
} else if (cmd == close) {
rx = ox;
ry = oy;
return close;
} else {
fprintf(stderr, "unknown command: %d\n", cmd);
// TODO: gracefully handle geometry parse failures
return end;
}
} else {
return end;
}
}
}
#endif
| 20.358974
| 71
| 0.493703
|
free1978
|
9617e0b6a859f09ae2edac9f830c28ff03cd67c9
| 4,998
|
cpp
|
C++
|
lib/cover/cover.cpp
|
spookey/full_power
|
a1c603da0ec552d15ee79ff1806e32619424a332
|
[
"MIT"
] | null | null | null |
lib/cover/cover.cpp
|
spookey/full_power
|
a1c603da0ec552d15ee79ff1806e32619424a332
|
[
"MIT"
] | null | null | null |
lib/cover/cover.cpp
|
spookey/full_power
|
a1c603da0ec552d15ee79ff1806e32619424a332
|
[
"MIT"
] | null | null | null |
#include "cover.hpp"
Cover::Cover(Cable& txt, Shell& exe, Flash& ini)
: txt(txt), exe(exe), ini(ini) {}
void Cover::setup(void) {
if (!WiFi.mode(WIFI_STA)) { this->txt.sos("wifi error", true); }
this->apply();
this->exe.add(this, &Cover::cmd_dialup, "wdial", "wifi dialup");
this->exe.add(this, &Cover::cmd_hangup, "whang", "wifi hangup");
this->exe.add(this, &Cover::cmd_lookup, "wlook", "mDNS lookup");
this->exe.add(this, &Cover::cmd_status, "wstat", "wifi status");
}
bool Cover::check(bool quick) {
if (WiFi.isConnected()) { return true; }
else if(quick) { return false; }
for (uint16_t tick = 2048; tick > 0; tick--) {
switch(WiFi.status()) {
case WL_DISCONNECTED: this->txt.text("~"); break;
case WL_IDLE_STATUS: this->txt.text("-"); break;
case WL_NO_SSID_AVAIL:
this->txt.log("cover", "wifi ssid can't be reached!");
return false;
case WL_CONNECT_FAILED:
this->txt.log("cover", "wifi password incorrect!");
return false;
case WL_CONNECTION_LOST:
this->txt.log("cover", "wifi connection lost!");
return false;
case WL_SCAN_COMPLETED:
this->txt.log("cover", "wifi scan completed.");
break;
case WL_CONNECTED:
this->txt.log("cover", "wifi connected!");
return true;
default: break;
}
delay(16);
}
this->txt.text(" ... giving up!", true);
return false;
}
bool Cover::hangup(void) {
if (!WiFi.isConnected()) { return true; }
this->txt.log("cover", "hangup");
this->txt.llg("connected", "hang up..");
WiFi.disconnect(true); delay(1024);
this->hangups++;
return (!WiFi.isConnected());
}
bool Cover::apply(void) {
String hostname = this->ini.get("hostname", this->txt.join(
COVER_H_NAME, "-", String(ESP.getChipId())
), true);
String wifissid = this->ini.get("wifissid", COVER_W_SSID, true);
String wifipass = this->ini.get("wifipass", COVER_W_PASS, true);
this->hangup();
this->txt.log("cover", "apply");
this->txt.llg("hostname", hostname);
this->txt.llg("ssid", wifissid);
this->txt.llg("pass", this->txt.fill(wifipass.length(), '*'));
WiFi.hostname(hostname);
WiFi.setAutoReconnect(true);
WiFi.begin(wifissid.c_str(), wifipass.c_str());
this->dialups++;
if (!this->check(false)) { return false; }
this->status();
if (MDNS.begin(hostname.c_str(), WiFi.localIP())) {
this->txt.llg("mDNS", "started");
MDNS.addService("http", "tcp", SERVE_HARBOR);
this->txt.llg("service", "registered");
}
return true;
}
void Cover::status(void) {
this->txt.log("cover", "status");
this->txt.llg("dialups", String(this->dialups));
this->txt.llg("hangups", String(this->hangups));
if (!WiFi.isConnected()) {
this->txt.llg("status", "disconnected!"); return;
} else {
this->txt.llg("status", "connected!");
}
this->txt.llg("ssid", WiFi.SSID());
this->txt.llg("bssid", WiFi.BSSIDstr());
this->txt.llg("mac", WiFi.macAddress());
this->txt.llg("channel", this->get_channel());
this->txt.llg("signal", this->get_signal());
this->txt.llg(":", this->get_hostname(), " ::");
this->txt.llg("address", WiFi.localIP().toString());
this->txt.llg("subnet", WiFi.subnetMask().toString());
this->txt.llg("gateway", WiFi.gatewayIP().toString());
this->txt.llg("dns", WiFi.dnsIP().toString());
}
void Cover::lookup(void) {
this->txt.log("cover", "lookup");
if (!WiFi.isConnected()) {
this->txt.llg("status", "disconnected!"); return;
}
const int query = MDNS.queryService("http", "tcp");
if (!query) { this->txt.llg("no results", "sorry"); return; }
this->txt.llg("results", String(query));
for (uint16_t idx = 0; idx < query; idx++) {
this->txt.llg(":", "#", String(idx + 1), " ::");
this->txt.llg("hostname", String(MDNS.hostname(idx)));
this->txt.llg("address", MDNS.IP(idx).toString());
this->txt.llg("port", String(MDNS.port(idx)));
}
}
void Cover::loop(void) {
if (this->repeat <= 1) {
if ((millis() - this->replay) > COVER_REPLAY) {
this->repeat = COVER_REPEAT; return;
}
return;
}
if (this->check(true)) { this->repeat = COVER_REPEAT; return; }
this->replay = millis(); this->repeat--;
this->apply();
}
uint8_t Cover::cmd_dialup(String _) {
this->repeat = 0; return (this->apply() ? 0 : 1);
}
uint8_t Cover::cmd_hangup(String _) {
this->repeat = 0; return (this->hangup() ? 0 : 1);
}
String Cover::get_hostname(void) { return WiFi.hostname(); }
String Cover::get_signal(void) {
return this->txt.join(String(WiFi.RSSI()), " dBm");
}
String Cover::get_channel(void) {
return this->txt.join("#", String(WiFi.channel()));
}
| 35.446809
| 70
| 0.572429
|
spookey
|
961a80fab4c34c5d50cfbb2aabb1c5c8c59f5a4f
| 8,222
|
cpp
|
C++
|
gui/tool-bar.cpp
|
lukas-ke/faint-graphics-editor
|
33eb9e6a3f2216fb2cf6ef9709a14f3d20b78fbf
|
[
"Apache-2.0"
] | 10
|
2016-12-28T22:06:31.000Z
|
2021-05-24T13:42:30.000Z
|
gui/tool-bar.cpp
|
lukas-ke/faint-graphics-editor
|
33eb9e6a3f2216fb2cf6ef9709a14f3d20b78fbf
|
[
"Apache-2.0"
] | 4
|
2015-10-09T23:55:10.000Z
|
2020-04-04T08:09:22.000Z
|
gui/tool-bar.cpp
|
lukas-ke/faint-graphics-editor
|
33eb9e6a3f2216fb2cf6ef9709a14f3d20b78fbf
|
[
"Apache-2.0"
] | null | null | null |
// -*- coding: us-ascii-unix -*-
// Copyright 2012 Lukas Kemmer
//
// Licensed under the Apache License, Version 2.0 (the "License"); you
// may not use this file except in compliance with the License. You
// may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
#include <vector>
#include "wx/sizer.h"
#include "app/resource-id.hh"
#include "bitmap/bitmap.hh"
#include "bitmap/color.hh"
#include "bitmap/draw.hh"
#include "geo/int-size.hh"
#include "gui/art.hh"
#include "gui/events.hh" // LayerChangeEvent
#include "gui/image-toggle-ctrl.hh"
#include "gui/setting-events.hh"
#include "gui/status-button.hh"
#include "gui/tool-bar.hh"
#include "gui/tool-drop-down-button.hh"
#include "util-wx/bind-event.hh"
#include "util-wx/convert-wx.hh"
#include "util-wx/fwd-wx.hh"
#include "util-wx/layout-wx.hh"
#include "util/color-bitmap-util.hh" // with_border
#include "util/setting-id.hh"
namespace faint{
const wxSize g_toolButtonSize(25,25);
const IntSetting g_layerSetting;
// Create the shaded "selected" tool graphic
static wxBitmap create_selected_bitmap(const wxBitmap& image){
auto bg(with_border(Bitmap(to_faint(image.GetSize()), Color(113,152,207,209)),
Color(113,153,208,115), LineStyle::SOLID));
blend(at_top_left(to_faint(image)), onto(bg));
return to_wx_bmp(bg);
}
class Toolbar::ToolbarImpl{
public:
ToolbarImpl(wxWindow* parent,
StatusInterface& status,
Art& art)
: m_activeButton(nullptr),
m_groupButton(nullptr),
m_panel(create_panel(parent))
{
using namespace layout;
auto hline = [this](int down){
return SizerItem(create_hline(m_panel),
Proportion(0), wxEXPAND|wxDOWN, down);
};
m_layerChoice = create_image_toggle(m_panel, g_layerSetting,
IntSize(30, 32),
status,
Tooltip("Raster or Object layer"),
{ToggleImage(art.Get(Icon::LAYER_RASTER), to_int(Layer::RASTER),
"Select the Raster Layer"),
ToggleImage(art.Get(Icon::LAYER_OBJECT), to_int(Layer::OBJECT),
"Select the Object Layer")},
Axis::HORIZONTAL,
IntSize(3, 3));
set_sizer(m_panel, create_column(OuterSpacing(0), ItemSpacing(0), {
{m_layerChoice, Proportion(0), wxEXPAND|wxDOWN, 5},
hline(5),
{CreateToolButtons(art, status),
Proportion(0), wxALIGN_CENTER_HORIZONTAL}}));
bind_fwd(m_panel, wxEVT_TOGGLEBUTTON,
[&](wxCommandEvent& event){
if (event.GetEventObject() != m_groupButton){
SendToolChoiceEvent(to_tool_id(event.GetId()));
}
event.Skip();
});
bind_fwd(m_panel, EVT_FAINT_IntSettingChange,
[&](const SettingEvent<IntSetting>& e){
assert(e.GetSetting() == g_layerSetting);
events::layer_change(m_panel, to_layerstyle(e.GetValue()));
});
}
wxWindow* AsWindow(){
return m_panel;
}
void SendToolChoiceEvent(ToolId id){
// Remove the selected indication from the current tool button
m_activeButton->SetValue(false);
auto it = m_idToButton.find(id);
if (it != end(m_idToButton)){
wxBitmapToggleButton* button = it->second;
if (!button->IsEnabled()){
// Do not select a disabled tool
return;
}
// Add the selected indication to the new tool
m_activeButton = button;
m_activeButton->SetValue(true);
}
else if (m_groupButton->SetSelectedTool(id)){
m_activeButton = m_groupButton;
}
else{
// Tool without button.
}
events::tool_change(m_panel, id);
}
void SendLayerChoiceEvent(Layer layer){
m_layerChoice->SetValue(to_int(layer));
m_layerChoice->SendChangeEvent();
}
private:
void AddTool(const wxBitmap& bmpInactive,
const Tooltip& tooltip,
const Description& description,
ToolId id,
wxGridSizer* sizer,
StatusInterface& status)
{
wxBitmap bmpActive(create_selected_bitmap(bmpInactive));
auto button = make_wx<ToggleStatusButton>(m_panel,
to_int(id),
m_panel->FromDIP(g_toolButtonSize),
status,
bmpInactive,
bmpActive,
tooltip,
description);
m_idToButton[id] = button;
sizer->Add(button);
if (m_activeButton == nullptr){
m_activeButton = button;
}
}
ToolDropDownButton* AddToolGroup(wxGridSizer* sizer,
const std::vector<ToolInfo>& tools)
{
auto* button = tool_drop_down_button(
m_panel,
to_faint(m_panel->FromDIP(g_toolButtonSize)),
tools);
sizer->Add(button);
events::on_tool_change(button,
[&](ToolId toolId){
SendToolChoiceEvent(toolId);
});
return button;
}
wxSizer* CreateToolButtons(Art& art, StatusInterface& status){
auto sizer = make_wx<wxGridSizer>(0, 2, 0, 0);
auto add_tool =
[&](Icon icon,
const Tooltip& tooltip,
const Description& description,
ToolId id)
{
AddTool(art.Get(icon),
tooltip,
description,
id,
sizer,
status);
};
add_tool(Icon::TOOL_SELECTION,
Tooltip("Selection"),
Description("Adjusts the selection."),
ToolId::SELECTION);
add_tool(Icon::TOOL_PEN,
Tooltip("Pen"),
Description("Draws single pixels."),
ToolId::PEN);
add_tool(Icon::TOOL_BRUSH,
Tooltip("Brush"),
Description("Free hand drawing with selected brush shape and size."),
ToolId::BRUSH);
add_tool(Icon::TOOL_PICKER,
Tooltip("Color picker"),
Description("Selects a color in the image."),
ToolId::PICKER);
add_tool(Icon::TOOL_LINE,
Tooltip("Line"),
Description("Draws lines."),
ToolId::LINE);
add_tool(Icon::TOOL_PATH,
Tooltip("Path"),
Description("Draws paths."),
ToolId::PATH);
add_tool(Icon::TOOL_RECTANGLE,
Tooltip("Rectangle"),
Description("Draws rectangles or squares."),
ToolId::RECTANGLE);
add_tool(Icon::TOOL_ELLIPSE,
Tooltip("Ellipse"),
Description("Draws ellipses or circles."),
ToolId::ELLIPSE);
add_tool(Icon::TOOL_POLYGON,
Tooltip("Polygon"),
Description("Draws polygons."),
ToolId::POLYGON);
add_tool(Icon::TOOL_TEXT,
Tooltip("Text"),
Description("Writes text."),
ToolId::TEXT);
m_groupButton = AddToolGroup(sizer, {
{ art.Get(Icon::TOOL_CALIBRATE),
create_selected_bitmap(art.Get(Icon::TOOL_CALIBRATE)),
Tooltip("Calibrate"),
Description("Defines image measurements."),
ToolId::CALIBRATE},
{ art.Get(Icon::TOOL_TAPE_MEASURE),
create_selected_bitmap(art.Get(Icon::TOOL_TAPE_MEASURE)),
Tooltip("Tape measure"),
Description("Image measurements"),
ToolId::TAPE_MEASURE},
{ art.Get(Icon::TOOL_LEVEL),
create_selected_bitmap(art.Get(Icon::TOOL_LEVEL)),
Tooltip("Level"),
Description("Image alignment"),
ToolId::LEVEL},
{ art.Get(Icon::TOOL_HOT_SPOT),
create_selected_bitmap(art.Get(Icon::TOOL_HOT_SPOT)),
Tooltip("Hot spot"),
Description("Sets the image hot spot."),
ToolId::HOT_SPOT}});
add_tool(Icon::TOOL_FLOODFILL,
Tooltip("Fill"),
Description("Fills contiguous areas."),
ToolId::FLOOD_FILL);
return sizer;
}
private:
wxBitmapToggleButton* m_activeButton;
ToolDropDownButton* m_groupButton;
wxWindow* m_panel;
std::map<ToolId, wxBitmapToggleButton*> m_idToButton;
IntSettingCtrl* m_layerChoice;
};
Toolbar::Toolbar(wxWindow* parent, StatusInterface& status, Art& art){
m_impl = make_dumb<ToolbarImpl>(parent, status, art);
}
wxWindow* Toolbar::AsWindow(){
return m_impl->AsWindow();
}
void Toolbar::SendLayerChoiceEvent(Layer layer){
m_impl->SendLayerChoiceEvent(layer);
}
void Toolbar::SendToolChoiceEvent(ToolId toolId){
m_impl->SendToolChoiceEvent(toolId);
}
} // namespace
| 27.406667
| 80
| 0.658721
|
lukas-ke
|
961da7e11f5eb214302d009f5624b574a4979a27
| 414
|
hpp
|
C++
|
trader/tools/PreprocessorOptions.hpp
|
joshuakarbi/trader
|
07f3ecf1f0eefd800464e2dfe9ee27b58c15254f
|
[
"MIT"
] | 11
|
2019-01-10T19:34:14.000Z
|
2019-09-24T05:30:03.000Z
|
trader/tools/PreprocessorOptions.hpp
|
joshuakarbi/trader
|
07f3ecf1f0eefd800464e2dfe9ee27b58c15254f
|
[
"MIT"
] | 8
|
2019-01-10T21:18:23.000Z
|
2019-02-12T20:11:56.000Z
|
trader/tools/PreprocessorOptions.hpp
|
joshuakarbi/trader
|
07f3ecf1f0eefd800464e2dfe9ee27b58c15254f
|
[
"MIT"
] | 2
|
2019-01-10T19:37:10.000Z
|
2019-07-12T01:49:18.000Z
|
#include <exception>
// override rapidjson assertions to throw exceptions instead
// this is better
#ifndef RAPIDJSON_ASSERT
#define RAPIDJSON_ASSERT(x) if(!(x)){ \
throw std::runtime_error("ERROR: rapidjson internal assertion failure: " #x); }
#endif
// required for paper trading vs. real url to be used
#define PAPER
// #define REAL
// toggle between regular and debug log files to be used
#define DEBUG
| 24.352941
| 81
| 0.743961
|
joshuakarbi
|
9620151bddeb826f190047268d1a0e3323664403
| 2,121
|
cpp
|
C++
|
Projetos/Aula16/main.cpp
|
chaua/programacao-avancada
|
4f580006d6e7e79e1bb6b32a62702eda3daa5874
|
[
"MIT"
] | 15
|
2018-04-05T00:15:01.000Z
|
2022-03-26T00:08:32.000Z
|
Projetos/Aula16/main.cpp
|
chaua/programacao-avancada
|
4f580006d6e7e79e1bb6b32a62702eda3daa5874
|
[
"MIT"
] | null | null | null |
Projetos/Aula16/main.cpp
|
chaua/programacao-avancada
|
4f580006d6e7e79e1bb6b32a62702eda3daa5874
|
[
"MIT"
] | 7
|
2018-03-23T00:11:56.000Z
|
2020-05-05T02:55:44.000Z
|
#include <iostream>
#include <fstream>
#include <string>
#include "data.h"
#include "data_dao.h"
using namespace std;
// ARQUIVOS
// - Caminho Absoluto:
// - Realiza a busca do arquivo a partir da raiz do sistema operacional
// - Utiliza o caminho inteiro do arquivo
// - Precisa conhecer a estrutura de diretorios do disco
// - Exemplo:
// C:\projeto\teste\arquivo.txt
// C:/projeto/teste/arquivo.txt
// /home/user/arquivo.txt
//
// - Caminho Relativo
// - Busca o arquivo a partir do diretorio que se executa o programa
// - Exemplo:
// arquivo.txt
// ./arquivo.txt (. representa o diretorio corrente)
// ../arquivo.txt (.. representa o diretorio pai)
// ../../teste.txt
// pasta/arquivo.txt
int main() {
// =========================
// ESCREVER DADOS NO ARQUIVO
// =========================
// 1. Abre o arquivo para escrita
// - param1: nome do arquivo
// - param2: modo de abertura
// ios_base::out - escrita destrutiva (padrao)
// ios_base::ate - escrita concatenada
// ios_base::app - escrita com append
ofstream fout("teste.txt", ios_base::out);
// 2. Escreve dados no arquivo
fout << "Isso eh uma linha de texto!!!" << endl;
fout << "Isso eh um numero: " << 99902 << endl;
// 3. Fecha o arquivo
fout.close(); // EOF
// ====================
// LER DADOS DO ARQUIVO
// ====================
// 1. Abre o arquivo para leitura
// ios_base::in
ifstream fin("teste.txt", ios_base::in);
// 2. Le os dados do arquivo
string buffer;
// leitura de token por token
// fin >> palavra1 >> palavra2 >> numero >> palavra3;
// leitura do arquivo linha a linha
while (getline(fin, buffer)) {
cout << buffer << endl;
}
// 3. Fecha o arquivo
fin.close();
// Teste da classe DAO
Data data(7, 6, 2021);
DataDAO dao;
dao.insere(data);
Data novaData = dao.consulta();
cout << "nova data: " << novaData << endl;
return 0;
}
| 25.554217
| 76
| 0.548326
|
chaua
|
9628f2598883bdefd15c3295e6e4514d01cff0af
| 8,569
|
hpp
|
C++
|
include/MCTS/MCTS.hpp
|
gress2/symreg
|
345071111bf2f030ff42d7f1325151abf78eca12
|
[
"MIT"
] | null | null | null |
include/MCTS/MCTS.hpp
|
gress2/symreg
|
345071111bf2f030ff42d7f1325151abf78eca12
|
[
"MIT"
] | null | null | null |
include/MCTS/MCTS.hpp
|
gress2/symreg
|
345071111bf2f030ff42d7f1325151abf78eca12
|
[
"MIT"
] | null | null | null |
#pragma once
#include <algorithm>
#include <fstream>
#include <iostream>
#include <map>
#include <memory>
#include <queue>
#include <random>
#include <unordered_map>
#include <vector>
#include "brick.hpp"
#include "dataset.hpp"
#include "loss.hpp"
#include "training_example.hpp"
#include "util.hpp"
#include "MCTS/scorer.hpp"
#include "MCTS/search_node.hpp"
#include "MCTS/simulator/simulator.hpp"
#define LOG_LEVEL 1
namespace symreg
{
namespace MCTS
{
using AST = brick::AST::AST;
/**
* @brief returns a pointer to the child of a search node with the highest
* UCB1 value.
*
* UCB1: (v/n) + 2 * sqrt(log(N) / n)
*
* Design decision: this metric and its hyperparameters
*
* @return a pointer to the child of a search node with highest UCB1 value
* if children exist, a nullptr otherwise.
*/
search_node* choose_move(search_node* node, double terminal_thresh) {
std::vector<search_node*> moves;
std::vector<search_node*> weak_terminals;
double max = -std::numeric_limits<double>::infinity();
for (auto& child : node->get_children()) {
if (child.get_ast_node()->is_terminal()) {
if (child.get_q() < terminal_thresh) {
weak_terminals.push_back(&child);
continue;
}
}
auto n = child.get_n();
if (n > max) {
max = n;
moves.clear();
moves.push_back(&child);
} else if (n == max) {
moves.push_back(&child);
}
}
// this just assures that we always end up with a valid AST
// from move making
if (moves.empty()) {
for (auto term : weak_terminals) {
auto n = term->get_n();
if (n > max) {
max = n;
moves.clear();
moves.push_back(term);
} else if (n == max) {
moves.push_back(term);
}
}
}
auto random = util::get_random_int(0, moves.size() - 1, symreg::mt);
return moves[random];
}
/**
* @brief the actual coordinator for monte carlo tree search
*/
template <class Regressor = symreg::DNN>
class MCTS {
private:
// MEMBERS
const int num_simulations_;
dataset& dataset_;
search_node root_;
search_node* curr_;
std::ofstream log_stream_;
std::shared_ptr<brick::AST::AST> result_ast_;
double terminal_thresh_ = .999;
simulator::simulator<Regressor> simulator_;
training_examples examples_;
// HELPERS
void write_game_state(int) const;
bool game_over();
std::shared_ptr<brick::AST::AST> build_current_ast();
std::vector<std::shared_ptr<brick::AST::AST>> top_asts_;
public:
// composable constructor for testability
MCTS(dataset&, simulator::simulator<Regressor>, int);
// .toml configurable
MCTS(dataset&, Regressor*, util::config);
void iterate();
std::string to_gv() const;
dataset& get_dataset();
void reset();
std::shared_ptr<brick::AST::AST> get_result();
std::vector<std::shared_ptr<brick::AST::AST>> get_top_n_asts();
training_examples get_training_examples() const;
std::size_t get_num_explored() const;
};
/**
* @brief an MCTS constructor which allows you to inject some
* arbitrary simulator. likely this is only useful for writing
* tests.
* @param ds a reference to a dataset
* @param simulator a simulator instance
* @param num_simulations the number of times you want the simulator
* to simulate between moves
*/
template <class Regressor>
MCTS<Regressor>::MCTS(
dataset& ds,
simulator::simulator<Regressor> _simulator,
int num_simulations
)
: num_simulations_(num_simulations),
dataset_(ds),
root_(search_node(std::make_unique<brick::AST::posit_node>())),
curr_(&root_),
log_stream_("mcts.log"),
result_ast_(nullptr),
simulator_(_simulator)
{
simulator_.add_actions(curr_);
}
/**
* @brief .toml configurable MCTS constructor
* @param ds a reference to a dataset
* @param regr a pointer to a regressor capable of evaluating a search nodes
* value and policy
* @param cfg a wrapper around a cpptoml table
*/
template <class Regressor>
MCTS<Regressor>::MCTS(dataset& ds, Regressor* regr, util::config cfg)
: num_simulations_(cfg.get<int>("mcts.num_simulations")),
dataset_(ds),
root_(search_node(std::make_unique<brick::AST::posit_node>())),
curr_(&root_),
log_stream_(cfg.get<std::string>("logging.file")),
result_ast_(nullptr),
simulator_(simulator::simulator<Regressor>(cfg, ds, regr))
{
simulator_.add_actions(curr_);
}
/**
* @brief The driver for all of the MCTS iterations
*
* A simple loop which first runs a simulation step
* which explores/expands the tree followed by a step
* which heuristically decides a move to take in the tree.
* If make_move() returns false, a move was not made in the
* game, and the game is over.
*
* @param n number determining how many time we wish to loop
*/
template <class Regressor>
void MCTS<Regressor>::iterate() {
std::size_t i = 0;
while (true) {
if (game_over()) {
break;
}
simulator_.simulate(curr_, num_simulations_);
if (simulator_.got_reward_within_thresh()) {
result_ast_ = simulator_.get_ast_within_thresh();
break;
}
search_node* prev = curr_;
examples_.push_back(
training_example{build_current_ast()->to_string(), curr_->get_pi(), 0}
);
curr_ = choose_move(curr_, terminal_thresh_);
#if LOG_LEVEL > 0
log_stream_ << "Iteration: " << i << std::endl;
write_game_state(i);
#endif
if (!curr_) {
curr_ = prev;
break;
}
i++;
}
if (result_ast_) {
simulator_.push_priq(result_ast_);
} else {
simulator_.push_priq(build_current_ast());
}
// assign rewards to examples
auto final_ast = get_result();
auto final_reward = simulator_.get_reward(final_ast);
for (auto& ex : examples_) {
ex.reward = final_reward;
}
}
/**
* @brief writes the MCTS tree as a gv to file
* @param iteration an integer which determines the name of the gv file
*/
template <class Regressor>
void MCTS<Regressor>::write_game_state(int iteration) const {
std::ofstream out_file(std::to_string(iteration) + ".gv");
out_file << to_gv() << std::endl;
}
/**
* @brief a check to determine whether or not more simulation is possible
* given the current move
*/
template <class Regressor>
bool MCTS<Regressor>::game_over() {
return curr_->is_dead_end();
}
/**
* @brief A recursive method for generating a graph viz representation for
* the entire MCTS tree
*
* @return the graph viz string representation
*/
template <class Regressor>
std::string MCTS<Regressor>::to_gv() const {
std::stringstream ss;
ss << "digraph {" << std::endl;
ss << root_.to_gv();
ss << "}" << std::endl;
return ss.str();
}
/**
* @brief a simple getter for the MCTS class' symbol table
*
* @return a non-const reference to the MCTS class' symbol table
*/
template <class Regressor>
dataset& MCTS<Regressor>::get_dataset() {
return dataset_;
}
/**
* @brief Returns the AST which this MCTS has currently
* decided is optimal
*
* @return a shared pointer to an AST
*/
template <class Regressor>
std::shared_ptr<brick::AST::AST> MCTS<Regressor>::build_current_ast() {
return simulator::build_ast_upward(curr_);
}
/**
* @brief returns the best AST the search was able to find.
* @return if the simulator encountered an AST whose value
* was within the early termination threshold, that AST is returned.
* otherwise, we simply return the AST that was formed from traditional
* move making within the tree.
*/
template <class Regressor>
std::shared_ptr<brick::AST::AST> MCTS<Regressor>::get_result() {
return get_top_n_asts().back();
}
/**
* @brief Resets the state of the MCTS search, allowing the next
* iterate call to operate from a blank slate
*/
template <class Regressor>
void MCTS<Regressor>::reset() {
root_.get_children().clear();
root_.set_q(0);
root_.set_n(0);
curr_ = &root_;
result_ast_ = nullptr;
simulator_.reset();
top_asts_.clear();
}
template <class Regressor>
std::vector<std::shared_ptr<brick::AST::AST>> MCTS<Regressor>::get_top_n_asts() {
if (top_asts_.empty()) {
top_asts_ = simulator_.dump_pri_q();
}
return top_asts_;
}
/**
* @brief a getter for the training_examples needed to
* train the regressor/neural network about MCTS states.
* @return a copy of the training examples vector
*/
template <class Regressor>
training_examples MCTS<Regressor>::get_training_examples() const {
return examples_;
}
template <class Regressor>
std::size_t MCTS<Regressor>::get_num_explored() const {
return simulator_.get_num_explored();
}
}
}
| 26.204893
| 81
| 0.681993
|
gress2
|
962aa251123eb7fb2b26abbdccd127e06b9aa338
| 4,707
|
hpp
|
C++
|
src/ngraph/runtime/cpu/pass/cpu_fusion.hpp
|
tzerrell/ngraph
|
b02b0812745ca1cb5f73d426ae9e0ad729eb0bbd
|
[
"Apache-2.0"
] | null | null | null |
src/ngraph/runtime/cpu/pass/cpu_fusion.hpp
|
tzerrell/ngraph
|
b02b0812745ca1cb5f73d426ae9e0ad729eb0bbd
|
[
"Apache-2.0"
] | null | null | null |
src/ngraph/runtime/cpu/pass/cpu_fusion.hpp
|
tzerrell/ngraph
|
b02b0812745ca1cb5f73d426ae9e0ad729eb0bbd
|
[
"Apache-2.0"
] | null | null | null |
//*****************************************************************************
// Copyright 2017-2019 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************
#pragma once
#include "ngraph/pass/graph_rewrite.hpp"
#include "ngraph/runtime/cpu/cpu_backend_visibility.h"
namespace ngraph
{
namespace runtime
{
namespace cpu
{
namespace pass
{
class CPUFusion;
class CPUQuantFusion;
}
}
}
}
class CPU_BACKEND_API ngraph::runtime::cpu::pass::CPUFusion : public ngraph::pass::GraphRewrite
{
public:
typedef ngraph::pass::FusionType FusionType;
typedef ngraph::pass::FusionTypeMask FusionTypeMask;
CPUFusion(FusionTypeMask fusions = FusionType::ALL_FUSIONS)
: GraphRewrite()
{
if (fusions.is_set(FusionType::DIFFERENTIABLE_FUSIONS))
{
construct_conv_bias(); // DEPRECATED - Use CoreFusion
construct_sigmoid_multiply();
}
if (fusions.is_set(FusionType::REGULAR_FUSIONS))
{
construct_matmul();
construct_matmulbias();
construct_fprop_bn();
construct_conv_bias_bprop();
construct_conv_bias_folded_batch_norm();
construct_conv_bias_affine_folding();
construct_groupconv_batchnorm_global_stats_folding();
construct_groupconv_batchnorm_global_stats_folding_relu();
construct_batch_norm_relu();
construct_batch_norm_relu_global_stats();
construct_conv_relu();
construct_conv_bias_relu();
construct_conv_bias_add(); // DEPRECATED - Use CoreFusion
construct_conv_bias_add_relu();
construct_leaky_relu();
construct_bounded_relu();
// construct_conv_add() should always be after construct_conv_bias()
construct_conv_add();
construct_conv_add_relu();
construct_update_slice();
construct_fuse_lstm_recurrent_state();
if (std::getenv("NGRAPH_DECONV_FUSE") != nullptr)
{
// Note: enable when the deconv perf is better than convbackpropdata
construct_deconvolution_affine_folding();
construct_deconvolution_affine_folding_relu();
}
construct_dropout();
}
}
private:
void construct_matmul();
void construct_matmulbias();
void construct_conv_bias();
void construct_conv_bias_bprop();
void construct_fprop_bn();
void construct_sigmoid_multiply();
void construct_batch_norm_relu();
void construct_batch_norm_relu_global_stats();
void construct_conv_relu();
void construct_conv_bias_relu();
void construct_conv_bias_add();
void construct_conv_bias_add_relu();
void construct_conv_add();
void construct_conv_add_relu();
void construct_leaky_relu();
void construct_bounded_relu();
void construct_conv_bias_folded_batch_norm();
void construct_conv_bias_affine_folding();
void construct_groupconv_batchnorm_global_stats_folding();
void construct_groupconv_batchnorm_global_stats_folding_relu();
void construct_update_slice();
void construct_fuse_lstm_recurrent_state();
void construct_deconvolution_affine_folding();
void construct_deconvolution_affine_folding_relu();
void construct_dropout();
};
class CPU_BACKEND_API ngraph::runtime::cpu::pass::CPUQuantFusion : public ngraph::pass::GraphRewrite
{
public:
CPUQuantFusion()
: GraphRewrite()
{
construct_qconv_relu(true);
construct_qconv_relu(false);
construct_qavg_pool();
construct_qmax_pool();
construct_qconcat();
construct_qconvb_add();
construct_dq_q();
construct_quantized_matmul();
}
private:
void construct_qconv_relu(bool with_bias);
void construct_qavg_pool();
void construct_qmax_pool();
void construct_qconcat();
void construct_dq_q();
void construct_qconvb_add();
void construct_quantized_matmul();
};
| 34.357664
| 100
| 0.657106
|
tzerrell
|
96335137b48dde4b2aea5a746e46240bcb2b8698
| 7,495
|
cpp
|
C++
|
simulation/Simulation.cpp
|
walachey/football-worldcup-simulator
|
36e6f80e3498b4a4dc7b8bf18d45af6c95a8fbe7
|
[
"MIT"
] | 1
|
2018-08-14T08:15:47.000Z
|
2018-08-14T08:15:47.000Z
|
simulation/Simulation.cpp
|
walachey/football-worldcup-simulator
|
36e6f80e3498b4a4dc7b8bf18d45af6c95a8fbe7
|
[
"MIT"
] | 2
|
2020-01-22T07:17:46.000Z
|
2020-01-22T07:17:54.000Z
|
simulation/Simulation.cpp
|
walachey/football-worldcup-simulator
|
36e6f80e3498b4a4dc7b8bf18d45af6c95a8fbe7
|
[
"MIT"
] | null | null | null |
#include "stdafx.h"
#include "Simulation.h"
#include <thread>
#include <chrono>
namespace sim
{
Simulation *Simulation::singleton = nullptr;
void Simulation::reset()
{
assert(Simulation::singleton == nullptr);
Simulation::singleton = this;
numberOfThreads = 1;
tournamentID = 0;
randomSeed = (unsigned int)std::chrono::system_clock::now().time_since_epoch().count();
}
Simulation::Simulation(json_spirit::Value &jsonData)
{
reset();
json_spirit::Object jsonObject = jsonData.get_obj();
// It is crucial that the teams are setup before the rules.
// To achieve that, we just delay rule initialization.
json_spirit::Array ruleData;
for (json_spirit::Pair &pair : jsonObject)
{
std::string &key = pair.name_;
if (key == "thread_count") numberOfThreads = pair.value_.get_int();
else if (key == "run_count") numberOfRuns = pair.value_.get_int();
else if (key == "tournament_id") tournamentID = pair.value_.get_int();
else if (key == "tournament_type") tournamentType = pair.value_.get_str();
else if (key == "teams") setupTeams(pair.value_.get_array());
else if (key == "rules") ruleData = pair.value_.get_array();
else if (key == "match_database") setupKnownMatches(pair.value_.get_array());
else
std::cerr << "sim::Simulation: invalid property \"" << key << "\"" << std::endl;
}
// Finally (after the teams are setup) init the rules.
if (!ruleData.empty())
setupRules(ruleData);
}
Simulation::~Simulation()
{
for (auto &tournament : tournaments)
delete tournament;
}
void Simulation::setupTeams(json_spirit::Array &teamData)
{
int teamIndex = 0;
for (json_spirit::Value &val : teamData)
{
teams.push_back(Team(val.get_obj(), teamIndex++));
}
}
void Simulation::setupRules(json_spirit::Array &ruleData)
{
for (json_spirit::Value &val : ruleData)
{
rules.push_back(Rule(val.get_obj()));
}
}
void Simulation::setupKnownMatches(json_spirit::Array &matches)
{
for (json_spirit::Value &val : matches)
{
json_spirit::Object &data = val.get_obj();
int teams[2] = { -1, -1 };
int goals[2] = { -1, -1 };
bool hadOvertime = false;
std::string cluster = "all";
int bofRound = -1;
for (json_spirit::Pair &pair : data)
{
std::string &key = pair.name_;
if (key == "teams")
{
for (int i = 0; i < 2; ++i)
teams[i] = pair.value_.get_array().at(i).get_int();
}
else if (key == "goals")
{
for (int i = 0; i < 2; ++i)
goals[i] = pair.value_.get_array().at(i).get_int();
}
else if (key == "bof_round")
{
bofRound = pair.value_.get_int();
}
}
assert(bofRound != -1);
assert(teams[0] != -1);
assert(goals[0] != -1);
if (!knownMatchResults.count(bofRound))
knownMatchResults[bofRound] = std::vector<KnownMatchResult>();
knownMatchResults[bofRound].push_back(KnownMatchResult(bofRound, cluster, teams, goals, hadOvertime));
}
}
void Simulation::execute()
{
// some safety & sanity checks
if (teams.empty())
{
throw "No teams are active. Aborting the tournament.";
}
if (rules.empty())
{
throw "No rules are active. Aborting the tournament.";
}
// 16 threads for one tournament sound impractical
int realThreadCount = std::min(numberOfThreads, numberOfRuns);
std::vector<std::thread> threads;
threads.resize(realThreadCount);
tournaments.resize(realThreadCount);
int remainingRuns = numberOfRuns;
int runsPerThread = numberOfRuns / realThreadCount;
for (int i = 0; i < realThreadCount; ++i, remainingRuns -= runsPerThread)
{
int runsForTournament = std::min(remainingRuns, runsPerThread);
// make sure that there are no remaining runs that don't get distributed
// example: 20 runs and 8 threads, runs per thread = 2, only 2*8=16 tournaments would be started
if (i == realThreadCount - 1)
runsForTournament = remainingRuns;
tournaments[i] = Tournament::newOfType(tournamentType, this, runsForTournament);
tournaments[i]->doSanityChecks(); // allow the tournament some checking prior to the launch
threads[i] = std::thread(&Tournament::start, tournaments[i]);
}
// wait for the simulation to finish
for (auto &thread : threads)
{
thread.join();
}
// setup rank data
{ // scope
std::unique_ptr<Tournament> tournament(Tournament::newOfType(tournamentType, this, 0));
for (RankData const & rank : tournament->getRankDataAssignment())
ranks.push_back(rank);
}
// and then join the results
for (Tournament* &tournament : tournaments)
{
// first the team data
for (auto &clusterToMerge : tournament->clusterTeamResults)
{
std::map<int, TeamResult> &cluster = clusterTeamResults[clusterToMerge.first];
for (auto &team : teams)
{
if (!cluster.count(team.id))
cluster.emplace(std::make_pair(team.id, TeamResult(clusterToMerge.second[team.id])));
else
cluster[team.id].merge(clusterToMerge.second[team.id]);
}
}
// and then the match cluster statistics
for (auto &clusterToMerge : tournament->clusterMatchResultStatisticsLists)
{
clusterMatchResultStatisticsLists[clusterToMerge.first].merge(clusterToMerge.second);
}
}
}
json_spirit::Object Simulation::getJSONResults()
{
json_spirit::Object root;
root.push_back(json_spirit::Pair("tournament_id", tournamentID));
root.push_back(json_spirit::Pair("ranks", json_spirit::Array()));
json_spirit::Array &ranks = root.back().value_.get_array();
fillRankResults(ranks);
root.push_back(json_spirit::Pair("matches", json_spirit::Object()));
json_spirit::Object &matches= root.back().value_.get_obj();
for (auto &cluster : clusterTeamResults)
{
matches.push_back(json_spirit::Pair(cluster.first, json_spirit::Object()));
json_spirit::Object &match = matches.back().value_.get_obj();
match.push_back(json_spirit::Pair("teams", json_spirit::Array()));
json_spirit::Array &teams = match.back().value_.get_array();
fillTeamResults(teams, cluster.first);
match.push_back(json_spirit::Pair("results", json_spirit::Array()));
json_spirit::Array &results = match.back().value_.get_array();
fillMatchResults(results, cluster.first);
if (cluster.first != "all")
{
match.push_back(json_spirit::Pair("bof_round", clusterMatchResultStatisticsLists[cluster.first].bofRound));
match.push_back(json_spirit::Pair("game_in_round", clusterMatchResultStatisticsLists[cluster.first].gameInRound));
}
else
{
match.push_back(json_spirit::Pair("bof_round", 0));
match.push_back(json_spirit::Pair("game_in_round", 0));
}
}
return root;
}
void Simulation::fillRankResults(json_spirit::Array &ranks)
{
for (RankData &rankData : this->ranks)
ranks.push_back(rankData.toJSONObject());
}
void Simulation::fillMatchResults(json_spirit::Array &results, std::string cluster)
{
results = clusterMatchResultStatisticsLists[cluster].toJSONArray();
}
void Simulation::fillTeamResults(json_spirit::Array &teamList, std::string cluster)
{
for (auto &team : teams)
{
json_spirit::Object teamData;
teamData.push_back(json_spirit::Pair("id", team.id));
if (cluster == "all")
{
teamData.push_back(json_spirit::Pair("ranks", clusterTeamResults[cluster][team.id].rankDataToJSONArray(ranks)));
teamData.push_back(json_spirit::Pair("avg_place", clusterTeamResults[cluster][team.id].getAvgPlace()));
}
teamData.push_back(json_spirit::Pair("match_data", clusterTeamResults[cluster][team.id].toJSONObject()));
teamData.push_back(json_spirit::Pair("avg_goals", clusterTeamResults[cluster][team.id].getAvgGoals()));
teamList.push_back(teamData);
}
}
} // namespace sim
| 29.050388
| 117
| 0.70567
|
walachey
|
963ce0e2c4978bd9501a55fe22131ebff42e7a01
| 3,539
|
cpp
|
C++
|
Jamma/src/Main.cpp
|
malisimo/Jamma
|
69831e79a64e652e82aa41f8141e082c3899896b
|
[
"MIT"
] | null | null | null |
Jamma/src/Main.cpp
|
malisimo/Jamma
|
69831e79a64e652e82aa41f8141e082c3899896b
|
[
"MIT"
] | null | null | null |
Jamma/src/Main.cpp
|
malisimo/Jamma
|
69831e79a64e652e82aa41f8141e082c3899896b
|
[
"MIT"
] | null | null | null |
///////////////////////////////////////////////////////////
//
// Copyright(c) 2018-2019 Matt Jones
// Subject to the MIT license, see LICENSE file.
//
///////////////////////////////////////////////////////////
#include "Main.h"
#include "Window.h"
#include "PathUtils.h"
#include "../io/TextReadWriter.h"
#include "../io/InitFile.h"
#include <vector>
#include <fstream>
#include <sstream>
using namespace engine;
using namespace base;
using namespace resources;
using namespace graphics;
using namespace utils;
using namespace io;
#define MAX_JSON_CHARS 1000000u
void SetupConsole()
{
AllocConsole();
FILE* newStdout = nullptr;
FILE* newStderr = nullptr;
FILE* newStdin = nullptr;
freopen_s(&newStdout, "CONOUT$", "w", stdout);
freopen_s(&newStderr, "CONOUT$", "w", stderr);
freopen_s(&newStdin, "CONIN$", "r", stdin);
}
std::optional<io::InitFile> LoadIni()
{
std::wstring initPath = GetPath(PATH_ROAMING) + L"/Jamma/defaults.json";
io::TextReadWriter txtFile;
auto res = txtFile.Read(initPath, MAX_JSON_CHARS);
std::string iniTxt = InitFile::DefaultJson;
if (!res.has_value())
txtFile.Write(initPath, iniTxt, (unsigned int)iniTxt.size(), 0);
else
{
auto [ini, numChars, unused] = res.value();
iniTxt = ini;
}
std::stringstream ss(iniTxt);
return InitFile::FromStream(std::move(ss));
}
std::optional<io::JamFile> LoadJam(io::InitFile& ini)
{
io::TextReadWriter txtFile;
std::string jamJson = JamFile::DefaultJson;
auto res = txtFile.Read(ini.Jam, MAX_JSON_CHARS);
if (!res.has_value())
{
ini.Jam = GetPath(PATH_ROAMING) + L"/Jamma/default.jam";
txtFile.Write(ini.Jam,
jamJson,
(unsigned int)jamJson.size(),
0);
}
else
{
auto [str, numChars, unused] = res.value();
jamJson = str;
}
std::stringstream ss(jamJson);
return JamFile::FromStream(std::move(ss));
}
std::optional<io::RigFile> LoadRig(io::InitFile& ini)
{
io::TextReadWriter txtFile;
std::string rigJson = RigFile::DefaultJson;
auto res = txtFile.Read(ini.Rig, MAX_JSON_CHARS);
if (!res.has_value())
{
ini.Rig = GetPath(PATH_ROAMING) + L"/Jamma/default.rig";
txtFile.Write(ini.Rig,
rigJson,
(unsigned int)rigJson.size(),
0);
}
else
{
auto [str, numChars, unused] = res.value();
rigJson = str;
}
std::stringstream ss(rigJson);
return RigFile::FromStream(std::move(ss));
}
int APIENTRY wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow)
{
SetupConsole();
auto defaults = LoadIni();
SceneParams sceneParams(DrawableParams{ "" }, SizeableParams{ 1400, 1000 });
JamFile jam;
RigFile rig;
if (defaults.has_value())
{
auto jamOpt = LoadJam(defaults.value());
if (jamOpt.has_value())
jam = jamOpt.value();
auto rigOpt = LoadRig(defaults.value());
if (rigOpt.has_value())
rig = rigOpt.value();
}
auto scene = Scene::FromFile(sceneParams, jam, rig, utils::GetParentDirectory(defaults.value().Jam));
if (!scene.has_value())
{
std::cout << "Failed to create Scene... quitting" << std::endl;
return -1;
}
ResourceLib resourceLib;
Window window(*(scene.value()), resourceLib);
if (window.Create(hInstance, nCmdShow) != 0)
PostQuitMessage(1);
scene.value()->InitAudio();
MSG msg;
bool active = true;
while (active)
{
while (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE))
{
if (msg.message == WM_QUIT)
{
scene.value()->CloseAudio();
active = false;
}
TranslateMessage(&msg);
DispatchMessage(&msg);
}
window.Render();
window.Swap();
}
window.Release();
return (int)msg.wParam;
}
| 21.579268
| 102
| 0.659226
|
malisimo
|
9640e1097c204a196f850ce686d3ad76fd9b5e4d
| 1,048
|
hpp
|
C++
|
src/CError.hpp
|
Vince0789/SA-MP-MySQL
|
9524fcc9088004948770ddd6e05a6074581d3095
|
[
"BSD-3-Clause"
] | 182
|
2015-01-17T09:55:05.000Z
|
2022-03-30T13:08:48.000Z
|
src/CError.hpp
|
Tuise233/SA-MP-MySQL
|
a8113cd3a7b5dcee1002622c5901ff78e3e6e3fe
|
[
"BSD-3-Clause"
] | 226
|
2015-01-01T12:22:11.000Z
|
2022-02-18T20:36:37.000Z
|
src/CError.hpp
|
Tuise233/SA-MP-MySQL
|
a8113cd3a7b5dcee1002622c5901ff78e3e6e3fe
|
[
"BSD-3-Clause"
] | 149
|
2015-01-05T16:42:45.000Z
|
2022-03-26T22:04:24.000Z
|
#pragma once
#include <string>
#include <fmt/format.h>
using std::string;
template<typename T>
class CError
{
using ErrorType = typename T::Error;
public:
CError() :
m_Type(ErrorType::NONE)
{ }
CError(ErrorType type, string &&msg) :
m_Type(type),
m_Message(std::move(msg))
{ }
template<typename... Args>
CError(ErrorType type, string &&format, Args &&...args) :
m_Type(type),
m_Message(fmt::format(format, std::forward<Args>(args)...))
{ }
~CError() = default;
operator bool() const
{
return m_Type != ErrorType::NONE;
}
const string &msg() const
{
return m_Message;
}
const ErrorType type() const
{
return m_Type;
}
const string &module() const
{
return T::ModuleName;
}
void set(ErrorType type, string &&msg)
{
m_Type = type;
m_Message.assign(std::move(msg));
}
template<typename... Args>
void set(ErrorType type, string &&format, Args &&...args)
{
m_Type = type;
m_Message.assign(fmt::format(format, std::forward<Args>(args)...));
}
private:
ErrorType m_Type;
string m_Message;
};
| 16.903226
| 69
| 0.659351
|
Vince0789
|
9644b8367042090055f72412600c5c3445ee6bd0
| 1,188
|
cpp
|
C++
|
src/prod/src/ServiceModel/ProvisionedFabricCodeVersionQueryResultItem.cpp
|
vishnuk007/service-fabric
|
d0afdea185ae932cc3c9eacf179692e6fddbc630
|
[
"MIT"
] | 2,542
|
2018-03-14T21:56:12.000Z
|
2019-05-06T01:18:20.000Z
|
src/prod/src/ServiceModel/ProvisionedFabricCodeVersionQueryResultItem.cpp
|
vishnuk007/service-fabric
|
d0afdea185ae932cc3c9eacf179692e6fddbc630
|
[
"MIT"
] | 994
|
2019-05-07T02:39:30.000Z
|
2022-03-31T13:23:04.000Z
|
src/prod/src/ServiceModel/ProvisionedFabricCodeVersionQueryResultItem.cpp
|
vishnuk007/service-fabric
|
d0afdea185ae932cc3c9eacf179692e6fddbc630
|
[
"MIT"
] | 300
|
2018-03-14T21:57:17.000Z
|
2019-05-06T20:07:00.000Z
|
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#include "stdafx.h"
using namespace std;
using namespace Common;
using namespace ServiceModel;
ProvisionedFabricCodeVersionQueryResultItem::ProvisionedFabricCodeVersionQueryResultItem()
: codeVersion_()
{
}
ProvisionedFabricCodeVersionQueryResultItem::ProvisionedFabricCodeVersionQueryResultItem(wstring const & codeVersion)
: codeVersion_(codeVersion)
{
}
void ProvisionedFabricCodeVersionQueryResultItem::ToPublicApi(
__in Common::ScopedHeap & heap,
__out FABRIC_PROVISIONED_CODE_VERSION_QUERY_RESULT_ITEM & publicQueryResult) const
{
publicQueryResult.CodeVersion = heap.AddString(codeVersion_);
}
void ProvisionedFabricCodeVersionQueryResultItem::WriteTo(TextWriter& w, FormatOptions const &) const
{
w.Write(ToString());
}
wstring ProvisionedFabricCodeVersionQueryResultItem::ToString() const
{
return wformatString("CodeVersion = '{0}'", codeVersion_);
}
| 31.263158
| 117
| 0.714646
|
vishnuk007
|
9647fe7c5acc92e8db0b91caa67a37662d46364d
| 2,141
|
cc
|
C++
|
flare/testing/redis_mock_test.cc
|
AriCheng/flare
|
b2c84588fe4ac52f0875791d22284d7e063fd057
|
[
"CC-BY-3.0",
"BSD-2-Clause",
"BSD-3-Clause"
] | 868
|
2021-05-28T04:00:22.000Z
|
2022-03-31T08:57:14.000Z
|
flare/testing/redis_mock_test.cc
|
AriCheng/flare
|
b2c84588fe4ac52f0875791d22284d7e063fd057
|
[
"CC-BY-3.0",
"BSD-2-Clause",
"BSD-3-Clause"
] | 33
|
2021-05-28T08:44:47.000Z
|
2021-09-26T13:09:21.000Z
|
flare/testing/redis_mock_test.cc
|
AriCheng/flare
|
b2c84588fe4ac52f0875791d22284d7e063fd057
|
[
"CC-BY-3.0",
"BSD-2-Clause",
"BSD-3-Clause"
] | 122
|
2021-05-28T08:22:23.000Z
|
2022-03-29T09:52:09.000Z
|
// Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the
// License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
#include "flare/testing/redis_mock.h"
#include "gmock/gmock-matchers.h"
#include "gtest/gtest.h"
#include "flare/net/redis/redis_channel.h"
#include "flare/net/redis/redis_client.h"
#include "flare/testing/main.h"
using namespace std::literals;
using testing::_;
namespace flare::testing::detail {
TEST(RedisMock, All) {
RedisChannel channel;
FLARE_CHECK(channel.Open("mock://whatever-it-wants-to-be."));
RedisClient client(&channel);
FLARE_EXPECT_REDIS_COMMAND(RedisCommandEq(RedisCommand("GET", "x")))
.WillRepeatedly(Return(RedisString("str")));
FLARE_EXPECT_REDIS_COMMAND(RedisCommandOpEq("SET"))
.WillRepeatedly(Return(RedisString("str")));
FLARE_EXPECT_REDIS_COMMAND(RedisCommandUserMatch([](auto&& cmd) {
return GetRedisCommandOp(cmd) == "SCAN";
})).WillRepeatedly(Return(RedisString("str")));
auto result = client.Execute(RedisCommand("GET", "x"), 1s);
ASSERT_TRUE(result.is<RedisString>());
EXPECT_EQ("str", *result.as<RedisString>());
result = client.Execute(RedisCommand("SET", "x", "y"), 1s);
ASSERT_TRUE(result.is<RedisString>());
EXPECT_EQ("str", *result.as<RedisString>());
result = client.Execute(RedisCommand("SCAN", "0"), 1s);
ASSERT_TRUE(result.is<RedisString>());
EXPECT_EQ("str", *result.as<RedisString>());
FLARE_EXPECT_REDIS_COMMAND(_).WillRepeatedly(Return(RedisNull()));
EXPECT_TRUE(
client.Execute(RedisCommand("GET", "not existing"), 1s).is<RedisNull>());
}
} // namespace flare::testing::detail
FLARE_TEST_MAIN
| 33.453125
| 80
| 0.726296
|
AriCheng
|
964a78c866872ed3ebf3a5f76e755e953c6044af
| 784
|
cpp
|
C++
|
Recursion/39. Combination Sum/Soluition.cpp
|
VarunSAthreya/LeetCode-Solutions
|
aeab92df5bca208c2442ffdb1487fe5e3aadb3de
|
[
"MIT"
] | 1
|
2021-11-24T16:20:32.000Z
|
2021-11-24T16:20:32.000Z
|
Recursion/39. Combination Sum/Soluition.cpp
|
VarunSAthreya/LeetCode-Solutions
|
aeab92df5bca208c2442ffdb1487fe5e3aadb3de
|
[
"MIT"
] | null | null | null |
Recursion/39. Combination Sum/Soluition.cpp
|
VarunSAthreya/LeetCode-Solutions
|
aeab92df5bca208c2442ffdb1487fe5e3aadb3de
|
[
"MIT"
] | 3
|
2021-09-03T15:14:12.000Z
|
2022-03-07T04:04:32.000Z
|
class Solution
{
public:
vector<vector<int>> combinationSum(vector<int> &candidates, int target)
{
vector<vector<int>> res;
if (candidates.size() == 0)
return res;
vector<int> ds;
solve(candidates, target, res, ds, 0);
return res;
}
void solve(vector<int> &candidates, int target, vector<vector<int>> &res, vector<int> &ds, int ind)
{
if (ind == candidates.size() || target <= 0)
{
if (target == 0)
{
res.push_back(ds);
}
return;
}
ds.push_back(candidates[ind]);
solve(candidates, target - candidates[ind], res, ds, ind);
ds.pop_back();
solve(candidates, target, res, ds, ind + 1);
}
};
| 26.133333
| 103
| 0.510204
|
VarunSAthreya
|
964cd89b95b7fcf7e07190110fc208074d425ec7
| 376
|
cpp
|
C++
|
kikilib/TimerEventService.cpp
|
YukangLiu/kikilib
|
a6b5d43e720186ac290eb9953f9c03ce4bb5386b
|
[
"MIT"
] | 46
|
2019-12-05T16:35:59.000Z
|
2022-03-26T14:23:19.000Z
|
kikilib/TimerEventService.cpp
|
WoBuShiXiaoKang/kikilib
|
a6b5d43e720186ac290eb9953f9c03ce4bb5386b
|
[
"MIT"
] | 1
|
2019-12-11T08:02:04.000Z
|
2019-12-19T14:28:05.000Z
|
kikilib/TimerEventService.cpp
|
WoBuShiXiaoKang/kikilib
|
a6b5d43e720186ac290eb9953f9c03ce4bb5386b
|
[
"MIT"
] | 8
|
2019-12-06T11:08:19.000Z
|
2022-03-05T02:30:51.000Z
|
//@Author Liu Yukang
#include "TimerEventService.h"
using namespace kikilib;
TimerEventService::TimerEventService(Socket& sock, EventManager* evMgr)
: EventService(sock, evMgr)
{ }
TimerEventService::TimerEventService(Socket&& sock, EventManager* evMgr)
: EventService(std::move(sock), evMgr)
{ }
void TimerEventService::handleReadEvent()
{
readAll();
runExpired();
}
| 20.888889
| 72
| 0.757979
|
YukangLiu
|
965810bd0b47a5e8a4cbdff646c20d655fce0973
| 6,344
|
cpp
|
C++
|
Wing.cpp
|
ancientlore/wing
|
7a86926729a72f603b1ea43a4dd5c2e45a230c64
|
[
"MIT"
] | 1
|
2021-09-19T21:48:40.000Z
|
2021-09-19T21:48:40.000Z
|
Wing.cpp
|
ancientlore/wing
|
7a86926729a72f603b1ea43a4dd5c2e45a230c64
|
[
"MIT"
] | null | null | null |
Wing.cpp
|
ancientlore/wing
|
7a86926729a72f603b1ea43a4dd5c2e45a230c64
|
[
"MIT"
] | null | null | null |
// Wing.cpp : main source file for Wing.exe
//
#include "stdafx.h"
#include <atlframe.h>
#include <atlctrls.h>
#include <atldlgs.h>
#include "resource.h"
#include "LayeredWindow.h"
volatile bool gTimeToQuit = false;
typedef struct {
UCHAR Ttl;
UCHAR Tos;
UCHAR Flags;
UCHAR OptionsSize;
PUCHAR OptionsData;
} IP_OPTION_INFORMATION, *PIP_OPTION_INFORMATION;
typedef struct {
ULONG Address;
ULONG Status;
ULONG RoundTripTime;
USHORT DataSize;
USHORT Reserved;
PVOID Data;
IP_OPTION_INFORMATION Options;
} ICMPECHO;
HMODULE hIcmpDll;
HANDLE (WINAPI *lpfnIcmpCreateFile)();
BOOL (WINAPI *lpfnIcmpCloseHandle)(HANDLE);
DWORD (WINAPI *lpfnIcmpSendEcho2)(HANDLE, HANDLE, FARPROC, PVOID, ULONG, LPVOID, WORD, PIP_OPTION_INFORMATION, LPVOID, DWORD, DWORD);
DWORD (WINAPI *lpfnIcmpParseReplies)(LPVOID, DWORD);
#include "aboutdlg.h"
#include "optionsdlg.h"
#include "SkinData.h"
#include "sampleskin.h"
#include "selectskindlg.h"
#include "MainFrm.h"
CAppModule _Module;
class CWingThreadManager
{
public:
// thread init param
struct _RunData
{
LPTSTR lpstrCmdLine;
int nCmdShow;
TCHAR WindowID[255];
};
// thread proc
static DWORD WINAPI RunThread(LPVOID lpData)
{
CMessageLoop theLoop;
_Module.AddMessageLoop(&theLoop);
_RunData* pData = (_RunData*)lpData;
CMainFrame wndFrame;
CString s = pData->WindowID;
s.TrimLeft();
s.TrimRight();
if (!s.IsEmpty())
wndFrame.WindowID = s;
//if(wndFrame.CreateEx() == NULL)
if(wndFrame.CreateEx(NULL, NULL, WS_POPUP, WS_EX_LAYERED | WS_EX_NOACTIVATE) == NULL)
{
ATLTRACE(_T("Frame window creation failed!\n"));
return 0;
}
wndFrame.ShowWindow(pData->nCmdShow);
::SetForegroundWindow(wndFrame); // Win95 needs this
delete pData;
int nRet = theLoop.Run();
_Module.RemoveMessageLoop();
return nRet;
}
DWORD m_dwCount;
HANDLE m_arrThreadHandles[MAXIMUM_WAIT_OBJECTS - 1];
CWingThreadManager() : m_dwCount(0)
{ }
// Operations
DWORD AddThread(LPTSTR lpstrCmdLine, int nCmdShow, LPTSTR winID = NULL)
{
if(m_dwCount == (MAXIMUM_WAIT_OBJECTS - 1))
{
::MessageBox(NULL, _T("ERROR: Cannot create ANY MORE threads!!!"), _T("Wing"), MB_OK);
return 0;
}
_RunData* pData = new _RunData;
pData->lpstrCmdLine = lpstrCmdLine;
pData->nCmdShow = nCmdShow;
if (winID != NULL)
_tcscpy(pData->WindowID, winID);
else
pData->WindowID[0] = _T('\0');
DWORD dwThreadID;
HANDLE hThread = ::CreateThread(NULL, 0, RunThread, pData, 0, &dwThreadID);
if(hThread == NULL)
{
::MessageBox(NULL, _T("ERROR: Cannot create thread!!!"), _T("Wing"), MB_OK);
return 0;
}
m_arrThreadHandles[m_dwCount] = hThread;
m_dwCount++;
return dwThreadID;
}
void RemoveThread(DWORD dwIndex)
{
::CloseHandle(m_arrThreadHandles[dwIndex]);
if(dwIndex != (m_dwCount - 1))
m_arrThreadHandles[dwIndex] = m_arrThreadHandles[m_dwCount - 1];
m_dwCount--;
}
int Run(LPTSTR lpstrCmdLine, int nCmdShow)
{
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData)) {
::MessageBox(NULL, _T("ERROR: Could not initialize Windows Sockets"), _T("Error"), MB_OK);
return 0;
}
hIcmpDll = LoadLibrary(_T("ICMP.DLL"));
if (hIcmpDll == INVALID_HANDLE_VALUE) {
::MessageBox(NULL, _T("ERROR: Unable to load ICMP DLL"), _T("Error"), MB_OK);
WSACleanup();
return 0;
}
lpfnIcmpCreateFile = (HANDLE (WINAPI *)()) GetProcAddress(hIcmpDll, "IcmpCreateFile");
lpfnIcmpCloseHandle = (BOOL (WINAPI *)(HANDLE)) GetProcAddress(hIcmpDll, "IcmpCloseHandle");
lpfnIcmpSendEcho2 = (DWORD (WINAPI *)(HANDLE, HANDLE, FARPROC, PVOID, ULONG, LPVOID, WORD, PIP_OPTION_INFORMATION, LPVOID, DWORD, DWORD)) GetProcAddress(hIcmpDll, "IcmpSendEcho2");
lpfnIcmpParseReplies = (DWORD (WINAPI *)(LPVOID, DWORD)) GetProcAddress(hIcmpDll, "IcmpParseReplies");
if (!lpfnIcmpCreateFile || !lpfnIcmpCloseHandle) {
::MessageBox(NULL, _T("ERROR: Unable to find ICMP functions"), _T("Error"), MB_OK);
FreeLibrary(hIcmpDll);
WSACleanup();
return 0;
}
MSG msg;
// force message queue to be created
::PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);
CRegKey key;
if (key.Create(HKEY_CURRENT_USER, _T("Software\\Lore\\Wing\\Windows")) == ERROR_SUCCESS) {
TCHAR kname[256];
DWORD sz = 255;
DWORD i = 0;
while (key.EnumKey(i, kname, &sz) == ERROR_SUCCESS) {
AddThread(lpstrCmdLine, nCmdShow, kname);
sz = 255;
i++;
}
if (i == 0)
AddThread(lpstrCmdLine, nCmdShow);
}
else
AddThread(lpstrCmdLine, nCmdShow);
int nRet = m_dwCount;
DWORD dwRet;
while(m_dwCount > 0)
{
dwRet = ::MsgWaitForMultipleObjects(m_dwCount, m_arrThreadHandles, FALSE, INFINITE, QS_ALLINPUT);
if(dwRet == 0xFFFFFFFF)
{
::MessageBox(NULL, _T("ERROR: Wait for multiple objects failed!!!"), _T("Wing"), MB_OK);
}
else if(dwRet >= WAIT_OBJECT_0 && dwRet <= (WAIT_OBJECT_0 + m_dwCount - 1))
{
RemoveThread(dwRet - WAIT_OBJECT_0);
}
else if(dwRet == (WAIT_OBJECT_0 + m_dwCount))
{
if(::PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
if(msg.message == WM_USER)
AddThread(lpstrCmdLine, SW_SHOWNORMAL);
}
}
else
{
::MessageBeep((UINT)-1);
}
}
FreeLibrary(hIcmpDll);
WSACleanup();
return nRet;
}
};
int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE /*hPrevInstance*/, LPTSTR lpstrCmdLine, int nCmdShow)
{
HRESULT hRes = ::CoInitialize(NULL);
// If you are running on NT 4.0 or higher you can use the following call instead to
// make the EXE free threaded. This means that calls come in on a random RPC thread.
// HRESULT hRes = ::CoInitializeEx(NULL, COINIT_MULTITHREADED);
ATLASSERT(SUCCEEDED(hRes));
// this resolves ATL window thunking problem when Microsoft Layer for Unicode (MSLU) is used
::DefWindowProc(NULL, 0, 0, 0L);
AtlInitCommonControls(ICC_BAR_CLASSES); // add flags to support other controls
hRes = _Module.Init(NULL, hInstance);
ATLASSERT(SUCCEEDED(hRes));
int nRet = 0;
// BLOCK: Run application
{
CWingThreadManager mgr;
nRet = mgr.Run(lpstrCmdLine, nCmdShow);
}
_Module.Term();
::CoUninitialize();
return nRet;
}
| 26
| 183
| 0.667718
|
ancientlore
|
9659a1d55c8d410e0f909cb9c9dbdeac8964cafb
| 285
|
cc
|
C++
|
9_Palindrome_Number/Solution.cc
|
Samukawa-T1/LeetCode-Diary
|
551329796e7b6e8f9176d8cf85dc658b9211b7e9
|
[
"Apache-2.0"
] | null | null | null |
9_Palindrome_Number/Solution.cc
|
Samukawa-T1/LeetCode-Diary
|
551329796e7b6e8f9176d8cf85dc658b9211b7e9
|
[
"Apache-2.0"
] | null | null | null |
9_Palindrome_Number/Solution.cc
|
Samukawa-T1/LeetCode-Diary
|
551329796e7b6e8f9176d8cf85dc658b9211b7e9
|
[
"Apache-2.0"
] | null | null | null |
class Solution {
public:
bool isPalindrome(int x){
if(x < 0 || (x % 10 == 0 && x != 0)) {
return false;
}
int rev_last = 0;
while(x > rev_last) {
rev_last = rev_last * 10 + x % 10;
x /= 10;
}
return x == rev_last || x == rev_last/10;
}
};
| 19
| 45
| 0.477193
|
Samukawa-T1
|
965a8b567a6db0c4dbb4aa4a9f8a2776971ad3d6
| 1,298
|
hpp
|
C++
|
tests/performance/point_type.hpp
|
Roboauto/spatial
|
fe652631eb5ec23a719bf1788c68cbd67060e12b
|
[
"BSL-1.0"
] | 7
|
2015-12-07T02:10:23.000Z
|
2022-01-01T05:39:05.000Z
|
tests/performance/point_type.hpp
|
Roboauto/spatial
|
fe652631eb5ec23a719bf1788c68cbd67060e12b
|
[
"BSL-1.0"
] | 1
|
2021-01-28T15:07:42.000Z
|
2021-01-28T15:07:42.000Z
|
tests/performance/point_type.hpp
|
Roboauto/spatial
|
fe652631eb5ec23a719bf1788c68cbd67060e12b
|
[
"BSL-1.0"
] | 2
|
2016-08-31T13:30:18.000Z
|
2021-07-07T07:22:03.000Z
|
// -*- C++ -*-
#ifndef SPATIAL_EXAMPLE_POINT_TYPE_HPP
#define SPATIAL_EXAMPLE_POINT_TYPE_HPP
#include <algorithm> // std::fill
struct point3_type
{
typedef double value_type;
point3_type() { }
explicit point3_type (double value)
{ std::fill(values, values + 3, value); }
template <typename Distribution>
explicit point3_type(const Distribution& distrib)
{ values[0] = distrib(); values[1] = distrib(); values[2] = distrib(); }
double operator [] (std::size_t index) const { return values[index]; }
double& operator [] (std::size_t index) { return values[index]; }
private:
double values[3];
};
struct point9_type
{
typedef double value_type;
point9_type() { }
explicit point9_type (double value)
{ std::fill(values, values + 9, value); }
template <typename Distribution>
explicit point9_type(const Distribution& distrib)
{
values[0] = distrib(); values[1] = distrib(); values[2] = distrib();
values[3] = distrib(); values[4] = distrib(); values[5] = distrib();
values[6] = distrib(); values[7] = distrib(); values[8] = distrib();
}
double operator [] (std::size_t index) const { return values[index]; }
double& operator [] (std::size_t index) { return values[index]; }
private:
double values[9];
};
#endif // SPATIAL_EXAMPLE_POINT_TYPE_HPP
| 30.904762
| 74
| 0.680277
|
Roboauto
|
96612d790217efb5f7cdcedda512e8fffc06ad98
| 2,840
|
cpp
|
C++
|
math/power_of_two.cpp
|
Phonbopit/C-Plus-Plus
|
37a29008e6b77921a97a89ca8b7fd9e700aeccd0
|
[
"MIT"
] | 2
|
2022-02-21T06:59:21.000Z
|
2022-02-21T06:59:24.000Z
|
math/power_of_two.cpp
|
Phonbopit/C-Plus-Plus
|
37a29008e6b77921a97a89ca8b7fd9e700aeccd0
|
[
"MIT"
] | null | null | null |
math/power_of_two.cpp
|
Phonbopit/C-Plus-Plus
|
37a29008e6b77921a97a89ca8b7fd9e700aeccd0
|
[
"MIT"
] | 1
|
2022-03-10T11:13:20.000Z
|
2022-03-10T11:13:20.000Z
|
/**
* @file
* @brief Implementation to check whether a number is a power of 2 or not.
*
* @details
* This algorithm uses bit manipulation to check if a number is a power of 2 or
* not.
*
* ### Algorithm
* Let the input number be n, then the bitwise and between n and n-1 will let us
* know whether the number is power of 2 or not
*
* For Example,
* If N= 32 then N-1 is 31, if we perform bitwise and of these two numbers then
* the result will be zero, which indicates that it is the power of 2
* If N=23 then N-1 is 22, if we perform bitwise and of these two numbers then
* the result will not be zero , which indicates that it is not the power of 2
* \note This implementation is better than naive recursive or iterative
* approach.
*
* @author [Neha Hasija](https://github.com/neha-hasija17)
* @author [Rijul.S](https://github.com/Rijul24)
*/
#include <iostream> /// for IO operations
#include <cassert> /// for assert
/**
* @namespace math
* @brief Mathematical algorithms
*/
namespace math {
/**
* @brief This function finds whether a number is power of 2 or not
* @param n value for which we want to check
* prints the result, as "Yes, the number n is a power of 2" or
* "No, the number is not a power of 2" without quotes
* @returns 1 if `n` IS the power of 2
* @returns 0 if n is NOT a power of 2
*/
int power_of_two(int n) {
/// result stores the
/// bitwise and of n and n-1
int result = n & (n - 1);
if (result == 0) {
return 1;
}
return 0;
}
} // namespace math
/**
* @brief Self-test implementations
* @returns void
*/
static void test() {
std::cout << "First case testing... \n"; // for n = 32 return 1
assert(math::power_of_two(32) == 1);
std::cout << "\nPassed!\n";
std::cout << "Second case testing... \n"; // for n = 5 return 0
assert(math::power_of_two(5) == 0);
std::cout << "\nPassed!\n";
std::cout << "Third case testing... \n"; // for n = 232 return 0
assert(math::power_of_two(232) == 0);
std::cout << "\nPassed!\n";
std::cout << "\nAll test cases have successfully passed!\n";
}
/**
* @brief Take user input in the test cases (optional; currently commented)
* @returns void
*/
void user_input_test() {
int n = 0; // input from user
std::cout << "Enter a number " << std::endl;
std::cin >> n;
/// function call with @param n
int result = math::power_of_two(n);
if (result == 1) {
std::cout << "Yes, the number " << n << " is a power of 2\n";
}
else {
std::cout << "No, the number " << n << " is not a power of 2\n";
}
}
/**
* @brief Main function
* @returns 0 on exit
*/
int main() {
test(); // run self-test implementations
// uncomment the line below to take user inputs
//user_input_test();
return 0;
}
| 26.542056
| 80
| 0.616197
|
Phonbopit
|
96630164ccb876c0a4cea1fee916558013e2eae4
| 4,445
|
hpp
|
C++
|
include/xaos/detail/function.hpp
|
grisumbras/xaos
|
9d8a93911b9284a826ad43ba133a2febf960481c
|
[
"BSL-1.0"
] | null | null | null |
include/xaos/detail/function.hpp
|
grisumbras/xaos
|
9d8a93911b9284a826ad43ba133a2febf960481c
|
[
"BSL-1.0"
] | null | null | null |
include/xaos/detail/function.hpp
|
grisumbras/xaos
|
9d8a93911b9284a826ad43ba133a2febf960481c
|
[
"BSL-1.0"
] | null | null | null |
#ifndef XAOS_DETAIL_FUNCTION_HPP
#define XAOS_DETAIL_FUNCTION_HPP
#include <xaos/detail/backend_pointer.hpp>
#include <xaos/detail/function_alloc.hpp>
#include <xaos/detail/function_overloads.hpp>
#include <boost/core/empty_value.hpp>
#include <boost/mp11/algorithm.hpp>
#include <boost/mp11/list.hpp>
#include <boost/mp11/utility.hpp>
namespace xaos {
namespace detail {
template <class Signature, class Traits>
struct function_backend_interface
: alloc_interface
, boost::mp11::mp_apply<
boost::mp11::mp_inherit,
boost::mp11::mp_append<
maybe_clone_interface<Traits>,
boost::mp11::mp_transform<
call_overload_interface,
enabled_overloads<Signature, Traits>>>> {
using signature = Signature;
using traits = Traits;
};
template <class BackendInterface, class Allocator, class Callable>
struct function_backend final
: boost::mp11::mp_fold_q<
enabled_overloads<
typename BackendInterface::signature,
typename BackendInterface::traits>,
maybe_clone_implementation<
typename BackendInterface::traits,
function_backend<BackendInterface, Allocator, Callable>,
BackendInterface>,
boost::mp11::mp_bind_front<
call_overload,
function_backend<BackendInterface, Allocator, Callable>>>
, boost::empty_value<Callable, 0>
, pointer_storage_helper<
function_backend<BackendInterface, Allocator, Callable>,
Allocator,
1> {
using allocator_type = Allocator;
using callable_type = Callable;
using interface_type = BackendInterface;
using pointer_holder_t
= pointer_storage_helper<function_backend, Allocator, 1>;
function_backend(typename pointer_holder_t::pointer ptr, Callable callable)
: boost::empty_value<Callable, 0>(
boost::empty_init_t(), std::move(callable))
, pointer_holder_t(std::move(ptr)) {}
virtual auto relocate(void* type_erased_alloc) -> void* {
auto alloc
= restore_allocator<allocator_type, function_backend>(type_erased_alloc);
auto const raw_ptr = new_backend(alloc, std::move(callable()));
return static_cast<interface_type*>(raw_ptr);
};
virtual void delete_this(void* type_erased_alloc) {
auto alloc
= restore_allocator<allocator_type, function_backend>(type_erased_alloc);
auto const ptr = this->pointer_to(*this);
using proto_traits = std::allocator_traits<Allocator>;
using alloc_traits =
typename proto_traits::template rebind_traits<function_backend>;
alloc_traits::destroy(alloc, this);
alloc_traits::deallocate(alloc, ptr, 1);
};
auto callable() noexcept -> Callable& {
return boost::empty_value<Callable, 0>::get();
}
auto callable() const noexcept -> Callable const& {
return boost::empty_value<Callable, 0>::get();
}
};
template <class Signature, class Traits, class Allocator>
using backend_storage = boost::mp11::mp_apply_q<
boost::mp11::mp_if<
is_copyability_enabled<Traits>,
boost::mp11::mp_quote<copyable_backend_pointer>,
boost::mp11::mp_quote<backend_pointer>>,
boost::mp11::
mp_list<function_backend_interface<Signature, Traits>, Allocator>>;
template <class Signature, class Traits, class Allocator, class... Overloads>
class basic_function
: parens_overload<
basic_function<Signature, Traits, Allocator, Overloads...>,
are_rvalue_overloads_enabled<Traits>::value,
Overloads>...
{
private:
template <class, bool, class>
friend struct parens_overload;
using storage_t = backend_storage<Signature, Traits, Allocator>;
storage_t storage_;
public:
using allocator_type = typename storage_t::allocator_type;
template <class Callable>
basic_function(Callable callable, Allocator alloc = Allocator())
: storage_(alloc, callable) {}
using parens_overload<
basic_function<Signature, Traits, Allocator, Overloads...>,
are_rvalue_overloads_enabled<Traits>::value,
Overloads>::operator()...;
auto get_allocator() const -> allocator_type {
return storage_.get_allocator();
}
void swap(basic_function& other) { storage_.swap(other.storage_); }
};
template <class Signature, class Traits, class Allocator, class... Overloads>
void swap(
basic_function<Signature, Traits, Allocator, Overloads...>& l,
basic_function<Signature, Traits, Allocator, Overloads...>& r) {
l.swap(r);
}
} // namespace detail
} // namespace xaos
#endif // XAOS_DETAIL_FUNCTION_HPP
| 30.033784
| 79
| 0.728459
|
grisumbras
|
96666edbd8b62ccc00d0e736df792c1f29a392b4
| 1,695
|
hpp
|
C++
|
i23dSFM/stl/indexed_sort.hpp
|
zyxrrr/GraphSfM
|
1af22ec17950ffc8a5c737a6a46f4465c40aa470
|
[
"BSD-3-Clause"
] | null | null | null |
i23dSFM/stl/indexed_sort.hpp
|
zyxrrr/GraphSfM
|
1af22ec17950ffc8a5c737a6a46f4465c40aa470
|
[
"BSD-3-Clause"
] | null | null | null |
i23dSFM/stl/indexed_sort.hpp
|
zyxrrr/GraphSfM
|
1af22ec17950ffc8a5c737a6a46f4465c40aa470
|
[
"BSD-3-Clause"
] | 1
|
2019-02-18T09:49:32.000Z
|
2019-02-18T09:49:32.000Z
|
// Copyright (c) 2012, 2013 Pierre MOULON.
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef I23DSFM_STL_INDEXED_SORT_H
#define I23DSFM_STL_INDEXED_SORT_H
namespace stl
{
namespace indexed_sort
{
template<typename T1, typename T2>
struct sort_index_packet_ascend {
T1 val;
T2 index;
};
template<typename T1, typename T2>
struct sort_index_packet_descend {
T1 val;
T2 index;
};
template<typename T1, typename T2>
inline
bool
operator< (const sort_index_packet_ascend<T1,T2>& A,
const sort_index_packet_ascend<T1,T2>& B) {
return A.val < B.val;
}
template<typename T1, typename T2>
inline
bool
operator< (const sort_index_packet_descend<T1,T2>& A,
const sort_index_packet_descend<T1,T2>& B) {
return A.val > B.val;
}
/// Sort by default all indexed value, else sort only the NN smallest element of the indexed array.
template<typename packet_type, typename eT>
void
inline
sort_index_helper(std::vector<packet_type>& packet_vec,
const eT* in_mem, int NN = -1) {
const size_t n_elem = packet_vec.size();
for(size_t i=0; i<n_elem; ++i) {
packet_vec[i].val = in_mem[i];
packet_vec[i].index = i;
}
if (NN == -1)
std::sort( packet_vec.begin(), packet_vec.end() );
else
std::partial_sort(packet_vec.begin(), packet_vec.begin() + NN,
packet_vec.end());
}
} // namespace indexed_sort
} // namespace stl
#endif // I23DSFM_STL_INDEXED_SORT_H
| 25.298507
| 101
| 0.658997
|
zyxrrr
|
966a393e324b20538af1df465413e035a8bfd3ab
| 3,157
|
cpp
|
C++
|
YorozuyaGSLib/source/CAsyncLogger.cpp
|
lemkova/Yorozuya
|
f445d800078d9aba5de28f122cedfa03f26a38e4
|
[
"MIT"
] | 29
|
2017-07-01T23:08:31.000Z
|
2022-02-19T10:22:45.000Z
|
YorozuyaGSLib/source/CAsyncLogger.cpp
|
kotopes/Yorozuya
|
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
|
[
"MIT"
] | 90
|
2017-10-18T21:24:51.000Z
|
2019-06-06T02:30:33.000Z
|
YorozuyaGSLib/source/CAsyncLogger.cpp
|
kotopes/Yorozuya
|
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
|
[
"MIT"
] | 44
|
2017-12-19T08:02:59.000Z
|
2022-02-24T23:15:01.000Z
|
#include <CAsyncLogger.hpp>
START_ATF_NAMESPACE
CAsyncLogger::CAsyncLogger()
{
using org_ptr = void (WINAPIV*)(struct CAsyncLogger*);
(org_ptr(0x1403bda40L))(this);
};
void CAsyncLogger::ctor_CAsyncLogger()
{
using org_ptr = void (WINAPIV*)(struct CAsyncLogger*);
(org_ptr(0x1403bda40L))(this);
};
void CAsyncLogger::Destroy()
{
using org_ptr = void (WINAPIV*)();
(org_ptr(0x1403be1b0L))();
};
bool CAsyncLogger::FormatLog(int iType, char* fmt)
{
using org_ptr = bool (WINAPIV*)(struct CAsyncLogger*, int, char*);
return (org_ptr(0x1403bf220L))(this, iType, fmt);
};
int CAsyncLogger::GetTotalWaitSize()
{
using org_ptr = int (WINAPIV*)(struct CAsyncLogger*);
return (org_ptr(0x1403bfd60L))(this);
};
int CAsyncLogger::Init()
{
using org_ptr = int (WINAPIV*)(struct CAsyncLogger*);
return (org_ptr(0x1403be220L))(this);
};
struct CAsyncLogger* CAsyncLogger::Instance()
{
using org_ptr = struct CAsyncLogger* (WINAPIV*)();
return (org_ptr(0x1403be0f0L))();
};
void CAsyncLogger::Log(char* szFileName, char* szLog, int iLenStr)
{
using org_ptr = void (WINAPIV*)(struct CAsyncLogger*, char*, char*, int);
(org_ptr(0x1403c00e0L))(this, szFileName, szLog, iLenStr);
};
bool CAsyncLogger::Log(int iType, char* szLog)
{
using org_ptr = bool (WINAPIV*)(struct CAsyncLogger*, int, char*);
return (org_ptr(0x1403bfa00L))(this, iType, szLog);
};
bool CAsyncLogger::LogFromArg(int iType, char* fmt, char* arg_ptr)
{
using org_ptr = bool (WINAPIV*)(struct CAsyncLogger*, int, char*, char*);
return (org_ptr(0x1403bf620L))(this, iType, fmt, arg_ptr);
};
void CAsyncLogger::Loop()
{
using org_ptr = void (WINAPIV*)(struct CAsyncLogger*);
(org_ptr(0x1403be870L))(this);
};
void CAsyncLogger::ProcThread(void* p)
{
using org_ptr = void (WINAPIV*)(void*);
(org_ptr(0x1403bfe00L))(p);
};
void CAsyncLogger::ProcWrite()
{
using org_ptr = void (WINAPIV*)(struct CAsyncLogger*);
(org_ptr(0x1403beab0L))(this);
};
bool CAsyncLogger::Regist(ASYNC_LOG_TYPE eType, char* szDirPath, char* szTypeName, bool bAddDateFileName, unsigned int dwUpdateFileNameDelay)
{
using org_ptr = bool (WINAPIV*)(struct CAsyncLogger*, ASYNC_LOG_TYPE, char*, char*, bool, unsigned int);
return (org_ptr(0x1403bebb0L))(this, eType, szDirPath, szTypeName, bAddDateFileName, dwUpdateFileNameDelay);
};
void CAsyncLogger::SystemLog(char* fmt)
{
using org_ptr = void (WINAPIV*)(struct CAsyncLogger*, char*);
(org_ptr(0x1403bfe60L))(this, fmt);
};
CAsyncLogger::~CAsyncLogger()
{
using org_ptr = void (WINAPIV*)(struct CAsyncLogger*);
(org_ptr(0x1403bdc40L))(this);
};
void CAsyncLogger::dtor_CAsyncLogger()
{
using org_ptr = void (WINAPIV*)(struct CAsyncLogger*);
(org_ptr(0x1403bdc40L))(this);
};
END_ATF_NAMESPACE
| 33.585106
| 145
| 0.623377
|
lemkova
|
966e73f6d241e6fedffd21ef27bebb3bfc9b294f
| 476
|
hpp
|
C++
|
Engine/src/ecs/components/Renderable.hpp
|
dabbertorres/LinuxOpenGL
|
0dba561244d720e64bea4c839c95db036d479bdf
|
[
"MIT"
] | null | null | null |
Engine/src/ecs/components/Renderable.hpp
|
dabbertorres/LinuxOpenGL
|
0dba561244d720e64bea4c839c95db036d479bdf
|
[
"MIT"
] | 1
|
2016-05-05T00:51:58.000Z
|
2016-05-05T00:51:58.000Z
|
Engine/src/ecs/components/Renderable.hpp
|
dabbertorres/LinuxOpenGL
|
0dba561244d720e64bea4c839c95db036d479bdf
|
[
"MIT"
] | null | null | null |
#ifndef DBR_ENG_ECS_RENDERABLE_HPP
#define DBR_ENG_ECS_RENDERABLE_HPP
#include "Graphics/Types.hpp"
#include "ecs/Component.hpp"
namespace dbr
{
namespace eng
{
namespace ecs
{
class Renderable : public Component
{
public:
Renderable(Id id, gfx::HandleI bufferHandle);
~Renderable();
private:
gfx::HandleI bufferHandle;
};
}
}
}
#endif
| 17
| 61
| 0.548319
|
dabbertorres
|
96718ec412d1399e1c17c97b461e1635829bfd2d
| 255
|
hpp
|
C++
|
lab07/3.2_vehicle/vehicle/Car.hpp
|
AlexanderFadeev/oop
|
62ea584b2c49dea5457b9e520866bfd7a0d883c7
|
[
"MIT"
] | null | null | null |
lab07/3.2_vehicle/vehicle/Car.hpp
|
AlexanderFadeev/oop
|
62ea584b2c49dea5457b9e520866bfd7a0d883c7
|
[
"MIT"
] | 18
|
2018-02-07T07:10:18.000Z
|
2018-05-23T08:11:28.000Z
|
lab07/3.2_vehicle/vehicle/Car.hpp
|
AlexanderFadeev/oop
|
62ea584b2c49dea5457b9e520866bfd7a0d883c7
|
[
"MIT"
] | null | null | null |
#pragma once
#include "CarBrand.h"
template <typename CVehicle>
class CCar
: public CVehicle
{
public:
using Brand = CarBrand;
CCar(size_t seatsCount, Brand brand);
Brand GetBrand() const override;
private:
Brand m_brand;
};
#include "Car.ipp"
| 12.142857
| 38
| 0.72549
|
AlexanderFadeev
|
9675dfae28287c0efd9e911cd002c91a2cf54f50
| 2,267
|
hpp
|
C++
|
src/utils/block.hpp
|
ktrianta/jacobi-svd-evd
|
8162562c631c3d1541e23b1fa38ec7600a5032af
|
[
"MIT"
] | 3
|
2019-03-09T14:22:26.000Z
|
2021-04-24T05:40:44.000Z
|
src/utils/block.hpp
|
ktrianta/jacobi-svd-evd
|
8162562c631c3d1541e23b1fa38ec7600a5032af
|
[
"MIT"
] | 35
|
2019-03-17T14:02:55.000Z
|
2019-06-12T13:15:19.000Z
|
src/utils/block.hpp
|
ktrianta/jacobi-svd-evd
|
8162562c631c3d1541e23b1fa38ec7600a5032af
|
[
"MIT"
] | 4
|
2019-03-09T14:22:30.000Z
|
2020-09-28T19:36:42.000Z
|
#pragma once
#include <cstdlib>
#include "matrix.hpp"
// perform C = AB
void mult_block(struct matrix_t Amat, size_t blockA_row, size_t blockA_col, struct matrix_t Bmat, size_t blockB_row,
size_t blockB_col, struct matrix_t Cmat, size_t blockC_row, size_t blockC_col, size_t block_size);
// perform D = C + AB
void mult_add_block(struct matrix_t Amat, size_t blockA_row, size_t blockA_col, struct matrix_t Bmat, size_t blockB_row,
size_t blockB_col, struct matrix_t Cmat, size_t blockC_row, size_t blockC_col, struct matrix_t Dmat,
size_t blockD_row, size_t blockD_col, size_t block_size);
// perform C = (A^T)B
void mult_transpose_block(struct matrix_t Amat, size_t blockA_row, size_t blockA_col, struct matrix_t Bmat,
size_t blockB_row, size_t blockB_col, struct matrix_t Cmat, size_t blockC_row,
size_t blockC_col, size_t block_size);
// perform D = C + (A^T)B
void mult_add_transpose_block(struct matrix_t Amat, size_t blockA_row, size_t blockA_col, struct matrix_t Bmat,
size_t blockB_row, size_t blockB_col, struct matrix_t Cmat, size_t blockC_row,
size_t blockC_col, struct matrix_t Dmat, size_t blockD_row, size_t blockD_col,
size_t block_size);
// perform C = A(B^T)
void mult_transpose_block_right(struct matrix_t Amat, size_t blockA_row, size_t blockA_col, struct matrix_t Bmat,
size_t blockB_row, size_t blockB_col, struct matrix_t Cmat, size_t blockC_row,
size_t blockC_col, size_t block_size);
// perform D = C + A(B^T)
void mult_add_transpose_block_right(struct matrix_t Amat, size_t blockA_row, size_t blockA_col, struct matrix_t Bmat,
size_t blockB_row, size_t blockB_col, struct matrix_t Cmat, size_t blockC_row,
size_t blockC_col, struct matrix_t Dmat, size_t blockD_row, size_t blockD_col,
size_t block_size);
void copy_block(struct matrix_t S, size_t blockS_row, size_t blockS_col, struct matrix_t D, size_t blockD_row,
size_t blockD_col, size_t block_size);
| 70.84375
| 120
| 0.672695
|
ktrianta
|
9679b0ab04f8dfedb329c8aa0d72085a7c26fa22
| 5,991
|
cpp
|
C++
|
tcb/src/v20180608/model/DescribeCloudBaseRunServerDomainNameResponse.cpp
|
suluner/tencentcloud-sdk-cpp
|
a56c73cc3f488c4d1e10755704107bb15c5e000d
|
[
"Apache-2.0"
] | null | null | null |
tcb/src/v20180608/model/DescribeCloudBaseRunServerDomainNameResponse.cpp
|
suluner/tencentcloud-sdk-cpp
|
a56c73cc3f488c4d1e10755704107bb15c5e000d
|
[
"Apache-2.0"
] | null | null | null |
tcb/src/v20180608/model/DescribeCloudBaseRunServerDomainNameResponse.cpp
|
suluner/tencentcloud-sdk-cpp
|
a56c73cc3f488c4d1e10755704107bb15c5e000d
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/tcb/v20180608/model/DescribeCloudBaseRunServerDomainNameResponse.h>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Tcb::V20180608::Model;
using namespace std;
DescribeCloudBaseRunServerDomainNameResponse::DescribeCloudBaseRunServerDomainNameResponse() :
m_publicDomainHasBeenSet(false),
m_internalDomainHasBeenSet(false),
m_domainNameHasBeenSet(false)
{
}
CoreInternalOutcome DescribeCloudBaseRunServerDomainNameResponse::Deserialize(const string &payload)
{
rapidjson::Document d;
d.Parse(payload.c_str());
if (d.HasParseError() || !d.IsObject())
{
return CoreInternalOutcome(Core::Error("response not json format"));
}
if (!d.HasMember("Response") || !d["Response"].IsObject())
{
return CoreInternalOutcome(Core::Error("response `Response` is null or not object"));
}
rapidjson::Value &rsp = d["Response"];
if (!rsp.HasMember("RequestId") || !rsp["RequestId"].IsString())
{
return CoreInternalOutcome(Core::Error("response `Response.RequestId` is null or not string"));
}
string requestId(rsp["RequestId"].GetString());
SetRequestId(requestId);
if (rsp.HasMember("Error"))
{
if (!rsp["Error"].IsObject() ||
!rsp["Error"].HasMember("Code") || !rsp["Error"]["Code"].IsString() ||
!rsp["Error"].HasMember("Message") || !rsp["Error"]["Message"].IsString())
{
return CoreInternalOutcome(Core::Error("response `Response.Error` format error").SetRequestId(requestId));
}
string errorCode(rsp["Error"]["Code"].GetString());
string errorMsg(rsp["Error"]["Message"].GetString());
return CoreInternalOutcome(Core::Error(errorCode, errorMsg).SetRequestId(requestId));
}
if (rsp.HasMember("PublicDomain") && !rsp["PublicDomain"].IsNull())
{
if (!rsp["PublicDomain"].IsString())
{
return CoreInternalOutcome(Core::Error("response `PublicDomain` IsString=false incorrectly").SetRequestId(requestId));
}
m_publicDomain = string(rsp["PublicDomain"].GetString());
m_publicDomainHasBeenSet = true;
}
if (rsp.HasMember("InternalDomain") && !rsp["InternalDomain"].IsNull())
{
if (!rsp["InternalDomain"].IsString())
{
return CoreInternalOutcome(Core::Error("response `InternalDomain` IsString=false incorrectly").SetRequestId(requestId));
}
m_internalDomain = string(rsp["InternalDomain"].GetString());
m_internalDomainHasBeenSet = true;
}
if (rsp.HasMember("DomainName") && !rsp["DomainName"].IsNull())
{
if (!rsp["DomainName"].IsString())
{
return CoreInternalOutcome(Core::Error("response `DomainName` IsString=false incorrectly").SetRequestId(requestId));
}
m_domainName = string(rsp["DomainName"].GetString());
m_domainNameHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
string DescribeCloudBaseRunServerDomainNameResponse::ToJsonString() const
{
rapidjson::Document value;
value.SetObject();
rapidjson::Document::AllocatorType& allocator = value.GetAllocator();
if (m_publicDomainHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "PublicDomain";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_publicDomain.c_str(), allocator).Move(), allocator);
}
if (m_internalDomainHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "InternalDomain";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_internalDomain.c_str(), allocator).Move(), allocator);
}
if (m_domainNameHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "DomainName";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_domainName.c_str(), allocator).Move(), allocator);
}
rapidjson::Value iKey(rapidjson::kStringType);
string key = "RequestId";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value().SetString(GetRequestId().c_str(), allocator), allocator);
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
value.Accept(writer);
return buffer.GetString();
}
string DescribeCloudBaseRunServerDomainNameResponse::GetPublicDomain() const
{
return m_publicDomain;
}
bool DescribeCloudBaseRunServerDomainNameResponse::PublicDomainHasBeenSet() const
{
return m_publicDomainHasBeenSet;
}
string DescribeCloudBaseRunServerDomainNameResponse::GetInternalDomain() const
{
return m_internalDomain;
}
bool DescribeCloudBaseRunServerDomainNameResponse::InternalDomainHasBeenSet() const
{
return m_internalDomainHasBeenSet;
}
string DescribeCloudBaseRunServerDomainNameResponse::GetDomainName() const
{
return m_domainName;
}
bool DescribeCloudBaseRunServerDomainNameResponse::DomainNameHasBeenSet() const
{
return m_domainNameHasBeenSet;
}
| 34.431034
| 132
| 0.698381
|
suluner
|
9679c785626b7b81aa1da6d3092fe2867f87aef5
| 2,391
|
cpp
|
C++
|
Medium/3-longestsubnorep.cpp
|
mzhou08/Leetcode
|
b186f6cb4ecc6efb30d4da96be7f3ca15d7c4e59
|
[
"Apache-2.0"
] | null | null | null |
Medium/3-longestsubnorep.cpp
|
mzhou08/Leetcode
|
b186f6cb4ecc6efb30d4da96be7f3ca15d7c4e59
|
[
"Apache-2.0"
] | null | null | null |
Medium/3-longestsubnorep.cpp
|
mzhou08/Leetcode
|
b186f6cb4ecc6efb30d4da96be7f3ca15d7c4e59
|
[
"Apache-2.0"
] | null | null | null |
#include <iostream>
#include <string>
#include <vector>
using namespace std;
/*
Submission Statistics:
Runtime: 132 ms, faster than 11.94% of C++ online submissions for Longest Substring Without Repeating Characters.
Memory Usage: 104.4 MB, less than 9.22% of C++ online submissions for Longest Substring Without Repeating Characters.
*/
/*
Notes: You can use vector[char] to access an vector of ints with length 128.
Makes this problem a lot easier.
*/
class Solution {
public:
struct dict {
char val;
int index;
dict() : val('\0'), index(-2) {}
dict(char x, int ind) : val(x), index(ind) {}
};
vector<int> repeat(vector<dict*> d, char c, int start, int end) {
vector<int> res;
res.push_back(-1 /*index of dict*/);
res.push_back(-1 /*index of repeat*/);
for (int i = 0; i < d.size(); i++) {
if (d[i]->val == c && d[i]->index >= start) {
res[0] = i;
res[1] = d[i]->index;
return res;
}
}
return res;
}
int lengthOfLongestSubstring(string s) {
int start = 0;
int end = 0;
int longest = 0;
vector<dict*> d;
while (end < s.length()) {
if (repeat(d, s[end], start, end)[0] != -1) {
vector<int> rep = repeat(d, s[end], start, end);
//cout << rep[0] << " " << rep[1] << '\n';
longest = max(longest, end - start);
start = rep[1] + 1;
//Update the dictionary entry for the char at s[end]
dict* new_entry = new dict(s[end], end);
d[rep[0]] = new_entry;
} else if (end == s.length() - 1) {
longest = max(longest, end - start + 1);
} else {
dict* new_entry = new dict(s[end], end);
d.push_back(new_entry);
}
end++;
}
return longest;
}
};
int main () {
Solution S;
cout << "\"abcabcbb\": exp. 3: " << S.lengthOfLongestSubstring("abcabcbb") << "\n";
cout << "\"tmmzuxt\": exp. 5: " << S.lengthOfLongestSubstring("tmmzuxt") << "\n";
cout << "\"\": exp. 0: " << S.lengthOfLongestSubstring("") << "\n";
cout << "\"aabaab!bb\": exp. 3: " << S.lengthOfLongestSubstring("aabaab!bb") << "\n";
}
| 30.653846
| 117
| 0.495609
|
mzhou08
|
9679ec86b80d94cf8f31dda3a9705ef7ce836464
| 526
|
cpp
|
C++
|
63.cpp
|
bodhiye/Offer
|
c723210d3052bebd6cd9adfc2959c4aa2b8a2e0c
|
[
"MIT"
] | 1
|
2018-05-08T01:35:49.000Z
|
2018-05-08T01:35:49.000Z
|
63.cpp
|
bodhiye/Offer
|
c723210d3052bebd6cd9adfc2959c4aa2b8a2e0c
|
[
"MIT"
] | null | null | null |
63.cpp
|
bodhiye/Offer
|
c723210d3052bebd6cd9adfc2959c4aa2b8a2e0c
|
[
"MIT"
] | 1
|
2021-07-24T02:15:42.000Z
|
2021-07-24T02:15:42.000Z
|
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> v;
int n;
void Insert(int num) {
v.push_back(num);
n = v.size();
for (int i = n - 1; i > 0 && v[i] < v[i - 1]; --i)
swap(v[i], v[i - 1]);
}
double GetMedian() {
return (v[(n - 1) >> 1] + v[n >> 1]) / 2.0;
}
int main() {
ios::sync_with_stdio(false);
int m, tmp;
cin >> m;
for (int i = 0; i < m; i++) {
cin >> tmp;
Insert(tmp);
}
cout << GetMedian();
return 0;
}
| 16.4375
| 54
| 0.480989
|
bodhiye
|
967d120b5ae8b09b1288d1eea9d8a330f4b30149
| 687
|
cpp
|
C++
|
Zork/globals.cpp
|
Mefiso/zork
|
1eb26348f88edcd1cb168ce8061c5ccd5610d1f3
|
[
"MIT"
] | null | null | null |
Zork/globals.cpp
|
Mefiso/zork
|
1eb26348f88edcd1cb168ce8061c5ccd5610d1f3
|
[
"MIT"
] | null | null | null |
Zork/globals.cpp
|
Mefiso/zork
|
1eb26348f88edcd1cb168ce8061c5ccd5610d1f3
|
[
"MIT"
] | null | null | null |
#include "globals.h"
//using namespace std;
// -------------------------------------------------
bool Same(const string& a, const string& b)
{
return _stricmp(a.c_str(), b.c_str()) == 0;
}
bool Same(const char* a, const string& b)
{
return _stricmp(a, b.c_str()) == 0;
}
bool Same(const string& a, const char* b)
{
return _stricmp(a.c_str(), b) == 0;
}
int Roll(int min, int max)
{
return (max > 0) ? min + (rand() % (max - min)) : 0;
}
void Tokenize(const string& line, vector<string>& arguments)
{
const char* str = line.c_str();
do
{
const char *begin = str;
while(*str != ' ' && *str)
str++;
arguments.push_back(string(begin, str));
} while(0 != *str++);
}
| 17.175
| 60
| 0.554585
|
Mefiso
|
9681341aeca47a0444b1ae3e72e447cba5b786ab
| 1,767
|
hh
|
C++
|
src/c++/include/reference/Seed.hh
|
Illumina/Isaac4
|
0924fba8b467868da92e1c48323b15d7cbca17dd
|
[
"BSD-3-Clause"
] | 13
|
2018-02-09T22:59:39.000Z
|
2021-11-29T06:33:22.000Z
|
src/c++/include/reference/Seed.hh
|
Illumina/Isaac4
|
0924fba8b467868da92e1c48323b15d7cbca17dd
|
[
"BSD-3-Clause"
] | 17
|
2018-01-26T11:36:07.000Z
|
2022-02-03T18:48:43.000Z
|
src/c++/include/reference/Seed.hh
|
Illumina/Isaac4
|
0924fba8b467868da92e1c48323b15d7cbca17dd
|
[
"BSD-3-Clause"
] | 4
|
2018-10-19T20:00:00.000Z
|
2020-10-29T14:44:06.000Z
|
/**
** Isaac Genome Alignment Software
** Copyright (c) 2010-2017 Illumina, Inc.
** All rights reserved.
**
** This software is provided under the terms and conditions of the
** GNU GENERAL PUBLIC LICENSE Version 3
**
** You should have received a copy of the GNU GENERAL PUBLIC LICENSE Version 3
** along with this program. If not, see
** <https://github.com/illumina/licenses/>.
**
** \file Seed.hh
**
** \brief Seeds are used to find alignment candidates in the reference genome
**
** \author Roman Petrovski
**/
#ifndef iSAAC_REFERENCE_SEED_HH
#define iSAAC_REFERENCE_SEED_HH
#include <iostream>
#include "oligo/Kmer.hh"
namespace isaac
{
namespace reference
{
template <typename KmerT>
class InterleavedSeed
{
public:
typedef KmerT KmerType;
static const unsigned STEP = 1;
static const unsigned KMER_BASES = KmerType::KMER_BASES;
static const unsigned SEED_LENGTH = KMER_BASES * STEP;
InterleavedSeed() : kmer_(0) {}
InterleavedSeed(KmerT kmer) : kmer_(kmer) {}
KmerType &kmer() {return kmer_;}
private:
KmerType kmer_;
};
template <typename KmerT>
inline std::ostream &operator<<(std::ostream &os, const InterleavedSeed<KmerT> &seed)
{
typedef InterleavedSeed<KmerT> SeedT;
return os << "InterleavedSeed(" << oligo::Bases<oligo::BITS_PER_BASE, typename SeedT::KmerType>(seed.getKmer(), oligo::KmerTraits<typename SeedT::KmerType>::KMER_BASES) <<
"(" << oligo::ReverseBases<oligo::BITS_PER_BASE, typename SeedT::KmerType>(seed.getKmer(), oligo::KmerTraits<typename SeedT::KmerType>::KMER_BASES) << ")" <<
")";
}
template <typename KmerT> struct Seed : public InterleavedSeed<KmerT>
{
};
} // namespace reference
} // namespace isaac
#endif // #ifndef iSAAC_REFERENCE_SEED_HH
| 26.772727
| 175
| 0.710243
|
Illumina
|
9681401242d880547108b3a6efc748f5bbeafd16
| 408
|
hpp
|
C++
|
include/RED4ext/Scripting/Natives/Generated/ent/VertexAnimationMapperSourceType.hpp
|
jackhumbert/RED4ext.SDK
|
2c55eccb83beabbbe02abae7945af8efce638fca
|
[
"MIT"
] | 42
|
2020-12-25T08:33:00.000Z
|
2022-03-22T14:47:07.000Z
|
include/RED4ext/Scripting/Natives/Generated/ent/VertexAnimationMapperSourceType.hpp
|
jackhumbert/RED4ext.SDK
|
2c55eccb83beabbbe02abae7945af8efce638fca
|
[
"MIT"
] | 38
|
2020-12-28T22:36:06.000Z
|
2022-02-16T11:25:47.000Z
|
include/RED4ext/Scripting/Natives/Generated/ent/VertexAnimationMapperSourceType.hpp
|
jackhumbert/RED4ext.SDK
|
2c55eccb83beabbbe02abae7945af8efce638fca
|
[
"MIT"
] | 20
|
2020-12-28T22:17:38.000Z
|
2022-03-22T17:19:01.000Z
|
#pragma once
// This file is generated from the Game's Reflection data
#include <cstdint>
namespace RED4ext
{
namespace ent {
enum class VertexAnimationMapperSourceType : uint32_t
{
FloatTrack = 0,
TranslationX = 1,
TranslationY = 2,
TranslationZ = 3,
RotationQuatX = 4,
RotationQuatY = 5,
RotationQuatZ = 6,
RotationQuatW = 7,
};
} // namespace ent
} // namespace RED4ext
| 18.545455
| 57
| 0.683824
|
jackhumbert
|
96818053ea161b7b0fc284b9617776c30bc8af05
| 334
|
hpp
|
C++
|
include/mio/unordered_set.hpp
|
inie0722/mio
|
205411c2a24fe216c9f981b6a974cdb0118f7560
|
[
"BSL-1.0"
] | null | null | null |
include/mio/unordered_set.hpp
|
inie0722/mio
|
205411c2a24fe216c9f981b6a974cdb0118f7560
|
[
"BSL-1.0"
] | null | null | null |
include/mio/unordered_set.hpp
|
inie0722/mio
|
205411c2a24fe216c9f981b6a974cdb0118f7560
|
[
"BSL-1.0"
] | null | null | null |
#pragma once
#include <parallel_hashmap/phmap.h>
namespace mio
{
template <class T,
class Hash = phmap::priv::hash_default_hash<T>,
class Eq = phmap::priv::hash_default_eq<T>,
class Alloc = phmap::priv::Allocator<T>>
using unordered_set = phmap::node_hash_set<T, Hash, Eq, Alloc>;
}
| 27.833333
| 67
| 0.628743
|
inie0722
|
9683818f3d590400aa4d5b74a6a713ade34d187d
| 1,453
|
cpp
|
C++
|
led_tutorial/src/rgb_led.cpp
|
PigeonSensei/raspberry_pi_ros_tutorial
|
07f824bf43f304ebe328f1e557ca7fa5c9cad44c
|
[
"MIT"
] | null | null | null |
led_tutorial/src/rgb_led.cpp
|
PigeonSensei/raspberry_pi_ros_tutorial
|
07f824bf43f304ebe328f1e557ca7fa5c9cad44c
|
[
"MIT"
] | null | null | null |
led_tutorial/src/rgb_led.cpp
|
PigeonSensei/raspberry_pi_ros_tutorial
|
07f824bf43f304ebe328f1e557ca7fa5c9cad44c
|
[
"MIT"
] | 3
|
2021-11-15T00:34:08.000Z
|
2022-02-28T09:55:38.000Z
|
#include <ros/ros.h>
#include <wiringPi.h>
#include "led_tutorial/SetRGBDigital.h"
bool R = true;
bool G = true;
bool B = true;
bool SetRGBDigitalCallBack(led_tutorial::SetRGBDigital::Request &req,
led_tutorial::SetRGBDigital::Response &res)
{
R = req.R;
G = req.G;
B = req.B;
res.result = "True";
res.message = "Set R : " + std::to_string(R) + ", Set G : " + std::to_string(G) + ", Set B : " + std::to_string(B);
res.Timestamp = ros::Time::now();
ROS_INFO("Set R : %d, Set G : %d, Set B : %d", R,G,B);
return true;
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "rgb_led_node");
ros::NodeHandle n("~");
ros::Rate loop_rate(10);
ros::ServiceServer service_server_set_rgb_digital;
service_server_set_rgb_digital = n.advertiseService("setRGBDigital", SetRGBDigitalCallBack);
int r_pin = 0;
int g_pin = 0;
int b_pin = 0;
n.param<int>("RPin", r_pin, 0);
n.param<int>("GPin", g_pin, 0);
n.param<int>("BPin", b_pin, 0);
ROS_INFO("R Pin : %d", r_pin);
ROS_INFO("G Pin : %d", g_pin);
ROS_INFO("B Pin : %d", b_pin);
wiringPiSetupGpio();
pinMode(r_pin, OUTPUT);
pinMode(g_pin, OUTPUT);
pinMode(b_pin, OUTPUT);
while(ros::ok())
{
digitalWrite(r_pin,R);
digitalWrite(g_pin,G);
digitalWrite(b_pin,B);
loop_rate.sleep();
ros::spinOnce();
}
digitalWrite(r_pin,LOW);
digitalWrite(g_pin,LOW);
digitalWrite(b_pin,LOW);
return 0;
}
| 21.367647
| 117
| 0.623538
|
PigeonSensei
|
96876780bfc31d4afa27bc75d31ba62b9af5b9fe
| 1,567
|
hpp
|
C++
|
include/tweedledee/quil/ast/nodes/decl_parameter.hpp
|
boschmitt/tweedledee
|
a7f5041681350601469b38311b9654e2c22643c0
|
[
"MIT"
] | 4
|
2018-07-21T08:11:56.000Z
|
2019-05-30T20:06:43.000Z
|
include/tweedledee/quil/ast/nodes/decl_parameter.hpp
|
boschmitt/tweedledee
|
a7f5041681350601469b38311b9654e2c22643c0
|
[
"MIT"
] | null | null | null |
include/tweedledee/quil/ast/nodes/decl_parameter.hpp
|
boschmitt/tweedledee
|
a7f5041681350601469b38311b9654e2c22643c0
|
[
"MIT"
] | 1
|
2019-05-15T14:11:28.000Z
|
2019-05-15T14:11:28.000Z
|
/*-------------------------------------------------------------------------------------------------
| This file is distributed under the MIT License.
| See accompanying file /LICENSE for details.
*------------------------------------------------------------------------------------------------*/
#pragma once
#include "../ast_node.hpp"
#include "../ast_node_kinds.hpp"
#include <cstdint>
#include <memory>
#include <ostream>
#include <rang/rang.hpp>
#include <string>
namespace tweedledee {
namespace quil {
/*! \brief Parameter declaration (decl) AST node
Formal parameters are names prepended with a ‘%’ symbol, which can be defined
in a gate and circuit declarations.
*/
class decl_parameter final : public ast_node {
public:
static std::unique_ptr<decl_parameter>
build(std::uint32_t location, std::string_view identifier)
{
auto result = std::unique_ptr<decl_parameter>(
new decl_parameter(location, std::move(identifier)));
return result;
}
std::string_view identifier() const
{
return identifier_;
}
private:
decl_parameter(std::uint32_t location, std::string_view identifier)
: ast_node(location)
, identifier_(std::move(identifier))
{}
ast_node_kinds do_get_kind() const override
{
return ast_node_kinds::decl_parameter;
}
void do_print(std::ostream& out) const override
{
using namespace rang;
out << style::bold << fgB::green << "decl_parameter " << style::reset << fgB::cyan
<< identifier_ << fg::reset;
}
private:
std::string identifier_;
};
} // namespace quil
} // namespace tweedledee
| 24.484375
| 99
| 0.627313
|
boschmitt
|
9687d82b43d145ca22f54e7219ac6f0a49256427
| 1,665
|
cpp
|
C++
|
1098/main.cpp
|
Heliovic/PAT_Solutions
|
7c5dd554654045308f2341713c3e52cc790beb59
|
[
"MIT"
] | 2
|
2019-03-18T12:55:38.000Z
|
2019-09-07T10:11:26.000Z
|
1098/main.cpp
|
Heliovic/My_PAT_Answer
|
7c5dd554654045308f2341713c3e52cc790beb59
|
[
"MIT"
] | null | null | null |
1098/main.cpp
|
Heliovic/My_PAT_Answer
|
7c5dd554654045308f2341713c3e52cc790beb59
|
[
"MIT"
] | null | null | null |
#include <cstdio>
#include <algorithm>
#include <cstring>
#define MAX_N 128
using namespace std;
int orignum[MAX_N];
int tempnum[MAX_N];
int destnum[MAX_N];
int N;
bool check()
{
for (int i = 1 ; i <= N; i++)
if (destnum[i] != tempnum[i])
return false;
return true;
}
bool insertion()
{
for (int i = 2; i <= N; i++)
{
sort(tempnum + 1, tempnum + 1 + i);
if (check())
{
sort(tempnum + 1, tempnum + 1 + i + 1);
return true;
}
}
return false;
}
void down_adjust(int s, int n)
{
int i = s, j = 2 * i;
while (j <= n)
{
if (j + 1 <= n && tempnum[j] < tempnum[j + 1])
j++;
swap(tempnum[i], tempnum[j]);
i = j;
j = 2 * i;
}
}
int main()
{
scanf("%d", &N);
for (int i = 1; i <= N; i++)
scanf("%d", &orignum[i]);
for (int i = 1; i <= N; i++)
scanf("%d", &destnum[i]);
memcpy(tempnum, orignum, MAX_N * sizeof(int));
if (insertion())
{
printf("Insertion Sort\n");
for (int i = 1; i <= N; i++)
{
if (i != 1)
printf(" ");
printf("%d", tempnum[i]);
}
return 0;
}
memcpy(tempnum, destnum, MAX_N * sizeof(int));
for (int j = N; j >= 1; j--)
{
if (tempnum[j] < tempnum[1])
{
swap(tempnum[j], tempnum[1]);
down_adjust(1, j - 1);
break;
}
}
printf("Heap Sort\n");
for (int i = 1; i <= N; i++)
{
if (i != 1)
printf(" ");
printf("%d", tempnum[i]);
}
return 0;
}
| 17.526316
| 54
| 0.417417
|
Heliovic
|
96891869ad7149c5ddad7a946e73f1393c97b885
| 4,613
|
cpp
|
C++
|
src/kernels/cpu/reference/convolution.cpp
|
louareg/nncase
|
0125654eb57b7ff753fe9c396c84b264c01f34d3
|
[
"Apache-2.0"
] | null | null | null |
src/kernels/cpu/reference/convolution.cpp
|
louareg/nncase
|
0125654eb57b7ff753fe9c396c84b264c01f34d3
|
[
"Apache-2.0"
] | null | null | null |
src/kernels/cpu/reference/convolution.cpp
|
louareg/nncase
|
0125654eb57b7ff753fe9c396c84b264c01f34d3
|
[
"Apache-2.0"
] | null | null | null |
/* Copyright 2019-2021 Canaan Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <nncase/kernels/cpu/reference/convolution.h>
#include <nncase/kernels/kernel_utils.h>
using namespace nncase;
using namespace nncase::runtime;
using namespace nncase::kernels;
using namespace nncase::kernels::cpu;
using namespace nncase::kernels::cpu::reference;
result<void> reference::conv2d(const float *input, const float *weights, const float *bias, float *output,
const runtime_shape_t &in_shape, const runtime_shape_t &in_strides, const runtime_shape_t &w_shape, const runtime_shape_t &w_strides,
const runtime_shape_t &bias_strides, const runtime_shape_t &out_strides, const padding &padding_h, const padding &padding_w,
int32_t groups, int32_t stride_h, int32_t stride_w, int32_t dilation_h, int32_t dilation_w, value_range<float> fused_activation,
NNCASE_UNUSED kernel_context &context) noexcept
{
const auto filter_h = (int32_t)w_shape[2];
const auto filter_w = (int32_t)w_shape[3];
const auto out_channels = w_shape[0];
const auto out_h = kernels::detail::get_windowed_output_size(in_shape[2], filter_h, stride_h, dilation_h, padding_h);
const auto out_w = kernels::detail::get_windowed_output_size(in_shape[3], filter_w, stride_w, dilation_w, padding_w);
const auto g_ic = in_shape[1] / groups;
const auto g_oc = out_channels / groups;
runtime_shape_t in_index(4);
runtime_shape_t w_index(4);
runtime_shape_t bias_index(1);
runtime_shape_t out_index(4);
for (size_t batch = 0; batch < in_shape[0]; batch++)
{
in_index[0] = out_index[0] = batch;
for (size_t og = 0; og < (size_t)groups; og++)
{
for (size_t oc = 0; oc < g_oc; oc++)
{
out_index[1] = w_index[0] = bias_index[0] = og * g_oc + oc;
for (size_t oy = 0; oy < out_h; oy++)
{
out_index[2] = oy;
for (size_t ox = 0; ox < out_w; ox++)
{
out_index[3] = ox;
const int32_t in_y_origin = (oy * stride_h) - padding_h.before;
const int32_t in_x_origin = (ox * stride_w) - padding_w.before;
const size_t filter_y_start = (size_t)std::max(0, (-in_y_origin + dilation_h - 1) / dilation_h);
const size_t filter_y_end = (size_t)std::min(filter_h, ((int32_t)in_shape[2] - in_y_origin + dilation_h - 1) / dilation_h);
const size_t filter_x_start = (size_t)std::max(0, (-in_x_origin + dilation_w - 1) / dilation_w);
const size_t filter_x_end = (size_t)std::min(filter_w, ((int32_t)in_shape[3] - in_x_origin + dilation_w - 1) / dilation_w);
float value = bias[offset(bias_strides, bias_index)];
for (size_t ic = 0; ic < g_ic; ic++)
{
in_index[1] = og * g_ic + ic;
w_index[1] = ic;
for (size_t ky = filter_y_start; ky < filter_y_end; ky++)
{
w_index[2] = ky;
for (size_t kx = filter_x_start; kx < filter_x_end; kx++)
{
w_index[3] = kx;
in_index[2] = in_y_origin + dilation_h * ky;
in_index[3] = in_x_origin + dilation_w * kx;
const float in_v = input[offset(in_strides, in_index)];
const float w = weights[offset(w_strides, w_index)];
value += in_v * w;
}
}
}
output[offset(out_strides, out_index)] = kernels::detail::apply_activation(value, fused_activation);
}
}
}
}
}
return ok();
}
| 49.074468
| 147
| 0.567743
|
louareg
|
f7b2d83e65c0ecda36a39fc44adf55e2c50a6c75
| 1,443
|
cpp
|
C++
|
ex02-find-extremes/ExtremesMain.cpp
|
kglogins/bitl-ds-workspace-cpp
|
0999247f3da9f63d77faebbdef7ba2c6a554f9dd
|
[
"MIT"
] | null | null | null |
ex02-find-extremes/ExtremesMain.cpp
|
kglogins/bitl-ds-workspace-cpp
|
0999247f3da9f63d77faebbdef7ba2c6a554f9dd
|
[
"MIT"
] | null | null | null |
ex02-find-extremes/ExtremesMain.cpp
|
kglogins/bitl-ds-workspace-cpp
|
0999247f3da9f63d77faebbdef7ba2c6a554f9dd
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <iomanip>
#include "Student.h"
using namespace std;
using namespace ds_course;
Student getMin(Student *ss, int count);
Student getMax(Student *ss, int count);
int main()
{
int studentsCount;
cin >> studentsCount;
Student students[studentsCount];
std::string studentInput;
cin.ignore(10000, '\n');
int age;
double height;
for (int i = 0; i < studentsCount; i++)
{
cin >> age >> height;
Student student;
student.age = age;
student.height = height;
students[i] = student;
}
Student minStudent = getMin(students, studentsCount);
Student maxStudent = getMax(students, studentsCount);
cout << minStudent.age << " " << fixed << setprecision(5) << minStudent.height << endl;
cout << maxStudent.age << " " << fixed << setprecision(5) << maxStudent.height << endl;
}
Student getMin(Student *ss, int count)
{
Student minStudent = ss[0];
for (int i = 0; i < count; i++)
{
if (minStudent.compareTo(ss[i]) == 1)
{
minStudent = ss[i];
}
}
return minStudent;
}
Student getMax(Student *ss, int count)
{
Student maxStudent = ss[0];
for (int i = 0; i < count; i++)
{
if (maxStudent.compareTo(ss[i]) == -1)
{
maxStudent = ss[i];
}
}
return maxStudent;
}
| 19.5
| 91
| 0.580735
|
kglogins
|
f7b747f64abc6d158a6f781eec3c64a96b511b81
| 1,218
|
hpp
|
C++
|
src/3rd party/boost/boost/python/detail/construct.hpp
|
OLR-xray/OLR-3.0
|
b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611
|
[
"Apache-2.0"
] | 8
|
2016-01-25T20:18:51.000Z
|
2019-03-06T07:00:04.000Z
|
src/3rd party/boost/boost/python/detail/construct.hpp
|
OLR-xray/OLR-3.0
|
b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611
|
[
"Apache-2.0"
] | null | null | null |
src/3rd party/boost/boost/python/detail/construct.hpp
|
OLR-xray/OLR-3.0
|
b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611
|
[
"Apache-2.0"
] | 3
|
2016-02-14T01:20:43.000Z
|
2021-02-03T11:19:11.000Z
|
// Copyright David Abrahams 2002. Permission to copy, use,
// modify, sell and distribute this software is granted provided this
// copyright notice appears in all copies. This software is provided
// "as is" without express or implied warranty, and with no claim as
// to its suitability for any purpose.
#ifndef CONSTRUCT_REFERENCE_DWA2002716_HPP
# define CONSTRUCT_REFERENCE_DWA2002716_HPP
namespace boost { namespace python { namespace detail {
template <class T, class Arg>
void construct_pointee(void* storage, Arg& x
# if !defined(BOOST_MSVC) || BOOST_MSVC > 1300
, T const volatile*
# else
, T const*
# endif
)
{
new (storage) T(x);
}
template <class T, class Arg>
void construct_referent_impl(void* storage, Arg& x, T&(*)())
{
construct_pointee(storage, x, (T*)0);
}
template <class T, class Arg>
void construct_referent(void* storage, Arg const& x, T(*tag)() = 0)
{
construct_referent_impl(storage, x, tag);
}
template <class T, class Arg>
void construct_referent(void* storage, Arg& x, T(*tag)() = 0)
{
construct_referent_impl(storage, x, tag);
}
}}} // namespace boost::python::detail
#endif // CONSTRUCT_REFERENCE_DWA2002716_HPP
| 27.681818
| 69
| 0.697865
|
OLR-xray
|
f7b8f01a1a001a3314d1d9bb7234a9b98b3fa2b0
| 1,436
|
cpp
|
C++
|
1101-9999/1654. Minimum Jumps to Reach Home.cpp
|
erichuang1994/leetcode-solution
|
d5b3bb3ce2a428a3108f7369715a3700e2ba699d
|
[
"MIT"
] | null | null | null |
1101-9999/1654. Minimum Jumps to Reach Home.cpp
|
erichuang1994/leetcode-solution
|
d5b3bb3ce2a428a3108f7369715a3700e2ba699d
|
[
"MIT"
] | null | null | null |
1101-9999/1654. Minimum Jumps to Reach Home.cpp
|
erichuang1994/leetcode-solution
|
d5b3bb3ce2a428a3108f7369715a3700e2ba699d
|
[
"MIT"
] | null | null | null |
class Solution
{
public:
int minimumJumps(vector<int> &forbidden, int a, int b, int x)
{
// int left = min(0,x-2*a-1);
// int right = x+2*b+1;
int left = -1;
int right = 4001;
unordered_set<int> f;
for (auto &n : forbidden)
{
f.insert(n);
}
unordered_set<string> visited;
queue<pair<int, int>> q;
int cnt = 0;
q.push(make_pair(0, 1));
visited.insert(make_key(0, 1));
while (!q.empty())
{
int len = q.size();
// cout<<len<<endl;
for (int i = 0; i < len; i++)
{
auto t = q.front();
q.pop();
if (t.first == x)
{
// cout<<t.first<<" "<<t.second<<endl;
return cnt;
}
string tmpk = make_key(t.first + a, 1);
if (t.first + a < right && visited.find(tmpk) == visited.end() && f.find(t.first + a) == f.end())
{
visited.insert(tmpk);
q.push(make_pair(t.first + a, 1));
}
if (t.second == 1)
{
tmpk = make_key(t.first - b, 0);
if (t.first - b > left && visited.find(tmpk) == visited.end() && f.find(t.first - b) == f.end())
{
visited.insert(tmpk);
q.push(make_pair(t.first - b, 0));
}
}
}
cnt++;
// if(cnt==10)break;
}
return -1;
}
string make_key(int x, int left)
{
return to_string(x) + "_" + to_string(left);
}
};
| 24.758621
| 106
| 0.460306
|
erichuang1994
|
f7bdc65129288c8bda92e00828a0ec72e4bf69bf
| 1,682
|
hpp
|
C++
|
include/fixed_containers/string_literal.hpp
|
alexkaratarakis/fixed-containers
|
f845532e9cc5f79a651e22a679ff4a77b5e4967a
|
[
"MIT"
] | 32
|
2021-06-29T03:07:49.000Z
|
2022-03-30T06:13:09.000Z
|
include/fixed_containers/string_literal.hpp
|
alexkaratarakis/fixed-containers
|
f845532e9cc5f79a651e22a679ff4a77b5e4967a
|
[
"MIT"
] | 1
|
2021-11-10T20:20:04.000Z
|
2021-11-22T22:49:25.000Z
|
include/fixed_containers/string_literal.hpp
|
alexkaratarakis/fixed-containers
|
f845532e9cc5f79a651e22a679ff4a77b5e4967a
|
[
"MIT"
] | 4
|
2021-10-11T02:47:57.000Z
|
2022-01-23T18:38:45.000Z
|
#pragma once
#include <cassert>
#include <cstddef>
#include <string_view>
namespace fixed_containers
{
/**
* Fully constexpr implementation of a compile-time literal null-terminated string.
* StringLiteral is trivially_copyable and standard_layout. Furthermore, all functions are
* constexpr.
*
* Compare:
* <ul>
* <li> static constexpr const char* s = "blah";
* <li> static constexpr const char s[5] = "blah"; // size 5 = 4 chars + null terminator
* <li> static constexpr StringLiteral s = "blah"; // size 4 (null-terminator is not counted)
* </ul>
*
* StringLiteral is cleaner to use, no confusion about size (null terminator), constant time
* size(), safe to use as a return type, size not hardcoded in the type (which would make it
* hard to change the string) and is implicitly convertible to std::string_view and c_str for
* convenient use in existing APIs.
*/
class StringLiteral
{
public:
template <std::size_t N>
/*implicit*/ consteval StringLiteral(const char (&str)[N]) noexcept
: size_(N - 1)
, cstr_(str)
{
assert(cstr_[N - 1] == '\0');
}
constexpr StringLiteral() noexcept
: size_(0)
, cstr_("")
{
}
[[nodiscard]] constexpr std::size_t size() const { return size_; }
[[nodiscard]] constexpr const char* c_str() const { return cstr_; }
/*implicit*/ constexpr operator const char*() const { return c_str(); }
[[nodiscard]] constexpr std::string_view as_view() const { return {cstr_, size_}; }
/*implicit*/ constexpr operator std::string_view() const { return as_view(); }
private:
std::size_t size_;
const char* cstr_;
};
} // namespace fixed_containers
| 29.508772
| 94
| 0.670036
|
alexkaratarakis
|
f7c4e3bf0308c996f826b4fa1fb4ba17ef1a22e1
| 1,111
|
cpp
|
C++
|
src/svgdom/elements/gradients.cpp
|
JaimeIvanCervantes/svgdom
|
8339d6d84a573cbeb0e235f4c828f4f898d67a6c
|
[
"MIT"
] | null | null | null |
src/svgdom/elements/gradients.cpp
|
JaimeIvanCervantes/svgdom
|
8339d6d84a573cbeb0e235f4c828f4f898d67a6c
|
[
"MIT"
] | null | null | null |
src/svgdom/elements/gradients.cpp
|
JaimeIvanCervantes/svgdom
|
8339d6d84a573cbeb0e235f4c828f4f898d67a6c
|
[
"MIT"
] | null | null | null |
#include "gradients.hpp"
#include <utki/debug.hpp>
#include "../util.hxx"
#include "../visitor.hpp"
using namespace svgdom;
const std::string gradient::stop_element::tag = "stop";
const std::string linear_gradient_element::tag = "linearGradient";
const std::string radial_gradient_element::tag = "radialGradient";
void radial_gradient_element::accept(visitor& v){
v.visit(*this);
}
void radial_gradient_element::accept(const_visitor& v) const {
v.visit(*this);
}
void linear_gradient_element::accept(visitor& v){
v.visit(*this);
}
void linear_gradient_element::accept(const_visitor& v) const {
v.visit(*this);
}
void gradient::stop_element::accept(visitor& v){
v.visit(*this);
}
void gradient::stop_element::accept(const_visitor& v) const {
v.visit(*this);
}
std::string gradient::spread_method_to_string() const {
switch(this->spread_method_){
default:
case gradient::spread_method::default_:
return "";
case gradient::spread_method::pad:
return "pad";
case gradient::spread_method::reflect:
return "reflect";
case gradient::spread_method::repeat:
return "repeat";
}
}
| 21.784314
| 66
| 0.729973
|
JaimeIvanCervantes
|
f7c842142c324965ab1574612727cd99a68a97ad
| 2,418
|
cpp
|
C++
|
CsPlugin/Source/CsCore/Public/Managers/Sense/CsSenseInfo.cpp
|
closedsum/core
|
c3cae44a177b9684585043a275130f9c7b67fef0
|
[
"Unlicense"
] | 2
|
2019-03-17T10:43:53.000Z
|
2021-04-20T21:24:19.000Z
|
CsPlugin/Source/CsCore/Public/Managers/Sense/CsSenseInfo.cpp
|
closedsum/core
|
c3cae44a177b9684585043a275130f9c7b67fef0
|
[
"Unlicense"
] | null | null | null |
CsPlugin/Source/CsCore/Public/Managers/Sense/CsSenseInfo.cpp
|
closedsum/core
|
c3cae44a177b9684585043a275130f9c7b67fef0
|
[
"Unlicense"
] | null | null | null |
// Copyright 2017-2021 Closed Sum Games, LLC. All Rights Reserved.
#include "Managers/Sense/CsSenseInfo.h"
#include "CsCore.h"
#include "Managers/Sense/CsSensingObject.h"
// ICsSenseInfo
#pragma region
const FCsSensedObject& FCsSenseInfo::GetObject() const
{
return Object;
}
void FCsSenseInfo::SetObject(ICsSensedObject* InSenseObject, UObject* InObject)
{
Object.SetInterface(InSenseObject);
Object.SetObject(InObject);
}
#pragma endregion ICsSenseInfo
void FCsSenseInfo::Update(const float& CurrentTime, ICsSensingObject* SensingObject)
{
ICsSensedObject* SensedObject = Object.GetInterface();
for (TPair<FCsSenseInfoKey, FCsSenseInfoValue>& Pair : Data)
{
const FCsSenseInfoKey& Key = Pair.Key;
FCsSenseInfoValue& Value = Pair.Value;
FVector& MeToObject = Value.MeToObject;
float& Distance = Value.Distance;
float& DistanceSq = Value.DistanceSq;
float& DistanceXY = Value.DistanceXY;
float& DistanceSqXY = Value.DistanceSqXY;
FVector& Direction = Value.Direction;
FVector& DirectionXY = Value.DirectionXY;
float& Dot = Value.Dot;
float& DotXY = Value.DotXY;
const FVector FromLocation = SensingObject->GetCustomLocation(Key.From);
const FVector ToLocation = SensedObject->GetCustomLocation(Key.To);
MeToObject = ToLocation - FromLocation;
// Distance
DistanceSqXY = MeToObject.SizeSquared2D();
DistanceSq = DistanceSqXY + FMath::Square(MeToObject.Z);
Distance = FMath::Sqrt(DistanceSq);
DistanceXY = FMath::Sqrt(DistanceSqXY);
// Direction
Direction = MeToObject;
{
if (DistanceSq == 1.f)
{
// Do Nothing
}
else
if (DistanceSq < SMALL_NUMBER)
{
Direction = FVector::ZeroVector;
}
else
{
const float Scale = FMath::InvSqrt(DistanceSq);
Direction *= Scale;
}
}
DirectionXY = MeToObject;
DirectionXY.Z = 0.0f;
{
if (DistanceSqXY == 1.f)
{
// Do Nothing
}
else
if (DistanceSqXY < SMALL_NUMBER)
{
DirectionXY = FVector::ZeroVector;
}
else
{
const float Scale = FMath::InvSqrt(DistanceSqXY);
DirectionXY *= Scale;
}
}
// Dot
const FVector DotDirection = SensingObject->GetCustomDirection(Key.Direction);
if (DotDirection != FVector::ZeroVector)
{
Dot = FVector::DotProduct(DotDirection, Direction);
DotXY = DotDirection.X * Direction.X + DotDirection.Y * Direction.Y;
}
else
{
Dot = 0.0f;
DotXY = 0.0f;
}
}
}
| 23.940594
| 84
| 0.696857
|
closedsum
|
f7cb2b54a8491271663c4b9d4b25c7c89fb86598
| 6,558
|
cpp
|
C++
|
src/main.cpp
|
DawidPietrykowski/GPURayTracer
|
66f150441d68587ddb3d4d73a7620310c5e26959
|
[
"MIT"
] | null | null | null |
src/main.cpp
|
DawidPietrykowski/GPURayTracer
|
66f150441d68587ddb3d4d73a7620310c5e26959
|
[
"MIT"
] | null | null | null |
src/main.cpp
|
DawidPietrykowski/GPURayTracer
|
66f150441d68587ddb3d4d73a7620310c5e26959
|
[
"MIT"
] | null | null | null |
#include <array>
#include <string>
#include <vector>
#include <iostream>
#include <ComputeEngine.h>
#include "Utils.h"
#include "DataStructures.h"
#include "Config.h"
#include "Scene.h"
#define UPDATE_OBJECT_BUFFERS 0
void UpdateKeys(ComputeEngine& renderer, CameraData& camera, std::vector<SceneObject>& objects, ShaderData& shader_data, Texture& tex_output) {
if (renderer.IsKeyClicked(GLFW_KEY_P)) {
renderer.SwitchInput();
}
if (renderer.GetInput()) {
if (renderer.IsKeyPressed(GLFW_KEY_W))
camera.AccelerateCamera(new float[3]{ 0, 0, 1.0f });
if (renderer.IsKeyPressed(GLFW_KEY_A))
camera.AccelerateCamera(new float[3]{ -1.0f, 0, 0 });
if (renderer.IsKeyPressed(GLFW_KEY_S))
camera.AccelerateCamera(new float[3]{ 0, 0, -1.0f });
if (renderer.IsKeyPressed(GLFW_KEY_D))
camera.AccelerateCamera(new float[3]{ 1.0f, 0, 0 });
if (renderer.IsKeyPressed(GLFW_KEY_SPACE))
camera.AccelerateCamera(new float[3]{ 0, 1.0f, 0 });
if (renderer.IsKeyPressed(GLFW_KEY_LEFT_CONTROL))
camera.AccelerateCamera(new float[3]{ 0, -1.0f, 0 });
if (renderer.IsKeyPressed(GLFW_KEY_E)) {
}
if (renderer.IsKeyPressed(GLFW_KEY_Q)) {
}
if (renderer.IsKeyClicked(GLFW_KEY_F11)) {
renderer.SwitchFullScreen();
}
if (renderer.IsKeyClicked(GLFW_KEY_ESCAPE))
renderer.CloseWindow();
if (renderer.IsKeyClicked(GLFW_KEY_L)) {
renderer.SaveScreen("screenshot");
}
}
int width, height;
shader_data.GetWindowSize(width, height);
renderer.GetWindowSize(shader_data._screen_size[0], shader_data._screen_size[1]);
if (width != shader_data.GetWidth() || height != shader_data.GetHeight())
tex_output.Resize(shader_data.GetWidth(), shader_data.GetHeight());
}
void UpdateInput(ComputeEngine& renderer, CameraData& camera, std::vector<SceneObject>& objects, ShaderData& shader_data, Texture& tex_output) {
renderer.PollEvents();
UpdateKeys(renderer, camera, objects, shader_data, tex_output);
double dx, dy;
renderer.GetMouseDelta(dx, dy);
dx *= (renderer.GetFrametime() / 1000.0);
dy *= (renderer.GetFrametime() / 1000.0);
double xp, yp;
int w, h;
renderer.GetWindowSize(w, h);
renderer.GetMousePos(xp, yp);
bool in_window = xp > 0 && yp > 0 && xp < w && yp < h;
if (renderer.IsMouseButtonClicked(GLFW_MOUSE_BUTTON_1) && !renderer.GetInput())
{
renderer.SetInput(true);
}
camera.RotateCamera((float)dx, (float)dy);
camera.UpdateCameraData((float)(renderer.GetFrametime() / 1000.0));
}
int main(int argc, char** argv)
{
srand((unsigned)time(0));
std::string config_filename = "configs/config.txt";
if (argc > 1)
config_filename = argv[1];
if (!FileExists(config_filename)) {
LOG_ERROR(config_filename + " does not exist");
return -1;
}
std::cout << "config file name: " << config_filename << std::endl;
Config config(config_filename);
int width = config.m_window_width;
int height = config.m_window_height;
// init renderer
ComputeEngine renderer(width, height, config.m_window_name, config.m_start_focused, true);
Shader pixel_compute_shader(config.m_pixel_shader_path);
if (!pixel_compute_shader.Compiled()) {
LOG_ERROR("shader compilation fail");
return -1;
}
Program pixel_compute_program(pixel_compute_shader);
// init data for shader
ShaderData shader_data = {};
shader_data._screen_size = { width, height };
shader_data._iterations = config.m_iterations;
shader_data._samples = config.m_samples_per_frame;
shader_data._fov = config.m_fov;
// init textures
Texture tex_output("img_output", width, height);
// bind textures
pixel_compute_program.BindTextureImage(tex_output, 0);
config.BindTextures(pixel_compute_program);
// init buffers
UBO data_buffer(2);
UBO objects_buffer(3);
SSBO index_buffer(4);
SSBO vert_buffer(5);
SSBO texture_vert_buffer(6);
// fill buffers with data
data_buffer.Set(&shader_data);
objects_buffer.Set(config.GetObjects());
index_buffer.Set(config.GetIndexBuffer());
vert_buffer.Set(config.GetVertexBuffer());
texture_vert_buffer.Set(config.GetTextureBuffer());
// init camera
CameraData camera;
camera.position = config.m_camera_position;
camera.rotation = config.m_camera_rotation;
camera.sensitivity = config.m_camera_sensitivity;
camera.m_width = width;
camera.m_height = height;
camera.CopyData(shader_data);
printf("faces: %d\nvertices: %d\nobjects: %d\n", config.GetFaceCount(), config.GetVertexCount(), config.GetObjectCount());
while (!renderer.ShouldClose()) {
// update input
camera.SetChanged(false);
UpdateInput(renderer, camera, *config.GetObjects(), shader_data, tex_output);
// update data for shader
if (camera.HasChanged()) {
shader_data._sample = 1;
shader_data._pixel_offset = { 0.5f, 0.5f };
}
else {
shader_data._sample++;
shader_data._pixel_offset = { (GetRand() - 0.5f), (GetRand() - 0.5f) };
}
shader_data.UpdateSeed();
shader_data._objectcount = config.GetObjectCount();
camera.UpdateWindowSize(shader_data.GetWidth(), shader_data.GetHeight());
camera.CopyData(shader_data);
// update buffers
data_buffer.Update(&shader_data);
#if UPDATE_OBJECT_BUFFERS
objects_buffer.Update(config.GetObjects());
index_buffer.Update(config.GetIndexBuffer());
vert_buffer.Update(config.GetVertexBuffer());
texture_vert_buffer.Update(config.GetTextureBuffer());
#endif
// dispatch compute shader
pixel_compute_program.DispatchCompute(shader_data.GetWidth(), shader_data.GetHeight());
renderer.UpdateFrametime();
// draw rendered image
renderer.DrawTexture(tex_output);
// glFinish call
renderer.Finish();
//print frametime every 50 frames
if(renderer.GetFramecount()%50 == 0)
printf("f:%.2fms w:%d h:%d samples:%d\n", renderer.GetFrametime(), renderer.GetWidth(), renderer.GetHeight(), shader_data._sample * shader_data._samples);
}
//print average frametime
printf("average frametime: %.3fms", renderer.GetAverageFrametime());
return 0;
}
| 33.28934
| 166
| 0.660415
|
DawidPietrykowski
|
f7cdb776f05cded77cea56aa65bec9d95207d44c
| 1,647
|
cpp
|
C++
|
src/ButtonInfoBar.cpp
|
xaviarmengol/M5Stack-GUI
|
ae7ad8897a0d695b0784f4a25cc5469c9e8a14ce
|
[
"MIT"
] | 71
|
2018-03-17T17:38:48.000Z
|
2022-02-18T04:43:41.000Z
|
src/ButtonInfoBar.cpp
|
xaviarmengol/M5Stack-GUI
|
ae7ad8897a0d695b0784f4a25cc5469c9e8a14ce
|
[
"MIT"
] | 6
|
2018-09-03T18:47:51.000Z
|
2021-01-18T10:03:33.000Z
|
src/ButtonInfoBar.cpp
|
xaviarmengol/M5Stack-GUI
|
ae7ad8897a0d695b0784f4a25cc5469c9e8a14ce
|
[
"MIT"
] | 20
|
2018-04-28T23:06:31.000Z
|
2022-02-17T23:56:14.000Z
|
#include "ButtonInfoBar.h"
using namespace Codingfield::UI;
void ButtonInfoBar::SetButtonAText(const std::string& t) {
if(btnAText != t) {
oldBtnAText = btnAText;
btnAText = t;
}
}
void ButtonInfoBar::SetButtonBText(const std::string& t) {
if(btnBText != t) {
oldBtnBText = btnBText;
btnBText = t;
}
}
void ButtonInfoBar::SetButtonCText(const std::string& t) {
if(btnCText != t) {
oldBtnCText = btnCText;
btnCText = t;
}
}
void ButtonInfoBar::Draw() {
if(IsHidden()) return;
bool oldIsInvalidated = isInvalidated;
Bar::Draw();
if(oldIsInvalidated || (oldBtnAText != btnAText)) {
M5.Lcd.setTextDatum(TC_DATUM);
M5.Lcd.setTextColor(color);
M5.Lcd.drawString(oldBtnAText.c_str(), (size.width/6), position.y + 5);
M5.Lcd.setTextColor(BLACK);
M5.Lcd.drawString(btnAText.c_str(), (size.width/6), position.y + 5);
oldBtnAText = btnAText;
}
if(oldIsInvalidated || (oldBtnBText != btnBText)) {
M5.Lcd.setTextDatum(TC_DATUM);
M5.Lcd.setTextColor(color);
M5.Lcd.drawString(oldBtnBText.c_str(), size.width/2, position.y + 5);
M5.Lcd.setTextColor(BLACK);
M5.Lcd.drawString(btnBText.c_str(), size.width/2, position.y + 5);
oldBtnBText = btnBText;
}
if(oldIsInvalidated || (oldBtnCText != btnCText)) {
M5.Lcd.setTextDatum(TC_DATUM);
M5.Lcd.setTextColor(color);
M5.Lcd.drawString(oldBtnCText.c_str(), ((size.width/3)*2) + (size.width/6), position.y + 5);
M5.Lcd.setTextColor(BLACK);
M5.Lcd.drawString(btnCText.c_str(), ((size.width/3)*2) + (size.width/6), position.y + 5);
oldBtnCText = btnCText;
}
isInvalidated = false;
}
| 26.564516
| 96
| 0.663024
|
xaviarmengol
|
f7d173e94c252ca127e58a36ec96a85202fd959c
| 6,737
|
hpp
|
C++
|
include/engine/script/luascriptsystem.hpp
|
eXl-Nic/eXl
|
a5a0f77f47db3179365c107a184bb38b80280279
|
[
"MIT"
] | null | null | null |
include/engine/script/luascriptsystem.hpp
|
eXl-Nic/eXl
|
a5a0f77f47db3179365c107a184bb38b80280279
|
[
"MIT"
] | null | null | null |
include/engine/script/luascriptsystem.hpp
|
eXl-Nic/eXl
|
a5a0f77f47db3179365c107a184bb38b80280279
|
[
"MIT"
] | null | null | null |
/*
Copyright 2009-2021 Nicolas Colombe
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#pragma once
#ifdef EXL_LUA
#include <core/lua/luamanager.hpp>
#include <core/lua/luascript.hpp>
#include <core/type/fundesc.hpp>
#include <engine/common/world.hpp>
#include <boost/optional.hpp>
#include <core/path.hpp>
namespace eXl
{
class LuaScriptBehaviour;
struct BehaviourDesc
{
Name behaviourName;
UnorderedMap<Name, FunDesc> functions;
};
class EXL_ENGINE_API LuaScriptSystem : public ComponentManager
{
DECLARE_RTTI(LuaScriptSystem, ComponentManager);
public:
LuaScriptSystem();
~LuaScriptSystem();
static void AddBehaviourDesc(BehaviourDesc iDesc);
static BehaviourDesc const* GetBehaviourDesc(Name iName);
static Vector<Name> GetBehaviourNames();
void LoadScript(const LuaScriptBehaviour& iBehaviour);
void AddBehaviour(ObjectHandle, const LuaScriptBehaviour& iBehaviour);
void DeleteComponent(ObjectHandle) override;
static World* GetWorld();
template <typename Ret, typename... Args>
static bool ValidateCall(Name iBehaviour, Name iFunction)
{
BehaviourDesc const* desc = GetBehaviourDesc(iBehaviour);
if (desc == nullptr)
{
return false;
}
auto iter = desc->functions.find(iFunction);
if (iter == desc->functions.end())
{
return false;
}
if (!iter->second.ValidateSignature<Ret, Args...>())
{
return false;
}
return true;
}
template <typename Ret, typename... Args>
struct Caller
{
static boost::optional<Ret> Call(LuaScriptSystem& iSys, ObjectHandle iHandle, Name iBehaviour, Name iFunction, Args&&... iArgs)
{
if (!iSys.ValidateCall<Ret, Args...>(iBehaviour, iFunction))
{
return {};
}
LuaStateHandle stateHandle = iSys.m_LuaWorld.GetState();
lua_State* state = stateHandle.GetState();
int32_t curTop = lua_gettop(state);
luabind::object scriptObject;
luabind::object function = iSys.FindFunction(iHandle, iBehaviour, iFunction, scriptObject);
if (!function.is_valid())
{
return {};
}
boost::optional<Ret> res;
{
auto call = stateHandle.PrepareCall(function);
call.Push(scriptObject);
call.PushArgs(std::forward<Args>(iArgs)...);
auto res = call.Call(1);
if (!res || *res == 0)
{
return {};
}
luabind::object retObj(luabind::from_stack(state, -1));
luabind::default_converter<Ret> converter;
if (converter.match(state, luabind::decorate_type_t<Ret>(), -1) < 0)
{
luabind::detail::cast_error<Ret>(state);
return {};
}
//return converter.to_cpp(state, luabind::decorate_type_t<Ret>(), -1);
res = converter.to_cpp(state, luabind::decorate_type_t<Ret>(), -1);
}
eXl_ASSERT(curTop == lua_gettop(state));
return res;
}
};
template <typename... Args>
struct Caller<void, Args...>
{
static Err Call(LuaScriptSystem& iSys, ObjectHandle iHandle, Name iBehaviour, Name iFunction, Args&&... iArgs)
{
if (!iSys.ValidateCall<void, Args...>(iBehaviour, iFunction))
{
return Err::Failure;
}
LuaStateHandle stateHandle = iSys.m_LuaWorld.GetState();
lua_State* state = stateHandle.GetState();
int32_t curTop = lua_gettop(state);
luabind::object scriptObject;
luabind::object function = iSys.FindFunction(iHandle, iBehaviour, iFunction, scriptObject);
if (!function.is_valid())
{
return Err::Failure;
}
{
auto call = stateHandle.PrepareCall(function);
call.Push(scriptObject);
call.PushArgs(std::forward<Args>(iArgs)...);
auto res = call.Call(0);
if (!res)
{
return Err::Failure;
}
}
eXl_ASSERT(curTop == lua_gettop(state));
return Err::Success;
}
};
template <typename Ret, typename... Args, typename std::enable_if<!std::is_same<Ret, void>::value, bool>::type = true>
boost::optional<Ret> CallBehaviour(ObjectHandle iHandle, Name iBehaviour, Name iFunction, Args&&... iArgs)
{
return Caller<Ret, Args...>::Call(*this, iHandle, iBehaviour, iFunction, std::forward<Args>(iArgs)...);
}
template <typename Ret, typename... Args, typename std::enable_if<std::is_same<Ret, void>::value, bool>::type = true>
Err CallBehaviour(ObjectHandle iHandle, Name iBehaviour, Name iFunction, Args&&... iArgs)
{
return Caller<void, Args...>::Call(*this, iHandle, iBehaviour, iFunction, std::forward<Args>(iArgs)...);
}
protected:
luabind::object FindFunction(ObjectHandle iHandle, Name iBehaviour, Name iFunction, luabind::object& oScriptObj);
struct ScriptEntry
{
ResourceHandle<LuaScriptBehaviour> m_ScriptHandle;
luabind::object m_ScriptObject;
luabind::object m_InitFunction;
UnorderedMap<Name, luabind::object> m_ScriptFunctions;
};
ObjectTable<ScriptEntry> m_Scripts;
using ScriptHandle = ObjectTableHandle<ScriptEntry>;
UnorderedMap<Resource::UUID, ScriptHandle> m_LoadedScripts;
ScriptHandle LoadScript_Internal(const LuaScriptBehaviour& iBehaviour);
struct ObjectEntry
{
ScriptHandle m_Script;
luabind::object m_ScriptData;
};
struct BehaviourReg
{
UnorderedMap<ObjectHandle, ObjectEntry> m_RegisteredObjects;
};
UnorderedMap<Name, BehaviourReg> m_ObjectToBehaviour;
LuaWorld m_LuaWorld;
};
}
#endif
| 32.863415
| 460
| 0.658008
|
eXl-Nic
|
f7d189fd792cf2f5f514da97367a04b17e389bca
| 1,349
|
cpp
|
C++
|
Demo/src/main.cpp
|
billy4479/BillyEngine
|
df7d519f740d5862c4743872dbf89b3654eeb423
|
[
"MIT"
] | 1
|
2021-09-05T20:50:59.000Z
|
2021-09-05T20:50:59.000Z
|
Demo/src/main.cpp
|
billy4479/sdl-tests
|
df7d519f740d5862c4743872dbf89b3654eeb423
|
[
"MIT"
] | null | null | null |
Demo/src/main.cpp
|
billy4479/sdl-tests
|
df7d519f740d5862c4743872dbf89b3654eeb423
|
[
"MIT"
] | null | null | null |
#include <BillyEngine.hpp>
#include "FPSCounter.hpp"
#include "MouseChaser.hpp"
#include "Spawner.hpp"
#include "SpinningQuad.hpp"
int main() {
BillyEngine::AppConfig appConfig;
appConfig.Maximized = true;
appConfig.AssetsPath = "assets";
BillyEngine::Application app(appConfig);
app.LoadFont("OpenSans-Regular.ttf", "OpenSans", 28);
app.LoadFont("JetBrains Mono Regular Nerd Font Complete Mono.ttf",
"JetBrainsMono", 34);
app.CreateEntityAndAddBehavior<SpinningQuad>();
app.CreateEntityAndAddBehavior<FPSCounter>();
app.CreateEntityAndAddBehavior<MouseChaser>();
app.CreateEntityAndAddBehavior<Spawner>();
{
auto e = app.CreateEntity();
e.AddComponent<BillyEngine::Components::Text>(
"BillyEngine!", app.GetFont("JetBrainsMono"));
auto& t = e.GetComponentM<BillyEngine::Components::Transform>();
t.Position = app.GetSize() / 2;
app.RegisterEventListenerFor<BillyEngine::WindowResizeEvent>(
[&e, &app](BillyEngine::WindowResizeEvent&) -> bool {
auto& t = e.GetComponentM<BillyEngine::Components::Transform>();
t.Position = app.GetSize() / 2;
return false;
});
t.Anchor = BillyEngine::CenterPoint::CENTER_CENTER;
}
app.Run();
return 0;
}
| 32.119048
| 80
| 0.644181
|
billy4479
|
f7d2d0746c75afa58e6d8203f21176da0de199d4
| 6,181
|
cpp
|
C++
|
jam/src/Mesh.cpp
|
gzito/jamengine
|
451ab1e1d74231a3239a56aed4c40dc445fa6db8
|
[
"MIT"
] | null | null | null |
jam/src/Mesh.cpp
|
gzito/jamengine
|
451ab1e1d74231a3239a56aed4c40dc445fa6db8
|
[
"MIT"
] | null | null | null |
jam/src/Mesh.cpp
|
gzito/jamengine
|
451ab1e1d74231a3239a56aed4c40dc445fa6db8
|
[
"MIT"
] | null | null | null |
/**********************************************************************************
*
* Mesh.cpp
*
* This file is part of Jam
*
* Copyright (c) 2014-2019 Giovanni Zito.
* Copyright (c) 2014-2019 Jam contributors (cf. AUTHORS.md)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
**********************************************************************************/
#include "stdafx.h"
#include <jam/Mesh.h>
#include <jam/Gfx.h>
#include <jam/Shader.h>
namespace jam
{
//*******************
//
// Class Mesh
//
//*******************
Mesh::Mesh() :
m_pMaterial(0),
m_vertices(0),
m_normals(0),
m_texCoords(0),
m_tangents(0),
m_bitangents(0),
m_elements(0),
m_vbos(),
m_elementsVbo(),
m_vao(),
m_uploaded(false),
m_tangentsDisabled(true),
m_needsCalculateTangents(true)
{
m_pMaterial = new Material() ;
for( size_t i=0; i<m_vbos.length()-1; i++ ) {
m_vbos[i].setTarget(GL_ARRAY_BUFFER) ;
}
m_elementsVbo.setTarget(GL_ELEMENT_ARRAY_BUFFER) ;
}
Mesh::~Mesh()
{
}
void Mesh::setMaterial( Material* pMaterial )
{
m_pMaterial.assign( pMaterial, true ) ;
}
void Mesh::create(int numOfVertices, int numOfElements)
{
m_vertices.create( numOfVertices ) ;
m_normals.create( numOfVertices ) ;
m_texCoords.create( numOfVertices ) ;
m_tangents.create( numOfVertices ) ;
m_bitangents.create( numOfVertices ) ;
m_elements.create( numOfElements ) ;
}
void Mesh::destroy()
{
for( size_t i=0; i<m_vbos.length(); i++ ) {
m_vbos[i].destroy() ;
}
m_elementsVbo.destroy() ;
m_vao.destroy() ;
m_vertices.destroy() ;
m_normals.destroy() ;
m_texCoords.destroy() ;
m_tangents.destroy() ;
m_bitangents.destroy() ;
m_elements.destroy() ;
}
void Mesh::upload()
{
if( m_uploaded ) {
return ;
}
if( !m_tangentsDisabled && m_needsCalculateTangents ) {
calculateTangents() ;
}
Shader* pShader = m_pMaterial->getShader() ;
pShader->use();
for( size_t i=0; i<m_vbos.length(); i++ ) {
m_vbos[i].create() ;
}
m_vao.create() ;
// bind vao
// all glBindBuffer, glVertexAttribPointer, and glEnableVertexAttribArray calls are tracked and stored in the vao
m_vao.bind() ;
int vboIdx = 0 ;
// upload vertices
m_vbos[vboIdx].bind() ;
m_vbos[vboIdx].bufferData( m_vertices.byteSize(), m_vertices.data() ) ;
pShader->setVertexAttribPointer(JAM_PROGRAM_ATTRIB_POSITION, 3, GL_FLOAT, GL_FALSE, sizeof(Vector3), 0) ;
pShader->enableVertexAttribArray(JAM_PROGRAM_ATTRIB_POSITION) ;
// upload normals
vboIdx++;
m_vbos[vboIdx].bind() ;
m_vbos[vboIdx].bufferData( m_normals.byteSize(), m_normals.data() ) ;
pShader->setVertexAttribPointer(JAM_PROGRAM_ATTRIB_NORMAL, 3, GL_FLOAT, GL_FALSE, sizeof(Vector3), 0) ;
pShader->enableVertexAttribArray(JAM_PROGRAM_ATTRIB_NORMAL) ;
// upload texture coordinates
vboIdx++;
m_vbos[vboIdx].bind() ;
m_vbos[vboIdx].bufferData( m_texCoords.byteSize(), m_texCoords.data() ) ;
pShader->setVertexAttribPointer(JAM_PROGRAM_ATTRIB_TEXCOORDS, 2, GL_FLOAT, GL_FALSE, sizeof(Vector2), 0) ;
pShader->enableVertexAttribArray(JAM_PROGRAM_ATTRIB_TEXCOORDS) ;
// upload tangents
if( !m_tangentsDisabled ) {
vboIdx++;
m_vbos[vboIdx].bind() ;
m_vbos[vboIdx].bufferData( m_tangents.byteSize(), m_tangents.data() ) ;
pShader->setVertexAttribPointer(JAM_PROGRAM_ATTRIB_TANGENT, 3, GL_FLOAT, GL_FALSE, sizeof(Vector3), 0) ;
pShader->enableVertexAttribArray(JAM_PROGRAM_ATTRIB_TANGENT) ;
}
// upload indices
m_elementsVbo.bind() ;
m_elementsVbo.bufferData( m_elements.byteSize(), m_elements.data() ) ;
// unbind vao
m_vao.unbind() ;
// unbind ARRAY_BUFFER and ELEMENT_ARRAY_BUFFER
m_vbos[vboIdx].unbind() ;
m_elementsVbo.unbind() ;
m_uploaded = true ;
}
void Mesh::draw()
{
if( !isUploaded() ) {
upload() ;
}
GetGfx().drawIndexedPrimitive( &m_vao, getElementsArray().length(), m_pMaterial ) ;
}
void jam::Mesh::disableTangents( bool value )
{
m_tangentsDisabled = value ;
}
void Mesh::calculateTangents()
{
m_tangents.setZero() ;
m_bitangents.setZero() ;
U16* triangle = m_elements.data() ;
Vector3* vertex = m_vertices.data() ;
Vector2* texcoord = m_texCoords.data() ;
for (U16 a = 0; a < m_elements.length(); a += 3)
{
U16 i1 = triangle[a];
U16 i2 = triangle[a+1];
U16 i3 = triangle[a+2];
const Vector3& v1 = vertex[i1];
const Vector3& v2 = vertex[i2];
const Vector3& v3 = vertex[i3];
const Vector2& w1 = texcoord[i1];
const Vector2& w2 = texcoord[i2];
const Vector2& w3 = texcoord[i3];
F32 x1 = v2.x - v1.x;
F32 x2 = v3.x - v1.x;
F32 y1 = v2.y - v1.y;
F32 y2 = v3.y - v1.y;
F32 z1 = v2.z - v1.z;
F32 z2 = v3.z - v1.z;
F32 s1 = w2.x - w1.x;
F32 s2 = w3.x - w1.x;
F32 t1 = w2.y - w1.y;
F32 t2 = w3.y - w1.y;
F32 r = 1.0f / (s1 * t2 - s2 * t1);
Vector3 sdir( (t2 * x1 - t1 * x2) * r, (t2 * y1 - t1 * y2) * r, (t2 * z1 - t1 * z2) * r ) ;
Vector3 tdir( (s1 * x2 - s2 * x1) * r, (s1 * y2 - s2 * y1) * r, (s1 * z2 - s2 * z1) * r ) ;
m_tangents[i1] += sdir;
m_tangents[i2] += sdir;
m_tangents[i3] += sdir;
m_bitangents[i1] += tdir;
m_bitangents[i2] += tdir;
m_bitangents[i3] += tdir;
}
m_needsCalculateTangents = false ;
}
void Mesh::doNotCalculateTangents()
{
m_needsCalculateTangents = false ;
}
}
| 25.861925
| 114
| 0.671089
|
gzito
|
f7d970d0ec992544da3f6ca5196ae68e4bd81195
| 7,381
|
hpp
|
C++
|
Old/tests/fept_test.hpp
|
waterswims/MC_HAMR
|
eb0492bc12a6eb67ec1709e5b59bdd53ee999892
|
[
"MIT"
] | 1
|
2021-08-02T23:14:45.000Z
|
2021-08-02T23:14:45.000Z
|
Old/tests/fept_test.hpp
|
waterswims/MC_HAMR
|
eb0492bc12a6eb67ec1709e5b59bdd53ee999892
|
[
"MIT"
] | null | null | null |
Old/tests/fept_test.hpp
|
waterswims/MC_HAMR
|
eb0492bc12a6eb67ec1709e5b59bdd53ee999892
|
[
"MIT"
] | 1
|
2021-08-02T23:14:45.000Z
|
2021-08-02T23:14:45.000Z
|
#ifndef _FEPTTEST
#define _FEPTTEST
#include "test_functions.hpp"
///////////////////////////////////////////////////////
// FePt model tests - 3D
///////////////////////////////////////////////////////
TEST(FePt, 3d_energy_zero_field)
{
field_3d_h field = gen_3d_heis_fm(1, 0, 0);
ham_FePt hamil;
hamil.init_dim(&field);
EXPECT_FLOAT_EQ(-94845.01392843794, hamil.calc_E(&field));
field = gen_3d_heis_fm(0, 1, 0);
EXPECT_FLOAT_EQ(-94845.01392843794, hamil.calc_E(&field));
field = gen_3d_heis_fm(0, 0, 1);
EXPECT_FLOAT_EQ(-96045.87686933874, hamil.calc_E(&field));
field = gen_3d_heis_fm(-1, 0, 0);
EXPECT_FLOAT_EQ(-94845.01392843794, hamil.calc_E(&field));
field = gen_3d_heis_fm(0, -1, 0);
EXPECT_FLOAT_EQ(-94845.01392843794, hamil.calc_E(&field));
field = gen_3d_heis_fm(0, 0, -1);
EXPECT_FLOAT_EQ(-96045.87686933874, hamil.calc_E(&field));
// Anti
field = gen_3d_heis_afm(1, 0, 0);
EXPECT_FLOAT_EQ(14349.191660944736, hamil.calc_E(&field));
field = gen_3d_heis_afm(0, 1, 0);
EXPECT_FLOAT_EQ(14349.191660944736, hamil.calc_E(&field));
field = gen_3d_heis_afm(0, 0, 1);
EXPECT_FLOAT_EQ(14481.605270298143, hamil.calc_E(&field));
field = gen_3d_heis_afm(-1, 0, 0);
EXPECT_FLOAT_EQ(14349.191660944736, hamil.calc_E(&field));
field = gen_3d_heis_afm(0, -1, 0);
EXPECT_FLOAT_EQ(14349.191660944736, hamil.calc_E(&field));
field = gen_3d_heis_afm(0, 0, -1);
EXPECT_FLOAT_EQ(14481.605270298143, hamil.calc_E(&field));
}
TEST(FePt, 3d_energy_ext_field)
{
field_3d_h field = gen_3d_heis_fm(1, 0, 0);
ham_FePt hamil(1);
hamil.init_dim(&field);
EXPECT_FLOAT_EQ(-94845.01392843794, hamil.calc_E(&field));
field = gen_3d_heis_fm(0, 1, 0);
EXPECT_FLOAT_EQ(-94845.01392843794, hamil.calc_E(&field));
field = gen_3d_heis_fm(0, 0, 1);
EXPECT_FLOAT_EQ(-97045.87686933874, hamil.calc_E(&field));
field = gen_3d_heis_fm(-1, 0, 0);
EXPECT_FLOAT_EQ(-94845.01392843794, hamil.calc_E(&field));
field = gen_3d_heis_fm(0, -1, 0);
EXPECT_FLOAT_EQ(-94845.01392843794, hamil.calc_E(&field));
field = gen_3d_heis_fm(0, 0, -1);
EXPECT_FLOAT_EQ(-95045.87686933874, hamil.calc_E(&field));
// Anti
field = gen_3d_heis_afm(1, 0, 0);
EXPECT_FLOAT_EQ(14349.191660944736, hamil.calc_E(&field));
field = gen_3d_heis_afm(0, 1, 0);
EXPECT_FLOAT_EQ(14349.191660944736, hamil.calc_E(&field));
field = gen_3d_heis_afm(0, 0, 1);
EXPECT_FLOAT_EQ(14481.605270298143, hamil.calc_E(&field));
field = gen_3d_heis_afm(-1, 0, 0);
EXPECT_FLOAT_EQ(14349.191660944736, hamil.calc_E(&field));
field = gen_3d_heis_afm(0, -1, 0);
EXPECT_FLOAT_EQ(14349.191660944736, hamil.calc_E(&field));
field = gen_3d_heis_afm(0, 0, -1);
EXPECT_FLOAT_EQ(14481.605270298143, hamil.calc_E(&field));
}
TEST(FePt, 3d_mag)
{
field_3d_h field = gen_3d_heis_fm(1, 0, 0);
ham_FePt hamil;
hamil.init_dim(&field);
std::vector<double> mag = hamil.calc_M(&field);
EXPECT_EQ(1000, mag[0]);
EXPECT_EQ(0, mag[1]);
EXPECT_EQ(0, mag[2]);
field = gen_3d_heis_fm(-1, 0, 0);
mag = hamil.calc_M(&field);
EXPECT_EQ(-1000, mag[0]);
EXPECT_EQ(0, mag[1]);
EXPECT_EQ(0, mag[2]);
field = gen_3d_heis_fm(0, 1, 0);
mag = hamil.calc_M(&field);
EXPECT_EQ(0, mag[0]);
EXPECT_EQ(1000, mag[1]);
EXPECT_EQ(0, mag[2]);
field = gen_3d_heis_fm(0, -1, 0);
mag = hamil.calc_M(&field);
EXPECT_EQ(0, mag[0]);
EXPECT_EQ(-1000, mag[1]);
EXPECT_EQ(0, mag[2]);
field = gen_3d_heis_fm(0, 0, 1);
mag = hamil.calc_M(&field);
EXPECT_EQ(0, mag[0]);
EXPECT_EQ(0, mag[1]);
EXPECT_EQ(1000, mag[2]);
field = gen_3d_heis_fm(0, 0, -1);
mag = hamil.calc_M(&field);
EXPECT_EQ(0, mag[0]);
EXPECT_EQ(0, mag[1]);
EXPECT_EQ(-1000, mag[2]);
field = gen_3d_heis_afm(1, 0, 0);
mag = hamil.calc_M(&field);
EXPECT_EQ(0, mag[0]);
EXPECT_EQ(0, mag[1]);
EXPECT_EQ(0, mag[2]);
field = gen_3d_heis_afm(-1, 0, 0);
mag = hamil.calc_M(&field);
EXPECT_EQ(0, mag[0]);
EXPECT_EQ(0, mag[1]);
EXPECT_EQ(0, mag[2]);
field = gen_3d_heis_afm(0, 1, 0);
mag = hamil.calc_M(&field);
EXPECT_EQ(0, mag[0]);
EXPECT_EQ(0, mag[1]);
EXPECT_EQ(0, mag[2]);
field = gen_3d_heis_afm(0, -1, 0);
mag = hamil.calc_M(&field);
EXPECT_EQ(0, mag[0]);
EXPECT_EQ(0, mag[1]);
EXPECT_EQ(0, mag[2]);
field = gen_3d_heis_afm(0, 0, 1);
mag = hamil.calc_M(&field);
EXPECT_EQ(0, mag[0]);
EXPECT_EQ(0, mag[1]);
EXPECT_EQ(0, mag[2]);
field = gen_3d_heis_afm(0, 0, -1);
mag = hamil.calc_M(&field);
EXPECT_EQ(0, mag[0]);
EXPECT_EQ(0, mag[1]);
EXPECT_EQ(0, mag[2]);
}
TEST(FePt, 3d_submag)
{
field_3d_h field = gen_3d_heis_fm(1, 0, 0);
ham_FePt hamil;
hamil.init_dim(&field);
std::vector<double> mag = hamil.calc_subM(&field, 1);
EXPECT_EQ(500, mag[0]);
EXPECT_EQ(0, mag[1]);
EXPECT_EQ(0, mag[2]);
field = gen_3d_heis_fm(-1, 0, 0);
mag = hamil.calc_subM(&field, 1);
EXPECT_EQ(-500, mag[0]);
EXPECT_EQ(0, mag[1]);
EXPECT_EQ(0, mag[2]);
field = gen_3d_heis_fm(0, 1, 0);
mag = hamil.calc_subM(&field, 1);
EXPECT_EQ(0, mag[0]);
EXPECT_EQ(500, mag[1]);
EXPECT_EQ(0, mag[2]);
field = gen_3d_heis_fm(0, -1, 0);
mag = hamil.calc_subM(&field, 1);
EXPECT_EQ(0, mag[0]);
EXPECT_EQ(-500, mag[1]);
EXPECT_EQ(0, mag[2]);
field = gen_3d_heis_fm(0, 0, 1);
mag = hamil.calc_subM(&field, 1);
EXPECT_EQ(0, mag[0]);
EXPECT_EQ(0, mag[1]);
EXPECT_EQ(500, mag[2]);
field = gen_3d_heis_fm(0, 0, -1);
mag = hamil.calc_subM(&field, 1);
EXPECT_EQ(0, mag[0]);
EXPECT_EQ(0, mag[1]);
EXPECT_EQ(-500, mag[2]);
field = gen_3d_heis_afm(1, 0, 0);
mag = hamil.calc_subM(&field, 1);
EXPECT_EQ(500, mag[0]);
EXPECT_EQ(0, mag[1]);
EXPECT_EQ(0, mag[2]);
field = gen_3d_heis_afm(-1, 0, 0);
mag = hamil.calc_subM(&field, 1);
EXPECT_EQ(-500, mag[0]);
EXPECT_EQ(0, mag[1]);
EXPECT_EQ(0, mag[2]);
field = gen_3d_heis_afm(0, 1, 0);
mag = hamil.calc_subM(&field, 1);
EXPECT_EQ(0, mag[0]);
EXPECT_EQ(500, mag[1]);
EXPECT_EQ(0, mag[2]);
field = gen_3d_heis_afm(0, -1, 0);
mag = hamil.calc_subM(&field, 1);
EXPECT_EQ(0, mag[0]);
EXPECT_EQ(-500, mag[1]);
EXPECT_EQ(0, mag[2]);
field = gen_3d_heis_afm(0, 0, 1);
mag = hamil.calc_subM(&field, 1);
EXPECT_EQ(0, mag[0]);
EXPECT_EQ(0, mag[1]);
EXPECT_EQ(500, mag[2]);
field = gen_3d_heis_afm(0, 0, -1);
mag = hamil.calc_subM(&field, 1);
EXPECT_EQ(0, mag[0]);
EXPECT_EQ(0, mag[1]);
EXPECT_EQ(-500, mag[2]);
}
TEST(FePt, 3d_dE_consist)
{
field_3d_h field = gen_3d_heis_fm(1, 0, 0);
ham_FePt hamil(4);
hamil.init_dim(&field);
std::vector<int> pos(3);
double old_E = hamil.calc_E(&field);
for(int i = 0; i < 100; i++)
{
pos[0] = int(st_rand_double.gen()*10 + 1);
pos[1] = int(st_rand_double.gen()*10 + 1);
pos[2] = int(st_rand_double.gen()*10 + 1);
double dE = hamil.dE(&field, pos);
field.change_to_test(pos, &hamil);
double new_E = hamil.calc_E(&field);
EXPECT_FLOAT_EQ(old_E + dE, new_E);
old_E = new_E;
}
}
#endif
| 27.438662
| 62
| 0.606151
|
waterswims
|
f7dbce953e61954bc8871fe27a97e70b08f5e4d2
| 3,757
|
cc
|
C++
|
src/mesh/mesh_moab/test/test_hex_2x2x1.cc
|
ajkhattak/amanzi
|
fed8cae6af3f9dfa5984381d34b98401c3b47655
|
[
"RSA-MD"
] | 1
|
2021-02-23T18:34:47.000Z
|
2021-02-23T18:34:47.000Z
|
src/mesh/mesh_moab/test/test_hex_2x2x1.cc
|
ajkhattak/amanzi
|
fed8cae6af3f9dfa5984381d34b98401c3b47655
|
[
"RSA-MD"
] | null | null | null |
src/mesh/mesh_moab/test/test_hex_2x2x1.cc
|
ajkhattak/amanzi
|
fed8cae6af3f9dfa5984381d34b98401c3b47655
|
[
"RSA-MD"
] | null | null | null |
#include <iostream>
#include "Epetra_Map.h"
#include "mpi.h"
#include "UnitTest++.h"
#include "AmanziComm.hh"
#include "../Mesh_MOAB.hh"
TEST(MOAB_HEX_2x2x1)
{
int i, j, k, nc, nf, nv;
Amanzi::AmanziMesh::Entity_ID_List faces, cnodes, fnodes;
std::vector<int> facedirs;
std::vector<Amanzi::AmanziGeometry::Point> ccoords, fcoords;
int NV = 18;
int NF = 20;
int NC = 4;
double xyz[18][3] = {{-0.5,-0.5, 0.25},
{-0.5,-0.5,-0.25},
{-0.5, 0, -0.25},
{-0.5, 0, 0.25},
{ 0, -0.5, 0.25},
{ 0, -0.5,-0.25},
{ 0, 0, -0.25},
{ 0, 0, 0.25},
{-0.5, 0.5,-0.25},
{-0.5, 0.5, 0.25},
{ 0, 0.5,-0.25},
{ 0, 0.5, 0.25},
{ 0.5,-0.5, 0.25},
{ 0.5,-0.5,-0.25},
{ 0.5, 0, -0.25},
{ 0.5, 0, 0.25},
{ 0.5, 0.5,-0.25},
{ 0.5, 0.5, 0.25}};
unsigned int cellnodes[4][8] = {{0,1,2,3,4,5,6,7},
{3,2,8,9,7,6,10,11},
{4,5,6,7,12,13,14,15},
{7,6,10,11,15,14,16,17}};
unsigned int cellfaces[4][6] = {{8,4,16,0,10,17},
{16,5,12,1,11,18},
{9,6,19,2,17,14},
{19,7,13,3,18,15}};
int cellfacedirs[4][6] = {{1,1,1,1,1,1},
{-1,1,1,1,1,1},
{1,1,1,1,-1,1},
{-1,1,1,1,-1,1}};
unsigned int facenodes[20][4] = {{3,0,4,7},
{9,3,7,11},
{7,4,12,15},
{11,7,15,17},
{1,2,6,5},
{2,8,10,6},
{5,6,14,13},
{6,10,16,14},
{0,1,5,4},
{4,5,13,12},
{0,3,2,1},
{3,9,8,2},
{8,9,11,10},
{10,11,17,16},
{12,13,14,15},
{15,14,16,17},
{2,3,7,6},
{4,5,6,7},
{7,6,10,11},
{6,7,15,14}};
unsigned int cfstd[6][4] = {{0,1,5,4}, // Expected cell-face-node pattern
{1,2,6,5},
{2,3,7,6},
{3,0,4,7},
{0,3,2,1},
{4,5,6,7}};
auto comm = Amanzi::getDefaultComm();
// Load four hexes from the ExodusII file
Amanzi::AmanziMesh::Mesh_MOAB mesh("test/hex_2x2x1_ss.exo",comm);
nv = mesh.num_entities(Amanzi::AmanziMesh::NODE,Amanzi::AmanziMesh::Parallel_type::OWNED);
CHECK_EQUAL(NV,nv);
for (i = 0; i < nv; i++) {
Amanzi::AmanziGeometry::Point coords;
mesh.node_get_coordinates(i,&coords);
CHECK_ARRAY_EQUAL(xyz[i],coords,3);
}
nf = mesh.num_entities(Amanzi::AmanziMesh::FACE,Amanzi::AmanziMesh::Parallel_type::OWNED);
CHECK_EQUAL(NF,nf);
nc = mesh.num_entities(Amanzi::AmanziMesh::CELL,Amanzi::AmanziMesh::Parallel_type::OWNED);
CHECK_EQUAL(NC,nc);
for (i = 0; i < nc; i++) {
mesh.cell_get_nodes(i,&cnodes);
mesh.cell_get_faces_and_dirs(i,&faces,&facedirs,true);
CHECK_ARRAY_EQUAL(cellfaces[i],faces,6);
CHECK_ARRAY_EQUAL(cellfacedirs[i],facedirs,6);
for (j = 0; j < 6; j++) {
mesh.face_get_nodes(faces[j],&fnodes);
mesh.face_get_coordinates(faces[j],&fcoords);
for (k = 0; k < 4; k++) {
CHECK_EQUAL(facenodes[faces[j]][k],fnodes[k]);
CHECK_ARRAY_EQUAL(xyz[facenodes[faces[j]][k]],&(fcoords[k][0]),3);
}
}
mesh.cell_get_coordinates(i,&ccoords);
for (j = 0; j < 8; j++) {
CHECK_EQUAL(cellnodes[i][j],cnodes[j]);
CHECK_ARRAY_EQUAL(xyz[cellnodes[i][j]],&(ccoords[j][0]),3);
}
}
// verify global IDs
Amanzi::AmanziMesh::Entity_ID_List c2f;
Epetra_Map cell_map(mesh.cell_map(true));
Epetra_Map face_map(mesh.face_map(false));
for (int c = cell_map.MinLID(); c <= cell_map.MaxLID(); c++) {
CHECK_EQUAL(cell_map.GID(c),mesh.GID(c,Amanzi::AmanziMesh::CELL));
mesh.cell_get_faces( c, &c2f, true );
for (j = 0; j < 6; ++j) {
int f = face_map.LID(mesh.GID(c2f[j],Amanzi::AmanziMesh::FACE));
CHECK(f == c2f[j]);
}
}
}
| 25.910345
| 92
| 0.519031
|
ajkhattak
|
f7e0c6d004b5f8e9f0805e3566a8a2c6f6d75b4c
| 935
|
cpp
|
C++
|
Broccoli/src/Broccoli/Renderer/Texture.cpp
|
tross2552/broccoli
|
d7afc472e076fa801d0e7745e209553b73c34486
|
[
"Apache-2.0"
] | 1
|
2021-08-03T01:38:41.000Z
|
2021-08-03T01:38:41.000Z
|
Broccoli/src/Broccoli/Renderer/Texture.cpp
|
tross2552/broccoli
|
d7afc472e076fa801d0e7745e209553b73c34486
|
[
"Apache-2.0"
] | null | null | null |
Broccoli/src/Broccoli/Renderer/Texture.cpp
|
tross2552/broccoli
|
d7afc472e076fa801d0e7745e209553b73c34486
|
[
"Apache-2.0"
] | null | null | null |
#include "brclpch.h"
#include "Texture.h"
#include "Renderer.h"
#include "Platform/OpenGL/OpenGLTexture2D.h"
namespace brcl
{
std::unique_ptr<Texture2D> Texture2D::Create(uint32_t width, uint32_t height)
{
switch (renderer::GetAPI())
{
case RendererAPI::API::None: BRCL_CORE_ASSERT(false, "RendererAPI::None is currently not supported!"); return nullptr;
case RendererAPI::API::OpenGL: return std::make_unique<OpenGLTexture2D>(width, height);
}
BRCL_CORE_ASSERT(false, "Unknown RendererAPI!");
return nullptr;
}
std::unique_ptr<Texture2D> Texture2D::Create(const std::string& path)
{
switch (renderer::GetAPI())
{
case RendererAPI::API::None: BRCL_CORE_ASSERT(false, "RendererAPI::None is currently not supported!"); return nullptr;
case RendererAPI::API::OpenGL: return std::make_unique<OpenGLTexture2D>(path);
}
BRCL_CORE_ASSERT(false, "Unknown RendererAPI!");
return nullptr;
}
}
| 26.714286
| 123
| 0.727273
|
tross2552
|
f7e8b11ae57f39a2e2bbadad65377a146cf1e02d
| 570
|
cpp
|
C++
|
Classes/Hole.cpp
|
khanhdrag9/TetrisHole
|
d2773cb9da0756c4d8a2f0e8ef7823fb7de8584c
|
[
"MIT"
] | null | null | null |
Classes/Hole.cpp
|
khanhdrag9/TetrisHole
|
d2773cb9da0756c4d8a2f0e8ef7823fb7de8584c
|
[
"MIT"
] | null | null | null |
Classes/Hole.cpp
|
khanhdrag9/TetrisHole
|
d2773cb9da0756c4d8a2f0e8ef7823fb7de8584c
|
[
"MIT"
] | null | null | null |
#include "Hole.h"
#include "Skill.h"
#include "Board.h"
#include "Templates.h"
Hole::Hole():
_spriteNode(nullptr),
_boardParrent(nullptr),
_skill(nullptr)
{
_spriteNode = Node::create();
}
Hole::~Hole()
{
CC_SAFE_DELETE(_spriteNode);
_boardParrent = nullptr;
_skill = nullptr;
}
void Hole::useSkill(float dt)
{
if (_skill && _boardParrent)
{
this->_skill->use(dt);
}
}
void Hole::setSkill(const skill skill, std::function<void()> callback)
{
if (skill == skill::stuck)
{
_skill = make_unique<Suck>(shared_from_this(), callback);
}
}
| 15.405405
| 70
| 0.659649
|
khanhdrag9
|
f7e8b64b0a7a4fe217770f73ffee035b4abcf3b0
| 871
|
cpp
|
C++
|
Snippets/lazy-segtree.cpp
|
KerakTelor86/CP-Stuff
|
31269195a913d55826fd2e34b091d0cd186c7af9
|
[
"Unlicense"
] | null | null | null |
Snippets/lazy-segtree.cpp
|
KerakTelor86/CP-Stuff
|
31269195a913d55826fd2e34b091d0cd186c7af9
|
[
"Unlicense"
] | null | null | null |
Snippets/lazy-segtree.cpp
|
KerakTelor86/CP-Stuff
|
31269195a913d55826fd2e34b091d0cd186c7af9
|
[
"Unlicense"
] | null | null | null |
int n;
vector<ll> seg,lazy;
void propagate(int idx,int l,int r)
{
if(!lazy[idx])
return;
int lc=(idx<<1)+1,rc=lc+1;
seg[idx]+=(r-l+1)*lazy[idx];
if(l!=r)
{
lazy[lc]+=lazy[idx];
lazy[rc]+=lazy[idx];
}
lazy[idx]=0;
}
void update(int u,int v,int w,int idx=0,int l=0,int r=n-1)
{
propagate(idx,l,r);
if(u>r||v<l)
return;
if(u<=l&&v>=r)
{
lazy[idx]+=w;
propagate(idx,l,r);
return;
}
int lc=(idx<<1)+1,rc=lc+1,m=l+((r-l)>>1);
update(u,v,w,lc,l,m);
update(u,v,w,rc,m+1,r);
seg[idx]=seg[lc]+seg[rc];
}
ll query(int u,int v,int idx=0,int l=0,int r=n-1)
{
propagate(idx,l,r);
if(u>r||v<l)
return 0;
if(u<=l&&v>=r)
return seg[idx];
int lc=(idx<<1)+1,rc=lc+1,m=l+((r-l)>>1);
return query(u,v,lc,l,m)+query(u,v,rc,m+1,r);
}
| 18.934783
| 58
| 0.482204
|
KerakTelor86
|
f7edf5ec82381548ad4ebc4bcaadecd56b8535b6
| 622
|
cpp
|
C++
|
Cpp/1008.construct-binary-search-tree-from-preorder-traversal.cpp
|
zszyellow/leetcode
|
2ef6be04c3008068f8116bf28d70586e613a48c2
|
[
"MIT"
] | 1
|
2015-12-19T23:05:35.000Z
|
2015-12-19T23:05:35.000Z
|
Cpp/1008.construct-binary-search-tree-from-preorder-traversal.cpp
|
zszyellow/leetcode
|
2ef6be04c3008068f8116bf28d70586e613a48c2
|
[
"MIT"
] | null | null | null |
Cpp/1008.construct-binary-search-tree-from-preorder-traversal.cpp
|
zszyellow/leetcode
|
2ef6be04c3008068f8116bf28d70586e613a48c2
|
[
"MIT"
] | null | null | null |
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* bstFromPreorder(vector<int>& preorder) {
int i = 0;
return build(preorder, i, INT_MAX);
}
TreeNode* build(vector<int>& A, int& i, int bound) {
if (i == A.size() || A[i] > bound) return NULL;
TreeNode* root = new TreeNode(A[i++]);
root->left = build(A, i, root->val);
root->right = build(A, i, bound);
return root;
}
};
| 25.916667
| 59
| 0.538585
|
zszyellow
|
f7edf703c84b774df1e0f62b471141fb40d93d3c
| 643
|
cpp
|
C++
|
0001-0100/3-longest-substring-without-repeating-characters/main.cpp
|
janreggie/leetcode
|
c59718e127b598c4de7d07c9c93064eb12b2e5c9
|
[
"MIT",
"Unlicense"
] | null | null | null |
0001-0100/3-longest-substring-without-repeating-characters/main.cpp
|
janreggie/leetcode
|
c59718e127b598c4de7d07c9c93064eb12b2e5c9
|
[
"MIT",
"Unlicense"
] | null | null | null |
0001-0100/3-longest-substring-without-repeating-characters/main.cpp
|
janreggie/leetcode
|
c59718e127b598c4de7d07c9c93064eb12b2e5c9
|
[
"MIT",
"Unlicense"
] | null | null | null |
#include <algorithm>
#include <string>
#include <unordered_set>
class Solution
{
public:
int lengthOfLongestSubstring(const std::string& s)
{
std::unordered_map<char, size_t> inds; // inds[c] = last index of c
size_t a = 0, b = 0;
size_t record = 0; // largest b-a
// Now what is our loop condition?
while (true) {
while (b < s.size() && (inds.count(s.at(b)) == 0 || inds.at(s.at(b)) < a)) {
inds[s.at(b)] = b;
++b;
}
record = std::max(record, b - a);
// At this point, either b == s.size() or s.at(b) in letters
if (b == s.size()) {
break;
}
a = inds[s.at(b)] + 1;
}
return record;
}
};
| 19.484848
| 79
| 0.562986
|
janreggie
|
f7f6eaf345aa924b4e1543e79c311b0c9ee1eb7c
| 806
|
cpp
|
C++
|
control_app/main.cpp
|
houcy/wall-e-1
|
b159d05b0afa343cb161f60ec98974bc2f063afd
|
[
"MIT"
] | 1
|
2021-05-05T14:11:03.000Z
|
2021-05-05T14:11:03.000Z
|
control_app/main.cpp
|
houcy/wall-e-1
|
b159d05b0afa343cb161f60ec98974bc2f063afd
|
[
"MIT"
] | null | null | null |
control_app/main.cpp
|
houcy/wall-e-1
|
b159d05b0afa343cb161f60ec98974bc2f063afd
|
[
"MIT"
] | null | null | null |
#include "main_widget.h"
#include "tcp_server.h"
#include "log.h"
#include "common.h"
#include <QApplication>
#ifdef Q_WS_QWS
#include <QAbstractSlider>
#include <QWSServer>
#endif
void outOfMemHandler()
{
fatal("Failed to allocate memory");
}
int main(int argc, char *argv[])
{
std::set_new_handler(outOfMemHandler);
QApplication a(argc, argv);
QCoreApplication::setOrganizationName(COMPANY_NAME);
QCoreApplication::setApplicationName(APPLICATION_NAME);
MainWidget mainWidget;
#ifdef Q_WS_QWS
QList<QAbstractSlider *> sliders = mainWidget.findChildren<QAbstractSlider *>();
foreach (QAbstractSlider *slider, sliders)
slider->setAttribute(Qt::WA_AcceptTouchEvents);
QWSServer::setCursorVisible(false);
#endif
mainWidget.show();
return a.exec();
}
| 21.783784
| 84
| 0.729529
|
houcy
|
f7f6fd54f4469ad46aeab6dcf21e8350579fe795
| 6,306
|
cpp
|
C++
|
source/hydra_next/source/graphics/debug_renderer.cpp
|
JorenJoestar/DataDrivenRendering
|
b9078ea3d2d63d1c2cbc6f9ed655e49e23747969
|
[
"Zlib"
] | 164
|
2019-06-30T18:14:38.000Z
|
2022-03-13T14:36:10.000Z
|
source/hydra_next/source/graphics/debug_renderer.cpp
|
JorenJoestar/DataDrivenRendering
|
b9078ea3d2d63d1c2cbc6f9ed655e49e23747969
|
[
"Zlib"
] | null | null | null |
source/hydra_next/source/graphics/debug_renderer.cpp
|
JorenJoestar/DataDrivenRendering
|
b9078ea3d2d63d1c2cbc6f9ed655e49e23747969
|
[
"Zlib"
] | 11
|
2019-09-11T13:40:59.000Z
|
2022-01-28T09:24:24.000Z
|
#include "graphics/debug_renderer.hpp"
#include "graphics/camera.hpp"
#include "graphics/command_buffer.hpp"
namespace hydra {
namespace gfx {
//
//
struct LineVertex {
vec3s position;
hydra::Color color;
void set( vec3s position_, hydra::Color color_ ) { position = position_; color = color_; }
void set( vec2s position_, hydra::Color color_ ) { position = { position_.x, position_.y, 0 }; color = color_; }
}; // struct LineVertex
//
//
struct LineVertex2D {
vec2s position;
u32 color;
}; // struct LineVertex2D
static const u32 k_max_lines = 100000;
static LineVertex s_line_buffer[ k_max_lines ];
static LineVertex2D s_line_buffer_2d[ k_max_lines ];
struct LinesGPULocalConstants {
mat4s view_projection;
mat4s projection;
vec4s resolution;
f32 line_width;
f32 pad[ 3 ];
};
// DebugRenderer ////////////////////////////////////////////////////////////////
void DebugRenderer::init( hydra::gfx::Renderer* renderer ) {
using namespace hydra::gfx;
// Constants
lines_cb = renderer->create_buffer( BufferType::Constant_mask, ResourceUsageType::Dynamic, sizeof(LinesGPULocalConstants), nullptr, "line_renderer_cb" );
// Line segments buffers
lines_vb = renderer->create_buffer( BufferType::Vertex_mask, ResourceUsageType::Dynamic, sizeof( LineVertex ) * k_max_lines, nullptr, "lines_vb" );
lines_vb_2d = renderer->create_buffer( BufferType::Vertex_mask, ResourceUsageType::Dynamic, sizeof( LineVertex2D ) * k_max_lines, nullptr, "lines_vb_2d" );
current_line = current_line_2d = 0;
this->material = nullptr;
}
void DebugRenderer::shutdown( hydra::gfx::Renderer* renderer ) {
//renderer.destroy_material( material );
renderer->destroy_buffer( lines_vb );
renderer->destroy_buffer( lines_vb_2d );
renderer->destroy_buffer( lines_cb );
}
void DebugRenderer::reload( hydra::gfx::Renderer* renderer, hydra::ResourceManager* resource_manager ) {
renderer->destroy_material( material );
material = resource_manager->load<hydra::gfx::Material>( "line_material" );
}
void DebugRenderer::render( hydra::gfx::Renderer& renderer, hydra::gfx::CommandBuffer* gpu_commands, hydra::gfx::Camera& camera ) {
using namespace hydra::gfx;
if ( current_line || current_line_2d ) {
LinesGPULocalConstants* cb_data = ( LinesGPULocalConstants* )renderer.dynamic_allocate( lines_cb );
if ( cb_data ) {
cb_data->view_projection = camera.view_projection;
camera.get_projection_ortho_2d( cb_data->projection.raw );
cb_data->resolution = { renderer.width * 1.0f, renderer.height * 1.0f, 1.0f / renderer.width, 1.0f / renderer.height };
cb_data->line_width = 1.f;
}
if ( this->material == nullptr ) {
hprint( "DebugRenderer does not have assigned a material. Skipping rendering.\n" );
return;
}
}
u64 sort_key = 0;
if ( current_line ) {
const u32 mapping_size = sizeof( LineVertex ) * current_line;
LineVertex* vtx_dst = ( LineVertex* )renderer.map_buffer( lines_vb, 0, mapping_size );
if ( vtx_dst ) {
memcpy( vtx_dst, &s_line_buffer[ 0 ], mapping_size );
renderer.unmap_buffer( lines_vb );
}
MaterialPass& pass = material->passes[ 0 ];
gpu_commands->bind_pipeline( sort_key++, pass.pipeline );
gpu_commands->bind_vertex_buffer( sort_key++, lines_vb->handle, 0, 0 );
gpu_commands->bind_resource_list( sort_key++, &pass.resource_list, 1, nullptr, 0 );
// Draw using instancing and 6 vertices.
const uint32_t num_vertices = 6;
gpu_commands->draw( sort_key++, TopologyType::Triangle, 0, num_vertices, 0, current_line / 2 );
current_line = 0;
}
if ( current_line_2d ) {
const u32 mapping_size = sizeof( LineVertex2D ) * current_line;
LineVertex2D* vtx_dst = ( LineVertex2D* )renderer.map_buffer( lines_vb, 0, mapping_size );
if ( vtx_dst ) {
memcpy( vtx_dst, &s_line_buffer_2d[ 0 ], mapping_size );
}
MaterialPass& pass = material->passes[ 1 ];
gpu_commands->bind_pipeline( sort_key++, pass.pipeline );
gpu_commands->bind_vertex_buffer( sort_key++, lines_vb->handle, 0, 0 );
gpu_commands->bind_resource_list( sort_key++, &pass.resource_list, 1, nullptr, 0 );
// Draw using instancing and 6 vertices.
const uint32_t num_vertices = 6;
gpu_commands->draw( sort_key++, TopologyType::Triangle, 0, num_vertices, 0, current_line_2d / 2 );
current_line_2d = 0;
}
}
void DebugRenderer::line( const vec3s& from, const vec3s& to, hydra::Color color ) {
line( from, to, color, color );
}
void DebugRenderer::line( const vec3s& from, const vec3s& to, hydra::Color color0, hydra::Color color1 ) {
if ( current_line >= k_max_lines )
return;
s_line_buffer[ current_line++ ].set( from, color0 );
s_line_buffer[ current_line++ ].set( to, color1 );
}
void DebugRenderer::box( const vec3s& min, const vec3s max, hydra::Color color ) {
const float x0 = min.x;
const float y0 = min.y;
const float z0 = min.z;
const float x1 = max.x;
const float y1 = max.y;
const float z1 = max.z;
line( { x0, y0, z0 }, { x0, y1, z0 }, color, color );
line( { x0, y1, z0 }, { x1, y1, z0 }, color, color );
line( { x1, y1, z0 }, { x1, y0, z0 }, color, color );
line( { x1, y0, z0 }, { x0, y0, z0 }, color, color );
line( { x0, y0, z0 }, { x0, y0, z1 }, color, color );
line( { x0, y1, z0 }, { x0, y1, z1 }, color, color );
line( { x1, y1, z0 }, { x1, y1, z1 }, color, color );
line( { x1, y0, z0 }, { x1, y0, z1 }, color, color );
line( { x0, y0, z1 }, { x0, y1, z1 }, color, color );
line( { x0, y1, z1 }, { x1, y1, z1 }, color, color );
line( { x1, y1, z1 }, { x1, y0, z1 }, color, color );
line( { x1, y0, z1 }, { x0, y0, z1 }, color, color );
}
} // namespace gfx
} // namespace hydra
| 37.094118
| 159
| 0.606565
|
JorenJoestar
|
f7f87dc0a12162cb19956915ef45c3e62742b8b2
| 6,307
|
cc
|
C++
|
extern/glow/src/glow/data/TextureData.cc
|
rovedit/Fort-Candle
|
445fb94852df56c279c71b95c820500e7fb33cf7
|
[
"MIT"
] | null | null | null |
extern/glow/src/glow/data/TextureData.cc
|
rovedit/Fort-Candle
|
445fb94852df56c279c71b95c820500e7fb33cf7
|
[
"MIT"
] | null | null | null |
extern/glow/src/glow/data/TextureData.cc
|
rovedit/Fort-Candle
|
445fb94852df56c279c71b95c820500e7fb33cf7
|
[
"MIT"
] | null | null | null |
#include "TextureData.hh"
#include "SurfaceData.hh"
#include <glow/common/log.hh>
#include <glow/common/profiling.hh>
#include <glow/common/str_utils.hh>
using namespace glow;
TextureData::LoadFromFileFunc TextureData::sLoadFunc = nullptr;
TextureData::TextureData() {}
void TextureData::addSurface(const SharedSurfaceData& surface) { mSurfaces.push_back(surface); }
SharedTextureData TextureData::createFromFile(const std::string& filename, ColorSpace colorSpace)
{
GLOW_ACTION();
auto ending = util::toLower(util::fileEndingOf(filename));
// try custom loader
if (sLoadFunc)
{
auto tex = sLoadFunc(filename, ending, colorSpace);
if (tex)
return tex;
}
// lodepng
if (ending == ".png")
return loadWithLodepng(filename, ending, colorSpace);
// stb
if (ending == ".png" || //
ending == ".jpg" || //
ending == ".jpeg" || //
ending == ".tga" || //
ending == ".bmp" || //
ending == ".psd" || //
ending == ".gif" || //
ending == ".hdr" || //
ending == ".pic" || //
ending == ".ppm" || //
ending == ".pgm")
return loadWithStb(filename, ending, colorSpace);
// try Qt
#ifdef GLOW_USE_QT
return loadWithQt(filename, ending, colorSpace);
#endif
error() << "file type of `" << filename << "' not recognized.";
return nullptr;
}
SharedTextureData TextureData::createFromRawPng(const unsigned char* rawData, size_t rawDataSize, ColorSpace colorSpace)
{
return loadWithLodepng(rawData, rawDataSize, colorSpace);
}
SharedTextureData TextureData::createFromFileCube(
const std::string& fpx, const std::string& fnx, const std::string& fpy, const std::string& fny, const std::string& fpz, const std::string& fnz, ColorSpace colorSpace)
{
GLOW_ACTION();
auto tpx = createFromFile(fpx, colorSpace);
auto tnx = createFromFile(fnx, colorSpace);
auto tpy = createFromFile(fpy, colorSpace);
auto tny = createFromFile(fny, colorSpace);
auto tpz = createFromFile(fpz, colorSpace);
auto tnz = createFromFile(fnz, colorSpace);
SharedTextureData ts[] = {tpx, tnx, tpy, tny, tpz, tnz};
for (auto i = 0; i < 6; ++i)
if (!ts[i])
return nullptr;
for (auto i = 1; i < 6; ++i)
if (ts[0]->getWidth() != ts[i]->getWidth() || ts[0]->getHeight() != ts[i]->getHeight())
{
std::string files[] = {fpx, fnx, fpy, fny, fpz, fnz};
error() << "CubeMaps require same size for every texture: ";
error() << " " << ts[0]->getWidth() << "x" << ts[0]->getHeight() << ", " << files[0];
error() << " " << ts[i]->getWidth() << "x" << ts[i]->getHeight() << ", " << files[i];
return nullptr;
}
auto tex = tpx;
tex->setTarget(GL_TEXTURE_CUBE_MAP);
for (auto const& s : tex->getSurfaces())
s->setTarget(GL_TEXTURE_CUBE_MAP_POSITIVE_X);
for (auto i = 1; i < 6; ++i)
for (auto const& s : ts[i]->getSurfaces())
{
s->setTarget(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i);
tex->addSurface(s);
}
return tex;
}
SharedTextureData TextureData::createFromRawPngCube(const unsigned char* rpx,
size_t rpxs,
const unsigned char* rnx,
size_t rnxs,
const unsigned char* rpy,
size_t rpys,
const unsigned char* rny,
size_t rnys,
const unsigned char* rpz,
size_t rpzs,
const unsigned char* rnz,
size_t rnzs,
ColorSpace colorSpace)
{
GLOW_ACTION();
auto tpx = createFromRawPng(rpx, rpxs, colorSpace);
auto tnx = createFromRawPng(rnx, rnxs, colorSpace);
auto tpy = createFromRawPng(rpy, rpys, colorSpace);
auto tny = createFromRawPng(rny, rnys, colorSpace);
auto tpz = createFromRawPng(rpz, rpzs, colorSpace);
auto tnz = createFromRawPng(rnz, rnzs, colorSpace);
SharedTextureData ts[] = {tpx, tnx, tpy, tny, tpz, tnz};
for (auto i = 0; i < 6; ++i)
if (!ts[i])
return nullptr;
for (auto i = 1; i < 6; ++i)
if (ts[0]->getWidth() != ts[i]->getWidth() || ts[0]->getHeight() != ts[i]->getHeight())
{
error() << "CubeMaps require same size for every texture: ";
error() << " " << ts[0]->getWidth() << "x" << ts[0]->getHeight() << 0;
error() << " " << ts[i]->getWidth() << "x" << ts[i]->getHeight() << i;
return nullptr;
}
auto tex = tpx;
tex->setTarget(GL_TEXTURE_CUBE_MAP);
for (auto const& s : tex->getSurfaces())
s->setTarget(GL_TEXTURE_CUBE_MAP_POSITIVE_X);
for (auto i = 1; i < 6; ++i)
for (auto const& s : ts[i]->getSurfaces())
{
s->setTarget(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i);
tex->addSurface(s);
}
return tex;
}
void TextureData::saveToFile(const std::string& filename, int quality)
{
GLOW_ACTION();
auto ending = util::toLower(util::fileEndingOf(filename));
// TODO: 3D texture
if (mDepth > 1)
{
warning() << "Texture has " << mDepth << " layers, only first one will be saved to " << filename;
}
// lodepng
if (ending == ".png")
{
saveWithLodepng(this, filename, ending);
return;
}
// stb
if (ending == ".tga" || //
ending == ".bmp" || //
ending == ".hdr")
{
saveWithStb(this, filename, ending);
return;
}
// try Qt
#ifdef GLOW_USE_QT
{
saveWithQt(this, filename, ending);
return;
}
#endif
error() << "file type of `" << filename << "' not recognized.";
return;
}
void TextureData::setLoadFunction(const TextureData::LoadFromFileFunc& func) { sLoadFunc = func; }
| 32.510309
| 170
| 0.526875
|
rovedit
|
f7fb115b479020ffcfe3b5a245ce14ac2fa31d00
| 1,735
|
cpp
|
C++
|
Recursion and Backtracking/Kpartition.cpp
|
Ankitlenka26/IP2021
|
99322c9c84a8a9c9178a505afbffdcebd312b059
|
[
"MIT"
] | null | null | null |
Recursion and Backtracking/Kpartition.cpp
|
Ankitlenka26/IP2021
|
99322c9c84a8a9c9178a505afbffdcebd312b059
|
[
"MIT"
] | null | null | null |
Recursion and Backtracking/Kpartition.cpp
|
Ankitlenka26/IP2021
|
99322c9c84a8a9c9178a505afbffdcebd312b059
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <vector>
using namespace std;
static int counter = 0;
void solution(int i, int n, int k, int cones, vector<vector<int>> &ans)
{
//write your code here
if (i > n)
{
// cout << "Hello" << endl;
if (cones == k)
{
counter++;
cout << counter << ". ";
for (const vector<int> &row : ans)
{
cout << "[";
for (int i = 0; i < row.size(); i++)
{
if (i == row.size() - 1)
{
cout << row[i];
}
else
{
cout << row[i] << ", ";
}
}
cout << "] ";
}
cout << endl;
}
return;
}
for (int j = 0; j < ans.size(); j++)
{
// cout << ans[j].size() << endl ;
if (ans[j].size() != 0)
{
// cout << "Already full set" << endl ;
ans[j].push_back(i);
solution(i + 1, n, k, cones, ans);
// since we hae not added any non empty sets;
ans[j].pop_back();
}
else
{
// cout << "Empty set" << endl;
ans[j].push_back(i);
solution(i + 1, n, k, cones + 1, ans);
ans[j].pop_back();
break;
}
}
}
int main()
{
int n, k;
cin >> n >> k;
vector<vector<int>> ans(k, vector<int>());
// for(int i=0 ; i<)
solution(1, n, k, 0, ans);
return 0;
}
/*
cones => count of non empty sets
1 => start of number
n => end of number
k => no of partition
*/
| 23.445946
| 71
| 0.358501
|
Ankitlenka26
|
f7fb5fd609bee157b8671ec92c5644458c59ca62
| 4,913
|
hpp
|
C++
|
sparta/cache/LineData.hpp
|
debjyoti0891/map
|
abdae67964420d7d36255dcbf83e4240a1ef4295
|
[
"MIT"
] | 44
|
2019-12-13T06:39:13.000Z
|
2022-03-29T23:09:28.000Z
|
sparta/cache/LineData.hpp
|
debjyoti0891/map
|
abdae67964420d7d36255dcbf83e4240a1ef4295
|
[
"MIT"
] | 222
|
2020-01-14T21:58:56.000Z
|
2022-03-31T20:05:12.000Z
|
sparta/cache/LineData.hpp
|
debjyoti0891/map
|
abdae67964420d7d36255dcbf83e4240a1ef4295
|
[
"MIT"
] | 19
|
2020-01-03T19:03:22.000Z
|
2022-01-09T08:36:20.000Z
|
#pragma once
#include <cstring>
#include "sparta/utils/ByteOrder.hpp"
#include "sparta/utils/SpartaException.hpp"
#include "cache/BasicCacheItem.hpp"
namespace sparta
{
namespace cache
{
class LineData : public BasicCacheItem
{
public:
// Constructor
LineData(uint64_t line_size) :
BasicCacheItem(),
line_sz_(line_size),
valid_(false),
modified_(false),
exclusive_(false),
shared_(false),
data_ptr_(new uint8_t[line_size]),
data_(data_ptr_.get())
{ }
// Copy constructor (for deep copy)
LineData(const LineData &rhs) :
BasicCacheItem(rhs),
line_sz_(rhs.line_sz_),
valid_(rhs.valid_),
modified_(rhs.modified_),
exclusive_(rhs.exclusive_),
shared_(rhs.shared_),
data_ptr_(new uint8_t[line_sz_]),
data_(data_ptr_.get())
{
memcpy(data_,rhs.data_,line_sz_);
}
void reset(uint64_t addr) {
setValid ( true );
setAddr ( addr );
setModified ( false );
setExclusive( true );
setShared ( false );
}
// Assigment operator (for deep copy)
LineData &operator=(const LineData &rhs)
{
if (&rhs != this) {
BasicCacheItem::operator=(rhs);
line_sz_ = rhs.line_sz_;
valid_ = rhs.valid_;
modified_ = rhs.modified_;
exclusive_ = rhs.exclusive_;
shared_ = rhs.shared_;
data_ptr_.reset(new uint8_t[line_sz_]);
data_ = data_ptr_.get();
memcpy(data_,rhs.data_,line_sz_);
}
return *this;
}
// Coherency states
// - Coherency states (MESI) are not known or managed by cache library
// - isValid() is required by the library
void setValid(bool v) { valid_ = v; }
void setModified(bool m) { modified_ = m; }
void setExclusive(bool e) { exclusive_ = e; }
void setShared(bool s) { shared_ = s; }
bool isValid() const { return valid_; }
bool isModified() const { return modified_; }
bool isExclusive() const { return exclusive_; }
bool isShared() const { return shared_; }
uint64_t getLineSize() const { return line_sz_; }
uint8_t *getDataPtr() { return data_; }
const uint8_t *getDataPtr() const { return data_; }
// The following templatized read & write methods were copied from
// ArchData.h. The intention is that there's a common interface
// to LineData as to all memory object in the simulator. At this point
// implementation details are TBD
template <typename T, ByteOrder BO>
T read(uint32_t offset, uint32_t idx=0) const {
uint32_t loc = offset + (idx*sizeof(T));
sparta_assert(loc + sizeof(T) <= line_sz_);
const uint8_t* d = data_ + loc;
T val = *reinterpret_cast<const T*>(d);
return reorder<T,BO>(val);
}
// Copied from ArchData.h. See comments on read above.
template <typename T, ByteOrder BO>
void write(uint32_t offset, const T& t, uint32_t idx=0) {
uint32_t loc = offset + (idx*sizeof(T));
sparta_assert(loc + sizeof(T) <= line_sz_);
uint8_t* d = data_ + loc;
T& val = *reinterpret_cast<T*>(d);
val = reorder<T,BO>(t);
}
bool read(uint64_t offset,
uint32_t size,
uint8_t *buf) const
{
sparta_assert( (offset + size) <= line_sz_ );
memcpy(buf, &data_[offset], size);
return true;
}
bool write(uint64_t offset,
uint32_t size,
const uint8_t *buf )
{
sparta_assert( (offset + size) <= line_sz_ );
memcpy(&data_[offset], buf, size);
return true;
}
private:
uint64_t line_sz_;
bool valid_;
bool modified_;
bool exclusive_;
bool shared_;
std::unique_ptr<uint8_t[]> data_ptr_;
uint8_t * data_ = nullptr;
}; // class LineData
}; // namespace cache
}; // namespace sparta
| 32.753333
| 83
| 0.483004
|
debjyoti0891
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.