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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
12b4b04a1335ec6c0c933a69d8c6e70a022cc609
| 885
|
cpp
|
C++
|
Gpu_Rvd/header/basic/string.cpp
|
stormHan/gpu_rvd
|
4029bfa604117c723c712445b42842b4aa499db2
|
[
"MIT"
] | null | null | null |
Gpu_Rvd/header/basic/string.cpp
|
stormHan/gpu_rvd
|
4029bfa604117c723c712445b42842b4aa499db2
|
[
"MIT"
] | null | null | null |
Gpu_Rvd/header/basic/string.cpp
|
stormHan/gpu_rvd
|
4029bfa604117c723c712445b42842b4aa499db2
|
[
"MIT"
] | null | null | null |
/**
* \file header/basic/string.cpp
*/
#include <basic\string.h>
namespace Gpu_Rvd{
/**
* \brief Builds the conversion error message
* \param[in] s the input string that could not be converted
* \param[in] type the expected destination type
* \return a string that contains the error message
*/
std::string conversion_error(
const std::string& s, const std::string& type
) {
std::ostringstream out;
out << "Conversion error: cannot convert string '"
<< s << "' to " << type;
return out.str();
}
}
namespace Gpu_Rvd{
namespace String{
/********************************************************************/
ConversionError::ConversionError(
const std::string& s, const std::string& type
) :
std::logic_error(conversion_error(s, type)) {
}
const char* ConversionError::what() const throw () {
return std::logic_error::what();
}
}
}
| 20.581395
| 72
| 0.611299
|
stormHan
|
12b4f3d137e79b2008ca8790d710cdde43d5a806
| 727
|
hpp
|
C++
|
libs/core/include/fcppt/cast/detail/promote_int_type.hpp
|
pmiddend/fcppt
|
9f437acbb10258e6df6982a550213a05815eb2be
|
[
"BSL-1.0"
] | null | null | null |
libs/core/include/fcppt/cast/detail/promote_int_type.hpp
|
pmiddend/fcppt
|
9f437acbb10258e6df6982a550213a05815eb2be
|
[
"BSL-1.0"
] | null | null | null |
libs/core/include/fcppt/cast/detail/promote_int_type.hpp
|
pmiddend/fcppt
|
9f437acbb10258e6df6982a550213a05815eb2be
|
[
"BSL-1.0"
] | null | null | null |
// Copyright Carl Philipp Reh 2009 - 2018.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef FCPPT_CAST_DETAIL_PROMOTE_INT_TYPE_HPP_INCLUDED
#define FCPPT_CAST_DETAIL_PROMOTE_INT_TYPE_HPP_INCLUDED
#include <fcppt/config/external_begin.hpp>
#include <type_traits>
#include <fcppt/config/external_end.hpp>
namespace fcppt
{
namespace cast
{
namespace detail
{
template<
typename Type
>
struct promote_int_type
{
static_assert(
std::is_integral<
Type
>::value,
"Type must be an integral type."
);
typedef
decltype(
+std::declval<
Type
>()
)
type;
};
}
}
}
#endif
| 15.145833
| 61
| 0.719395
|
pmiddend
|
12b8bece8c86682e30b16ae8d9836da79238b40b
| 12,915
|
cc
|
C++
|
src/occ_action.cc
|
dhatch/multiversioning
|
7b089437978fbe6e52fe54ad98d83ce50882064c
|
[
"MIT"
] | null | null | null |
src/occ_action.cc
|
dhatch/multiversioning
|
7b089437978fbe6e52fe54ad98d83ce50882064c
|
[
"MIT"
] | null | null | null |
src/occ_action.cc
|
dhatch/multiversioning
|
7b089437978fbe6e52fe54ad98d83ce50882064c
|
[
"MIT"
] | null | null | null |
#include <occ_action.h>
#include <algorithm>
#include <occ.h>
static bool try_acquire_single(volatile uint64_t *lock_ptr)
{
volatile uint64_t cmp_tid, locked_tid;
barrier();
cmp_tid = *lock_ptr;
barrier();
if (IS_LOCKED(cmp_tid))
return false;
locked_tid = (cmp_tid | 1);
return cmp_and_swap(lock_ptr, cmp_tid, locked_tid);
}
static void acquire_single(volatile uint64_t *lock_ptr)
{
uint32_t backoff, temp;
if (USE_BACKOFF)
backoff = 1;
while (true) {
if (try_acquire_single(lock_ptr)) {
assert(IS_LOCKED(*lock_ptr));
break;
}
if (USE_BACKOFF) {
// if (READ_COMMITTED) {
// barrier();
// for (i = 0; i < 100; ++i)
// single_work();
// barrier();
// do_pause();
// } else {
temp = backoff;
while (temp-- > 0)
single_work();
backoff = backoff*2;
// }
}
}
}
static void release_single(volatile uint64_t *lock_word)
{
uint64_t old_tid, xchged_tid;
old_tid = *lock_word;
assert(IS_LOCKED(old_tid));
old_tid = GET_TIMESTAMP(old_tid);
xchged_tid = xchgq(lock_word, old_tid);
assert(IS_LOCKED(xchged_tid));
assert(GET_TIMESTAMP(xchged_tid) == old_tid);
}
occ_composite_key::occ_composite_key(uint32_t table_id, uint64_t key,
bool is_rmw)
{
this->tableId = table_id;
this->key = key;
this->is_rmw = is_rmw;
this->is_locked = false;
this->is_initialized = false;
}
void* occ_composite_key::GetValue() const
{
uint64_t *temp = (uint64_t*)value;
return &temp[1];
}
void* occ_composite_key::StartRead()
{
volatile uint64_t *tid_ptr;
tid_ptr = (volatile uint64_t*)value;
while (true) {
barrier();
this->old_tid = *tid_ptr;
barrier();
if (!IS_LOCKED(this->old_tid))
break;
}
return (void*)&tid_ptr[1];
// return (void*)&((uint64_t*)value)[1];
}
bool occ_composite_key::FinishRead()
{
return true;
/*
assert(!IS_LOCKED(this->old_tid));
volatile uint64_t tid;
bool is_valid = false;
barrier();
tid = *(volatile uint64_t*)value;
barrier();
is_valid = (tid == this->old_tid);
assert(!is_valid || !IS_LOCKED(tid));
return is_valid;
// return true;
*/
}
uint64_t occ_composite_key::GetTimestamp()
{
return old_tid;
}
bool occ_composite_key::ValidateRead()
{
assert(!IS_LOCKED(old_tid));
volatile uint64_t *version_ptr;
volatile uint64_t cur_tid;
version_ptr = (volatile uint64_t*)value;
barrier();
cur_tid = *version_ptr;
barrier();
if ((GET_TIMESTAMP(cur_tid) != old_tid) ||
(IS_LOCKED(cur_tid) && !is_rmw))
return false;
return true;
}
void OCCAction::add_read_key(uint32_t tableId, uint64_t key)
{
occ_composite_key k(tableId, key, false);
readset.push_back(k);
}
OCCAction::OCCAction(txn *txn) : translator(txn)
{
}
void OCCAction::add_write_key(uint32_t tableId, uint64_t key, bool is_rmw)
{
occ_composite_key k(tableId, key, is_rmw);
writeset.push_back(k);
shadow_writeset.push_back(k);
}
void OCCAction::set_allocator(RecordBuffers *bufs)
{
this->record_alloc = bufs;
}
void OCCAction::set_tables(Table **tables, Table **lock_tables)
{
this->tables = tables;
this->lock_tables = lock_tables;
}
uint64_t OCCAction::stable_copy(uint64_t key, uint32_t table_id, void *record)
{
volatile uint64_t *tid_ptr;
uint32_t record_size;
uint64_t ret, after_read;
void *value;
value = this->tables[table_id]->Get(key);
record_size = REAL_RECORD_SIZE(this->tables[table_id]->RecordSize());
tid_ptr = (volatile uint64_t*)value;
while (true) {
barrier();
ret = *tid_ptr;
barrier();
if (!IS_LOCKED(ret)) {
memcpy(RECORD_VALUE_PTR(record),
RECORD_VALUE_PTR(value), record_size);
barrier();
after_read = *tid_ptr;
barrier();
if (after_read == ret)
return ret;
else if (READ_COMMITTED)
continue;
else
throw occ_validation_exception(READ_ERR);
return ret;
}
}
}
void OCCAction::validate_single(occ_composite_key &comp_key)
{
assert(!IS_LOCKED(comp_key.old_tid));
void *value;
volatile uint64_t *version_ptr;
uint64_t cur_tid;
value = tables[comp_key.tableId]->Get(comp_key.key);
version_ptr = (volatile uint64_t*)value;
barrier();
cur_tid = *version_ptr;
barrier();
if ((GET_TIMESTAMP(cur_tid) != comp_key.old_tid) ||
(IS_LOCKED(cur_tid) && !comp_key.is_rmw))
throw occ_validation_exception(VALIDATION_ERR);
}
void OCCAction::validate()
{
uint32_t num_reads, num_writes, i;
num_reads = this->readset.size();
for (i = 0; i < num_reads; ++i)
validate_single(this->readset[i]);
num_writes = this->writeset.size();
for (i = 0; i < num_writes; ++i)
if (this->writeset[i].is_rmw)
validate_single(this->writeset[i]);
}
void* OCCAction::write_ref(uint64_t key, uint32_t table_id)
{
uint64_t tid;
void *record;
uint32_t i, num_writes;
occ_composite_key *comp_key;
num_writes = this->writeset.size();
comp_key = NULL;
for (i = 0; i < num_writes; ++i) {
if (writeset[i].key == key && writeset[i].tableId == table_id) {
comp_key = &writeset[i];
break;
}
}
assert(comp_key != NULL);
if (comp_key->is_initialized == false) {
record = this->record_alloc->GetRecord(table_id);
comp_key->is_initialized = true;
comp_key->value = record;
if (writeset[i].is_rmw == true) {
tid = stable_copy(key, table_id, record);
comp_key->old_tid = tid;
}
}
return RECORD_VALUE_PTR(comp_key->value);
}
int OCCAction::rand()
{
return worker->gen_random();
}
void* OCCAction::read(uint64_t key, uint32_t table_id)
{
uint64_t tid;
void *record;
uint32_t i, num_reads;
occ_composite_key *comp_key;
num_reads = this->readset.size();
comp_key = NULL;
for (i = 0; i < num_reads; ++i) {
if (this->readset[i].key == key &&
this->readset[i].tableId == table_id) {
comp_key = &this->readset[i];
break;
}
}
assert(comp_key != NULL);
if (comp_key->is_initialized == false) {
record = this->record_alloc->GetRecord(table_id);
comp_key->is_initialized = true;
comp_key->value = record;
tid = stable_copy(key, table_id, record);
comp_key->old_tid = tid;
}
return RECORD_VALUE_PTR(comp_key->value);
}
void OCCAction::acquire_locks()
{
uint32_t i, num_writes, table_id;
uint64_t key;
void *value;
num_writes = this->writeset.size();
std::sort(this->writeset.begin(), this->writeset.end());
for (i = 0; i < num_writes; ++i) {
assert(this->writeset[i].is_locked == false);
table_id = this->writeset[i].tableId;
key = this->writeset[i].key;
if (READ_COMMITTED)
value = this->lock_tables[table_id]->GetAlways(key);
else
value = this->tables[table_id]->GetAlways(key);
acquire_single((volatile uint64_t*)value);
this->writeset[i].is_locked = true;
}
}
void OCCAction::release_locks()
{
uint32_t i, num_writes, table_id;
uint64_t key;
void *value;
num_writes = this->writeset.size();
for (i = 0; i < num_writes; ++i) {
assert(this->writeset[i].is_locked == true);
table_id = this->writeset[i].tableId;
key = this->writeset[i].key;
value = this->tables[table_id]->Get(key);
release_single((volatile uint64_t*)value);
this->writeset[i].is_locked = false;
}
}
void OCCAction::cleanup_single(occ_composite_key &comp_key)
{
// assert(comp_key.value != NULL);
this->record_alloc->ReturnRecord(comp_key.tableId, comp_key.value);
comp_key.value = NULL;
comp_key.is_initialized = false;
}
uint64_t OCCAction::compute_tid(uint32_t epoch, uint64_t last_tid)
{
uint64_t max_tid, cur_tid, key;
uint32_t num_reads, num_writes, i, table_id;
volatile uint64_t *value;
max_tid = CREATE_TID(epoch, 0);
if (max_tid < last_tid)
max_tid = last_tid;
assert(!IS_LOCKED(max_tid));
num_reads = this->readset.size();
num_writes = this->writeset.size();
for (i = 0; i < num_reads; ++i) {
cur_tid = GET_TIMESTAMP(this->readset[i].old_tid);
assert(!IS_LOCKED(cur_tid));
if (cur_tid > max_tid)
max_tid = cur_tid;
}
for (i = 0; i < num_writes; ++i) {
table_id = this->writeset[i].tableId;
key = this->writeset[i].key;
value = (volatile uint64_t*)this->tables[table_id]->Get(key);
assert(IS_LOCKED(*value));
barrier();
cur_tid = GET_TIMESTAMP(*value);
barrier();
assert(!IS_LOCKED(cur_tid));
if (cur_tid > max_tid)
max_tid = cur_tid;
}
max_tid += 0x10;
this->tid = max_tid;
assert(!IS_LOCKED(max_tid));
return max_tid;
}
bool OCCAction::run()
{
return this->t->Run();
}
void OCCAction::cleanup()
{
uint32_t i, num_writes, num_reads;
num_writes = this->writeset.size();
for (i = 0; i < num_writes; ++i) {
assert(this->writeset[i].is_locked == false);
if (this->writeset[i].is_initialized == true)
cleanup_single(this->writeset[i]);
}
num_reads = this->readset.size();
for (i = 0; i < num_reads; ++i) {
if (this->readset[i].is_initialized == true)
cleanup_single(this->readset[i]);
}
}
void OCCAction::install_single_write(occ_composite_key &comp_key)
{
if (READ_COMMITTED)
this->tid = 0;
assert(IS_LOCKED(this->tid) == false);
void *value;
uint64_t old_tid;
uint32_t record_size;
record_size = this->tables[comp_key.tableId]->RecordSize();
value = this->tables[comp_key.tableId]->GetAlways(comp_key.key);
if (READ_COMMITTED)
acquire_single((volatile uint64_t*)value);
old_tid = *(uint64_t*)value;
assert(IS_LOCKED(old_tid) == true);
memcpy(RECORD_VALUE_PTR(value), RECORD_VALUE_PTR(comp_key.value),
record_size - sizeof(uint64_t));
xchgq((volatile uint64_t*)value, this->tid);
if (READ_COMMITTED) {
value = this->lock_tables[comp_key.tableId]->GetAlways(comp_key.key);
release_single((volatile uint64_t*)value);
}
comp_key.is_locked = false;
}
void OCCAction::install_writes()
{
uint32_t i, num_writes;
num_writes = this->writeset.size();
for (i = 0; i < num_writes; ++i)
install_single_write(this->writeset[i]);
}
| 31.120482
| 85
| 0.513666
|
dhatch
|
12b908589d2e3dcebd2f852a9d924bb31032ab16
| 1,012
|
cpp
|
C++
|
src/rtl/HeadlightColor.cpp
|
potato3d/rtrt
|
cac9f2f80d94bf60adf0bbd009f5076973ee10c6
|
[
"MIT"
] | 2
|
2021-02-13T14:18:39.000Z
|
2021-11-04T07:21:21.000Z
|
src/rtl/HeadlightColor.cpp
|
potato3d/rtrt
|
cac9f2f80d94bf60adf0bbd009f5076973ee10c6
|
[
"MIT"
] | null | null | null |
src/rtl/HeadlightColor.cpp
|
potato3d/rtrt
|
cac9f2f80d94bf60adf0bbd009f5076973ee10c6
|
[
"MIT"
] | null | null | null |
#include <rtl/HeadlightColor.h>
namespace rtl {
void HeadlightColor::init()
{
_ambient.set( 0.1f, 0.1f, 0.1f );
_diffuse.set( 1.0f, 1.0f, 1.0f );
}
void HeadlightColor::shade( rts::RTstate& state )
{
const rtu::float3& normal = rtsComputeShadingNormal( state );
//rtu::float3 normal; rtsComputeFlatNormal( state, normal );
rtu::float3& resultColor = rtsResultColor( state );
rtu::float3& rayDir = rtsRayDirection( state );
rayDir.normalize();
const float nDotD = -( normal.dot( rayDir ) );
//const float nDotD = rtu::mathf::abs( normal.dot( rayDir ) );
resultColor.r = ( _ambient.r + ( _diffuse.r - _ambient.r ) * nDotD ) * _diffuse.r;
resultColor.g = ( _ambient.g + ( _diffuse.g - _ambient.g ) * nDotD ) * _diffuse.g;
resultColor.b = ( _ambient.b + ( _diffuse.b - _ambient.b ) * nDotD ) * _diffuse.b;
//resultColor = normal;
//resultColor.r = rtu::mathf::abs( normal.r );
//resultColor.g = rtu::mathf::abs( normal.g );
//resultColor.b = rtu::mathf::abs( normal.b );
}
} // namespace rtl
| 30.666667
| 83
| 0.661067
|
potato3d
|
12b97b19d443e890e387ca55c5d4217415d0e7d2
| 13,109
|
cpp
|
C++
|
userprog/clientprog.cpp
|
jonathanmeisel/C-LINK
|
6827c82143fa9ccd95cc8ae97f78d9f36058a451
|
[
"Apache-1.1"
] | null | null | null |
userprog/clientprog.cpp
|
jonathanmeisel/C-LINK
|
6827c82143fa9ccd95cc8ae97f78d9f36058a451
|
[
"Apache-1.1"
] | null | null | null |
userprog/clientprog.cpp
|
jonathanmeisel/C-LINK
|
6827c82143fa9ccd95cc8ae97f78d9f36058a451
|
[
"Apache-1.1"
] | null | null | null |
/** clientprog.cpp -- This is the program used by the USER to request a page
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <signal.h>
#include <string>
#include <iostream>
#include <fstream>
#include <sys/stat.h>
#include <sys/time.h>
#include <sendall.h>
#include <defines.h>
#include "pageretreaval.h"
/*checkcompleteness - checks to see that all configuration fields are
filled in, either with values read in of defaults
input:
filenames - map into which to put configuration values
*/
void checkcompleteness(stringtostring * filenames){
if(filenames ->find("kioskip")==filenames->end()){
(*filenames)["kioskip"]=DEFAULTKIOSKIP;
}
if(filenames->find("quota")==filenames->end()){
(*filenames)["quota"]=DEFAULTQUOTA;
}
if(filenames->find("free")==filenames->end()){
(*filenames)["free"]=DEFAULTSPACETOFREE;
}
if(filenames->find("sizefile")==filenames->end()){
(*filenames)["sizefile"]=DEFAULTSIZEFILE;
}
if(filenames->find("deletion")==filenames->end()){
(*filenames)["deletion"]=DEFAULTUSERDELFILE;
}
if(filenames->find("used")==filenames->end()){
(*filenames)["used"]=DEFAULTUSEDFILE;
}
if(filenames->find("LRU")==filenames->end()){
(*filenames)["LRU"]=DEFAULTLRUFILE;
}
if(filenames->find("debugdir")==filenames->end()){
(*filenames)["debugdir"]=NODEBUG;
}
}
void sigchld_handler(int s)
{
while(waitpid(-1, NULL, WNOHANG) > 0);
}
int main(int argc, char *argv[])
{
int sockfd, numbytes, listenfd, new_fd;
char buf[MAXDATASIZE];
struct hostent *he;
struct sockaddr_in their_addr; // connector's address information
struct sockaddr_in my_addr; // my address information
struct sockaddr_in kiosk_addr; // kiosk address information
socklen_t sin_size;
struct sigaction sa;
int mysize, len, initsize, content, newline, total, sizeofbuf;
string sendbuf;
char *dynamicbuf;
char *charpoint, *charpoint2;
char *size=new char;
int fieldsize;
string page, response;
ifstream fp;
int yes=1;
string argv2, argv1="NULL";
ifstream file;
int post=0,found=0;
stringtostring configuration;
ofstream output;
int header;
unsigned long int sum=0;
unsigned long int sum2=0;
char sumbuf[MAXDATASIZE];
string cacheable;
int movedpage=0;
string moveloc;
unsigned long int reqmade, reqserviced;
unsigned long int pretime;
string timingfile, timingfilepre;
struct timespec ts,ts2;
/* if an argument is given, it is the config file, otherwise, try the
default config file
*/
if (argc!=1){
fp.open(argv[1]);
} else {
fp.open(DEFAULTUSERFILE);
}
while(!fp.fail()){
fp.getline(buf,sizeof(buf));
response=buf;
if((response[0]!='#') && (numbytes=response.find('='))!=string::npos){
configuration[response.substr(0,numbytes)]=response.substr(numbytes+1);;
}
}
fp.close();
checkcompleteness(&configuration);
argv1=configuration["kioskip"];
timingfile=configuration["debugdir"];
timingfile+='/';
timingfile+=getenv("USER");
timingfilepre=timingfile;
timingfile+="timingpost";
timingfilepre+="timingpre";
if ((listenfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket");
exit(1);
}
if (setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) {
perror("setsockopt");
exit(1);
}
my_addr.sin_family = AF_INET; // host byte order
my_addr.sin_port = htons(FFPORT); // short, network byte order
my_addr.sin_addr.s_addr = htonl(INADDR_ANY); // automatically fill with my IP
memset(my_addr.sin_zero, '\0', sizeof my_addr.sin_zero);
if (bind(listenfd, (struct sockaddr *)&my_addr, sizeof my_addr) == -1) {
perror("bind");
exit(1);
}
if (listen(listenfd, BACKLOG) == -1) {
perror("listen");
exit(1);
}
sa.sa_handler = sigchld_handler; // reap all dead processes
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_RESTART;
if (sigaction(SIGCHLD, &sa, NULL) == -1) {
perror("sigaction");
exit(1);
}
while(1) { // main accept() loop
sin_size = sizeof their_addr;
if ((new_fd = accept(listenfd, (struct sockaddr *)&their_addr, \
&sin_size)) == -1) {
perror("accept");
continue;
}
if (!fork()) { // this is the child process
clock_gettime(CLOCK_REALTIME, &ts);
reqmade=ts.tv_nsec;
close(listenfd); // child doesn't need the listener
if ((initsize = recv(new_fd, buf,sizeof(buf), 0))== -1){
perror("recv");
close(new_fd);
exit(0);
}
sizeofbuf=initsize;
if((charpoint=strstr(buf,"GET "))==NULL){
charpoint=strstr(buf,"POST ");
post=1;
}
charpoint2=strstr(buf,"HTTP/");
// argv1="127.0.0.1";
argv2=(charpoint+post+4);
argv2.resize(charpoint2-charpoint-5-post);
if(argv2[argv2.length()-1]=='/'){
argv2+="index.html";
}
argv2=urlhash(argv2.c_str(), argv2.length());
if(post){
//there might be more then just 1024 bytes in a post request
charpoint=strstr(buf,"Content-Length: ");
content= atoi(charpoint+16);
charpoint=strstr(buf,"\r\n\r\n");
header = charpoint - buf +4;
content = content - (initsize - header);
dynamicbuf = new char[initsize+content];
sizeofbuf=initsize+content;
memcpy(dynamicbuf,buf,initsize);
total=initsize;
while(content > 0){
if ((newline = recv(new_fd, buf,sizeof(buf), 0))== -1){
perror("recv");
close(new_fd);
exit(0);
}
content-=newline;
memcpy(dynamicbuf+total,buf,newline);
total+=newline;
}
argv2+='_';
argv2+=urlhash(&dynamicbuf[header],initsize+content-header);
} else {
dynamicbuf = new char[initsize];
memcpy(dynamicbuf,buf,initsize);
}
/* before doing anything, check to see if we already have the page
This obviously only means something in the case of a GET, a POST
request has embedded data that does not show in the url
*/
// if(!post){
found=0;
page="/home/";
page+=getenv("USER");
page+="/localweb/";
page+=translate(argv2.c_str());
struct stat s;
if( stat(page.c_str(),&s) == 0 ){
if(s.st_mode & S_IFREG){
//it's a file
fp.open(page.c_str());
fp.read(buf,sizeof(buf));
len=fp.gcount();
sendall(new_fd,buf,&len);
cacheable=is_page_cacheable(buf);
while(!fp.fail()){
clock_gettime(CLOCK_REALTIME, &ts);
fp.read(buf,sizeof(buf));
len=fp.gcount();
sendall(new_fd,buf,&len);
}
clock_gettime(CLOCK_REALTIME, &ts2);
if(configuration["debugbir"].compare(NODEBUG)!=0){
lock_file(timingfile);
lock_file(timingfilepre);
output.open(timingfile.c_str(), ios::app);
output << "user-local " << argv2 << " " << ts2.tv_nsec - reqmade << endl;
output.close();
output.open(timingfilepre.c_str(), ios::app);
output << "user-local " << argv2 << " " << ts.tv_nsec - reqmade << endl;
output.close();
unlock_file(timingfile);
unlock_file(timingfilepre);
}
fp.close();
close(new_fd);
if(movedpage==1){
//treat as if it were a duplicate page
handle_duped_page(translate(argv2.c_str()));
exit(1);
}
lock_file(configuration["used"]);
output.open(configuration["used"].c_str(), ios::app);
output << getenv("USER") << ' ' << translate(argv2.c_str()) << endl;
output.close();
unlock_file(configuration["used"]);
found=1;
}
}
// }
/* establish a connection with the kiosk */
if ((he=gethostbyname(argv1.c_str())) == NULL) { // get the host info
herror("gethostbyname");
cout << "This is the one that failed" << endl;
exit(1);
}
if ((sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket");
exit(1);
}
kiosk_addr.sin_family = AF_INET; // host byte order
kiosk_addr.sin_port = htons(MYPORT); // short, network byte order
kiosk_addr.sin_addr = *((struct in_addr *)he->h_addr);
memset(kiosk_addr.sin_zero, '\0', sizeof kiosk_addr.sin_zero);
if (connect(sockfd, (struct sockaddr *)&kiosk_addr,
sizeof kiosk_addr) == -1) {
perror("connect");
exit(1);
}
/*send a message of type 000 (page request). The format is:
000 pagename user
we use sendall-recvall to ensure completness. However, recvall expects
message lengths, hence the "size" thing
If we have the page send a 001 if is it cacheable, 002 if it is not
*/
*size=3;
sendbuf=size;
if(found==0){
sendbuf+="000";
} else {
if(!cacheable.compare("no")){
sendbuf+="002";
} else {
sendbuf+="001";
}
}
*size=argv2.length();
sendbuf+=size;
sendbuf+=argv2;
*size=strlen(getenv("USER"));
sendbuf+=size;
sendbuf+=getenv("USER");
len = sendbuf.length();
delete size;
if (sendall(sockfd, sendbuf.c_str(), &len) == -1) {
perror("sendall");
printf("We only sent %d bytes because of the error!\n", len);
}
if (sendall(sockfd, dynamicbuf, &sizeofbuf) == -1) {
perror("sendall");
printf("We only sent %d bytes because of the error!\n", sizeofbuf);
}
/*get the reply*/
len = 3;
mysize=len;
if (receiveall(sockfd, buf, &len, 0) == -1) {
perror("recv");
printf("We still have space to receive %d more bytes\n", len);
}
buf[mysize-len] = '\0';
if(!strcmp(buf,"100")){
/* We have not found the page. The request has been queued
and we are done*/
clock_gettime(CLOCK_REALTIME,&ts);
sprintf(buf,"HTTP/1.1 200 OK\r\nProxy-Agent: Custom\r\nCache-Control:no-cache\r\n\r\n<h1>Please wait</h1>Your page, %s, has been sent to the city and will be ready after the next bus returns.\r\n\r\n", argv2.c_str());
len=strlen(buf);
sendall(new_fd, buf, &len);
clock_gettime(CLOCK_REALTIME,&ts2);
reqserviced=ts2.tv_nsec;
if(configuration["debugbir"].compare(NODEBUG)!=0){
lock_file(timingfilepre);
lock_file(timingfile);
output.open(timingfile.c_str(), ios::app);
output << "pending " << argv2 << " " << reqserviced - reqmade << endl;
output.close();
output.open(timingfilepre.c_str(), ios::app);
output << "pending " << argv2 << " " << ts.tv_nsec - reqmade << endl;
output.close();
unlock_file(timingfile);
unlock_file(timingfilepre);
}
} else if (!strcmp(buf,"200")) {
/*The page is somewhere on this very machine, handle the case*/
reqserviced = handle_local_page(sockfd, configuration, argv2.c_str(), new_fd, dynamicbuf, sizeofbuf, &pretime);
if(configuration["debugbir"].compare(NODEBUG)!=0){
lock_file(timingfile);
lock_file(timingfilepre);
output.open(timingfile.c_str(), ios::app);
output << "machine-local " << argv2 << " " << reqserviced - reqmade << endl;
output.close();
output.open(timingfilepre.c_str(), ios::app);
output << "machine-local " << argv2 << " " << pretime - reqmade << endl;
output.close();
unlock_file(timingfilepre);
unlock_file(timingfile);
}
} else if(!strcmp(buf,"201")) {
/*We got a message telling us where the page can be found in the
village use handle_remote_page to get it */
reqserviced = handle_remote_page(sockfd,argv1.c_str(), argv2.c_str(), new_fd, dynamicbuf, sizeofbuf, &pretime);
if(configuration["debugbir"].compare(NODEBUG)!=0){
lock_file(timingfile);
lock_file(timingfilepre);
output.open(timingfile.c_str(), ios::app);
output << "village " << argv2 << " " << reqserviced - reqmade << endl;
output.close();
output.open(timingfilepre.c_str(), ios::app);
output << "village " << argv2 << " " << pretime - reqmade << endl;
output.close();
unlock_file(timingfile);
unlock_file(timingfilepre);
}
} else if(!strcmp(buf,"202")) {
/*We have a message with the full page in it, the page was stored
on the kiosk */
reqserviced = handle_page_on_kiosk(sockfd, new_fd, &pretime);
if(configuration["debugbir"].compare(NODEBUG)!=0){
lock_file(timingfile);
lock_file(timingfilepre);
output.open(timingfile.c_str(), ios::app);
output << "kiosk " << argv2 << " " << reqserviced - reqmade << endl;
output.close();
output.open(timingfilepre.c_str(), ios::app);
output << "kiosk " << argv2 << " " << pretime - reqmade << endl;
output.close();
unlock_file(timingfile);
unlock_file(timingfilepre);
}
}else if(!strcmp(buf,"101")) {
/* purely informational */
}else if(!strcmp(buf,"102")) {
/* someone else owns the file now, delete this copy */
handle_duped_page(translate(argv2.c_str()));
}else {
/*something has gone seriously wrong*/
return 1;
}
delete[] dynamicbuf;
close(sockfd);
close(new_fd);
exit(0);
} //if (!fork())
close(new_fd); //parent doesn't need this
} //while(1)
return 0;
}
| 27.773305
| 218
| 0.626745
|
jonathanmeisel
|
12b9dc8b59a872157c878cb260fa4e74a3c71531
| 3,120
|
cpp
|
C++
|
osquery/tables/networking/freebsd/process_open_sockets.cpp
|
justintime32/osquery
|
721dd1ed624b25738c2471dae617d7868df8fb0d
|
[
"BSD-3-Clause"
] | 23
|
2016-12-07T15:26:58.000Z
|
2019-07-18T21:39:06.000Z
|
osquery/tables/networking/freebsd/process_open_sockets.cpp
|
justintime32/osquery
|
721dd1ed624b25738c2471dae617d7868df8fb0d
|
[
"BSD-3-Clause"
] | 4
|
2016-12-07T06:18:36.000Z
|
2017-01-19T19:39:38.000Z
|
osquery/tables/networking/freebsd/process_open_sockets.cpp
|
Acidburn0zzz/osquery
|
1cedf8d57310b4ac3ae0a39fe33dce00699f4a3b
|
[
"BSD-3-Clause"
] | 5
|
2017-06-26T11:54:37.000Z
|
2019-02-18T01:23:02.000Z
|
/*
* Copyright (c) 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/param.h>
#include <sys/queue.h>
#include <libprocstat.h>
#include <osquery/core.h>
#include <osquery/logger.h>
#include <osquery/tables.h>
#include "osquery/tables/system/freebsd/procstat.h"
namespace osquery {
namespace tables {
// Heavily inspired by procstat(1) on FreeBSD.
std::pair<std::string, int>& sockaddr_to_pair(struct sockaddr_storage* sstor) {
char buffer[INET6_ADDRSTRLEN] = {0};
struct sockaddr_in6* sin6 = nullptr;
struct sockaddr_in* sin = nullptr;
struct sockaddr_un* sun = nullptr;
static std::pair<std::string, int> addr;
switch (sstor->ss_family) {
case AF_LOCAL:
sun = (struct sockaddr_un*) sstor;
addr = std::make_pair(std::string(sun->sun_path), 0);
break;
case AF_INET:
sin = (struct sockaddr_in*) sstor;
addr = std::make_pair(std::string(inet_ntoa(sin->sin_addr)),
ntohs(sin->sin_port));
break;
case AF_INET6:
sin6 = (struct sockaddr_in6*) sstor;
inet_ntop(AF_INET6, &sin6->sin6_addr, buffer, sizeof(buffer));
addr = std::make_pair(std::string(buffer), ntohs(sin6->sin6_port));
break;
default:
addr = std::make_pair(std::string(""), 0);
break;
}
return addr;
}
void genSockets(struct procstat* pstat,
struct kinfo_proc* proc,
QueryData &results) {
Row r;
struct filestat_list* files = nullptr;
struct filestat* file = nullptr;
struct sockstat sock;
int error;
std::pair<std::string, int> addr;
files = procstat_getfiles(pstat, proc, 0);
if (files == nullptr) {
return;
}
STAILQ_FOREACH(file, files, next) {
// Skip files that aren't sockets.
if (file->fs_type != PS_FST_TYPE_SOCKET) {
continue;
}
error = procstat_get_socket_info(pstat, file, &sock, nullptr);
if (error != 0) {
continue;
}
r["pid"] = INTEGER(proc->ki_pid);
r["socket"] = INTEGER(file->fs_fd);
r["family"] = INTEGER(sock.dom_family);
r["protocol"] = INTEGER(sock.proto);
addr = sockaddr_to_pair(&(sock.sa_local));
r["local_address"] = TEXT(addr.first);
r["local_port"] = INTEGER(addr.second);
addr = sockaddr_to_pair(&(sock.sa_peer));
r["remote_address"] = TEXT(addr.first);
r["remote_port"] = INTEGER(addr.second);
results.push_back(r);
}
procstat_freefiles(pstat, files);
}
QueryData genOpenSockets(QueryContext &context) {
QueryData results;
struct kinfo_proc* procs = nullptr;
struct procstat* pstat = nullptr;
auto cnt = getProcesses(context, &pstat, &procs);
for (size_t i = 0; i < cnt; i++) {
genSockets(pstat, &procs[i], results);
}
procstatCleanup(pstat, procs);
return results;
}
}
}
| 25.785124
| 79
| 0.651603
|
justintime32
|
520d63ac5a9f0ad6cf20aa36965bdc7667a1d450
| 591
|
cxx
|
C++
|
src/ase/ase_clipper.cxx
|
ascottix/tickle
|
de3b7df8a6e719b7682398ac689a7e439b40876f
|
[
"MIT"
] | 1
|
2021-05-31T21:09:50.000Z
|
2021-05-31T21:09:50.000Z
|
src/ase/ase_clipper.cxx
|
ascottix/tickle
|
de3b7df8a6e719b7682398ac689a7e439b40876f
|
[
"MIT"
] | null | null | null |
src/ase/ase_clipper.cxx
|
ascottix/tickle
|
de3b7df8a6e719b7682398ac689a7e439b40876f
|
[
"MIT"
] | null | null | null |
/*
Analog sound emulation library
Copyright (c) 2004 Alessandro Scotti
*/
#include "ase_clipper.h"
AClipperLo::AClipperLo( AChannel & source, AFloat lo )
: AFilter( source )
{
lo_ = lo;
}
void AClipperLo::updateBuffer( AFloat * buf, unsigned len, unsigned ofs )
{
source().updateTo( ofs );
AFloat * src = source().stream() + streamSize();
while( len > 0 ) {
if( *src >= lo_ ) {
*buf = *src;
}
else {
*buf = 0;
}
src++;
buf++;
len--;
}
}
| 16.885714
| 74
| 0.475465
|
ascottix
|
52102183aa06b2d9536db606b5a190c9c907d955
| 7,608
|
cpp
|
C++
|
src/Modules/Perception/Ball/BallDetector.cpp
|
pedrohsreis/Mari
|
ef0e0f3ffbecdeb49e8238df9795f4a07b84ad8b
|
[
"MIT"
] | null | null | null |
src/Modules/Perception/Ball/BallDetector.cpp
|
pedrohsreis/Mari
|
ef0e0f3ffbecdeb49e8238df9795f4a07b84ad8b
|
[
"MIT"
] | null | null | null |
src/Modules/Perception/Ball/BallDetector.cpp
|
pedrohsreis/Mari
|
ef0e0f3ffbecdeb49e8238df9795f4a07b84ad8b
|
[
"MIT"
] | null | null | null |
#include "Core/Utils/Math.h"
#include "BallDetector.h"
#include "Core/InitManager.h"
#include "Core/Utils/RobotDefs.h"
#include "Core/Utils/RelativeCoord.h"
#include "Core/Utils/CombinedCamera.hpp"
#include "perception/vision/CameraToRR.hpp"
#include "perception/vision/WhichCamera.hpp"
#define R 2.0f
#define PI_2 1.5707963267f
#define TICK_TIME 30
using namespace cv;
BallDetector::BallDetector(SpellBook *spellBook)
: InnerModule(spellBook)
{
if(cascade.load("/home/nao/data/vision/cascade.xml"))
cout << "Cascade file loaded" << endl;
else
cout << "Cascade file not found" << endl;
targetYaw = 0;
targetPitch = 0;
method = CASCADE;
}
void BallDetector::Tick(float ellapsedTime, CameraFrame &top, CameraFrame &bottom, cv::Mat &combinedImage)
{
spellBook->perception.vision.BGR = true;
spellBook->perception.vision.HSV = true;
spellBook->perception.vision.GRAY = true;
bool detected = false;
switch(method)
{
case CASCADE:
detected = CascadeMethod(top, bottom);
break;
case GEOMETRIC:
detected = GeometricMethod(top, bottom);
break;
case NEURAL:
detected = NeuralMethod(top, bottom);
break;
default:
break;
}
spellBook->perception.vision.ball.ImageX = ball.x;
spellBook->perception.vision.ball.ImageY = ball.y;
spellBook->perception.vision.ball.BallDetected = detected;
if(detected)
{
spellBook->perception.vision.ball.BallLostCount = 0;
Blackboard *blackboard = InitManager::GetBlackboard();
SensorValues sensor = readFrom(motion, sensors);
float currHeadYaw = sensor.joints.angles[Joints::HeadYaw];
float currHeadPitch = sensor.joints.angles[Joints::HeadPitch];
RelativeCoord rr;
rr.fromPixel(ball.x, ball.y, currHeadYaw, currHeadPitch);
spellBook->perception.vision.ball.BallYaw = rr.getYaw();
spellBook->perception.vision.ball.BallDistance = rr.getDistance();
spellBook->perception.vision.ball.BallPitch = rr.getPitch();
float CONSTANT_X = (float)CAM_BALL_W / H_DOF;
float xDiff = -(ball.x - (CAM_BALL_W / 2)) / CONSTANT_X;
spellBook->perception.vision.ball.HeadYaw = xDiff - currHeadYaw;
float CONSTANT_Y = (float)CAM_BALL_H / V_DOF;
float yDiff = (ball.y - (CAM_BALL_H / 2)) / CONSTANT_Y;
spellBook->perception.vision.ball.HeadPitch = yDiff - currHeadPitch;
cout << rr.getDistance() << "m, " << Rad2Deg(rr.getYaw()) << "º" << endl;
}
else
spellBook->perception.vision.ball.BallLostCount++;
cout << "Encontrado: " << detected << endl;
/*
if(!detected)
{
//cout << "Not found" << endl;
spellBook->perception.vision.ball.BallDetected = false;
spellBook->perception.vision.ball.TimeSinceBallSeen += ellapsedTime;
spellBook->perception.vision.ball.HeadRelative = true;
spellBook->perception.vision.ball.BallYaw = 0;
spellBook->perception.vision.ball.BallPitch = 0;
if(spellBook->perception.vision.ball.TimeSinceBallSeen > 1.0f)
{
targetPitch = 0.0f;
targetYaw = 0.0f;
speed = 0.25f;
spellBook->perception.vision.ball.HeadRelative = false;
spellBook->perception.vision.ball.BallYaw = 0;
spellBook->perception.vision.ball.BallPitch = 0;
spellBook->perception.vision.ball.BallDistance = 0.0f;
spellBook->perception.vision.ball.HeadSpeed = speed;
}
}
else
{
Blackboard *blackboard = InitManager::GetBlackboard();
SensorValues sensor = readFrom(kinematics, sensorsLagged);
float currHeadYaw = sensor.joints.angles[Joints::HeadYaw];
float currHeadPitch = sensor.joints.angles[Joints::HeadPitch];
RelativeCoord ballPosRR;
//ballPosRR.fromPixel(ball.x, ball.y, currHeadYaw, currHeadPitch);
ballPosRR.fromPixel(ball.x, ball.y);
targetYaw = ballPosRR.getYaw();
//targetPitch = ballPosRR.getPitch();
distance = ballPosRR.getDistance();
if(distance > 1.0f)
targetPitch = 0.0f;
else
targetPitch = Deg2Rad(17.0f);
float factor = abs(targetYaw) / (float)H_FOV;
speed = 0.25f * factor;
cout << "Found: " << ball.x << ", " << ball.y << " [ " << ball.radius << " ] | [" << Rad2Deg(targetYaw) << "º, " << Rad2Deg(ballPosRR.getPitch()) << "º] " << distance << "m | " << speed << endl;
spellBook->perception.vision.ball.BallDetected = true;
spellBook->perception.vision.ball.HeadRelative = true;
spellBook->perception.vision.ball.BallYaw = -targetYaw;
spellBook->perception.vision.ball.BallPitch = targetPitch;
spellBook->perception.vision.ball.BallDistance = distance;
spellBook->perception.vision.ball.TimeSinceBallSeen = 0.0f;
spellBook->perception.vision.ball.HeadSpeed = speed;
}
*/
}
bool BallDetector::CascadeMethod(CameraFrame &top, CameraFrame &bottom)
{
vector<Rect> balls;
//cv::Mat hist;
cv::Mat mask;
//cv::equalizeHist(bottom.GRAY, hist);
inRange(bottom.HSV, Scalar(56, 102, 25), Scalar(116, 255, 255), mask);
cascade.detectMultiScale(bottom.GRAY, balls, 2, 1, 0, Size(16, 16));
//cascade.detectMultiScale(hist, balls, 1.3, 5, 8, Size(16, 16));
//cascade.detectMultiScale(gray, balls, 1.1, 5, 8, cv::Size(16, 16));
if (balls.size() == 0)
return false;
double melhorRaio;
double melhorConfidence = -1; // -1 ele continuar mostrando todos candidatos, =0
cv::Point melhorPt;
int step = 10;
double x;
double y;
double raio2;
for (int j = 0; j < balls.size(); j++)
{
double raio = balls[j].width / 2.0;
cv::Point pt(balls[j].x + raio, balls[j].y + raio);
raio2 = raio * 1.2;
double confidence = 0;
// quantos dos pontos analisados tem a cor verde (a cor branca da mask)
int contverde = 0;
//i++ e i+=10 tem diferenca, com ++ eu analizo 360 pontos e com 10, 10 ptos
for (int i = 0; i < 360; i += step)
{
//conversao para de grau p rad 0.0174532 = pi/180
x = raio2 * cos(i * 0.0174532) + pt.x;
y = raio2 * sin(i * 0.0174532) + pt.y;
if (mask.at<uchar>((int)y, (int)x) > 0)
{
contverde++;
}
}
//calculo de confianca no valor de acordo com o parametro (a quantidade de verde, só que é branco pela mask)
confidence = contverde / (360.0 / step);
if (confidence > melhorConfidence)
{
melhorConfidence = confidence;
melhorRaio = raio;
melhorPt = pt;
}
}
if (melhorConfidence <= 0)
{
//cout << "seria uma bola?" << "\t" << melhorConfidence << endl;
return false;
}
//cout << "Encontrado: " << melhorPt << " [ " << melhorRaio << " ] " << "\t" << (melhorConfidence * 100) << "%" << endl;
ball.radius = melhorRaio;
ball.x = melhorPt.x;
ball.y = melhorPt.y;
return true;
}
cv::RNG rng(12345);
bool BallDetector::GeometricMethod(CameraFrame &top, CameraFrame &bottom)
{
cv::Scalar low(0, 0, 0);
cv::Scalar high(180, 255, 140);
cv::Mat black;
cv::inRange(bottom.HSV, low, high, black);
cv::imshow("black", black);
return false;
}
bool BallDetector::NeuralMethod(CameraFrame &top, CameraFrame &bottom)
{
return false;
}
| 34.116592
| 202
| 0.609227
|
pedrohsreis
|
5217fc0a461cc8563efffd81a3cf645cc05193df
| 7,461
|
cpp
|
C++
|
src/Visuals/UI/ui-renderer.cpp
|
LazyFalcon/GameConcept-v1
|
e0259d683bb711921d068924de1aa1c30c00db4d
|
[
"MIT"
] | null | null | null |
src/Visuals/UI/ui-renderer.cpp
|
LazyFalcon/GameConcept-v1
|
e0259d683bb711921d068924de1aa1c30c00db4d
|
[
"MIT"
] | null | null | null |
src/Visuals/UI/ui-renderer.cpp
|
LazyFalcon/GameConcept-v1
|
e0259d683bb711921d068924de1aa1c30c00db4d
|
[
"MIT"
] | null | null | null |
#include "core.hpp"
#include "ui-renderer.hpp"
#include "ui-rendered.hpp"
#include "ui-text.hpp"
#include "Context.hpp"
#include "Assets.hpp"
#include "PerfTimers.hpp"
void UIRender::blurBackgroundCumulative(RenderedUIItems&){}
void UIRender::blurBackgroundEven(RenderedUIItems& ui){
auto& polygons = ui.get<RenderedUIItems::ToBlur>();
m_context.shape.quadCorner.bind().attrib(0).pointer_float(4).divisor(0);
// first pass
m_context.fbo[HALF].tex(m_context.tex.half.a)();
auto shader = assets::bindShader("blur-horizontal");
shader.uniform("pxViewSize", m_window.size*0.5f);
shader.uniform("uTexelSize", m_window.pixelSize*2.f);
shader.texture("uTexture", m_context.tex.ui, 0);
for(auto& poly : polygons){
shader.uniform("pxBlurPolygon", poly.poly*0.5f);
gl::DrawArrays(gl::TRIANGLE_STRIP, 0, 4);
}
m_context.fbo[HALF].tex(m_context.tex.half.b)();
shader = assets::bindShader("blur-vertical");
shader.uniform("pxViewSize", m_window.size*0.5f);
shader.uniform("uTexelSize", m_window.pixelSize*2.f);
shader.texture("uTexture", m_context.tex.half.a, 0);
for(auto& poly : polygons){
shader.uniform("pxBlurPolygon", poly.poly*0.5f);
gl::DrawArrays(gl::TRIANGLE_STRIP, 0, 4);
}
shader = assets::bindShader("copy-rect");
m_context.fbo[UI].tex(m_context.tex.full.a)();
shader.uniform("pxViewSize", m_window.size);
shader.texture("uTexture", m_context.tex.half.b, 0);
for(auto& poly : polygons){
shader.uniform("pxCopyPolygon", poly.poly);
gl::DrawArrays(gl::TRIANGLE_STRIP, 0, 4);
}
polygons.clear();
m_context.errors();
}
void UIRender::depthPrepass(RenderedUIItems& ui){
m_context.fbo[UI].tex(m_context.tex.depth)();
gl::ClearDepth(1);
gl::Clear(gl::DEPTH_BUFFER_BIT);
gl::DepthMask(gl::TRUE_);
gl::Enable(gl::DEPTH_TEST);
gl::DepthFunc(gl::LEQUAL);
gl::DepthRange(0.0f, 1.0f);
gl::Disable(gl::BLEND);
auto& backgrounds = ui.get<RenderedUIItems::Background>();
std::sort(backgrounds.begin(), backgrounds.end(), [](const auto& a, const auto& b){return a.depth < b.depth;});
auto shader = assets::getShader("ui-panel-background-depth");
shader.bind();
shader.uniform("uWidth", m_window.size.x);
shader.uniform("uHeight", m_window.size.y);
m_context.shape.quadCorner.bind().attrib(0).pointer_float(4).divisor(0);
m_context.getRandomBuffer().update(backgrounds)
.attrib(1).pointer_float(4, sizeof(RenderedUIItems::Background), (void*)offsetof(RenderedUIItems::Background, box)).divisor(1)
.attrib(2).pointer_float(1, sizeof(RenderedUIItems::Background), (void*)offsetof(RenderedUIItems::Background, texture)).divisor(1)
.attrib(3).pointer_float(1, sizeof(RenderedUIItems::Background), (void*)offsetof(RenderedUIItems::Background, depth)).divisor(1)
.attrib(4).pointer_color(sizeof(RenderedUIItems::Background), (void*)offsetof(RenderedUIItems::Background, color)).divisor(1);
gl::DrawArraysInstanced(gl::TRIANGLE_STRIP, 0, 4, backgrounds.size());
m_context.errors();
}
template<>
void UIRender::render(std::vector<RenderedUIItems::Background>& backgrounds){
auto shader = assets::getShader("ui-panel-background");
shader.bind();
shader.uniform("uWidth", m_window.size.x);
shader.uniform("uHeight", m_window.size.y);
gl::DrawArraysInstanced(gl::TRIANGLE_STRIP, 0, 4, backgrounds.size());
m_context.errors();
gl::BindBuffer(gl::ARRAY_BUFFER, 0);
gl::DisableVertexAttribArray(1);
gl::DisableVertexAttribArray(2);
gl::DisableVertexAttribArray(3);
gl::DisableVertexAttribArray(4);
backgrounds.clear();
}
template<>
void UIRender::render(std::vector<RenderedUIItems::ColoredBox>& coloredBoxes){
auto shader = assets::getShader("ui-panel-coloredPolygon");
shader.bind();
shader.uniform("uWidth", m_window.size.x);
shader.uniform("uHeight", m_window.size.y);
m_context.shape.quadCorner.bind().attrib(0).pointer_float(4).divisor(0);
m_context.getRandomBuffer().update(coloredBoxes)
.attrib(1).pointer_float(4, sizeof(RenderedUIItems::ColoredBox), (void*)offsetof(RenderedUIItems::ColoredBox, box)).divisor(1)
.attrib(2).pointer_float(1, sizeof(RenderedUIItems::ColoredBox), (void*)offsetof(RenderedUIItems::ColoredBox, depth)).divisor(1)
.attrib(3).pointer_color(sizeof(RenderedUIItems::ColoredBox), (void*)offsetof(RenderedUIItems::ColoredBox, color)).divisor(1);
gl::DrawArraysInstanced(gl::TRIANGLE_STRIP, 0, 4, coloredBoxes.size());
m_context.errors();
gl::BindBuffer(gl::ARRAY_BUFFER, 0);
gl::DisableVertexAttribArray(1);
gl::DisableVertexAttribArray(2);
gl::DisableVertexAttribArray(3);
gl::DisableVertexAttribArray(4);
coloredBoxes.clear();
}
template<>
void UIRender::render(std::vector<Text::Rendered>& text){
auto shader = assets::getShader("ui-text");
shader.bind();
shader.uniform("uFrameSize", m_window.size);
shader.atlas("uTexture", assets::getAtlas("Fonts").id);
m_context.shape.quadCorner.bind().attrib(0).pointer_float(4).divisor(0);
m_context.getRandomBuffer().update(text)
.attrib(1).pointer_float(4, sizeof(Text::Rendered), (void*)offsetof(Text::Rendered, polygon)).divisor(1)
.attrib(2).pointer_float(3, sizeof(Text::Rendered), (void*)offsetof(Text::Rendered, uv)).divisor(1)
.attrib(3).pointer_float(2, sizeof(Text::Rendered), (void*)offsetof(Text::Rendered, uvSize)).divisor(1)
.attrib(4).pointer_float(1, sizeof(Text::Rendered), (void*)offsetof(Text::Rendered, depth)).divisor(1)
.attrib(5).pointer_color(sizeof(Text::Rendered), (void*)offsetof(Text::Rendered, color)).divisor(1);
gl::DrawArraysInstanced(gl::TRIANGLE_STRIP, 0, 4, text.size()); // TODO: check if simple draw arrays wouldn't be faster
m_context.errors();
gl::BindBuffer(gl::ARRAY_BUFFER, 0);
gl::DisableVertexAttribArray(1);
gl::DisableVertexAttribArray(2);
gl::DisableVertexAttribArray(3);
gl::DisableVertexAttribArray(4);
gl::DisableVertexAttribArray(5);
text.clear();
}
void UIRender::render(RenderedUIItems& ui){
// auto fullA = m_context.tex.full.a.acquire();
// auto depth = m_context.tex.gbuffer.depth.acquire();
m_context.defaultVAO.bind();
// for all renderable objects(polygons) render depth
depthPrepass(ui);
gl::DepthMask(gl::FALSE_);
gl::Disable(gl::DEPTH_TEST);
m_context.fbo[UI].tex(m_context.tex.ui).tex(m_context.tex.depth)();
gl::ClearColor(0.f, 0.f, 0.f, 0.f);
gl::Clear(gl::COLOR_BUFFER_BIT);
blurBackgroundEven(ui);
m_context.fbo[UI].tex(m_context.tex.ui).tex(m_context.tex.depth)();
gl::Enable(gl::BLEND);
gl::BlendFunc(gl::ONE, gl::ONE_MINUS_SRC_ALPHA);
// render panel backgrounds, sorted, without depth test
render(ui.get<RenderedUIItems::Background>());
gl::Enable(gl::DEPTH_TEST);
// render as-is with depth enabled
render(ui.get<RenderedUIItems::ColoredBox>());
// render the rest with depth test
render(ui.get<Text::Rendered>());
m_context.fbo[UI].tex(m_context.tex.view)();
gl::Disable(gl::DEPTH_TEST);
gl::Enable(gl::BLEND);
gl::BlendFunc(gl::SRC_ALPHA, gl::ONE_MINUS_SRC_ALPHA);
auto shader = assets::getShader("ApplyFBO");
shader.bind();
shader.texture("uTexture", m_context.tex.ui);
m_context.drawScreen();
}
| 36.395122
| 138
| 0.690256
|
LazyFalcon
|
521aa5d945355020eebcbaa89883df77510346fb
| 15,542
|
hh
|
C++
|
dune/xt/common/print.hh
|
dune-community/dune-xt
|
da921524c6fff8d60c715cb4849a0bdd5f020d2b
|
[
"BSD-2-Clause"
] | 2
|
2020-02-08T04:08:52.000Z
|
2020-08-01T18:54:14.000Z
|
dune/xt/common/print.hh
|
dune-community/dune-xt
|
da921524c6fff8d60c715cb4849a0bdd5f020d2b
|
[
"BSD-2-Clause"
] | 35
|
2019-08-19T12:06:35.000Z
|
2020-03-27T08:20:39.000Z
|
dune/xt/common/print.hh
|
dune-community/dune-xt
|
da921524c6fff8d60c715cb4849a0bdd5f020d2b
|
[
"BSD-2-Clause"
] | 1
|
2020-02-08T04:09:34.000Z
|
2020-02-08T04:09:34.000Z
|
// This file is part of the dune-xt project:
// https://zivgitlab.uni-muenster.de/ag-ohlberger/dune-community/dune-xt
// Copyright 2009-2021 dune-xt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
// or GPL-2.0+ (http://opensource.org/licenses/gpl-license)
// with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
// Felix Schindler (2010, 2012 - 2017, 2020)
// René Fritze (2009 - 2016, 2018 - 2020)
// Sven Kaulmann (2011 - 2012)
// Tobias Leibner (2014, 2018, 2020)
#ifndef DUNE_XT_COMMON_PRINT_HH
#define DUNE_XT_COMMON_PRINT_HH
#include <iostream>
#include <string>
#include <utility>
#include <dune/xt/common/configuration.hh>
#include <dune/xt/common/filesystem.hh>
#include <dune/xt/common/parameter.hh>
#include <dune/xt/common/ranges.hh>
#include <dune/xt/common/string.hh>
#include <dune/xt/common/vector.hh>
#include <dune/xt/common/type_traits.hh>
namespace Dune::XT::Common {
// forward declarations
template <class T, bool use_repr = false, typename anything = void>
class Printer;
template <class T>
Printer<T, false> print(const T& /*value*/, const Configuration& /*param*/ = {});
namespace internal {
/// \note Should be used to derive from (except for vectors and matrices), when specializing Printer.
/// \todo Drop silenced warnings once all operator<< overloads in dune-xt and dune-gdt which are deprecated due to this
/// DefaultPrinter are removed!
/// \sa Printer
/// \sa VectorPrinter
template <class T, bool use_repr = false>
class DefaultPrinter
{
using ThisType = DefaultPrinter;
public:
using ValueType = T;
const ValueType& value;
const Configuration opts;
DefaultPrinter(const ValueType& val, const Configuration& cfg)
: value(val)
, opts(cfg)
{}
DefaultPrinter(const ThisType&) = default;
DefaultPrinter(ThisType&&) = default;
virtual ~DefaultPrinter() = default;
virtual void repr(std::ostream& out) const
{
if constexpr (is_printable<T>::value) {
// There are some of our operator<< overloads that are deprecated due to the introduction of this Printer.
#include <dune/xt/common/disable_warnings.hh>
out << value;
#include <dune/xt/common/reenable_warnings.hh>
} else {
out << "missing specialization for Printer<T> with T=" << Typename<T>::value();
}
}
virtual void str(std::ostream& out) const
{
this->repr(out);
}
void print(std::ostream& out) const
{
if (use_repr)
this->repr(out);
else
this->str(out);
}
}; // class DefaultPrinter
/// \note Should be used to derive from when specializing Printer for vectors.
/// \sa Printer
/// \sa DefaultPrinter
template <class T, bool use_repr>
class VectorPrinter : public internal::DefaultPrinter<T, use_repr>
{
public:
const std::string class_name;
VectorPrinter(const T& val, const Configuration& cfg = {}, std::string clss_nm = Typename<T>::value())
: internal::DefaultPrinter<T, use_repr>(val, cfg)
, class_name(std::move(clss_nm))
{}
void repr(std::ostream& out) const override
{
out << class_name << "(";
const auto sz = this->value.size();
if (sz > 0) {
const std::string delim =
(std::use_facet<std::numpunct<char>>(std::cout.getloc()).decimal_point() == ',') ? ";" : ",";
out << "{" << print(this->value[0], this->opts) /*V::get_entry(this->value, 0)*/;
for (auto&& ii : value_range(decltype(sz)(1), sz))
out << delim << " " << print(this->value[ii], this->opts) /*V::get_entry(this->value, ii)*/;
out << "}";
}
out << ")";
} // ... repr(...)
void str(std::ostream& out) const override
{
const auto sz = this->value.size();
if (sz == 0)
out << "[]";
else {
const std::string delim =
(std::use_facet<std::numpunct<char>>(std::cout.getloc()).decimal_point() == ',') ? ";" : ",";
out << "[" << print(this->value[0], this->opts) /*V::get_entry(this->value, 0)*/;
for (auto&& ii : value_range(decltype(sz)(1), sz))
out << delim << " " << print(this->value[ii], this->opts) /*V::get_entry(this->value, ii)*/;
out << "]";
}
} // ... str(...)
}; // class VectorPrinter
/// \note Should be used to derive from when specializing Printer for matrices.
/// \sa Printer
/// \sa DefaultPrinter
template <class T, bool use_repr>
class MatrixPrinter : public internal::DefaultPrinter<T, use_repr>
{
static_assert(is_matrix<T>::value);
using M = MatrixAbstraction<T>;
public:
const std::string class_name;
MatrixPrinter(const T& val, const Configuration& cfg = {}, std::string clss_nm = Typename<T>::value())
: internal::DefaultPrinter<T, use_repr>(val, cfg)
, class_name(std::move(clss_nm))
{}
void repr(std::ostream& out) const override
{
out << class_name << "(";
const auto rows = M::rows(this->value);
const auto cols = M::cols(this->value);
if (rows * cols > 0) {
out << "[";
const std::string delim =
(std::use_facet<std::numpunct<char>>(std::cout.getloc()).decimal_point() == ',') ? ";" : ",";
const std::string newline = "\n";
for (auto&& ii : value_range(rows)) {
out << (ii == 0 ? "[" : " ") << "[" << print(M::get_entry(this->value, ii, 0), this->opts);
for (auto&& jj : value_range(decltype(cols)(1), cols))
out << delim << " " << print(M::get_entry(this->value, ii, jj), this->opts);
out << "]" << ((ii == rows - 1) ? "" : ",") << ((ii == rows - 1) ? "" : newline);
}
out << "]";
}
out << ")";
} // ... repr(...)
void str(std::ostream& out) const override
{
const auto rows = M::rows(this->value);
const auto cols = M::cols(this->value);
out << "[";
if (rows * cols > 0) {
const std::string delim =
(std::use_facet<std::numpunct<char>>(std::cout.getloc()).decimal_point() == ',') ? ";" : ",";
const std::string newline = this->opts.get("oneline", false) ? "" : "\n";
for (auto&& ii : value_range(rows)) {
out << (ii == 0 ? "" : " ") << "[" << print(M::get_entry(this->value, ii, 0), this->opts);
for (auto&& jj : value_range(decltype(cols)(1), cols))
out << delim << " " << print(M::get_entry(this->value, ii, jj), this->opts);
out << "]" << ((ii == rows - 1) ? "" : ",") << ((ii == rows - 1) ? "" : newline);
}
}
out << "]";
} // ... str(...)
}; // class MatrixPrinter
} // namespace internal
/**
* \brief Specialize this class for your type to benefit from the print() and repr() functions.
*
* Any specialization of Printer is expected to have the following print() method
<code>
void print(std::ostream& out) const
{
if (use_repr)
this->repr(out);
else
this->str(out);
}
</code>
* the behaviour of which is supposed to change with use_repr. A possible implemenation is given in
* internal::DefaultPrinter, based on the following two methods:
<code>
void repr(std::ostream& out) const
{
out << "detailed and unambiguous description";
}
void str(std::ostream& out) const
{
out << "compact and readabale description";
}
</code>
* It is therefore recommended to derive from internal::DefaultPrinter or internal::VectorPrinter, where some of this
* is already provided.
*
* Similar to python, one can use repr(obj) to obtain an unambigous representation of obj (with as much detail as
* possible), while print(obj) mimics Pythons __str__ to obtain a compact and readable representation of obj.
*
* \sa internal::DefaultPrinter
* \sa print
* \sa repr
*/
template <class T, bool use_repr, typename anything>
class Printer : public internal::DefaultPrinter<T, use_repr>
{
public:
Printer(const T& val, const Configuration& param = {})
: internal::DefaultPrinter<T, use_repr>(val, param)
{}
};
/// Specialization of Printer for all our vectors
template <class V, bool use_repr>
class Printer<V, use_repr, std::enable_if_t<is_vector<V>::value>> : public internal::VectorPrinter<V, use_repr>
{
public:
Printer(const V& val, const Configuration& param)
: internal::VectorPrinter<V, use_repr>(val, param)
{}
}; // class Printer
/// Specialization of Printer for all our matrices
template <class M, bool use_repr>
class Printer<M, use_repr, std::enable_if_t<is_matrix<M>::value>> : public internal::MatrixPrinter<M, use_repr>
{
public:
Printer(const M& val, const Configuration& param = {{"oneline", "false"}})
: internal::MatrixPrinter<M, use_repr>(val, param)
{}
}; // class Printer
template <bool use_repr, typename anything>
class Printer<Configuration, use_repr, anything> : public internal::DefaultPrinter<Configuration, use_repr>
{
public:
Printer(const Configuration& val, const Configuration& param = {{"oneline", "false"}})
: internal::DefaultPrinter<Configuration, use_repr>(val, param)
{}
// let repr() default to operator<<, handled in internal::DefaultPrinter
void str(std::ostream& out) const override
{
if (!this->opts.get("oneline", false))
this->repr(out);
else {
const auto key_value_map = this->value.flatten();
const auto sz = key_value_map.size();
if (sz == 0)
out << "{}";
else {
out << "{";
size_t counter = 0;
for (const auto& key_value_pair : key_value_map) {
out << "\"" << key_value_pair.first << "\": \"" << key_value_pair.second << "\"";
if (counter < sz - 1)
out << ", ";
++counter;
}
out << "}";
}
}
} // ... str(...)
}; // class Printer
template <bool use_repr, typename anything>
class Printer<ParameterType, use_repr, anything> : public internal::DefaultPrinter<ParameterType, use_repr>
{
public:
Printer(const ParameterType& val, const Configuration& param = {})
: internal::DefaultPrinter<ParameterType, use_repr>(val, param)
{}
void repr(std::ostream& out) const override
{
out << "ParameterType(";
this->str(out);
out << ")";
}
void str(std::ostream& out) const override
{
const auto sz = this->value.size();
if (sz == 0)
out << "{}";
else {
out << "{";
size_t counter = 0;
for (const auto& key : this->value.keys()) {
out << key << ": " << this->value.get(key);
if (counter < sz - 1)
out << ", ";
++counter;
}
out << "}";
}
} // ... str(...)
}; // class Printer
template <bool use_repr, typename anything>
class Printer<Parameter, use_repr, anything> : public internal::DefaultPrinter<Parameter, use_repr>
{
public:
Printer(const Parameter& val, const Configuration& param = {})
: internal::DefaultPrinter<Parameter, use_repr>(val, param)
{}
void repr(std::ostream& out) const override
{
out << "Parameter(";
this->str(out);
out << ")";
}
void str(std::ostream& out) const override
{
const auto sz = this->value.size();
if (sz == 0)
out << "{}";
else {
out << "{";
size_t counter = 0;
for (const auto& key : this->value.keys()) {
out << key << ": " << print(this->value.get(key));
if (counter < sz - 1)
out << ", ";
++counter;
}
out << "}";
}
} // ... str(...)
}; // class Printer
/// \sa Printer
template <class T, bool use_repr>
std::ostream& operator<<(std::ostream& out, const Printer<T, use_repr>& printer)
{
printer.print(out);
return out;
}
/**
* The purpose of print(obj) is to provide a flexible and customizable means of modifying the behaviour of printing an
* object to a stream, without conflicting with implementations of operator<< for obj, which are often beyond the reach
* of the user. Can be used as in:
<code>
std::cout << print(complicated_object, {"tabular", "true"}) << std::endl;
</code>
* The output can be determined by specializing Printer<TypeOfComplicatedObject>, which keeps a reference to
* complicated_object and a Configuration({"tabular", "true"}), which can be used by the implementor to customize the
* output. Defaults to
<code>
std::cout << complicated_object << std::endl;
</code>
* if operator<< is available for complicated_object and no specialization of Printer is found.
*
* \sa Printer
* \sa repr
*/
template <class T>
Printer<T, false> print(const T& value, const Configuration& param)
{
return Printer<T, false>(value, param);
}
/**
* The purpose of repr(obj) is to provide a flexible and customizable means of modifying the behaviour of printing an
* object to a stream, without conflicting with implementations of operator<< for obj, which are often beyond the reach
* of the user. Can be used as in:
<code>
std::cout << print(complicated_object, {"tabular", "true"}) << std::endl;
</code>
* The output can be determined by specializing Printer<TypeOfComplicatedObject>, which keeps a reference to
* complicated_object and a Configuration({"tabular", "true"}), which can be used by the implementor to customize the
* output. Defaults to
<code>
std::cout << complicated_object << std::endl;
</code>
* if operator<< is available for complicated_object and no specialization of Printer is found.
*
* \sa Printer
* \sa print
*/
template <class T>
Printer<T, true> repr(const T& value, const Configuration& param = {})
{
return Printer<T, true>(value, param);
}
//! useful for visualizing sparsity patterns of matrices
template <class Matrix>
void matrix_to_gnuplot_stream(const Matrix& matrix, std::ostream& stream)
{
unsigned long nz = 0;
const auto cols = matrix.cols();
for (auto row : value_range(matrix.rows())) {
for (auto col : value_range(cols)) {
if (matrix.find(row, col))
stream << row << "\t" << col << "\t" << matrix(row, col) << "\n";
}
nz += matrix.numNonZeros(row);
stream << "#non zeros in row " << row << " " << matrix.numNonZeros(row) << " (of " << matrix.cols() << " cols)\n";
}
stream << "#total non zeros " << nz << " of " << matrix.rows() * matrix.cols() << " entries\n";
} // matrix_to_gnuplot_stream
//! maps 1,2,3 to x,y,z / X,Y,Z
inline std::string dim_to_axis_name(const size_t dim, const bool capitalize = false)
{
const size_t capitals_count{32};
char c = 'x';
c += dim;
if (capitalize)
c -= capitals_count;
return std::string() += c;
} // matrix_to_gnuplot_stream
/** Outputiterator to emulate python's str.join(iterable)
* \see http://codereview.stackexchange.com/questions/30132/comma-formatted-stl-vectors/30181#30181
* \example std::copy(strings.begin(), strings.end(), PrefixOutputIterator<string>(ostream, ","));
**/
template <typename T>
class PrefixOutputIterator
{
std::ostream& ostream;
std::string prefix;
bool first;
public:
using difference_type = std::size_t;
using value_type = T;
using pointer = T*;
using reference = T;
using iterator_category = std::output_iterator_tag;
PrefixOutputIterator(std::ostream& o, std::string p = "")
: ostream(o)
, prefix(std::move(p))
, first(true)
{}
PrefixOutputIterator& operator*()
{
return *this;
}
PrefixOutputIterator& operator++()
{
return *this;
}
PrefixOutputIterator& operator++(int)
{
return *this;
}
void operator=(T const& value)
{
if (first) {
ostream << value;
first = false;
} else {
ostream << prefix << value;
}
}
}; // class PrefixOutputIterator
} // namespace Dune::XT::Common
#endif // DUNE_XT_COMMON_PRINT_HH
| 29.94605
| 119
| 0.630807
|
dune-community
|
521b87da1c5f8f186bc130458d9f0fc7d9fbfe31
| 3,060
|
cpp
|
C++
|
app/dtkComposerEvaluator/main.cpp
|
eti-nne/dtk
|
b5095c7a181e7497391a6a1fa0bb37e71dfa4b56
|
[
"BSD-3-Clause"
] | null | null | null |
app/dtkComposerEvaluator/main.cpp
|
eti-nne/dtk
|
b5095c7a181e7497391a6a1fa0bb37e71dfa4b56
|
[
"BSD-3-Clause"
] | null | null | null |
app/dtkComposerEvaluator/main.cpp
|
eti-nne/dtk
|
b5095c7a181e7497391a6a1fa0bb37e71dfa4b56
|
[
"BSD-3-Clause"
] | null | null | null |
/* main.cpp ---
*
* Author: Nicolas Niclausse
* Copyright (C) 2014 - Nicolas Niclausse, Inria.
* Created: 2014/10/28 12:45:34
*/
/* Commentary:
*
*/
/* Change log:
*
*/
#include <dtkDistributed>
#include <dtkComposer>
#include <QtConcurrent>
int main(int argc, char **argv)
{
bool useGUI = false;
QApplication application(argc, argv, useGUI);
application.setApplicationName("dtkComposerEvaluator");
application.setApplicationVersion("1.0.0");
application.setOrganizationName("inria");
application.setOrganizationDomain("fr");
// plugins
dtkDistributedSettings settings;
settings.beginGroup("communicator");
qDebug() << "initialize plugin manager "<< settings.value("plugins").toString();
dtkDistributed::communicator::pluginManager().initialize(settings.value("plugins").toString());
qDebug() << "initialization done ";
settings.endGroup();
qDebug() << dtkDistributed::communicator::pluginManager().plugins();
qDebug() << dtkDistributed::communicator::pluginFactory().keys();
QStringList args = QCoreApplication::arguments();
if(args.count() < 2) {
qDebug() << "argv" << args;
qDebug() << "Usage: " << argv[0] << "--spawn | [-pg] <composition> ";
return 0;
}
dtkComposerNodeFactory *factory = new dtkComposerNodeFactory;
if (args[1] == "--spawn") {
// FIXME: don't hardcode plugin
dtkDistributedPolicy policy;
dtkDistributedWorkerManager manager;
policy.setType("mpi3");
manager.setPolicy(&policy);
dtkComposerEvaluatorProcess p;
QStringList hosts;
// dtkDistributedCommunicator *comm = manager.spawn();
dtkDistributedCommunicator *comm ;
manager.spawn();
p.setInternalCommunicator(comm);
p.setParentCommunicator(policy.communicator());
p.setFactory(factory);
p.setApplication("dtkComposerEvaluator");
int value;
do { value = p.exec(); } while (value == 0);
return value;
}
dtkComposerScene *scene = new dtkComposerScene;
dtkComposerStack *stack = new dtkComposerStack;
dtkComposerGraph *graph = new dtkComposerGraph;
dtkComposerEvaluator *evaluator = new dtkComposerEvaluator;;
scene->setFactory(factory);
scene->setStack(stack);
scene->setGraph(graph);
evaluator->setGraph(graph);
dtkComposerReader *reader;
reader = new dtkComposerReader;
reader->setFactory(factory);
reader->setScene(scene);
reader->setGraph(graph);
int index= 1;
if (args[1] == "-pg") {
index = 2;
evaluator->setProfiling(true);
}
if (!reader->read(argv[index])) {
qDebug() << "read failure for " << argv[index];
return 1;
} else {
QObject::connect(evaluator,SIGNAL(evaluationStopped()),&application, SLOT(quit()));
QtConcurrent::run(evaluator, &dtkComposerEvaluator::run_static, false);
application.exec();
// dtkPluginManager::instance()->uninitialize();
}
}
| 25.714286
| 99
| 0.64183
|
eti-nne
|
5221453cc5dbbdcbea3d00ee268373a987dfb23a
| 2,437
|
cpp
|
C++
|
DemoGame/Game/Source/SceneGameplay.cpp
|
Omicrxn/Automated-Builds-CI-CD
|
5a3729854dc2716407939e831079737e45f5690a
|
[
"MIT"
] | null | null | null |
DemoGame/Game/Source/SceneGameplay.cpp
|
Omicrxn/Automated-Builds-CI-CD
|
5a3729854dc2716407939e831079737e45f5690a
|
[
"MIT"
] | null | null | null |
DemoGame/Game/Source/SceneGameplay.cpp
|
Omicrxn/Automated-Builds-CI-CD
|
5a3729854dc2716407939e831079737e45f5690a
|
[
"MIT"
] | 1
|
2021-04-18T06:49:36.000Z
|
2021-04-18T06:49:36.000Z
|
#include "SceneGameplay.h"
#include "EntityManager.h"
SceneGameplay::SceneGameplay()
{
}
SceneGameplay::~SceneGameplay()
{}
bool SceneGameplay::Load(Textures* tex) /*EntityManager entityManager)*/
{
map = new Map(tex);
// L03: DONE: Load map
// L12b: Create walkability map on map loading
if (map->Load("platformer.tmx") == true)
{
int w, h;
uchar* data = NULL;
//if (map->CreateWalkabilityMap(w, h, &data)) pathFinding->SetMap(w, h, data);
RELEASE_ARRAY(data);
}
// Load music
//AudioManager::PlayMusic("Assets/Audio/Music/music_spy.ogg");
// Load game entities
//Player* player = (Player*)entityManager->CreateEntity(EntityType::PLAYER);
//player->SetTexture(tex->Load("Assets/Textures/player.png"));
//entityManager->CreateEntity(EntityType::ENEMY);
//entityManager->CreateEntity(EntityType::ENEMY);
//entityManager->CreateEntity(EntityType::ITEM);
//entityManager->CreateEntity(EntityType::ITEM);
//entityManager->CreateEntity(EntityType::ITEM);
// Initialize player
player = new Player();
player->position = iPoint(200, 400);
return false;
}
inline bool CheckCollision(SDL_Rect rec1, SDL_Rect rec2)
{
if ((rec1.x < (rec2.x + rec2.w) && (rec1.x + rec1.w) > rec2.x) &&
(rec1.y < (rec2.y + rec2.h) && (rec1.y + rec1.h) > rec2.y)) return true;
else return false;
}
bool SceneGameplay::Update(Input *input, float dt)
{
// Collision detection: map vs player
iPoint tempPlayerPosition = player->position;
player->Update(input, dt);
// Check if updated player position collides with next tile
// IMPROVEMENT: Just check adyacent tiles to player
for (int y = 0; y < map->data.height; y++)
{
for (int x = 0; x < map->data.width; x++)
{
if ((map->data.layers[2]->Get(x, y) >= 484) &&
CheckCollision(map->GetTilemapRec(x, y), player->GetBounds()))
{
player->position = tempPlayerPosition;
player->jumpSpeed = 0.0f;
break;
}
}
}
if (input->GetKey(SDL_SCANCODE_D) == KeyState::KEY_UP) map->drawColliders = !map->drawColliders;
// L02: DONE 3: Request Load / Save when pressing L/S
//if (input->GetKey(SDL_SCANCODE_L) == KEY_DOWN) app->LoadGameRequest();
//if (input->GetKey(SDL_SCANCODE_S) == KEY_DOWN) app->SaveGameRequest();
return true;
}
bool SceneGameplay::Draw(Render* render)
{
// Draw map
map->Draw(render);
player->Draw(render);
return false;
}
bool SceneGameplay::Unload()
{
// TODO: Unload all resources
return false;
}
| 23.892157
| 97
| 0.679524
|
Omicrxn
|
522542f7607697d44e8b4d06978ea4968f4ad04f
| 1,210
|
hpp
|
C++
|
iOS/G3MApp/G3MApp/G3MRasterLayersDemoScene.hpp
|
AeroGlass/g3m
|
a21a9e70a6205f1f37046ae85dafc6e3bfaeb917
|
[
"BSD-2-Clause"
] | null | null | null |
iOS/G3MApp/G3MApp/G3MRasterLayersDemoScene.hpp
|
AeroGlass/g3m
|
a21a9e70a6205f1f37046ae85dafc6e3bfaeb917
|
[
"BSD-2-Clause"
] | null | null | null |
iOS/G3MApp/G3MApp/G3MRasterLayersDemoScene.hpp
|
AeroGlass/g3m
|
a21a9e70a6205f1f37046ae85dafc6e3bfaeb917
|
[
"BSD-2-Clause"
] | null | null | null |
//
// G3MRasterLayersDemoScene.hpp
// G3MApp
//
// Created by Diego Gomez Deck on 11/16/13.
// Copyright (c) 2013 Igo Software SL. All rights reserved.
//
#ifndef __G3MApp__G3MRasterLayersDemoScene__
#define __G3MApp__G3MRasterLayersDemoScene__
#include "G3MDemoScene.hpp"
class LayerSet;
class G3MRasterLayersDemoScene : public G3MDemoScene {
private:
void createLayerSet(LayerSet* layerSet);
protected:
void rawActivate(const G3MContext* context);
void rawSelectOption(const std::string& option,
int optionIndex);
public:
G3MRasterLayersDemoScene(G3MDemoModel* model) :
G3MDemoScene(model, "Raster Layers", "", 0)
{
_options.push_back("Open Street Map");
_options.push_back("MapQuest OSM");
_options.push_back("MapQuest Aerial");
_options.push_back("MapBox OSM");
_options.push_back("MapBox Terrain");
_options.push_back("MapBox Aerial");
_options.push_back("CartoDB Meteorites");
_options.push_back("Nasa Blue Marble (WMS)");
// _options.push_back("ESRI ArcGis Online");
_options.push_back("Bing Aerial");
_options.push_back("Bing Aerial with Labels");
_options.push_back("Uruguay (WMS)");
}
};
#endif
| 23.269231
| 60
| 0.712397
|
AeroGlass
|
522a8eeab0250a935c469b984cfd878ef256e6a6
| 14,589
|
cpp
|
C++
|
src/pir_server.cpp
|
sga001/SealPIR
|
12f6c0ff34ed3e4da47072544efb0b44bb745e4b
|
[
"MIT"
] | 20
|
2018-06-03T00:15:23.000Z
|
2019-04-11T19:37:04.000Z
|
src/pir_server.cpp
|
sga001/SealPIR
|
12f6c0ff34ed3e4da47072544efb0b44bb745e4b
|
[
"MIT"
] | 3
|
2018-06-02T17:55:40.000Z
|
2019-02-18T00:48:51.000Z
|
src/pir_server.cpp
|
sga001/SealPIR
|
12f6c0ff34ed3e4da47072544efb0b44bb745e4b
|
[
"MIT"
] | 9
|
2018-06-02T16:40:39.000Z
|
2019-04-11T19:37:15.000Z
|
#include "pir_server.hpp"
#include "pir_client.hpp"
using namespace std;
using namespace seal;
using namespace seal::util;
PIRServer::PIRServer(const EncryptionParameters &enc_params,
const PirParams &pir_params)
: enc_params_(enc_params), pir_params_(pir_params),
is_db_preprocessed_(false) {
context_ = make_shared<SEALContext>(enc_params, true);
evaluator_ = make_unique<Evaluator>(*context_);
encoder_ = make_unique<BatchEncoder>(*context_);
}
void PIRServer::preprocess_database() {
if (!is_db_preprocessed_) {
for (uint32_t i = 0; i < db_->size(); i++) {
evaluator_->transform_to_ntt_inplace(db_->operator[](i),
context_->first_parms_id());
}
is_db_preprocessed_ = true;
}
}
// Server takes over ownership of db and will free it when it exits
void PIRServer::set_database(unique_ptr<vector<Plaintext>> &&db) {
if (!db) {
throw invalid_argument("db cannot be null");
}
db_ = move(db);
is_db_preprocessed_ = false;
}
void PIRServer::set_database(const std::unique_ptr<const uint8_t[]> &bytes,
uint64_t ele_num, uint64_t ele_size) {
uint32_t logt = floor(log2(enc_params_.plain_modulus().value()));
uint32_t N = enc_params_.poly_modulus_degree();
// number of FV plaintexts needed to represent all elements
uint64_t num_of_plaintexts = pir_params_.num_of_plaintexts;
// number of FV plaintexts needed to create the d-dimensional matrix
uint64_t prod = 1;
for (uint32_t i = 0; i < pir_params_.nvec.size(); i++) {
prod *= pir_params_.nvec[i];
}
uint64_t matrix_plaintexts = prod;
assert(num_of_plaintexts <= matrix_plaintexts);
auto result = make_unique<vector<Plaintext>>();
result->reserve(matrix_plaintexts);
uint64_t ele_per_ptxt = pir_params_.elements_per_plaintext;
uint64_t bytes_per_ptxt = ele_per_ptxt * ele_size;
uint64_t db_size = ele_num * ele_size;
uint64_t coeff_per_ptxt =
ele_per_ptxt * coefficients_per_element(logt, ele_size);
assert(coeff_per_ptxt <= N);
cout << "Elements per plaintext: " << ele_per_ptxt << endl;
cout << "Coeff per ptxt: " << coeff_per_ptxt << endl;
cout << "Bytes per plaintext: " << bytes_per_ptxt << endl;
uint32_t offset = 0;
for (uint64_t i = 0; i < num_of_plaintexts; i++) {
uint64_t process_bytes = 0;
if (db_size <= offset) {
break;
} else if (db_size < offset + bytes_per_ptxt) {
process_bytes = db_size - offset;
} else {
process_bytes = bytes_per_ptxt;
}
assert(process_bytes % ele_size == 0);
uint64_t ele_in_chunk = process_bytes / ele_size;
// Get the coefficients of the elements that will be packed in plaintext i
vector<uint64_t> coefficients(coeff_per_ptxt);
for (uint64_t ele = 0; ele < ele_in_chunk; ele++) {
vector<uint64_t> element_coeffs = bytes_to_coeffs(
logt, bytes.get() + offset + (ele_size * ele), ele_size);
std::copy(element_coeffs.begin(), element_coeffs.end(),
coefficients.begin() +
(coefficients_per_element(logt, ele_size) * ele));
}
offset += process_bytes;
uint64_t used = coefficients.size();
assert(used <= coeff_per_ptxt);
// Pad the rest with 1s
for (uint64_t j = 0; j < (pir_params_.slot_count - used); j++) {
coefficients.push_back(1);
}
Plaintext plain;
encoder_->encode(coefficients, plain);
// cout << i << "-th encoded plaintext = " << plain.to_string() << endl;
result->push_back(move(plain));
}
// Add padding to make database a matrix
uint64_t current_plaintexts = result->size();
assert(current_plaintexts <= num_of_plaintexts);
#ifdef DEBUG
cout << "adding: " << matrix_plaintexts - current_plaintexts
<< " FV plaintexts of padding (equivalent to: "
<< (matrix_plaintexts - current_plaintexts) *
elements_per_ptxt(logtp, N, ele_size)
<< " elements)" << endl;
#endif
vector<uint64_t> padding(N, 1);
for (uint64_t i = 0; i < (matrix_plaintexts - current_plaintexts); i++) {
Plaintext plain;
vector_to_plaintext(padding, plain);
result->push_back(plain);
}
set_database(move(result));
}
void PIRServer::set_galois_key(uint32_t client_id, seal::GaloisKeys galkey) {
galoisKeys_[client_id] = galkey;
}
PirQuery PIRServer::deserialize_query(stringstream &stream) {
PirQuery q;
for (uint32_t i = 0; i < pir_params_.d; i++) {
// number of ciphertexts needed to encode the index for dimension i
// keeping into account that each ciphertext can encode up to
// poly_modulus_degree indexes In most cases this is usually 1.
uint32_t ctx_per_dimension =
ceil((pir_params_.nvec[i] + 0.0) / enc_params_.poly_modulus_degree());
vector<Ciphertext> cs;
for (uint32_t j = 0; j < ctx_per_dimension; j++) {
Ciphertext c;
c.load(*context_, stream);
cs.push_back(c);
}
q.push_back(cs);
}
return q;
}
int PIRServer::serialize_reply(PirReply &reply, stringstream &stream) {
int output_size = 0;
for (int i = 0; i < reply.size(); i++) {
evaluator_->mod_switch_to_inplace(reply[i], context_->last_parms_id());
output_size += reply[i].save(stream);
}
return output_size;
}
PirReply PIRServer::generate_reply(PirQuery &query, uint32_t client_id) {
vector<uint64_t> nvec = pir_params_.nvec;
uint64_t product = 1;
for (uint32_t i = 0; i < nvec.size(); i++) {
product *= nvec[i];
}
auto coeff_count = enc_params_.poly_modulus_degree();
vector<Plaintext> *cur = db_.get();
vector<Plaintext> intermediate_plain; // decompose....
auto pool = MemoryManager::GetPool();
int N = enc_params_.poly_modulus_degree();
int logt = floor(log2(enc_params_.plain_modulus().value()));
for (uint32_t i = 0; i < nvec.size(); i++) {
cout << "Server: " << i + 1 << "-th recursion level started " << endl;
vector<Ciphertext> expanded_query;
uint64_t n_i = nvec[i];
cout << "Server: n_i = " << n_i << endl;
cout << "Server: expanding " << query[i].size() << " query ctxts" << endl;
for (uint32_t j = 0; j < query[i].size(); j++) {
uint64_t total = N;
if (j == query[i].size() - 1) {
total = n_i % N;
}
cout << "-- expanding one query ctxt into " << total << " ctxts " << endl;
vector<Ciphertext> expanded_query_part =
expand_query(query[i][j], total, client_id);
expanded_query.insert(
expanded_query.end(),
std::make_move_iterator(expanded_query_part.begin()),
std::make_move_iterator(expanded_query_part.end()));
expanded_query_part.clear();
}
cout << "Server: expansion done " << endl;
if (expanded_query.size() != n_i) {
cout << " size mismatch!!! " << expanded_query.size() << ", " << n_i
<< endl;
}
// Transform expanded query to NTT, and ...
for (uint32_t jj = 0; jj < expanded_query.size(); jj++) {
evaluator_->transform_to_ntt_inplace(expanded_query[jj]);
}
// Transform plaintext to NTT. If database is pre-processed, can skip
if ((!is_db_preprocessed_) || i > 0) {
for (uint32_t jj = 0; jj < cur->size(); jj++) {
evaluator_->transform_to_ntt_inplace((*cur)[jj],
context_->first_parms_id());
}
}
for (uint64_t k = 0; k < product; k++) {
if ((*cur)[k].is_zero()) {
cout << k + 1 << "/ " << product << "-th ptxt = 0 " << endl;
}
}
product /= n_i;
vector<Ciphertext> intermediateCtxts(product);
Ciphertext temp;
for (uint64_t k = 0; k < product; k++) {
evaluator_->multiply_plain(expanded_query[0], (*cur)[k],
intermediateCtxts[k]);
for (uint64_t j = 1; j < n_i; j++) {
evaluator_->multiply_plain(expanded_query[j], (*cur)[k + j * product],
temp);
evaluator_->add_inplace(intermediateCtxts[k],
temp); // Adds to first component.
}
}
for (uint32_t jj = 0; jj < intermediateCtxts.size(); jj++) {
evaluator_->transform_from_ntt_inplace(intermediateCtxts[jj]);
// print intermediate ctxts?
// cout << "const term of ctxt " << jj << " = " <<
// intermediateCtxts[jj][0] << endl;
}
if (i == nvec.size() - 1) {
return intermediateCtxts;
} else {
intermediate_plain.clear();
intermediate_plain.reserve(pir_params_.expansion_ratio * product);
cur = &intermediate_plain;
for (uint64_t rr = 0; rr < product; rr++) {
EncryptionParameters parms;
if (pir_params_.enable_mswitching) {
evaluator_->mod_switch_to_inplace(intermediateCtxts[rr],
context_->last_parms_id());
parms = context_->last_context_data()->parms();
} else {
parms = context_->first_context_data()->parms();
}
vector<Plaintext> plains =
decompose_to_plaintexts(parms, intermediateCtxts[rr]);
for (uint32_t jj = 0; jj < plains.size(); jj++) {
intermediate_plain.emplace_back(plains[jj]);
}
}
product = intermediate_plain.size(); // multiply by expansion rate.
}
cout << "Server: " << i + 1 << "-th recursion level finished " << endl;
cout << endl;
}
cout << "reply generated! " << endl;
// This should never get here
assert(0);
vector<Ciphertext> fail(1);
return fail;
}
inline vector<Ciphertext> PIRServer::expand_query(const Ciphertext &encrypted,
uint32_t m,
uint32_t client_id) {
GaloisKeys &galkey = galoisKeys_[client_id];
// Assume that m is a power of 2. If not, round it to the next power of 2.
uint32_t logm = ceil(log2(m));
Plaintext two("2");
vector<int> galois_elts;
auto n = enc_params_.poly_modulus_degree();
if (logm > ceil(log2(n))) {
throw logic_error("m > n is not allowed.");
}
for (int i = 0; i < ceil(log2(n)); i++) {
galois_elts.push_back((n + exponentiate_uint(2, i)) /
exponentiate_uint(2, i));
}
vector<Ciphertext> temp;
temp.push_back(encrypted);
Ciphertext tempctxt;
Ciphertext tempctxt_rotated;
Ciphertext tempctxt_shifted;
Ciphertext tempctxt_rotatedshifted;
for (uint32_t i = 0; i < logm - 1; i++) {
vector<Ciphertext> newtemp(temp.size() << 1);
// temp[a] = (j0 = a (mod 2**i) ? ) : Enc(x^{j0 - a}) else Enc(0). With
// some scaling....
int index_raw = (n << 1) - (1 << i);
int index = (index_raw * galois_elts[i]) % (n << 1);
for (uint32_t a = 0; a < temp.size(); a++) {
evaluator_->apply_galois(temp[a], galois_elts[i], galkey,
tempctxt_rotated);
// cout << "rotate " <<
// client.decryptor_->invariant_noise_budget(tempctxt_rotated) << ", ";
evaluator_->add(temp[a], tempctxt_rotated, newtemp[a]);
multiply_power_of_X(temp[a], tempctxt_shifted, index_raw);
// cout << "mul by x^pow: " <<
// client.decryptor_->invariant_noise_budget(tempctxt_shifted) << ", ";
multiply_power_of_X(tempctxt_rotated, tempctxt_rotatedshifted, index);
// cout << "mul by x^pow: " <<
// client.decryptor_->invariant_noise_budget(tempctxt_rotatedshifted) <<
// ", ";
// Enc(2^i x^j) if j = 0 (mod 2**i).
evaluator_->add(tempctxt_shifted, tempctxt_rotatedshifted,
newtemp[a + temp.size()]);
}
temp = newtemp;
/*
cout << "end: ";
for (int h = 0; h < temp.size();h++){
cout << client.decryptor_->invariant_noise_budget(temp[h]) << ", ";
}
cout << endl;
*/
}
// Last step of the loop
vector<Ciphertext> newtemp(temp.size() << 1);
int index_raw = (n << 1) - (1 << (logm - 1));
int index = (index_raw * galois_elts[logm - 1]) % (n << 1);
for (uint32_t a = 0; a < temp.size(); a++) {
if (a >= (m - (1 << (logm - 1)))) { // corner case.
evaluator_->multiply_plain(temp[a], two,
newtemp[a]); // plain multiplication by 2.
// cout << client.decryptor_->invariant_noise_budget(newtemp[a]) << ", ";
} else {
evaluator_->apply_galois(temp[a], galois_elts[logm - 1], galkey,
tempctxt_rotated);
evaluator_->add(temp[a], tempctxt_rotated, newtemp[a]);
multiply_power_of_X(temp[a], tempctxt_shifted, index_raw);
multiply_power_of_X(tempctxt_rotated, tempctxt_rotatedshifted, index);
evaluator_->add(tempctxt_shifted, tempctxt_rotatedshifted,
newtemp[a + temp.size()]);
}
}
vector<Ciphertext>::const_iterator first = newtemp.begin();
vector<Ciphertext>::const_iterator last = newtemp.begin() + m;
vector<Ciphertext> newVec(first, last);
return newVec;
}
inline void PIRServer::multiply_power_of_X(const Ciphertext &encrypted,
Ciphertext &destination,
uint32_t index) {
auto coeff_mod_count = enc_params_.coeff_modulus().size() - 1;
auto coeff_count = enc_params_.poly_modulus_degree();
auto encrypted_count = encrypted.size();
// cout << "coeff mod count for power of X = " << coeff_mod_count << endl;
// cout << "coeff count for power of X = " << coeff_count << endl;
// First copy over.
destination = encrypted;
// Prepare for destination
// Multiply X^index for each ciphertext polynomial
for (int i = 0; i < encrypted_count; i++) {
for (int j = 0; j < coeff_mod_count; j++) {
negacyclic_shift_poly_coeffmod(encrypted.data(i) + (j * coeff_count),
coeff_count, index,
enc_params_.coeff_modulus()[j],
destination.data(i) + (j * coeff_count));
}
}
}
void PIRServer::simple_set(uint64_t index, Plaintext pt) {
if (is_db_preprocessed_) {
evaluator_->transform_to_ntt_inplace(pt, context_->first_parms_id());
}
db_->operator[](index) = pt;
}
Ciphertext PIRServer::simple_query(uint64_t index) {
// There is no transform_from_ntt that takes a plaintext
Ciphertext ct;
Plaintext pt = db_->operator[](index);
evaluator_->multiply_plain(one_, pt, ct);
evaluator_->transform_from_ntt_inplace(ct);
return ct;
}
void PIRServer::set_one_ct(Ciphertext one) {
one_ = one;
evaluator_->transform_to_ntt_inplace(one_);
}
| 32.93228
| 80
| 0.61327
|
sga001
|
5232ad5c29704ebca92667e1e6bb0dbdcbe0c910
| 387
|
cpp
|
C++
|
UnderstandingCpp11/src/attribute.cpp
|
elloop/algorithm
|
5485be0aedbc18968f775cff9533a2d444dbdcb5
|
[
"MIT"
] | 15
|
2015-11-04T12:53:23.000Z
|
2021-08-10T09:53:12.000Z
|
UnderstandingCpp11/src/attribute.cpp
|
elloop/algorithm
|
5485be0aedbc18968f775cff9533a2d444dbdcb5
|
[
"MIT"
] | null | null | null |
UnderstandingCpp11/src/attribute.cpp
|
elloop/algorithm
|
5485be0aedbc18968f775cff9533a2d444dbdcb5
|
[
"MIT"
] | 6
|
2015-11-13T10:17:01.000Z
|
2020-05-14T07:25:48.000Z
|
#include "attribute.h"
NS_BEGIN( elloop )
NS_BEGIN( attribute )
#ifdef _MSC_VER
#else
[[noreturn]]void throwAway() {
throw "away";
}
#endif
void foo() {
pln( "in foo" );
#ifdef _MSC_VER
pln( "vc don't work" );
#else
throwAway();
#endif
pln( "can't reach here" );
}
BEGIN_TEST( Attribute, NoReturn, @);
foo();
END_TEST;
NS_END( attribute )
NS_END( elloop )
| 12.483871
| 36
| 0.620155
|
elloop
|
523378bc2a37c013b5db7100a660f50eaeb27c69
| 4,204
|
cc
|
C++
|
src/nqsok/shader.cc
|
CaffeineViking/nqsok
|
1f4c7c2b7e7e907facd794b3267f07a2e01f6f87
|
[
"MIT"
] | 1
|
2019-06-18T07:17:51.000Z
|
2019-06-18T07:17:51.000Z
|
src/nqsok/shader.cc
|
CaffeineViking/nqsok
|
1f4c7c2b7e7e907facd794b3267f07a2e01f6f87
|
[
"MIT"
] | null | null | null |
src/nqsok/shader.cc
|
CaffeineViking/nqsok
|
1f4c7c2b7e7e907facd794b3267f07a2e01f6f87
|
[
"MIT"
] | null | null | null |
#include "shader.hh"
#include <fstream>
#include <iterator>
#include <iostream>
nq::Shader::Shader(const std::string& vertex_shader_path,
const std::string& fragment_shader_path)
: vertex_shader_file {vertex_shader_path},
fragment_shader_file {fragment_shader_path} {
std::cout << "\nShader (compiling and linking)..." << std::endl;
GLuint vertex_shader {load_shader(vertex_shader_path, GL_VERTEX_SHADER)};
GLuint fragment_shader {load_shader(fragment_shader_path, GL_FRAGMENT_SHADER)};
GLuint shader_program {load_program(vertex_shader, fragment_shader)};
handle = shader_program; // Oooops. This is important (forgot...)
glUseProgram(handle); // User needs to be aware of this.
std::cout << "Linking successful, deleting shaders" << std::endl;
glDeleteShader(fragment_shader);
glDeleteShader(vertex_shader);
std::cout << "...done (Shader)" << std::endl;
}
nq::Shader::~Shader() { glDeleteProgram(handle); }
nq::Shader* nq::Shader::current {nullptr};
bool nq::Shader::is_current() const {
if (current == this) return true;
else return false;
}
void nq::Shader::uniformf(const std::string& name, float value) {
if (!is_current()) use(); // Make sure we are using this...
GLint location {glGetUniformLocation(handle, name.c_str())};
glUniform1f(location, value);
}
void nq::Shader::uniformi(const std::string& name, int value) {
if (!is_current()) use(); // Make sure we are using this...
GLint location {glGetUniformLocation(handle, name.c_str())};
glUniform1i(location, value);
}
void nq::Shader::uniform_vector(const std::string& name, const glm::vec3& value) {
if (!is_current()) use(); // Make sure we are using this...
GLint location {glGetUniformLocation(handle, name.c_str())};
glUniform3fv(location, 1, glm::value_ptr(value));
}
void nq::Shader::uniform_matrix(const std::string& name, const glm::mat4& value) {
if (!is_current()) use(); // Make sure we are using this...
GLint location {glGetUniformLocation(handle, name.c_str())};
glUniformMatrix4fv(location, 1, GL_FALSE, glm::value_ptr(value));
}
GLint nq::Shader::attribute_location(const std::string& name) const {
return glGetAttribLocation(handle, name.c_str());
}
GLuint nq::Shader::load_shader(const std::string& shader_path, GLenum type) {
std::ifstream shader_file {shader_path};
if (!shader_file) throw Shader_error{"Shader error (#1) file not found"};
std::string shader_source {std::istreambuf_iterator<char>{shader_file}, std::istreambuf_iterator<char>{}};
const char* shader_csource = shader_source.c_str(); int shader_length = shader_source.length();
std::cout << shader_path << " (compiling)...";
GLuint shader {glCreateShader(type)};
glShaderSource(shader, 1, &shader_csource, &shader_length);
glCompileShader(shader);
GLint shader_state {GL_TRUE};
glGetShaderiv(shader, GL_COMPILE_STATUS, &shader_state);
if (shader_state == GL_FALSE) {
GLint log_size {42};
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &log_size);
char* log {new char[log_size]};
glGetShaderInfoLog(shader, log_size, nullptr, log);
std::string shader_error {"Shader error (#2) "}; shader_error += log; delete log;
throw Shader_error{shader_error};
}
std::cout << "done" << std::endl;
return shader;
}
GLuint nq::Shader::load_program(GLuint vertex_shader, GLuint fragment_shader) {
GLuint shader_program {glCreateProgram()};
glAttachShader(shader_program, vertex_shader);
glAttachShader(shader_program, fragment_shader);
glLinkProgram(shader_program);
GLint shader_state {GL_TRUE};
glGetProgramiv(shader_program, GL_LINK_STATUS, &shader_state);
if (shader_state == GL_FALSE) {
GLint log_size {42};
glGetProgramiv(shader_program, GL_INFO_LOG_LENGTH, &log_size);
char* log {new char[log_size]};
glGetProgramInfoLog(shader_program, log_size, nullptr, log);
std::string shader_error {"Shader error (#3) "}; shader_error += log; delete log;
throw Shader_error{shader_error};
}
return shader_program;
}
| 39.660377
| 110
| 0.692198
|
CaffeineViking
|
52375bbdc645b1069e4b8bd88e36aa3e209e0936
| 3,108
|
cpp
|
C++
|
Final/midtermtwo_ec602/midtermtwo_template.cpp
|
chenchuw/EC602-Design-by-Software
|
c233c9d08a67abc47235282fedd866d67ccaf4ce
|
[
"MIT"
] | null | null | null |
Final/midtermtwo_ec602/midtermtwo_template.cpp
|
chenchuw/EC602-Design-by-Software
|
c233c9d08a67abc47235282fedd866d67ccaf4ce
|
[
"MIT"
] | null | null | null |
Final/midtermtwo_ec602/midtermtwo_template.cpp
|
chenchuw/EC602-Design-by-Software
|
c233c9d08a67abc47235282fedd866d67ccaf4ce
|
[
"MIT"
] | 1
|
2022-01-11T20:23:47.000Z
|
2022-01-11T20:23:47.000Z
|
// Copyright 2020 jbc@bu.edu
//
// RULES:
// - brackets are allowed
// - iostream, string, vector can be included, nothing else.
// - your program should compile as submitted (main() must be here)
// - astyle and cpplint will not be used, but I
// may read and evaluate your code as part of the grade
// you may add more using statements, but not more includes.
#include<iostream>
#include<string>
#include<vector>
using std::string;
using std::vector;
// ---------------VISTANCE----------------
/*
Distance Between Two Vectors (vistance)
---------------------------------------
Given two vectors of integers which are
re-arrangements of each other, write
a function to find
the distance between the
locations (ie. the difference of their
index values) of the matching elements.
Example:
vistance({3,9,5},{5,3,9}) = 4
because 3 has been moved 1 spot, 9 moved 1 spot , and 5 moved 2 spots
vistance({2,5,3},{5,2,3}) = 2
because 2 and 5 are each 1 away from
where they are in the other vector
vistance({42,12},{42,12}) = 0
because the values are in the same locations
in each vector.
If the vectors are not
re-arrangements of each other,
throw the string "vistance is an illusion"
extra credit: make it fast.
You may assume that the elements
are unique.
The function signature for vistance() must not be modified.
*/
// ADD YOUR CODE HERE
// template for vistance
int vistance(const vector<int> &a, const vector<int> &b) {
// a = [1,2,3]; b = [3,2,1]
return 0; // placeholder return, change it to correct value
}
// ----------------------SUMPARSER
/*
Write a class SumParser that analyses strings
containing the additions and subtractions
of integers written in a base from 2 to 10.
The string will have no spaces and only integer values.
There will never be back-to-back
+ and - symbols.
The main program is already written, you can use it as is
or modify it as desired. However, the constructor and two methods
that main() references must be implemented such that this version
of main will still work.
In this main, the base and the string-to-be-evaluated are entered
on a line, then the result of the evaluation is printed as an int (in base
10) and then as a string in the base specified.
*/
// template for SumParser (intentionally left blank)
class SumParser {
public:
string _s;
int _base;
SumParser(string, int);
int get_value();
string show_result();
}
SumParser::SumParser(string s, int base) {
_s = s;
_base = base;
}
// MAIN
// I will ignore code below // MAIN and replace it with my own
// test code.
int main() {
// test code for SumParser
// this test code is pretty complete and does not
// need modification
std::string s;
int base;
while (std::cin >> base >> s) {
SumParser a{s, base};
try {
std::cout << a.get_value() << " "
<< a.show_result() << "\n";
} catch (...) {
std::cout << "invalid\n";
}
}
// test code for vistance
// this is very bare-bones, you will want to do more testing
//return vistance({3, 6, 9}, {9, 3, 6});
return 0;
}
| 21.287671
| 74
| 0.664414
|
chenchuw
|
523cac6c288c324561ff5e9fcc0526802ea366e5
| 20
|
cpp
|
C++
|
src/ChessDotCpp/magics.cpp
|
GediminasMasaitis/chess-dot-cpp
|
60995f235387efc5acc03d46c8245960efef3e81
|
[
"MIT"
] | null | null | null |
src/ChessDotCpp/magics.cpp
|
GediminasMasaitis/chess-dot-cpp
|
60995f235387efc5acc03d46c8245960efef3e81
|
[
"MIT"
] | null | null | null |
src/ChessDotCpp/magics.cpp
|
GediminasMasaitis/chess-dot-cpp
|
60995f235387efc5acc03d46c8245960efef3e81
|
[
"MIT"
] | 1
|
2021-05-01T11:57:03.000Z
|
2021-05-01T11:57:03.000Z
|
#include "magics.h"
| 10
| 19
| 0.7
|
GediminasMasaitis
|
523fb81608e17d6ae17fa1e8c5c736998cac79f2
| 1,725
|
cpp
|
C++
|
xlib/IMC.cpp
|
X547/xlibe
|
fbab795ad8a86503174ecfcb8603ec868537d069
|
[
"MIT"
] | 1
|
2022-01-02T16:10:26.000Z
|
2022-01-02T16:10:26.000Z
|
xlib/IMC.cpp
|
X547/xlibe
|
fbab795ad8a86503174ecfcb8603ec868537d069
|
[
"MIT"
] | null | null | null |
xlib/IMC.cpp
|
X547/xlibe
|
fbab795ad8a86503174ecfcb8603ec868537d069
|
[
"MIT"
] | null | null | null |
/*
* Copyright 2021, Haiku, Inc. All rights reserved.
* Distributed under the terms of the MIT license.
*/
extern "C" {
#include <X11/Xlib.h>
}
extern "C" XIM
XOpenIM(Display* dpy,
struct _XrmHashBucketRec* rdb, char* res_name, char* res_class)
{
// Unimplemented.
return NULL;
}
extern "C" Display*
XDisplayOfIM(XIM im)
{
return NULL;
}
extern "C" char*
XLocaleOfIM(XIM im)
{
return NULL;
}
extern "C" char*
XGetIMValues(XIM im, ...)
{
return NULL;
}
extern "C" char*
XSetIMValues(XIM im, ...)
{
return NULL;
}
extern "C" Bool
XRegisterIMInstantiateCallback(Display* dpy,
struct _XrmHashBucketRec* rdb, char* res_name, char* res_class,
XIDProc callback, XPointer client_data)
{
return False;
}
extern "C" Bool
XUnregisterIMInstantiateCallback(Display* dpy,
struct _XrmHashBucketRec* rdb, char* res_name, char* res_class,
XIDProc callback, XPointer client_data)
{
return False;
}
extern "C" Status
XCloseIM(XIM xim)
{
return 0;
}
extern "C" XIC
XCreateIC(XIM xim, ...)
{
// Unimplemented.
return NULL;
}
extern "C" XIM
XIMOfIC(XIC ic)
{
return NULL;
}
extern "C" char*
XmbResetIC(XIC ic)
{
return NULL;
}
extern "C" void
XDestroyIC(XIC ic)
{
}
extern "C" char*
XSetICValues(XIC ic, ...)
{
return NULL;
}
extern "C" char*
XGetICValues(XIC ic, ...)
{
return NULL;
}
extern "C" void
XSetICFocus(XIC ic)
{
}
extern "C" void
XUnsetICFocus(XIC ic)
{
}
extern "C" Bool
XFilterEvent(XEvent *event, Window window)
{
return 0;
}
extern "C" int
Xutf8LookupString(XIC ic, XKeyPressedEvent* event,
char* buffer_return, int bytes_buffer, KeySym* keysym_return, Status* status_return)
{
return BadImplementation;
}
extern "C" XVaNestedList
XVaCreateNestedList(int dummy, ...)
{
return NULL;
}
| 13.476563
| 85
| 0.703768
|
X547
|
52464adb612d01ee4c2c465782e6bc01b394670d
| 1,704
|
cpp
|
C++
|
ContinuumEngine3D/Engine/Renderer/GameObject/AnimatedObject/ColladaParser/xmlParser/XmlNode.cpp
|
Arieandel/ContinuumEngine
|
46688dd99195dd88ab15a4ffe0532ac03bc8e373
|
[
"MIT"
] | null | null | null |
ContinuumEngine3D/Engine/Renderer/GameObject/AnimatedObject/ColladaParser/xmlParser/XmlNode.cpp
|
Arieandel/ContinuumEngine
|
46688dd99195dd88ab15a4ffe0532ac03bc8e373
|
[
"MIT"
] | null | null | null |
ContinuumEngine3D/Engine/Renderer/GameObject/AnimatedObject/ColladaParser/xmlParser/XmlNode.cpp
|
Arieandel/ContinuumEngine
|
46688dd99195dd88ab15a4ffe0532ac03bc8e373
|
[
"MIT"
] | null | null | null |
#include "XmlNode.h"
XmlNode::XmlNode()
{
name = "";
}
XmlNode::XmlNode(std::string name_)
{
name = name_;
}
XmlNode::~XmlNode()
{
}
std::string XmlNode::getName() {
return name;
}
std::string XmlNode::getData() {
return data;
}
std::string XmlNode::getAttribute(std::string attr_) {
if (!attributes.empty()) {
return attributes[attr_];
}
else {
return NULL;
}
}
XmlNode* XmlNode::getChild(std::string childName_) {
if (childNodes.size() != 0) {
for (int i = 0; i < childNodes.size(); i++) {
nodes.push_back(childNodes[childName_][i]);
if (nodes[i]->getName() == childName_) {
return nodes[i];
}
}
}
return nullptr;
}
std::vector<XmlNode*> XmlNode::getChildren(std::string name_) {
if (!childNodes.empty()) {
std::vector<XmlNode*> children = childNodes[name_];
if (!children.empty()) {
return children;
}
}
return std::vector<XmlNode*>();
}
XmlNode* XmlNode::getChildWithAttribute(std::string childName_, std::string attr_, std::string value_) {
std::vector<XmlNode*> children = getChildren(childName_);
if (children.empty()) {
return nullptr; // XmlNode();
}
for (XmlNode* child : children) {
std::string val = child->getAttribute(attr_);
if (value_ == val) {
return child;
}
}
return nullptr;// XmlNode();
}
void XmlNode::addAttribute(std::string attr_, std::string value_) {
attributes[attr_] = value_;
}
void XmlNode::addChild(XmlNode* child_) {
std::vector<XmlNode*> childs = childNodes[child_->name];
if (childs.empty()) {
childNodes[child_->name] = list;
}
list.push_back(child_);
}
void XmlNode::setData(std::string data_) {
data = data_;
}
void XmlNode::setName(std::string name_) {
name = name_;
}
| 17.212121
| 104
| 0.653169
|
Arieandel
|
524da28f97bd0038dddb8e9f371aa4e38ade3ace
| 2,443
|
cpp
|
C++
|
src/dxapi/native/tickdb/http/xml/stream/bg_proc_info_impl.cpp
|
noop-dev/TimeBaseClientCpp
|
3cbbee85f2a8f1f38a31fc14a993fceb05d650f1
|
[
"Apache-2.0"
] | null | null | null |
src/dxapi/native/tickdb/http/xml/stream/bg_proc_info_impl.cpp
|
noop-dev/TimeBaseClientCpp
|
3cbbee85f2a8f1f38a31fc14a993fceb05d650f1
|
[
"Apache-2.0"
] | null | null | null |
src/dxapi/native/tickdb/http/xml/stream/bg_proc_info_impl.cpp
|
noop-dev/TimeBaseClientCpp
|
3cbbee85f2a8f1f38a31fc14a993fceb05d650f1
|
[
"Apache-2.0"
] | 2
|
2021-05-14T09:39:50.000Z
|
2022-03-24T23:42:41.000Z
|
/*
* Copyright 2021 EPAM Systems, Inc
*
* See the NOTICE file distributed with this work for additional information
* regarding copyright ownership. 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 "../xml_request.h"
#include "bg_proc_info_impl.h"
using namespace std;
using namespace DxApi;
using namespace DxApiImpl;
const char * infoExecutionStatus[] = {
"None",
"Running",
"Completed",
"Aborted",
"Failed"
};
IMPLEMENT_ENUM(uint8_t, ExecutionStatus, false)
{}
#define ADD(x) xml.add(#x, v.x).add('\n')
//#define ADD(x) do { ss << tag(#x, x).append("\n"); } while (0)
using namespace XmlGen;
namespace DxApiImpl {
template<> XmlOutput& operator<<(XmlOutput& xml, const BackgroundProcessInfoImpl &v)
{
xml.add('\n');
ADD(name);
ADD(status);
// ADD(affectedStreams); // TODO:
ADD(progress);
ADD(startTime);
ADD(endTime);
return xml;
}
}
using namespace XmlParse;
#define GET(FIELDNAME) tmp = getText(root, #FIELDNAME); if(NULL != tmp) if (!parse(this->FIELDNAME, tmp)) break;
// TODO: Add == ?
//bool BackgroundProcessInfoImpl::operator==(const BackgroundProcessInfoImpl &other) const
//{
// return name == other.name
// && status == other.status
// && affectedStreams == other.affectedStreams
// && progress == other.progress
// && startTime == other.startTime
// && endTime == other.endTime;
//}
template<> bool XmlParse::parse(ExecutionStatus &type, const char *from)
{
return NULL == from ? false : (type = ExecutionStatus(from), true);
}
bool BackgroundProcessInfoImpl::fromXML(tinyxml2::XMLElement *root)
{
const char *tmp;
while (1) {
GET(name);
GET(status);
// TODO:
//GET(affectedStreams);
GET(progress);
GET(startTime);
GET(endTime);
return true;
}
return false;
}
| 24.928571
| 112
| 0.644699
|
noop-dev
|
524df9a9b6feb96c6ba2545faf06f5a9dc640142
| 1,319
|
cpp
|
C++
|
third-party/Empirical/demos/utils/words/annotate-length.cpp
|
koellingh/empirical-p53-simulator
|
aa6232f661e8fc65852ab6d3e809339557af521b
|
[
"MIT"
] | null | null | null |
third-party/Empirical/demos/utils/words/annotate-length.cpp
|
koellingh/empirical-p53-simulator
|
aa6232f661e8fc65852ab6d3e809339557af521b
|
[
"MIT"
] | null | null | null |
third-party/Empirical/demos/utils/words/annotate-length.cpp
|
koellingh/empirical-p53-simulator
|
aa6232f661e8fc65852ab6d3e809339557af521b
|
[
"MIT"
] | null | null | null |
// This file is part of Empirical, https://github.com/devosoft/Empirical
// Copyright (C) Michigan State University, 2019.
// Released under the MIT Software license; see doc/LICENSE
//
//
// Annotate all of the words in an input list with their length.
#include <iostream>
#include <set>
#include "../../../include/emp/base/assert.hpp"
#include "../../../include/emp/config/command_line.hpp"
#include "../../../include/emp/io/File.hpp"
#include "../../../include/emp/math/math.hpp"
#include "../../../include/emp/datastructs/set_utils.hpp"
#include "../../../include/emp/tools/string_utils.hpp"
void Process(std::istream & is, std::ostream & os) {
std::string cur_str;
while (is) {
is >> cur_str;
os << cur_str.size() << " " << cur_str << std::endl;
}
}
int main(int argc, char* argv[])
{
emp::vector<std::string> args = emp::cl::args_to_strings(argc, argv);
if (args.size() > 3) {
std::cerr << "Only a single input filename and output filename are allowed as arguments."
<< std::endl;
exit(1);
}
if (args.size() > 1) {
std::ifstream is(args[1]);
if (args.size() > 2) {
std::ofstream os(args[2]);
Process(is, os);
os.close();
} else {
Process(is, std::cout);
}
is.close();
}
else {
Process(std::cin, std::cout);
}
}
| 25.365385
| 93
| 0.605004
|
koellingh
|
5250f4e7e6e4500c4a43304eaafd781891e4b908
| 576
|
hpp
|
C++
|
include/RED4ext/Scripting/Natives/Generated/game/ui/QuadRacerSprite.hpp
|
WSSDude420/RED4ext.SDK
|
eaca8bdf7b92c48422b18431ed8cd0876f53bdb3
|
[
"MIT"
] | null | null | null |
include/RED4ext/Scripting/Natives/Generated/game/ui/QuadRacerSprite.hpp
|
WSSDude420/RED4ext.SDK
|
eaca8bdf7b92c48422b18431ed8cd0876f53bdb3
|
[
"MIT"
] | null | null | null |
include/RED4ext/Scripting/Natives/Generated/game/ui/QuadRacerSprite.hpp
|
WSSDude420/RED4ext.SDK
|
eaca8bdf7b92c48422b18431ed8cd0876f53bdb3
|
[
"MIT"
] | null | null | null |
#pragma once
// This file is generated from the Game's Reflection data
#include <cstdint>
#include <RED4ext/Common.hpp>
#include <RED4ext/Scripting/Natives/Generated/game/ui/SideScrollerMiniGameDynObjectLogic.hpp>
namespace RED4ext
{
namespace game::ui {
struct QuadRacerSprite : game::ui::SideScrollerMiniGameDynObjectLogic
{
static constexpr const char* NAME = "gameuiQuadRacerSprite";
static constexpr const char* ALIAS = NAME;
uint8_t unk80[0x88 - 0x80]; // 80
};
RED4EXT_ASSERT_SIZE(QuadRacerSprite, 0x88);
} // namespace game::ui
} // namespace RED4ext
| 26.181818
| 93
| 0.762153
|
WSSDude420
|
5251249a8c53c1cfc638d6aa2a2032bbd25fd8dd
| 2,267
|
cpp
|
C++
|
src/systems/MenuSystem.cpp
|
TransNeptunianStudios/Triangulum
|
7fa5e1948f1085e8d7122dd57ddd7f2efeb2739e
|
[
"MIT"
] | 32
|
2015-02-09T11:30:51.000Z
|
2022-02-02T11:29:49.000Z
|
src/systems/MenuSystem.cpp
|
TransNeptunianStudios/Triangulum
|
7fa5e1948f1085e8d7122dd57ddd7f2efeb2739e
|
[
"MIT"
] | null | null | null |
src/systems/MenuSystem.cpp
|
TransNeptunianStudios/Triangulum
|
7fa5e1948f1085e8d7122dd57ddd7f2efeb2739e
|
[
"MIT"
] | 7
|
2016-04-16T11:02:12.000Z
|
2020-04-10T04:52:45.000Z
|
#include "systems/MenuSystem.h"
#include "systems/Events.h"
#include "components/Menu.h"
#include "KeyHandler.h"
using namespace entityx;
MenuSystem::MenuSystem(EntityManager& entities,
EventManager& eventManager,
sf::RenderWindow& window)
: m_entitiyManager(entities)
, m_eventManager(eventManager)
, m_window(window)
{
}
void MenuSystem::configure(EventManager& eventManager)
{
eventManager.subscribe<EvKeyboard>(*this);
}
void MenuSystem::update(EntityManager& entities,
EventManager& events,
double dt)
{
Menu::Handle menu;
for (Entity entity : entities.entities_with_components(menu))
{
menu->spMenu->update(events, dt);
menu->spMenu->draw(m_window);
}
}
void MenuSystem::receive(const EvKeyboard& keyboard)
{
Menu::Handle menu;
int activeMenus = 0;
for (Entity entity : m_entitiyManager.entities_with_components(menu))
{
if (keyboard.isDown)
menu->spMenu->onKey(keyboard.key);
if(keyboard.key == sf::Keyboard::Return && keyboard.isDown)
menu->spMenu->onConfirm(m_eventManager);
else if(keyboard.key == sf::Keyboard::Escape && keyboard.isDown)
menu->spMenu->onCancel(m_eventManager);
else if(keyboard.key == sf::Keyboard::Up && keyboard.isDown)
menu->spMenu->onUp(m_eventManager);
else if(keyboard.key == sf::Keyboard::Down && keyboard.isDown)
menu->spMenu->onDown(m_eventManager);
else if(keyboard.key == sf::Keyboard::Left && keyboard.isDown)
menu->spMenu->onLeft(m_eventManager);
else if(keyboard.key == sf::Keyboard::Right && keyboard.isDown)
menu->spMenu->onRight(m_eventManager);
activeMenus++;
}
if( !activeMenus ){
if(keyboard.key == sf::Keyboard::Escape && keyboard.isDown)
m_eventManager.emit<EvPauseGame>();
}
// Don't really know where to put stuff like this
// Pretty sure it's not menu's business
if(keyboard.key == sf::Keyboard::F1 && keyboard.isDown)
{
m_eventManager.emit<EvMusicVolume>(0);
}
if(keyboard.key == sf::Keyboard::F2 && keyboard.isDown)
{
m_eventManager.emit<EvQuitGame>();
}
}
| 30.226667
| 73
| 0.636524
|
TransNeptunianStudios
|
525633c74f1aef0969d102a80b347f804a5ea670
| 11,445
|
hpp
|
C++
|
Include/SA/Maths/Transform/Transform.hpp
|
SapphireSuite/Maths
|
df193e3d8fc5cd127626f2f1e2b0bd14cd6cb4eb
|
[
"MIT"
] | null | null | null |
Include/SA/Maths/Transform/Transform.hpp
|
SapphireSuite/Maths
|
df193e3d8fc5cd127626f2f1e2b0bd14cd6cb4eb
|
[
"MIT"
] | 1
|
2022-02-08T18:22:21.000Z
|
2022-02-08T18:22:21.000Z
|
Include/SA/Maths/Transform/Transform.hpp
|
SapphireSuite/Maths
|
df193e3d8fc5cd127626f2f1e2b0bd14cd6cb4eb
|
[
"MIT"
] | null | null | null |
// Copyright (c) 2022 Sapphire Development Team. All Rights Reserved.
#pragma once
#ifndef SAPPHIRE_MATHS_TRANSFORM_GUARD
#define SAPPHIRE_MATHS_TRANSFORM_GUARD
#include <SA/Maths/Debug.hpp>
#include <SA/Maths/Transform/Functors/TransformTRSMatrixFunctor.hpp>
#include <SA/Maths/Transform/Functors/TransformRotateAxisFunctor.hpp>
/**
* @file Transform.hpp
*
* @brief \b Transform type definition
*
* @ingroup Maths_Transform
* @{
*/
namespace Sa
{
/**
* @brief \e Transform Sapphire's class.
*
* @tparam T Transform type.
* @tparam Args Transform component types.
*/
template <typename T, template <typename> typename... Args>
struct Tr : public Args<T>...
{
/// Transform type alias.
using Type = T;
/**
* @brief \e compile-time HasComponent.
*
* @tparam Comp Transform Component type
* @return Wether this has 'Comp' component.
*/
template <template <typename> typename Comp>
static constexpr bool HasComponent() noexcept;
//{ Equals
/**
* \brief Whether this transform is a zero transform.
*
* \return True if this is a zero transform.
*/
bool IsZero() const noexcept;
/**
* \brief Whether this transform is an identity transform.
*
* \return True if this is an identity transform.
*/
bool IsIdentity() const noexcept;
/**
* \brief \e Compare 2 transform.
*
* \param[in] _other Other transform to compare to.
* \param[in] _epsilon Epsilon value for threshold comparison.
*
* \return Whether this and _other are equal.
*/
bool Equals(const Tr& _other, T _epsilon = std::numeric_limits<T>::epsilon()) const noexcept;
/**
* \brief \e Compare 2 transform equality.
*
* \param[in] _rhs Other transform to compare to.
*
* \return Whether this and _rhs are equal.
*/
bool operator==(const Tr& _rhs) const noexcept;
/**
* \brief \e Compare 2 transform inequality.
*
* \param[in] _rhs Other transform to compare to.
*
* \return Whether this and _rhs are non-equal.
*/
bool operator!=(const Tr& _rhs) const noexcept;
//}
//{ Transformation
/**
* \brief \e Getter of \b right vector (X axis) of this transform.
*
* \return transformed right vector normalized.
*/
template <typename TrFunc = TrRotateAxisFunctor>
Vec3<T> Right(TrFunc _functor = TrFunc()) const;
/**
* \brief \e Getter of \b up vector (Y axis) of this transform.
*
* \return transformed up vector normalized.
*/
template <typename TrFunc = TrRotateAxisFunctor>
Vec3<T> Up(TrFunc _functor = TrFunc()) const;
/**
* \brief \e Getter of \b forward vector (Z axis) of this transform.
*
* \return transformed forward vector normalized.
*/
template <typename TrFunc = TrRotateAxisFunctor>
Vec3<T> Forward(TrFunc _functor = TrFunc()) const;
/**
* @brief \b Compute matrix from transform
* Use default TRS order application.
*
* @return transformation matrix.
*/
template <typename TrFunc = TrTRSMatrixFunctor>
Mat4<T> Matrix(TrFunc _functor = TrFunc()) const noexcept;
//}
//{ Lerp
/**
* \brief <b> Clamped Lerp </b> from _start to _end at _alpha.
*
* Reference: https://en.wikipedia.org/wiki/Linear_interpolation
*
* \param _start Starting point of the lerp.
* \param _end Ending point of the lerp.
* \param _alpha Alpha of the lerp.
*
* \return interpolation between _start and _end. return _start when _alpha == 0.0f and _end when _alpha == 1.0f.
*/
static Tr Lerp(const Tr& _start, const Tr& _end, float _alpha) noexcept;
/**
* \brief <b> Unclamped Lerp </b> from _start to _end at _alpha.
*
* Reference: https://en.wikipedia.org/wiki/Linear_interpolation
*
* \param _start Starting point of the lerp.
* \param _end Ending point of the lerp.
* \param _alpha Alpha of the lerp.
*
* \return interpolation between _start and _end. return _start when _alpha == 0.0f and _end when _alpha == 1.0f.
*/
static Tr LerpUnclamped(const Tr& _start, const Tr& _end, float _alpha) noexcept;
//}
//{ Operators
/**
* \brief \b Multiply transform to compute transformation.
*
* \param[in] _rhs Transform to multiply.
*
* \return new transform result.
*/
template <template <typename> typename... InArgs>
Tr operator*(const Tr<T, InArgs...>& _rhs) const;
/**
* \brief \b Divide transform to compute inverse-transformation.
*
* \param[in] _rhs Transform to divide.
*
* \return new transform result.
*/
template <template <typename> typename... InArgs>
Tr operator/(const Tr<T, InArgs...>& _rhs) const;
/**
* \brief \b Multiply transform to compute transformation.
*
* \param[in] _rhs Transform to multiply.
*
* \return self transform result.
*/
template <template <typename> typename... InArgs>
Tr& operator*=(const Tr<T, InArgs...>& _rhs);
/**
* \brief \b Divide transform to compute inverse-transformation.
*
* \param[in] _rhs Transform to divide.
*
* \return self transform result.
*/
template <template <typename> typename... InArgs>
Tr& operator/=(const Tr<T, InArgs...>& _rhs);
//}
//{ Cast
/**
* \brief \e Cast operator into other Transf type.
*
* \tparam TOut Type of the casted transform.
* \tparam ArgsOut Args Type of the casted transform.
*
* \return \e Casted result.
*/
template <typename TOut, template <typename> typename... ArgsOut>
operator Tr<TOut, ArgsOut...>() const noexcept;
//}
private:
//{ Packed
template <typename CurrT, typename... PArgs>
bool IsZeroPacked() const noexcept;
template <typename CurrT, typename... PArgs>
bool IsIdentityPacked() const noexcept;
template <typename CurrT, typename... PArgs>
bool EqualsPacked(const Tr& _other, T _epsilon) const noexcept;
template <typename CurrT, typename... PArgs>
void LerpUnclampedPacked(const Tr& _start, const Tr& _end, float _alpha) noexcept;
template <typename TrIn, typename CurrT, typename... PArgs>
void MultiplyPacked(const Tr& _lhs, const TrIn& _rhs) noexcept;
template <typename TrIn, typename CurrT, typename... PArgs>
void DividePacked(const Tr& _lhs, const TrIn& _rhs) noexcept;
//}
#if SA_LOGGER_IMPL
template <typename CurrT, typename... PArgs>
std::string ToStringPacked() const noexcept;
public:
std::string ToString() const noexcept;
#endif
};
#if SA_LOGGER_IMPL
/**
* \brief ToString Transform implementation
*
* Convert Transform as a string.
*
* \tparam T Input Transform type.
* \tparam Args Input Transform component types.
*
* \param[in] _tr Input Transform.
*
* \return input transform as a string.
*/
template <typename T, template <typename> typename... Args>
std::string ToString(const Tr<T, Args...>& _tr) { return _tr.ToString(); }
#endif
//{ Aliases
//{ Tr aliases
/// Alias for Position Tranf.
template <typename T>
using TrP = Tr<T, TrPosition>;
/// Alias for Rotation Tranf.
template <typename T>
using TrR = Tr<T, TrRotation>;
/// Alias for Scale Tranf.
template <typename T>
using TrS = Tr<T, TrScale>;
/// Alias for UScale Tranf.
template <typename T>
using TrUS = Tr<T, TrUScale>;
/// Alias for Position Rotation Tranf.
template <typename T>
using TrPR = Tr<T, TrPosition, TrRotation>;
/// Alias for Position Rotation Scale Tranf.
template <typename T>
using TrPRS = Tr<T, TrPosition, TrRotation, TrScale>;
/// Alias for Position Rotation UScale Tranf.
template <typename T>
using TrPRUS = Tr<T, TrPosition, TrRotation, TrUScale>;
//{ Float
/// Alias for Position Tranf float.
using TrPf = Tr<float, TrPosition>;
/// Alias for Rotation Tranf float.
using TrRf = Tr<float, TrRotation>;
/// Alias for Scale Tranf float.
using TrSf = Tr<float, TrScale>;
/// Alias for UScale Tranf float.
using TrUSf = Tr<float, TrUScale>;
/// Alias for Position Rotation Tranf float.
using TrPRf = Tr<float, TrPosition, TrRotation>;
/// Alias for Position Rotation Scale Tranf float.
using TrPRSf = Tr<float, TrPosition, TrRotation, TrScale>;
/// Alias for Position Rotation UScale Tranf float.
using TrPRUSf = Tr<float, TrPosition, TrRotation, TrUScale>;
//}
//{ Double
/// Alias for Position Tranf double.
using TrPd = Tr<double, TrPosition>;
/// Alias for Rotation Tranf double.
using TrRd = Tr<double, TrRotation>;
/// Alias for Scale Tranf double.
using TrSd = Tr<double, TrScale>;
/// Alias for UScale Tranf double.
using TrUSd = Tr<double, TrUScale>;
/// Alias for Position Rotation Tranf double.
using TrPRd = Tr<double, TrPosition, TrRotation>;
/// Alias for Position Rotation Scale Tranf double.
using TrPRSd = Tr<double, TrPosition, TrRotation, TrScale>;
/// Alias for Position Rotation UScale Tranf double.
using TrPRUSd = Tr<double, TrPosition, TrRotation, TrUScale>;
//}
//}
//{ Transform aliases
/// Template alias of Tr
template <typename T, template <typename> typename... Args>
using Transform = Tr<T, Args...>;
/// Alias for Position Transform.
template <typename T>
using TransformP = Transform<T, TrPosition>;
/// Alias for Rotation Transform.
template <typename T>
using TransformR = Transform<T, TrRotation>;
/// Alias for Scale Transform.
template <typename T>
using TransformS = Transform<T, TrScale>;
/// Alias for UScale Transform.
template <typename T>
using TransformUS = Transform<T, TrUScale>;
/// Alias for Position Rotation Transform.
template <typename T>
using TransformPR = Transform<T, TrPosition, TrRotation>;
/// Alias for Position Rotation Scale Transform.
template <typename T>
using TransformPRS = Transform<T, TrPosition, TrRotation, TrScale>;
/// Alias for Position Rotation UScale Transform.
template <typename T>
using TransformPRUS = Transform<T, TrPosition, TrRotation, TrUScale>;
//{ Float
/// Alias for Position Transform float.
using TransformPf = Transform<float, TrPosition>;
/// Alias for Rotation Transform float.
using TransformRf = Transform<float, TrRotation>;
/// Alias for Scale Transform float.
using TransformSf = Transform<float, TrScale>;
/// Alias for UScale Transform float.
using TransformUSf = Transform<float, TrUScale>;
/// Alias for Position Rotation Transform float.
using TransformPRf = Transform<float, TrPosition, TrRotation>;
/// Alias for Position Rotation Scale Transform float.
using TransformPRSf = Transform<float, TrPosition, TrRotation, TrScale>;
/// Alias for Position Rotation UScale Transform float.
using TransformPRUSf = Transform<float, TrPosition, TrRotation, TrUScale>;
//}
//{ Double
/// Alias for Position Transform double.
using TransformPd = Transform<double, TrPosition>;
/// Alias for Rotation Transform double.
using TransformRd = Transform<double, TrRotation>;
/// Alias for Scale Transform double.
using TransformSd = Transform<double, TrScale>;
/// Alias for UScale Transform double.
using TransformUSd = Transform<double, TrUScale>;
/// Alias for Position Rotation Transform double.
using TransformPRd = Transform<double, TrPosition, TrRotation>;
/// Alias for Position Rotation Scale Transform double.
using TransformPRSd = Transform<double, TrPosition, TrRotation, TrScale>;
/// Alias for Position Rotation UScale Transform double.
using TransformPRUSd = Transform<double, TrPosition, TrRotation, TrUScale>;
//}
//}
//}
}
/**
* @example TransformTests.cpp
* Examples and Unitary Tests for Transform.
*/
/** @} */
#include <SA/Maths/Transform/Transform.inl>
#endif // GUARD
| 24.196617
| 114
| 0.694976
|
SapphireSuite
|
525688826eb5492aa75836c31cb7d7c06ecaa3a6
| 1,481
|
hpp
|
C++
|
base/Aabb.hpp
|
sydneyzh/cluster_forward_demo_vk
|
0a9d7cb24f6cff49fcf0f7b1e7da38142ee412cb
|
[
"MIT"
] | 47
|
2017-12-11T17:55:39.000Z
|
2022-02-18T12:55:41.000Z
|
base/Aabb.hpp
|
sydneyzh/cluster_forward_demo_vk
|
0a9d7cb24f6cff49fcf0f7b1e7da38142ee412cb
|
[
"MIT"
] | null | null | null |
base/Aabb.hpp
|
sydneyzh/cluster_forward_demo_vk
|
0a9d7cb24f6cff49fcf0f7b1e7da38142ee412cb
|
[
"MIT"
] | 5
|
2018-02-04T20:37:55.000Z
|
2021-08-16T02:32:03.000Z
|
#pragma once
#include <glm/glm.hpp>
namespace base
{
class Aabb
{
public:
glm::vec3 min;
glm::vec3 max;
Aabb(const glm::vec3& min, const glm::vec3& max)
:min(min), max(max)
{}
Aabb(const glm::vec3& position, const float radius)
{
min=position - radius;
max=position + radius;
}
const glm::vec3 gen_center() const
{
return (min + max)*.5f;
}
const glm::vec3 get_half_size() const
{
return (max - min)*.5f;
}
const glm::vec3 get_diagonal() const
{
return max - min;
}
float get_volume() const
{
glm::vec3 d=get_diagonal();
return d.x*d.y*d.z;
}
float get_surface_area() const
{
glm::vec3 d=get_diagonal();
return 2.f*(d.x*d.y + d.y*d.x + d.z*d.x);
}
bool inside(const glm::vec3& pt)
{
return max.x > pt.x && min.x<pt.x
&& max.y>pt.y && min.y<pt.y
&& max.z>pt.z && min.z < pt.z;
}
};
Aabb combine(const Aabb& a, const Aabb& b)
{
return Aabb{min(a.min, b.min), max(a.max, b.max)};
}
Aabb combine(const Aabb& a, const glm::vec3& pt)
{
return Aabb{min(a.min, pt), max(a.max, pt)};
}
bool overlaps(const Aabb& a, const Aabb& b)
{
return a.max.x > b.min.x && a.min.x<b.max.x
&& a.max.y>b.min.y && a.min.y<b.max.y
&& a.max.z>b.min.z && a.min.z < b.max.z;
}
Aabb operator*(const glm::mat4& transform, const Aabb& a);
} // namespace base
| 19.233766
| 58
| 0.533423
|
sydneyzh
|
525cbce9aaceba6cbe0aa1fa5b24435746a73e75
| 5,125
|
cpp
|
C++
|
Super Monaco GP/ModuleAbout.cpp
|
gerardpf2/SuperMonacoGP
|
dbb46ffff701e9781d7975586a82ea8c56f8dd9f
|
[
"MIT"
] | null | null | null |
Super Monaco GP/ModuleAbout.cpp
|
gerardpf2/SuperMonacoGP
|
dbb46ffff701e9781d7975586a82ea8c56f8dd9f
|
[
"MIT"
] | null | null | null |
Super Monaco GP/ModuleAbout.cpp
|
gerardpf2/SuperMonacoGP
|
dbb46ffff701e9781d7975586a82ea8c56f8dd9f
|
[
"MIT"
] | null | null | null |
#include "ModuleAbout.h"
#include <assert.h>
#include "Globals.h"
#include "Animation.h"
#include "ModuleFont.h"
#include "ModuleInput.h"
#include "ModuleSwitch.h"
#include "ModuleAboutUI.h"
#include "ModuleRenderer.h"
#include "ModuleAnimation.h"
ModuleAbout::ModuleAbout(GameEngine* gameEngine) :
Module(gameEngine)
{
baseAllRect = BASE_ALL_RECT;
carRect = CAR_RECT;
aboutPosition = ABOUT_POSITION;
projectPosition = PROJECT_POSITION;
projectValuePosition = PROJECT_VALUE_POSITION;
techPosition = TECH_POSITION;
techValuePosition = TECH_VALUE_POSITION;
authorPosition = AUTHOR_POSITION;
authorValuePosition = AUTHOR_VALUE_POSITION;
separationPosition = SEPARATION_POSITION;
controlsPosition = CONTROLS_POSITION;
controlsValuePosition0 = CONTROLS_VALUE_POSITION_0;
controlsValuePosition1 = CONTROLS_VALUE_POSITION_1;
controlsValuePosition2 = CONTROLS_VALUE_POSITION_2;
controlsValuePosition3 = CONTROLS_VALUE_POSITION_3;
}
ModuleAbout::~ModuleAbout()
{ }
bool ModuleAbout::setUp()
{
assert(getGameEngine());
assert(getGameEngine()->getModuleAnimation());
carAnimationGroupId = getGameEngine()->getModuleAnimation()->load("Resources/Configurations/Animations/About.json");
carAnimation = getGameEngine()->getModuleAnimation()->getAnimation(carAnimationGroupId, 0);
return true;
}
bool ModuleAbout::update(float deltaTimeS)
{
if(!getBlocked())
{
checkGoStart();
updateCar(deltaTimeS);
}
render();
return true;
}
void ModuleAbout::cleanUp()
{
assert(getGameEngine());
assert(getGameEngine()->getModuleAnimation());
getGameEngine()->getModuleAnimation()->unload(carAnimationGroupId);
carAnimation = nullptr;
}
void ModuleAbout::checkGoStart() const
{
assert(getGameEngine());
assert(getGameEngine()->getModuleInput());
assert(getGameEngine()->getModuleSwitch());
if(getGameEngine()->getModuleInput()->getKeyState(SDL_SCANCODE_RETURN) == KeyState::DOWN || getGameEngine()->getModuleInput()->getKeyState(SDL_SCANCODE_ESCAPE) == KeyState::DOWN)
getGameEngine()->getModuleSwitch()->setNewGameModule(GameModule::START);
}
void ModuleAbout::updateCar(float deltaTimeS)
{
assert(carAnimation);
carAnimation->update(deltaTimeS);
}
void ModuleAbout::render() const
{
assert(getGameEngine());
assert(getGameEngine()->getModuleRenderer());
getGameEngine()->getModuleRenderer()->renderRect(&baseAllRect, 0, 0, 0);
renderCar();
renderInfo();
}
void ModuleAbout::renderCar() const
{
assert(carAnimation);
assert(getGameEngine());
assert(getGameEngine()->getModuleRenderer());
const Texture* carT = carAnimation->getCurrentFrame();
assert(carT);
getGameEngine()->getModuleRenderer()->renderTexture(carT->t, carT->r, &carRect, carT->hFlipped);
}
void ModuleAbout::renderInfo() const
{
assert(getGameEngine());
assert(getGameEngine()->getModuleFont());
getGameEngine()->getModuleFont()->renderText("ABOUT", aboutPosition, HAlignment::CENTER, VAlignment::BOTTOM, ABOUT_POSITION_SCALE, ABOUT_POSITION_SCALE, 224, 160, 0);
getGameEngine()->getModuleFont()->renderText("PROJECT", projectPosition, HAlignment::LEFT, VAlignment::CENTER, POSITION_SCALE, POSITION_SCALE, 224, 160, 0);
getGameEngine()->getModuleFont()->renderText("SUPER MONACO GP CLONE", projectValuePosition, HAlignment::LEFT, VAlignment::CENTER, VALUE_POSITION_SCALE, VALUE_POSITION_SCALE, 248, 252, 248);
getGameEngine()->getModuleFont()->renderText("TECH", techPosition, HAlignment::LEFT, VAlignment::CENTER, POSITION_SCALE, POSITION_SCALE, 224, 160, 0);
getGameEngine()->getModuleFont()->renderText("C++ AND SDL", techValuePosition, HAlignment::LEFT, VAlignment::CENTER, VALUE_POSITION_SCALE, VALUE_POSITION_SCALE, 248, 252, 248);
getGameEngine()->getModuleFont()->renderText("AUTHOR", authorPosition, HAlignment::LEFT, VAlignment::CENTER, POSITION_SCALE, POSITION_SCALE, 224, 160, 0);
getGameEngine()->getModuleFont()->renderText("GERARD PF", authorValuePosition, HAlignment::LEFT, VAlignment::CENTER, VALUE_POSITION_SCALE, VALUE_POSITION_SCALE, 248, 252, 248);
getGameEngine()->getModuleFont()->renderText("------------------------------", separationPosition, HAlignment::CENTER, VAlignment::CENTER, POSITION_SCALE, POSITION_SCALE, 224, 160, 0);
getGameEngine()->getModuleFont()->renderText("CONTROLS", controlsPosition, HAlignment::LEFT, VAlignment::CENTER, POSITION_SCALE, POSITION_SCALE, 224, 160, 0);
getGameEngine()->getModuleFont()->renderText("WASD - DRIVE", controlsValuePosition0, HAlignment::LEFT, VAlignment::CENTER, VALUE_POSITION_SCALE, VALUE_POSITION_SCALE, 248, 252, 248);
getGameEngine()->getModuleFont()->renderText("ESCAPE - GO BACK", controlsValuePosition1, HAlignment::LEFT, VAlignment::CENTER, VALUE_POSITION_SCALE, VALUE_POSITION_SCALE, 248, 252, 248);
getGameEngine()->getModuleFont()->renderText("ENTER - SELECT OPTION", controlsValuePosition2, HAlignment::LEFT, VAlignment::CENTER, VALUE_POSITION_SCALE, VALUE_POSITION_SCALE, 248, 252, 248);
getGameEngine()->getModuleFont()->renderText("ARROWS - DRIVE AND CHANGE OPTION", controlsValuePosition3, HAlignment::LEFT, VAlignment::CENTER, VALUE_POSITION_SCALE, VALUE_POSITION_SCALE, 248, 252, 248);
}
| 35.590278
| 203
| 0.770732
|
gerardpf2
|
525cc8d1cb1e7e78996c640594faa44583ab1158
| 815
|
cpp
|
C++
|
editorqgadget.cpp
|
cbcalves/qgadgetEditor
|
f0d2be22f930f6d103d398b6f4ea1da234266c1f
|
[
"Apache-2.0"
] | null | null | null |
editorqgadget.cpp
|
cbcalves/qgadgetEditor
|
f0d2be22f930f6d103d398b6f4ea1da234266c1f
|
[
"Apache-2.0"
] | null | null | null |
editorqgadget.cpp
|
cbcalves/qgadgetEditor
|
f0d2be22f930f6d103d398b6f4ea1da234266c1f
|
[
"Apache-2.0"
] | null | null | null |
#include "editorqgadget.h"
#include <QFrame>
#include <QVBoxLayout>
#include <QEventLoop>
#include <QCloseEvent>
#include "elements/qgadgetfactory.h"
EditorQGadget::EditorQGadget(const QString &tipo, void *qGadget, QWidget *parent) :
QWidget(parent)
{
setWindowTitle(QStringLiteral("EditorQGadget [%0]").arg(tipo));
auto boxlayout = new QVBoxLayout;
setLayout(boxlayout);
boxlayout->setSizeConstraint(QLayout::SetFixedSize);
auto child = qGadgetFactory::decompose(tipo, qGadget);
boxlayout->addWidget(child);
}
void EditorQGadget::edit()
{
QEventLoop event;
QObject::connect(this, &EditorQGadget::closeProcess, &event, &QEventLoop::quit);
show();
event.exec();
}
void EditorQGadget::closeEvent(QCloseEvent *event)
{
emit closeProcess();
event->accept();
}
| 22.638889
| 84
| 0.71411
|
cbcalves
|
526188d3b4a68e49a4c22933ef7d1d78d233e572
| 5,376
|
cpp
|
C++
|
tests/testConfigHandler.cpp
|
semper24/HTTP-Server
|
1cb238385634ca17a5ee242d17e7d6926dc2bf21
|
[
"MIT"
] | null | null | null |
tests/testConfigHandler.cpp
|
semper24/HTTP-Server
|
1cb238385634ca17a5ee242d17e7d6926dc2bf21
|
[
"MIT"
] | null | null | null |
tests/testConfigHandler.cpp
|
semper24/HTTP-Server
|
1cb238385634ca17a5ee242d17e7d6926dc2bf21
|
[
"MIT"
] | null | null | null |
/*
** EPITECH PROJECT, 2020
** B-YEP-500-NAN-5-1-zia-arthur.bertaud
** File description:
** testConfigHandler.cpp
*/
#include <criterion/criterion.h>
#include <criterion/redirect.h>
#include "configHandler.hpp"
#include "pathHandler.hpp"
#include "Error.hpp"
#include <iostream>
#include <cstdlib>
#include <filesystem>
#include <unistd.h>
Test(testPathSoError, configHandler)
{
std::string tab[] = {
"{\n",
" \"zia\": {\n",
" \"modules\": [\n",
" \"libphpCgiModulett\",\n",
" \"sslModule\",\n",
" \"libsnakeModule\"\n",
" ]\n",
" }\n",
"}",
"\0"
};
std::ofstream outfile ("test.txt");
for (int index = 0; tab[index].length() != 0; index++)
outfile << tab[index];
outfile.close();
try {
configPaths paths;
paths.configPath = "test.txt";
configHandler configHand(paths);
}
catch (Error& e) {
cr_assert(std::strcmp(e.what(), "Error config file: the default config is not correct") == 0);
}
sleep(1);
}
Test(TestTagErr, configHandler)
{
std::string tab[] = {
"{\n",
" \"zia\": {\n",
" \"modules\": [\n",
" \"Error\",\n",
" \"Error\",\n",
" \"Error\",\n",
" \"Error\"\n",
" ]\n",
" }\n",
"}",
"\0"
};
std::ofstream outfile ("testErr.txt");
for (int index = 0; tab[index].length() != 0; index++)
outfile << tab[index];
outfile.close();
try {
configPaths paths;
paths.configPath = "testErr.txt";
configHandler configHand(paths);
}
catch (Error& e) {
cr_assert(std::strcmp(e.what(), "Error config file: the default config is not correct") == 0);
}
sleep(1);
}
Test(TestAllGood, configHandler)
{
std::filesystem::create_directories("FileSo");
std::string tab[] = {
"{\n",
" \"zia\": {\n",
" \"modules\": [\n",
" \"phpCgiModule\",\n",
" \"sslModule\",\n",
" \"snakeModule\"\n",
" ]\n",
" }\n",
"}",
"\0"
};
std::ofstream phpSo ("FileSo/libphpCgiModule.so");
phpSo.close();
std::ofstream sslSo ("FileSo/libsslModule.so");
sslSo.close();
std::ofstream snakeSo ("FileSo/libsnakeModule.so");
snakeSo.close();
std::ofstream outfile ("test.txt");
std::unordered_map<moduleType, std::string> modulePaths;
for (int index = 0; tab[index].length() != 0; index++)
outfile << tab[index];
outfile.close();
try {
configPaths paths;
paths.configPath = "test.txt";
paths.dirPath = "FileSo/";
configHandler configHand(paths);
modulePaths = configHand.getListModules();
}
catch (Error& e) {
}
cr_assert_eq(modulePaths[moduleType::PHPCGI], "FileSo/libphpCgiModule.so");
sleep(1);
}
Test(TestgetModule, configHandler)
{
int size = 0;
std::filesystem::create_directories("FileSo");
std::string tab[] = {
"{\n",
" \"zia\": {\n",
" \"modules\": [\n",
" \"phpCgiModule\",\n",
" \"sslModule\",\n",
" \"snakeModule\"\n",
" ]\n",
" }\n",
"}",
"\0"
};
std::ofstream phpSo ("FileSo/libphpCgiModule.so");
phpSo.close();
std::ofstream sslSo ("FileSo/libsslModule.so");
sslSo.close();
std::ofstream snakeSo ("FileSo/libsnakeModule.so");
snakeSo.close();
std::ofstream outfile ("test.txt");
for (int index = 0; tab[index].length() != 0; index++)
outfile << tab[index];
outfile.close();
try {
configPaths paths;
paths.configPath = "test.txt";
paths.dirPath = "FileSo/";
configHandler configHand(paths);
auto& modulePaths = configHand.getListModules();
modulePaths.clear();
modulePaths = configHand.getListModules();
size = modulePaths.size();
cr_assert_eq(size, 0);
}
catch (Error& e) {
}
sleep(1);
}
Test(TestgetProcess, configHandler)
{
int size = 0;
std::filesystem::create_directories("FileSo");
std::string tab[] = {
"{\n",
" \"zia\": {\n",
" \"modules\": [\n",
" \"phpCgiModule\",\n",
" \"sslModule\",\n",
" \"snakeModule\"\n",
" ]\n",
" }\n",
"}",
"\0"
};
std::ofstream phpSo ("FileSo/libphpCgiModule.so");
phpSo.close();
std::ofstream sslSo ("FileSo/libsslModule.so");
sslSo.close();
std::ofstream snakeSo ("FileSo/libsnakeModule.so");
snakeSo.close();
std::ofstream outfile ("test.txt");
for (int index = 0; tab[index].length() != 0; index++)
outfile << tab[index];
outfile.close();
try {
configPaths paths;
paths.configPath = "test.txt";
paths.dirPath = "FileSo/";
configHandler configHand(paths);
processingList processList = configHand.getCopyProcessList();
size = processList.getSize();
cr_assert_eq(size, 3);
}
catch (Error& e) {
}
sleep(1);
}
| 27.428571
| 102
| 0.499256
|
semper24
|
5264e92df9a2b1572c343a6fb120db98dc17efd2
| 8,852
|
hpp
|
C++
|
lib/ml/regression.hpp
|
OwenDeng1993/Husky
|
61ba0e8fc2a0ab025e89307de07a1c6833227857
|
[
"Apache-2.0"
] | 117
|
2016-08-31T04:05:08.000Z
|
2021-12-18T15:05:38.000Z
|
lib/ml/regression.hpp
|
OwenDeng1993/Husky
|
61ba0e8fc2a0ab025e89307de07a1c6833227857
|
[
"Apache-2.0"
] | 223
|
2016-09-12T05:32:44.000Z
|
2020-05-22T02:51:21.000Z
|
lib/ml/regression.hpp
|
OwenDeng1993/Husky
|
61ba0e8fc2a0ab025e89307de07a1c6833227857
|
[
"Apache-2.0"
] | 77
|
2016-08-31T04:02:57.000Z
|
2020-04-08T09:23:46.000Z
|
// Copyright 2016 Husky Team
//
// 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 <algorithm>
#include <functional>
#include "base/assert.hpp"
#include "base/log.hpp"
#include "core/context.hpp"
#include "core/objlist.hpp"
#include "lib/aggregator.hpp"
#include "lib/aggregator_factory.hpp"
#include "lib/ml/feature_label.hpp"
#include "lib/ml/parameter.hpp"
#include "lib/vector.hpp"
namespace husky {
namespace lib {
namespace ml {
using husky::lib::AggregatorFactory;
using husky::lib::Aggregator;
// base class for regression
template <typename FeatureT, typename LabelT, bool is_sparse, typename ParamT = ParameterBucket<double>>
class Regression {
typedef LabeledPointHObj<FeatureT, LabelT, is_sparse> ObjT;
typedef ObjList<ObjT> ObjL;
public:
bool report_per_round = false; // whether report error per iteration
// constructors
Regression() {}
explicit Regression(int _num_param) { set_num_param(_num_param); }
Regression( // standard (3 args):
std::function<Vector<FeatureT, is_sparse>(ObjT&, Vector<FeatureT, false>&)> _gradient_func, // gradient func
std::function<FeatureT(ObjT&, ParamT&)> _error_func, // error function
int _num_param) // number of params
: gradient_func_(_gradient_func),
error_func_(_error_func) {
set_num_param(_num_param);
}
// initialize parameter with positive size
void set_num_param(int _num_param) {
if (_num_param > 0) {
param_list_.init(_num_param, 0.0);
}
}
// query parameters
int get_num_param() { return param_list_.get_num_param(); } // get parameter size
// TODO(GUOYuyong): add get_param function to return vector for bindings
inline const ParamT& get_param() { return param_list_; }
void present_param() { // print each parameter to log
if (this->trained_ == true)
param_list_.present();
}
// predict and store in y
void set_predict_func(std::function<LabelT(ObjT&, ParamT&)> _predict_func) { this->predict_func_ = _predict_func; }
void predict(ObjL& data) {
ASSERT_MSG(this->predict_func_ != nullptr, "Predict function is not specified.");
list_execute(data, [&, this](ObjT& this_obj) {
auto& y = this_obj.y;
y = this->predict_func_(this_obj, this->param_list_);
});
}
// calculate average error rate
FeatureT avg_error(ObjL& data) {
Aggregator<int> num_samples_agg(0, [](int& a, const int& b) { a += b; });
Aggregator<FeatureT> error_agg(0.0, [](FeatureT& a, const FeatureT& b) { a += b; });
auto& ac = AggregatorFactory::get_channel();
list_execute(data, {}, {&ac}, [&, this](ObjT& this_obj) {
error_agg.update(this->error_func_(this_obj, this->param_list_));
num_samples_agg.update(1);
});
int num_samples = num_samples_agg.get_value();
auto global_error = error_agg.get_value();
auto mse = global_error / num_samples;
return mse;
}
// train model
template <template <typename, typename, bool> class GD>
void train(ObjL& data, int iters, double learning_rate) {
// check conditions
ASSERT_MSG(param_list_.get_num_param() > 0, "The number of parameters is 0.");
ASSERT_MSG(gradient_func_ != nullptr, "Gradient function is not specified.");
ASSERT_MSG(error_func_ != nullptr, "Error function is not specified.");
// statistics: total number of samples and error
Aggregator<int> num_samples_agg(0, [](int& a, const int& b) { a += b; }); // total number of samples
Aggregator<FeatureT> error_stat(0.0, [](FeatureT& a, const double& b) { a += b; }); // sum of error
error_stat.to_reset_each_iter(); // reset each round
// get statistics
auto& ac = AggregatorFactory::get_channel();
list_execute(data, {}, {&ac}, [&](ObjT& this_obj) { num_samples_agg.update(1); });
int num_samples = num_samples_agg.get_value();
// report statistics
if (Context::get_global_tid() == 0) {
husky::LOG_I << "Training set size = " << std::to_string(num_samples);
}
// use gradient descent to calculate step
GD<FeatureT, LabelT, is_sparse> gd(gradient_func_, learning_rate);
for (int round = 0; round < iters; round++) {
// delegate update operation to gd
gd.update_vec(data, param_list_, num_samples);
// option to report error rate
if (this->report_per_round == true) {
// calculate error rate
list_execute(data, {}, {&ac}, [&, this](ObjT& this_obj) {
auto error = this->error_func_(this_obj, this->param_list_);
error_stat.update(error);
});
if (Context::get_global_tid() == 0) {
husky::LOG_I << ("The error in iteration " + std::to_string(round + 1) + ": " +
std::to_string(error_stat.get_value() / num_samples));
}
}
}
this->trained_ = true;
} // end of train
// train and test model with early stopping
template <template <typename, typename, bool> class GD>
void train_test(ObjL& data, ObjL& Test, int iters, double learning_rate) {
// check conditions
ASSERT_MSG(param_list_.get_num_param() > 0, "The number of parameters is 0.");
ASSERT_MSG(gradient_func_ != nullptr, "Gradient function is not specified.");
ASSERT_MSG(error_func_ != nullptr, "Error function is not specified.");
// statistics: total number of samples and error
Aggregator<int> num_samples_agg(0, [](int& a, const int& b) { a += b; }); // total number of samples
Aggregator<FeatureT> error_stat(0.0, [](FeatureT& a, const FeatureT& b) { a += b; }); // sum of error
error_stat.to_reset_each_iter(); // reset each round
// get statistics
auto& ac = AggregatorFactory::get_channel();
list_execute(data, {}, {&ac}, [&](ObjT& this_obj) { num_samples_agg.update(1); });
int num_samples = num_samples_agg.get_value();
// report statistics
if (Context::get_global_tid() == 0) {
husky::LOG_I << "Training set size = " << num_samples;
}
// use gradient descent to calculate step
GD<FeatureT, LabelT, is_sparse> gd(gradient_func_, learning_rate);
double pastError = 0.0;
for (int round = 0; round < iters; round++) {
// delegate update operation to gd
gd.update_vec(data, param_list_, num_samples);
auto currentError = avg_error(Test);
// option to report error rate
if (this->report_per_round == true) {
if (Context::get_global_tid() == 0) {
husky::LOG_I << "The error in iteration " << (round + 1) << ": " << currentError;
}
}
// TODO(Tatiana): handle fluctuation in test error
// validation based early stopping -- naive version
if (currentError == 0.0 || (round != 0 && currentError > pastError)) {
if (Context::get_global_tid() == 0) {
husky::LOG_I << "Early stopping invoked. Training is completed.";
}
break;
}
pastError = currentError;
}
this->trained_ = true;
} // end of train_test
protected:
std::function<Vector<FeatureT, is_sparse>(ObjT&, Vector<FeatureT, false>&)> gradient_func_ = nullptr;
std::function<FeatureT(ObjT&, ParamT&)> error_func_ = nullptr; // error function
std::function<LabelT(ObjT&, ParamT&)> predict_func_ = nullptr;
ParamT param_list_; // parameter vector list
int num_feature_ = -1; // number of features (maybe != num_param)
bool trained_ = false; // indicate if model is trained
}; // Regression
} // namespace ml
} // namespace lib
} // namespace husky
| 42.354067
| 120
| 0.600655
|
OwenDeng1993
|
527551c95ea2b09cfc78e48cc0218d797b1148b6
| 12,281
|
cpp
|
C++
|
tests/math/TestVectorN.cpp
|
marek-cel/libmcutils
|
671a20f37378d32ade4decefdbfba70448d12504
|
[
"MIT"
] | null | null | null |
tests/math/TestVectorN.cpp
|
marek-cel/libmcutils
|
671a20f37378d32ade4decefdbfba70448d12504
|
[
"MIT"
] | null | null | null |
tests/math/TestVectorN.cpp
|
marek-cel/libmcutils
|
671a20f37378d32ade4decefdbfba70448d12504
|
[
"MIT"
] | null | null | null |
#include <gtest/gtest.h>
#include <cmath>
#include <mcutils/math/VectorN.h>
////////////////////////////////////////////////////////////////////////////////
class TestVectorN : public ::testing::Test
{
protected:
TestVectorN() {}
virtual ~TestVectorN() {}
void SetUp() override {}
void TearDown() override {}
};
////////////////////////////////////////////////////////////////////////////////
TEST_F(TestVectorN, CanConstruct)
{
mc::VectorN *v = nullptr;
EXPECT_NO_THROW( v = new mc::VectorN() );
delete v;
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(TestVectorN, CanDestruct)
{
mc::VectorN *v = new mc::VectorN();
EXPECT_NO_THROW( delete v );
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(TestVectorN, CanInstantiate)
{
mc::VectorN v1( 3 );
EXPECT_EQ( v1.getSize(), 3 );
EXPECT_DOUBLE_EQ( v1( 0 ), 0.0 );
EXPECT_DOUBLE_EQ( v1( 1 ), 0.0 );
EXPECT_DOUBLE_EQ( v1( 2 ), 0.0 );
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(TestVectorN, CanInstantiateAndCopy)
{
mc::VectorN v1( 3 );
v1( 0 ) = 1.0;
v1( 1 ) = 2.0;
v1( 2 ) = 3.0;
mc::VectorN v2( v1 );
EXPECT_DOUBLE_EQ( v2( 0 ), 1.0 );
EXPECT_DOUBLE_EQ( v2( 1 ), 2.0 );
EXPECT_DOUBLE_EQ( v2( 2 ), 3.0 );
EXPECT_EQ( v2.getSize(), 3 );
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(TestVectorN, CanValidate)
{
mc::VectorN v1( 3 );
v1( 0 ) = 1.0;
v1( 1 ) = 2.0;
v1( 2 ) = 3.0;
EXPECT_TRUE( v1.isValid() );
v1( 0 ) = std::numeric_limits<double>::quiet_NaN();
v1( 1 ) = 2.0;
v1( 2 ) = 3.0;
EXPECT_FALSE( v1.isValid() );
v1( 0 ) = 1.0;
v1( 1 ) = std::numeric_limits<double>::quiet_NaN();
v1( 2 ) = 3.0;
EXPECT_FALSE( v1.isValid() );
v1( 0 ) = 1.0;
v1( 1 ) = 2.0;
v1( 2 ) = std::numeric_limits<double>::quiet_NaN();
EXPECT_FALSE( v1.isValid() );
v1( 0 ) = std::numeric_limits<double>::quiet_NaN();
v1( 1 ) = std::numeric_limits<double>::quiet_NaN();
v1( 2 ) = std::numeric_limits<double>::quiet_NaN();
EXPECT_FALSE( v1.isValid() );
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(TestVectorN, CanGetLength)
{
// expected values calculated with GNU Octave
// tests/math/octave/test_vector.m
mc::VectorN v1( 3 );
EXPECT_DOUBLE_EQ( v1.getLength(), 0.0 );
v1( 0 ) = 1.0;
v1( 1 ) = 2.0;
v1( 2 ) = 3.0;
// sqrt( 1^2 + 2^2 + 3^2 ) = sqrt( 1 + 4 + 9 ) = sqrt( 14 )
EXPECT_NEAR( v1.getLength(), 3.741657, 1.0e-5 );
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(TestVectorN, CanNormalize)
{
// expected values calculated with GNU Octave
// tests/math/octave/test_vector3.m
// tests/math/octave/test_vector4.m
mc::VectorN v1( 3 );
v1( 0 ) = 1.0;
v1( 1 ) = 2.0;
v1( 2 ) = 3.0;
v1.normalize();
EXPECT_NEAR( v1( 0 ), 0.267261, 1.0e-5 );
EXPECT_NEAR( v1( 1 ), 0.534522, 1.0e-5 );
EXPECT_NEAR( v1( 2 ), 0.801784, 1.0e-5 );
EXPECT_DOUBLE_EQ( v1.getLength(), 1.0 );
mc::VectorN v2( 4 );
v2( 0 ) = 1.0;
v2( 1 ) = 2.0;
v2( 2 ) = 3.0;
v2( 3 ) = 4.0;
v2.normalize();
EXPECT_NEAR( v2( 0 ), 0.182574, 1.0e-5 );
EXPECT_NEAR( v2( 1 ), 0.365148, 1.0e-5 );
EXPECT_NEAR( v2( 2 ), 0.547723, 1.0e-5 );
EXPECT_NEAR( v2( 3 ), 0.730297, 1.0e-5 );
EXPECT_DOUBLE_EQ( v2.getLength(), 1.0 );
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(TestVectorN, CanGetArray)
{
mc::VectorN v1( 4 );
v1( 0 ) = 1.0;
v1( 1 ) = 2.0;
v1( 2 ) = 3.0;
v1( 3 ) = 4.0;
double x[4];
v1.getArray( x );
EXPECT_DOUBLE_EQ( x[ 0 ], 1.0 );
EXPECT_DOUBLE_EQ( x[ 1 ], 2.0 );
EXPECT_DOUBLE_EQ( x[ 2 ], 3.0 );
EXPECT_DOUBLE_EQ( x[ 3 ], 4.0 );
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(TestVectorN, CanGetItem)
{
mc::VectorN v1( 3 );
v1( 0 ) = 1.0;
v1( 1 ) = 2.0;
v1( 2 ) = 3.0;
EXPECT_DOUBLE_EQ( v1.getItem( 0 ), 1.0 );
EXPECT_DOUBLE_EQ( v1.getItem( 1 ), 2.0 );
EXPECT_DOUBLE_EQ( v1.getItem( 2 ), 3.0 );
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(TestVectorN, CanGetItemOutOfRange)
{
mc::VectorN v1( 3 );
v1( 0 ) = 1.0;
v1( 1 ) = 2.0;
v1( 2 ) = 3.0;
EXPECT_TRUE( std::isnan( v1.getItem( 3 ) ) );
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(TestVectorN, CanSetArray)
{
mc::VectorN v1( 3 );
double x[] = { 1.0, 2.0, 3.0 };
v1.setArray( x );
EXPECT_DOUBLE_EQ( v1( 0 ), 1.0 );
EXPECT_DOUBLE_EQ( v1( 1 ), 2.0 );
EXPECT_DOUBLE_EQ( v1( 2 ), 3.0 );
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(TestVectorN, CanSetItem)
{
mc::VectorN v1( 3 );
v1.setItem( 0, 1.0 );
v1.setItem( 1, 2.0 );
v1.setItem( 2, 3.0 );
EXPECT_DOUBLE_EQ( v1( 0 ), 1.0 );
EXPECT_DOUBLE_EQ( v1( 1 ), 2.0 );
EXPECT_DOUBLE_EQ( v1( 2 ), 3.0 );
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(TestVectorN, CanSetValue)
{
mc::VectorN v1( 3 );
v1.setValue( 1.0 );
EXPECT_DOUBLE_EQ( v1( 0 ), 1.0 );
EXPECT_DOUBLE_EQ( v1( 1 ), 1.0 );
EXPECT_DOUBLE_EQ( v1( 2 ), 1.0 );
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(TestVectorN, CanGetSize)
{
// TODO
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(TestVectorN, CanConvertToString)
{
mc::VectorN v1( 3 );
v1( 0 ) = 1.0;
v1( 1 ) = 2.0;
v1( 2 ) = 3.0;
EXPECT_STREQ( v1.toString().c_str(), "1,2,3" );
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(TestVectorN, CanResize)
{
// TODO
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(TestVectorN, CanZeroize)
{
mc::VectorN v1( 3 );
v1( 0 ) = 1.0;
v1( 1 ) = 2.0;
v1( 2 ) = 3.0;
v1.zeroize();
EXPECT_DOUBLE_EQ( v1( 0 ), 0.0 );
EXPECT_DOUBLE_EQ( v1( 1 ), 0.0 );
EXPECT_DOUBLE_EQ( v1( 2 ), 0.0 );
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(TestVectorN, CanAccessItemViaOperator)
{
mc::VectorN v1( 4 );
v1( 0 ) = 1.0;
v1( 1 ) = 2.0;
v1( 2 ) = 3.0;
v1( 3 ) = 4.0;
EXPECT_DOUBLE_EQ( v1( 0 ), 1.0 );
EXPECT_DOUBLE_EQ( v1( 1 ), 2.0 );
EXPECT_DOUBLE_EQ( v1( 2 ), 3.0 );
EXPECT_DOUBLE_EQ( v1( 3 ), 4.0 );
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(TestVectorN, CanAssign)
{
mc::VectorN v( 3 );
double x1[] = { 1.0, 0.0, 0.0 };
double x2[] = { 0.0, 1.0, 0.0 };
double x3[] = { 0.0, 0.0, 1.0 };
double x4[] = { 1.0, 2.0, 3.0 };
mc::VectorN v1( 3 );
mc::VectorN v2( 3 );
mc::VectorN v3( 3 );
mc::VectorN v4( 3 );
v1.setArray( x1 );
v2.setArray( x2 );
v3.setArray( x3 );
v4.setArray( x4 );
v = v1;
EXPECT_DOUBLE_EQ( v( 0 ), 1.0 );
EXPECT_DOUBLE_EQ( v( 1 ), 0.0 );
EXPECT_DOUBLE_EQ( v( 2 ), 0.0 );
v = v2;
EXPECT_DOUBLE_EQ( v( 0 ), 0.0 );
EXPECT_DOUBLE_EQ( v( 1 ), 1.0 );
EXPECT_DOUBLE_EQ( v( 2 ), 0.0 );
v = v3;
EXPECT_DOUBLE_EQ( v( 0 ), 0.0 );
EXPECT_DOUBLE_EQ( v( 1 ), 0.0 );
EXPECT_DOUBLE_EQ( v( 2 ), 1.0 );
v = v4;
EXPECT_DOUBLE_EQ( v( 0 ), 1.0 );
EXPECT_DOUBLE_EQ( v( 1 ), 2.0 );
EXPECT_DOUBLE_EQ( v( 2 ), 3.0 );
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(TestVectorN, CanAdd)
{
double x1[] = { 1.0, 2.0, 3.0 };
double x2[] = { 3.0, 2.0, 1.0 };
double x3[] = { 0.0, 0.0, 0.0 };
double x4[] = { 1.0, 2.0, 3.0 };
mc::VectorN v1( 3 );
mc::VectorN v2( 3 );
mc::VectorN v3( 3 );
mc::VectorN v4( 3 );
v1.setArray( x1 );
v2.setArray( x2 );
v3.setArray( x3 );
v4.setArray( x4 );
mc::VectorN v12 = v1 + v2;
mc::VectorN v34 = v3 + v4;
EXPECT_DOUBLE_EQ( v12( 0 ), 4.0 );
EXPECT_DOUBLE_EQ( v12( 1 ), 4.0 );
EXPECT_DOUBLE_EQ( v12( 2 ), 4.0 );
EXPECT_DOUBLE_EQ( v34( 0 ), 1.0 );
EXPECT_DOUBLE_EQ( v34( 1 ), 2.0 );
EXPECT_DOUBLE_EQ( v34( 2 ), 3.0 );
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(TestVectorN, CanAddWrongSize)
{
mc::VectorN v1( 3 );
mc::VectorN v2( 4 );
mc::VectorN v12 = v1 + v2;
EXPECT_TRUE( std::isnan( v12( 0 ) ) );
EXPECT_TRUE( std::isnan( v12( 1 ) ) );
EXPECT_TRUE( std::isnan( v12( 2 ) ) );
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(TestVectorN, CanNegate)
{
double x[] = { 1.0, 2.0, 3.0 };
mc::VectorN v1( 3 );
v1.setArray( x );
mc::VectorN v2 = -v1;
EXPECT_DOUBLE_EQ( v2( 0 ), -1.0 );
EXPECT_DOUBLE_EQ( v2( 1 ), -2.0 );
EXPECT_DOUBLE_EQ( v2( 2 ), -3.0 );
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(TestVectorN, CanSubstract)
{
double x1[] = { 3.0, 3.0, 3.0 };
double x2[] = { 1.0, 2.0, 3.0 };
mc::VectorN v1( 3 );
mc::VectorN v2( 3 );
v1.setArray( x1 );
v2.setArray( x2 );
mc::VectorN v = v1 - v2;
EXPECT_DOUBLE_EQ( v( 0 ), 2.0 );
EXPECT_DOUBLE_EQ( v( 1 ), 1.0 );
EXPECT_DOUBLE_EQ( v( 2 ), 0.0 );
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(TestVectorN, CanSubstractWrongSize)
{
mc::VectorN v1( 3 );
mc::VectorN v2( 4 );
mc::VectorN v12 = v1 - v2;
EXPECT_TRUE( std::isnan( v12( 0 ) ) );
EXPECT_TRUE( std::isnan( v12( 1 ) ) );
EXPECT_TRUE( std::isnan( v12( 2 ) ) );
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(TestVectorN, CanMultiplyByScalar)
{
double x[] = { 1.0, 2.0, 3.0 };
mc::VectorN v1( 3 );
v1.setArray( x );
mc::VectorN v2 = v1 * 2.0;
EXPECT_DOUBLE_EQ( v2( 0 ), 2.0 );
EXPECT_DOUBLE_EQ( v2( 1 ), 4.0 );
EXPECT_DOUBLE_EQ( v2( 2 ), 6.0 );
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(TestVectorN, CandivideByScalar)
{
double x[] = { 2.0, 4.0, 6.0 };
mc::VectorN v1( 3 );
v1.setArray( x );
mc::VectorN v2 = v1 / 2.0;
EXPECT_DOUBLE_EQ( v2( 0 ), 1.0 );
EXPECT_DOUBLE_EQ( v2( 1 ), 2.0 );
EXPECT_DOUBLE_EQ( v2( 2 ), 3.0 );
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(TestVectorN, CanUnaryAdd)
{
double x0[] = { 1.0, 2.0, 3.0 };
double x1[] = { 3.0, 2.0, 1.0 };
mc::VectorN v0( 3 );
mc::VectorN v1( 3 );
v0.setArray( x0 );
v1.setArray( x1 );
v0 += v1;
EXPECT_DOUBLE_EQ( v0( 0 ), 4.0 );
EXPECT_DOUBLE_EQ( v0( 1 ), 4.0 );
EXPECT_DOUBLE_EQ( v0( 2 ), 4.0 );
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(TestVectorN, CanUnarySubstract)
{
double x0[] = { 3.0, 3.0, 3.0 };
double x1[] = { 1.0, 2.0, 3.0 };
mc::VectorN v0( 3 );
mc::VectorN v1( 3 );
v0.setArray( x0 );
v1.setArray( x1 );
v0 -= v1;
EXPECT_DOUBLE_EQ( v0( 0 ), 2.0 );
EXPECT_DOUBLE_EQ( v0( 1 ), 1.0 );
EXPECT_DOUBLE_EQ( v0( 2 ), 0.0 );
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(TestVectorN, CanUnaryMultiplyByScalar)
{
double x0[] = { 1.0, 2.0, 3.0 };
mc::VectorN v0( 3 );
v0.setArray( x0 );
v0 *= 2.0;
EXPECT_DOUBLE_EQ( v0( 0 ), 2.0 );
EXPECT_DOUBLE_EQ( v0( 1 ), 4.0 );
EXPECT_DOUBLE_EQ( v0( 2 ), 6.0 );
}
////////////////////////////////////////////////////////////////////////////////
TEST_F(TestVectorN, CanUnaryDivideByScalar)
{
double x0[] = { 2.0, 4.0, 6.0 };
mc::VectorN v0( 3 );
v0.setArray( x0 );
v0 /= 2.0;
EXPECT_DOUBLE_EQ( v0( 0 ), 1.0 );
EXPECT_DOUBLE_EQ( v0( 1 ), 2.0 );
EXPECT_DOUBLE_EQ( v0( 2 ), 3.0 );
}
| 21.969589
| 80
| 0.420894
|
marek-cel
|
5277c5d2ce2c1fbb355e6a94e0787df194b4cf74
| 166
|
hpp
|
C++
|
src/data-structure/MergeCompat.hpp
|
inexorgame-obsolete/cube2-map-importer
|
ad81b347e4adfcf176257fdd83d6f6163c9eb30f
|
[
"CC-BY-4.0"
] | 3
|
2019-12-08T15:39:53.000Z
|
2020-04-22T11:31:48.000Z
|
src/data-structure/MergeCompat.hpp
|
inexorgame-obsolete/cube2-map-importer
|
ad81b347e4adfcf176257fdd83d6f6163c9eb30f
|
[
"CC-BY-4.0"
] | 4
|
2019-11-30T00:09:17.000Z
|
2020-01-04T13:39:20.000Z
|
src/data-structure/MergeCompat.hpp
|
inexorgame/cube2-map-importer
|
ad81b347e4adfcf176257fdd83d6f6163c9eb30f
|
[
"CC-BY-4.0"
] | 1
|
2021-01-14T17:27:45.000Z
|
2021-01-14T17:27:45.000Z
|
#pragma once
namespace inexor {
namespace cube2_map_importer {
//
#define ushort unsigned short
//
struct MergeCompat
{
ushort u1, u2, v1, v2;
};
};
};
| 9.764706
| 30
| 0.650602
|
inexorgame-obsolete
|
527b0436b19b9a2803ea066b2b9e9e7c27f51cc8
| 1,630
|
hpp
|
C++
|
12.ClusteringBig/include/ClusteringBig.hpp
|
shunjilin/AlgorithmsSpecialization
|
554996a0ce131139917dd02604ce0660ad6d2c2d
|
[
"MIT"
] | 1
|
2019-05-08T04:20:58.000Z
|
2019-05-08T04:20:58.000Z
|
12.ClusteringBig/include/ClusteringBig.hpp
|
shunjilin/AlgorithmsSpecialization
|
554996a0ce131139917dd02604ce0660ad6d2c2d
|
[
"MIT"
] | null | null | null |
12.ClusteringBig/include/ClusteringBig.hpp
|
shunjilin/AlgorithmsSpecialization
|
554996a0ce131139917dd02604ce0660ad6d2c2d
|
[
"MIT"
] | null | null | null |
#ifndef CLUSTERING_BIG_HPP
#define CLUSTERING_BIG_HPP
#include <vector>
#include <unordered_set>
#include <algorithm>
#include <cmath>
#include "BitstringFunctions.hpp"
#include "UnionFind.hpp"
namespace ClusteringBig {
unsigned kValueForSpacingOfAtLeast3(const std::vector<int>& nodes,
unsigned n_bits) {
auto _nodes = std::unordered_set<int>(std::begin(nodes),
std::end(nodes));
auto clusters = DataStructures::UnionFind(pow(2, n_bits));
unsigned n_clusters = _nodes.size();
for (auto node : nodes) {
auto distance_one_generator =
BitstringFunctions::DistanceOneGenerator(node, n_bits);
while (!distance_one_generator.done) {
auto generated = distance_one_generator.generate();
if (_nodes.find(generated) != _nodes.end() &&
!clusters.sameRoot(node, generated)) {
clusters.doUnion(node, generated);
n_clusters--;
}
}
auto distance_two_generator =
BitstringFunctions::DistanceTwoGenerator(node, n_bits);
while (!distance_two_generator.done) {
auto generated = distance_two_generator.generate();
if (_nodes.find(generated) != _nodes.end() &&
!clusters.sameRoot(node, generated)) {
clusters.doUnion(node, generated);
n_clusters--;
}
}
}
return n_clusters;
}
}
#endif
| 36.222222
| 71
| 0.552761
|
shunjilin
|
527fa7a1293ed35a4908e39062eb9af39f6aa205
| 3,090
|
hpp
|
C++
|
plane detection/include/GLViewer.hpp
|
isaackay/zed-examples
|
5ba69c32eacdcf4a1ca6733b77d9d92297e5d24b
|
[
"MIT"
] | 1
|
2019-07-01T07:58:02.000Z
|
2019-07-01T07:58:02.000Z
|
plane detection/include/GLViewer.hpp
|
isaackay/zed-examples
|
5ba69c32eacdcf4a1ca6733b77d9d92297e5d24b
|
[
"MIT"
] | null | null | null |
plane detection/include/GLViewer.hpp
|
isaackay/zed-examples
|
5ba69c32eacdcf4a1ca6733b77d9d92297e5d24b
|
[
"MIT"
] | null | null | null |
#ifndef __SIMPLE3DOBJECT_INCLUDE__
#define __SIMPLE3DOBJECT_INCLUDE__
#include <sl/Camera.hpp>
#include <GL/glew.h>
#include <GL/freeglut.h>
#include <mutex>
struct UserAction {
bool press_space;
bool hit;
sl::uint2 hit_coord;
void clear() {
press_space = false;
hit = false;
}
};
class Shader {
public:
Shader(GLchar* vs, GLchar* fs);
~Shader();
GLuint getProgramId();
static const GLint ATTRIB_VERTICES_POS = 0;
static const GLint ATTRIB_VERTICES_DIST = 1;
private:
bool compile(GLuint &shaderId, GLenum type, GLchar* src);
GLuint verterxId_;
GLuint fragmentId_;
GLuint programId_;
};
class MeshObject {
GLuint vaoID_;
GLuint vboID_[3];
int current_fc;
bool need_update;
std::vector<sl::float3> vert;
std::vector<float> edge_dist;
std::vector<sl::uint3> tri;
public:
MeshObject();
~MeshObject();
void updateMesh(std::vector<sl::float3> &vertices, std::vector<sl::uint3> &triangles, std::vector<int> &border);
void pushToGPU();
void draw();
sl::PLANE_TYPE type;
};
class GLViewer {
public:
GLViewer();
~GLViewer();
bool isAvailable();
bool init(int argc, char **argv, sl::CameraParameters, sl::MODEL cam_model);
UserAction updateImageAndState(sl::Mat &image, sl::Transform &pose, sl::TRACKING_STATE track_state);
void updateMesh(sl::Mesh &mesh, sl::PLANE_TYPE type);
void exit();
private:
// Rendering loop method called each frame by glutDisplayFunc
void render();
// Everything that needs to be updated before rendering must be done in this method
void update();
// Once everything is updated, every renderable objects must be drawn in this method
void draw();
void printText();
static void drawCallback();
static void keyReleasedCallback(unsigned char c, int x, int y);
static void mouseButtonCallback(int button, int state, int x, int y);
std::mutex mtx;
bool available;
bool change_state;
// For CUDA-OpenGL interoperability
cudaGraphicsResource* cuda_gl_ressource;//cuda GL resource
MeshObject mesh_object; // Opengl mesh container
sl::Transform camera_projection; // OpenGL camera projection matrix
sl::Mat image;
sl::Transform pose;
sl::TRACKING_STATE tracking_state;
sl::MODEL cam_model;
UserAction user_action;
bool new_data;
// Opengl object
Shader *shader_mesh; //GLSL Shader for mesh
Shader *shader_image;//GLSL Shader for image
GLuint imageTex; //OpenGL texture mapped with a cuda array (opengl gpu interop)
GLuint shMVPMatrixLoc; //Shader variable loc
GLuint shColorLoc; //Shader variable loc
GLuint texID; //Shader variable loc (sampler/texture)
GLuint fbo = 0; //FBO
GLuint renderedTexture = 0; //Render Texture for FBO
GLuint quad_vb; //buffer for vertices/coords for image
};
#endif
| 27.345133
| 117
| 0.647573
|
isaackay
|
5281bb4312e29c8869550e3d781559445eae7cea
| 3,632
|
cpp
|
C++
|
measure_cpp/test/src/measure_cppTest.cpp
|
Nobu19800/RTM-Lua-test
|
e3bac41085f0c287a5791bf0125430979aceeee6
|
[
"MIT"
] | null | null | null |
measure_cpp/test/src/measure_cppTest.cpp
|
Nobu19800/RTM-Lua-test
|
e3bac41085f0c287a5791bf0125430979aceeee6
|
[
"MIT"
] | null | null | null |
measure_cpp/test/src/measure_cppTest.cpp
|
Nobu19800/RTM-Lua-test
|
e3bac41085f0c287a5791bf0125430979aceeee6
|
[
"MIT"
] | null | null | null |
// -*- C++ -*-
/*!
* @file measure_cppTest.cpp
* @brief measurement of the processing time
* @date $Date$
*
* @author n-miyamoto@aist.go.jp
*
* MIT
*
* $Id$
*/
#include "measure_cppTest.h"
// Module specification
// <rtc-template block="module_spec">
static const char* measure_cpp_spec[] =
{
"implementation_id", "measure_cppTest",
"type_name", "measure_cppTest",
"description", "measurement of the processing time",
"version", "1.0.0",
"vendor", "Nobuhiko Miyamoto",
"category", "Sample",
"activity_type", "PERIODIC",
"kind", "DataFlowComponent",
"max_instance", "1",
"language", "C++",
"lang_type", "compile",
// Configuration variables
"conf.default.ior_str", "0",
"conf.default.exe_enable", "0",
"conf.default.max_count", "1000",
// Widget
"conf.__widget__.ior_str", "text",
"conf.__widget__.exe_enable", "radio",
"conf.__widget__.max_count", "text",
// Constraints
"conf.__constraints__.exe_enable", "(0,1)",
"conf.__type__.ior_str", "string",
"conf.__type__.exe_enable", "int",
"conf.__type__.max_count", "int",
""
};
// </rtc-template>
/*!
* @brief constructor
* @param manager Maneger Object
*/
measure_cppTest::measure_cppTest(RTC::Manager* manager)
// <rtc-template block="initializer">
: RTC::DataFlowComponentBase(manager),
m_servicePort("service")
// </rtc-template>
{
}
/*!
* @brief destructor
*/
measure_cppTest::~measure_cppTest()
{
}
RTC::ReturnCode_t measure_cppTest::onInitialize()
{
// Registration: InPort/OutPort/Service
// <rtc-template block="registration">
// Set InPort buffers
// Set OutPort buffer
// Set service provider to Ports
m_servicePort.registerProvider("interface", "Echo", m_interface);
// Set service consumers to Ports
// Set CORBA Service Ports
addPort(m_servicePort);
// </rtc-template>
// <rtc-template block="bind_config">
// Bind variables and configuration variable
bindParameter("ior_str", m_ior_str, "0");
bindParameter("exe_enable", m_exe_enable, "0");
bindParameter("max_count", m_max_count, "1000");
// </rtc-template>
return RTC::RTC_OK;
}
/*
RTC::ReturnCode_t measure_cppTest::onFinalize()
{
return RTC::RTC_OK;
}
*/
/*
RTC::ReturnCode_t measure_cppTest::onStartup(RTC::UniqueId ec_id)
{
return RTC::RTC_OK;
}
*/
/*
RTC::ReturnCode_t measure_cppTest::onShutdown(RTC::UniqueId ec_id)
{
return RTC::RTC_OK;
}
*/
RTC::ReturnCode_t measure_cppTest::onActivated(RTC::UniqueId ec_id)
{
return RTC::RTC_OK;
}
RTC::ReturnCode_t measure_cppTest::onDeactivated(RTC::UniqueId ec_id)
{
return RTC::RTC_OK;
}
RTC::ReturnCode_t measure_cppTest::onExecute(RTC::UniqueId ec_id)
{
return RTC::RTC_OK;
}
/*
RTC::ReturnCode_t measure_cppTest::onAborting(RTC::UniqueId ec_id)
{
return RTC::RTC_OK;
}
*/
/*
RTC::ReturnCode_t measure_cppTest::onError(RTC::UniqueId ec_id)
{
return RTC::RTC_OK;
}
*/
/*
RTC::ReturnCode_t measure_cppTest::onReset(RTC::UniqueId ec_id)
{
return RTC::RTC_OK;
}
*/
/*
RTC::ReturnCode_t measure_cppTest::onStateUpdate(RTC::UniqueId ec_id)
{
return RTC::RTC_OK;
}
*/
/*
RTC::ReturnCode_t measure_cppTest::onRateChanged(RTC::UniqueId ec_id)
{
return RTC::RTC_OK;
}
*/
extern "C"
{
void measure_cppTestInit(RTC::Manager* manager)
{
coil::Properties profile(measure_cpp_spec);
manager->registerFactory(profile,
RTC::Create<measure_cppTest>,
RTC::Delete<measure_cppTest>);
}
};
| 19.015707
| 69
| 0.647026
|
Nobu19800
|
5282191540e848a6fa9615fed4d08ba242b56102
| 1,474
|
cpp
|
C++
|
src/Client/EasyClient.cpp
|
TheQuantumPhysicist/HttpRpcRelay
|
810d9ed8907b4c769faa432ba7f829445b8d6f9f
|
[
"MIT"
] | null | null | null |
src/Client/EasyClient.cpp
|
TheQuantumPhysicist/HttpRpcRelay
|
810d9ed8907b4c769faa432ba7f829445b8d6f9f
|
[
"MIT"
] | null | null | null |
src/Client/EasyClient.cpp
|
TheQuantumPhysicist/HttpRpcRelay
|
810d9ed8907b4c769faa432ba7f829445b8d6f9f
|
[
"MIT"
] | null | null | null |
#include "EasyClient.h"
EasyClient::EasyClient()
{
startThreadsAndIoContext();
client = std::make_shared<ClientSession>(*ioc);
}
void EasyClient::run(http::verb verb,
const std::string& host,
const std::string& port,
const std::string& target,
const std::string& body,
int version,
const std::map<std::string, std::string>& fields)
{
client->run(verb, host, port, target, body, version, fields);
}
void EasyClient::run(const std::string& host,
const std::string& port,
boost::beast::http::request<http::string_body> request)
{
client->run(host, port, request);
}
std::future<http::response<http::string_body>> EasyClient::getResponse()
{
return client->getResponse();
}
void EasyClient::startThreadsAndIoContext()
{
ioc_work.reset();
thread.reset(); // destroy any running threads
ioc.reset();
ioc = std::make_unique<net::io_context>(1);
ioc_work = std::make_unique<net::io_context::work>(*ioc);
thread = std::unique_ptr<std::thread, decltype(threadDestructor)>(
new std::thread([this] { ioc->run(); }), threadDestructor);
}
| 33.5
| 76
| 0.506784
|
TheQuantumPhysicist
|
52821aab64f34abb37d585933bedfc26f524e390
| 4,010
|
cpp
|
C++
|
modules/preview/src/Preview/gmPreviewFboRenderer.cpp
|
GraphMIC/GraphMIC
|
8fc2aeb0143ee1292c6757f010fc9e8c68823e2b
|
[
"BSD-3-Clause"
] | 43
|
2016-04-11T11:34:05.000Z
|
2022-03-31T03:37:57.000Z
|
modules/preview/src/Preview/gmPreviewFboRenderer.cpp
|
kevinlq/GraphMIC
|
8fc2aeb0143ee1292c6757f010fc9e8c68823e2b
|
[
"BSD-3-Clause"
] | 1
|
2016-05-17T12:58:16.000Z
|
2016-05-17T12:58:16.000Z
|
modules/preview/src/Preview/gmPreviewFboRenderer.cpp
|
kevinlq/GraphMIC
|
8fc2aeb0143ee1292c6757f010fc9e8c68823e2b
|
[
"BSD-3-Clause"
] | 14
|
2016-05-13T20:23:16.000Z
|
2021-12-20T10:33:19.000Z
|
#include "gmLog.hpp"
#include "gmPreviewFboRenderer.hpp"
#include "gmPreviewFboOffscreenWindow.hpp"
#include "gmPreviewImageViewer.hpp"
#include <vtkRendererCollection.h>
#include <vtkCommand.h>
#include <vtkCamera.h>
namespace gm
{
namespace Preview
{
FboRenderer::FboRenderer(FboOffscreenWindow *offscreenWindow) : m_fboOffscreenWindow(offscreenWindow), m_fbo(0)
{
log_trace(Log::Func);
m_fboOffscreenWindow->Register(NULL);
m_fboOffscreenWindow->QtParentRenderer = this;
m_interactor = vtkSmartPointer<vtkRenderWindowInteractor>::New();
m_interactorStyle = vtkSmartPointer<vtkInteractorStyleTrackballCamera>::New();
m_interactor->SetRenderWindow(offscreenWindow);
m_interactor->Initialize();
m_interactor->SetInteractorStyle(m_interactorStyle);
}
auto FboRenderer::synchronize(QQuickFramebufferObject* fbo) -> void
{
if (!m_fbo)
{
auto viewer = static_cast<ImageViewer*>(fbo);
viewer->init();
}
}
auto FboRenderer::render() -> void
{
m_fboOffscreenWindow->PushState();
m_fboOffscreenWindow->OpenGLInitState();
m_fboOffscreenWindow->InternalRender();
m_fboOffscreenWindow->PopState();
}
auto FboRenderer::createFramebufferObject(const QSize &size) -> QOpenGLFramebufferObject*
{
QOpenGLFramebufferObjectFormat format;
format.setAttachment(QOpenGLFramebufferObject::Depth);
m_fbo = new QOpenGLFramebufferObject(size, format);
m_fboOffscreenWindow->SetFramebufferObject(m_fbo);
return m_fbo;
}
auto FboRenderer::onMouseEvent(QMouseEvent* event) -> void
{
if(this->m_interactor == NULL || event == NULL)
return;
if(!this->m_interactor->GetEnabled())
return;
this->m_interactor->SetEventInformation(event->x(), event->y(), (event->modifiers() & Qt::ControlModifier) > 0 ? 1 : 0, (event->modifiers() & Qt::ShiftModifier ) > 0 ? 1 : 0, 0, event->type() == QEvent::MouseButtonDblClick ? 1 : 0);
auto command = vtkCommand::NoEvent;
if (event->type() == QEvent::MouseMove)
command = vtkCommand::MouseMoveEvent;
else if (event->type() == QEvent::MouseButtonPress || event->type() == QEvent::MouseButtonDblClick)
{
switch (event->button())
{
case Qt::LeftButton: command = vtkCommand::LeftButtonPressEvent; break;
case Qt::RightButton: command = vtkCommand::RightButtonPressEvent; break;
case Qt::MidButton: command = vtkCommand::MiddleButtonPressEvent; break;
default: break;
}
}
else if (event->type() == QEvent::MouseButtonRelease)
{
switch (event->button())
{
case Qt::LeftButton: command = vtkCommand::LeftButtonReleaseEvent; break;
case Qt::RightButton: command = vtkCommand::RightButtonReleaseEvent; break;
case Qt::MidButton: command = vtkCommand::MiddleButtonReleaseEvent; break;
default: break;
}
}
this->m_interactor->InvokeEvent(command, event);
}
FboRenderer::~FboRenderer()
{
log_trace(Log::Del, this);
m_fboOffscreenWindow->QtParentRenderer = 0;
m_fboOffscreenWindow->Delete();
}
};
}
| 38.190476
| 244
| 0.539152
|
GraphMIC
|
528f9f52d21dfb4ce7ad67f66709a6dda135db26
| 463
|
cpp
|
C++
|
526 backtrack.cpp
|
WhiteDOU/LeetCode
|
47fee5bfc74c1417a17e6bc426a356ce9864d2b2
|
[
"MIT"
] | 1
|
2019-03-07T13:08:06.000Z
|
2019-03-07T13:08:06.000Z
|
526 backtrack.cpp
|
WhiteDOU/LeetCode
|
47fee5bfc74c1417a17e6bc426a356ce9864d2b2
|
[
"MIT"
] | null | null | null |
526 backtrack.cpp
|
WhiteDOU/LeetCode
|
47fee5bfc74c1417a17e6bc426a356ce9864d2b2
|
[
"MIT"
] | null | null | null |
class Solution
{
public:
int countArrangement(int N)
{
int res = 0;
vector<int> visited(N + 1, 0);
helper(N, visited, 1, res);
return res;
}
private:
void helper(int N, vector<int> &visited, int pos, int &res)
{
if (pos > N)
{
res++;
return;
}
for (int i = 1; i <= N; ++i)
{
if (visited[i] == 0 && (i % pos == 0 || pos % i == 0))
{
visited[i] = 1;
helper(N, visited, pos + 1, res);
visited[i] = 0;
}
}
}
};
| 14.030303
| 60
| 0.49676
|
WhiteDOU
|
5291fe710492274ce5328e6ae4faf73a01751447
| 1,233
|
hpp
|
C++
|
include/virt_wrap/enums/Domain/ModificationImpactFlag.hpp
|
AeroStun/virthttp
|
d6ae9d752721aa5ecc74dbc2dbb54de917ba31ad
|
[
"Apache-2.0"
] | 7
|
2019-08-22T20:48:15.000Z
|
2021-12-31T16:08:59.000Z
|
include/virt_wrap/enums/Domain/ModificationImpactFlag.hpp
|
AeroStun/virthttp
|
d6ae9d752721aa5ecc74dbc2dbb54de917ba31ad
|
[
"Apache-2.0"
] | 10
|
2019-08-22T21:40:43.000Z
|
2020-09-03T14:21:21.000Z
|
include/virt_wrap/enums/Domain/ModificationImpactFlag.hpp
|
AeroStun/virthttp
|
d6ae9d752721aa5ecc74dbc2dbb54de917ba31ad
|
[
"Apache-2.0"
] | 2
|
2019-08-22T21:08:28.000Z
|
2019-08-23T21:31:56.000Z
|
#pragma once
#include "virt_wrap/enums/Base.hpp"
#include "virt_wrap/utility.hpp"
#include <libvirt/libvirt-domain.h>
namespace virt::enums::domain {
class ModificationImpactFlag : private VirtEnumStorage<virDomainModificationImpact>,
public VirtEnumBase<ModificationImpactFlag>,
public EnumSetHelper<ModificationImpactFlag> {
friend VirtEnumBase<ModificationImpactFlag>;
friend EnumSetHelper<ModificationImpactFlag>;
enum class Underlying {
CURRENT = VIR_DOMAIN_AFFECT_CURRENT, /* Affect current domain state. */
LIVE = VIR_DOMAIN_AFFECT_LIVE, /* Affect running domain state. */
CONFIG = VIR_DOMAIN_AFFECT_CONFIG, /* Affect persistent domain state. */
} constexpr static default_value{};
protected:
constexpr static std::array values = {"live", "config"};
public:
using VirtEnumBase::VirtEnumBase;
constexpr static auto from_string(std::string_view sv) { return EnumSetHelper{}.from_string_base(sv); }
// using enum Underlying;
constexpr static auto CURRENT = Underlying::CURRENT;
constexpr static auto LIVE = Underlying::LIVE;
constexpr static auto CONFIG = Underlying::CONFIG;
};
}
| 41.1
| 107
| 0.705596
|
AeroStun
|
52932688758dbe915d4f7d8ea4ae62c413c83ec5
| 2,077
|
hpp
|
C++
|
source/NanairoCore/ToneMappingOperator/tone_mapping_operator.hpp
|
byzin/Nanairo
|
23fb6deeec73509c538a9c21009e12be63e8d0e4
|
[
"MIT"
] | 30
|
2015-09-06T03:14:29.000Z
|
2021-06-18T11:00:19.000Z
|
source/NanairoCore/ToneMappingOperator/tone_mapping_operator.hpp
|
byzin/Nanairo
|
23fb6deeec73509c538a9c21009e12be63e8d0e4
|
[
"MIT"
] | 31
|
2016-01-14T14:50:34.000Z
|
2018-06-25T13:21:48.000Z
|
source/NanairoCore/ToneMappingOperator/tone_mapping_operator.hpp
|
byzin/Nanairo
|
23fb6deeec73509c538a9c21009e12be63e8d0e4
|
[
"MIT"
] | 6
|
2017-04-09T13:07:47.000Z
|
2021-05-29T21:17:34.000Z
|
/*!
\file tone_mapping_operator.hpp
\author Sho Ikeda
Copyright (c) 2015-2018 Sho Ikeda
This software is released under the MIT License.
http://opensource.org/licenses/mit-license.php
*/
#ifndef NANAIRO_TONE_MAPPING_OPERATOR_HPP
#define NANAIRO_TONE_MAPPING_OPERATOR_HPP
// Standard C++ library
#include <memory>
// Zisc
#include "zisc/memory_resource.hpp"
#include "zisc/fnv_1a_hash_engine.hpp"
#include "zisc/unique_memory_pointer.hpp"
// Nanairo
#include "NanairoCore/nanairo_core_config.hpp"
#include "NanairoCore/Setting/setting_node_base.hpp"
namespace nanairo {
// Forward declaration
class HdrImage;
class LdrImage;
class System;
//! \addtogroup Core
//! \{
enum class ToneMappingType : uint32
{
kReinhard = zisc::Fnv1aHash32::hash("Reinhard"),
kFilmic = zisc::Fnv1aHash32::hash("Filmic"),
kUncharted2Filmic = zisc::Fnv1aHash32::hash("Uncharted2Filmic")
};
/*!
\brief The interface of tone mapping class.
\details
No detailed.
*/
class ToneMappingOperator
{
public:
//! Initialize the method
ToneMappingOperator(const System& system, const SettingNodeBase* settings) noexcept;
//! Finalize the method
virtual ~ToneMappingOperator() noexcept;
//! Return the exposure
Float exposure() const noexcept;
//! Return the inverse gamma value
Float inverseGamma() const noexcept;
//! Make a tonemapping method
static zisc::UniqueMemoryPointer<ToneMappingOperator> makeOperator(
System& system,
const SettingNodeBase* settings) noexcept;
//! Apply a tonemapping operator
void map(System& system,
const HdrImage& hdr_image,
LdrImage* ldr_image) const noexcept;
//! Apply a tonemap curve
virtual Float tonemap(const Float x) const noexcept = 0;
private:
//! Initialize
void initialize(const System& system, const SettingNodeBase* settings) noexcept;
Float inverse_gamma_;
Float exposure_;
};
//! \} Core
} // namespace nanairo
#include "tone_mapping_operator-inl.hpp"
#endif // NANAIRO_TONE_MAPPING_OPERATOR_HPP
| 23.077778
| 86
| 0.722195
|
byzin
|
52a4c5167e7b5fad86f9077282fe99a5cd42415c
| 19,326
|
cpp
|
C++
|
dbms/src/Common/tests/gtest_mpmc_queue.cpp
|
solotzg/tiflash
|
66f45c76692e941bc845c01349ea89de0f2cc210
|
[
"Apache-2.0"
] | 4
|
2022-03-25T21:34:15.000Z
|
2022-03-25T21:35:12.000Z
|
dbms/src/Common/tests/gtest_mpmc_queue.cpp
|
solotzg/tiflash
|
66f45c76692e941bc845c01349ea89de0f2cc210
|
[
"Apache-2.0"
] | null | null | null |
dbms/src/Common/tests/gtest_mpmc_queue.cpp
|
solotzg/tiflash
|
66f45c76692e941bc845c01349ea89de0f2cc210
|
[
"Apache-2.0"
] | 8
|
2022-03-25T10:20:08.000Z
|
2022-03-31T10:17:25.000Z
|
// Copyright 2022 PingCAP, Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <Common/MPMCQueue.h>
#include <TestUtils/TiFlashTestBasic.h>
#include <chrono>
#include <memory>
#include <random>
#include <string>
#include <thread>
#include <vector>
namespace DB::tests
{
namespace
{
class MPMCQueueTest : public ::testing::Test
{
protected:
std::random_device rd;
template <typename T>
struct ValueHelper;
template <typename T>
void testInitialize(Int64 capacity)
{
MPMCQueue<T> queue(capacity);
ASSERT_EQ(queue.getStatus(), MPMCQueueStatus::NORMAL);
ASSERT_EQ(queue.size(), 0);
testCannotTryPop(queue); /// will block if call `pop`
queue.cancel();
ASSERT_EQ(queue.getStatus(), MPMCQueueStatus::CANCELLED);
testCannotPop(queue); /// won't block
MPMCQueue<T> queue2(capacity);
queue2.finish();
ASSERT_EQ(queue2.getStatus(), MPMCQueueStatus::FINISHED);
testCannotPop(queue2); /// won't block
}
template <typename T>
void testDuplicateFinishCancel()
{
{
MPMCQueue<T> queue(1);
queue.cancel();
queue.finish();
ASSERT_EQ(queue.getStatus(), MPMCQueueStatus::CANCELLED);
}
{
MPMCQueue<T> queue(1);
queue.finish();
queue.finish();
ASSERT_EQ(queue.getStatus(), MPMCQueueStatus::FINISHED);
}
{
MPMCQueue<T> queue(1);
queue.finish();
queue.cancel();
ASSERT_EQ(queue.getStatus(), MPMCQueueStatus::FINISHED);
}
{
MPMCQueue<T> queue(1);
queue.cancel();
queue.cancel();
ASSERT_EQ(queue.getStatus(), MPMCQueueStatus::CANCELLED);
}
}
template <typename T>
void testCannotPush(MPMCQueue<T> & queue)
{
auto old_size = queue.size();
auto res = queue.push(ValueHelper<T>::make(-1));
auto new_size = queue.size();
if (res)
throw TiFlashTestException("Should push fail");
if (old_size != new_size)
throw TiFlashTestException(fmt::format("Size changed from {} to {} without push", old_size, new_size));
}
template <typename T>
void testCannotTryPush(MPMCQueue<T> & queue)
{
auto old_size = queue.size();
auto res = queue.tryPush(ValueHelper<T>::make(-1), std::chrono::microseconds(1));
auto new_size = queue.size();
if (res)
throw TiFlashTestException("Should push fail");
if (old_size != new_size)
throw TiFlashTestException(fmt::format("Size changed from {} to {} without push", old_size, new_size));
}
template <typename T>
void testCannotPop(MPMCQueue<T> & queue)
{
auto old_size = queue.size();
T res;
bool ok = queue.pop(res);
auto new_size = queue.size();
if (ok)
throw TiFlashTestException("Should pop fail");
if (old_size != new_size)
throw TiFlashTestException(fmt::format("Size changed from {} to {} without pop", old_size, new_size));
}
template <typename T>
void testCannotTryPop(MPMCQueue<T> & queue)
{
auto old_size = queue.size();
T res;
bool ok = queue.tryPop(res, std::chrono::microseconds(1));
auto new_size = queue.size();
if (ok)
throw TiFlashTestException("Should pop fail");
if (old_size != new_size)
throw TiFlashTestException(fmt::format("Size changed from {} to {} without pop", old_size, new_size));
}
template <typename T>
int testPushN(MPMCQueue<T> & queue, Int64 n, int start, bool full_after_push)
{
auto old_size = queue.size();
for (int i = 0; i < n; ++i)
queue.push(ValueHelper<T>::make(start++));
auto new_size = queue.size();
if (old_size + n != new_size)
throw TiFlashTestException(fmt::format("Size mismatch: expect {} but found {}", old_size + n, new_size));
if (full_after_push)
testCannotTryPush(queue);
return start;
}
template <typename T>
int testPopN(MPMCQueue<T> & queue, int n, int start, bool empty_after_pop)
{
auto old_size = queue.size();
for (int i = 0; i < n; ++i)
{
T res;
bool ok = queue.pop(res);
if (!ok)
throw TiFlashTestException("Should pop a value");
int expect = start++;
int actual = ValueHelper<T>::extract(res);
if (actual != expect)
throw TiFlashTestException(fmt::format("Value mismatch! actual: {}, expect: {}", actual, expect));
}
auto new_size = queue.size();
if (old_size - n != new_size)
throw TiFlashTestException(fmt::format("Size mismatch: expect {} but found {}", old_size - n, new_size));
if (empty_after_pop)
testCannotTryPop(queue);
return start;
}
template <typename T>
void testSequentialPushPop(Int64 capacity)
{
MPMCQueue<T> queue(capacity);
int read_start = 0;
int write_start = testPushN<T>(queue, capacity, 0, true);
std::mt19937 mt(rd());
std::uniform_int_distribution<int> dist(1, capacity - 1);
for (int i = 0; i < 100; ++i)
{
int pop_cnt = dist(mt);
read_start = testPopN(queue, pop_cnt, read_start, false);
write_start = testPushN<T>(queue, pop_cnt, write_start, true);
}
read_start = testPopN(queue, capacity, read_start, true);
ASSERT_EQ(read_start, write_start);
}
template <typename T>
void testFinishEmpty(Int64 capacity, int reader_cnt)
{
MPMCQueue<T> queue(capacity);
std::vector<std::thread> readers;
std::vector<UInt8> reader_results(reader_cnt, -1);
auto read_func = [&](int i) {
T res;
reader_results[i] = queue.pop(res);
};
for (int i = 0; i < reader_cnt; ++i)
readers.emplace_back(read_func, i);
std::this_thread::sleep_for(std::chrono::milliseconds(1));
queue.finish();
for (int i = 0; i < reader_cnt; ++i)
{
readers[i].join();
ASSERT_EQ(reader_results[i], 0);
}
ASSERT_EQ(queue.size(), 0);
for (int i = 0; i < 10; ++i)
{
T res;
ASSERT_TRUE(!queue.pop(res));
}
for (int i = 0; i < 10; ++i)
{
auto res = queue.push(ValueHelper<T>::make(i));
ASSERT_TRUE(!res);
}
}
template <typename T>
void testCancelEmpty(Int64 capacity, int reader_cnt)
{
MPMCQueue<T> queue(capacity);
std::vector<std::thread> readers;
std::vector<UInt8> reader_results(reader_cnt, -1);
auto read_func = [&](int i) {
T res;
reader_results[i] = queue.pop(res);
};
for (int i = 0; i < reader_cnt; ++i)
readers.emplace_back(read_func, i);
std::this_thread::sleep_for(std::chrono::milliseconds(1));
queue.cancel();
for (int i = 0; i < reader_cnt; ++i)
{
readers[i].join();
ASSERT_EQ(reader_results[i], 0);
}
for (int i = 0; i < 10; ++i)
{
T res;
ASSERT_TRUE(!queue.pop(res));
}
for (int i = 0; i < 10; ++i)
{
auto res = queue.push(ValueHelper<T>::make(i));
ASSERT_TRUE(!res);
}
}
template <typename T>
void testCancelConcurrentPop(int reader_cnt)
{
MPMCQueue<T> queue(1);
std::vector<std::thread> threads;
std::vector<int> reader_results(reader_cnt, 0);
auto read_func = [&](int i) {
T res;
reader_results[i] += queue.pop(res);
};
for (int i = 0; i < reader_cnt; ++i)
threads.emplace_back(read_func, i);
std::this_thread::sleep_for(std::chrono::milliseconds(1));
queue.cancel();
for (int i = 0; i < reader_cnt; ++i)
{
threads[i].join();
ASSERT_EQ(reader_results[i], 0);
}
testCannotPop(queue);
testCannotPush(queue);
}
template <typename T>
void testCancelConcurrentPush(int writer_cnt)
{
MPMCQueue<T> queue(1);
queue.push(ValueHelper<T>::make(0));
std::vector<std::thread> threads;
std::vector<int> writer_results(writer_cnt, 0);
auto write_func = [&](int i) {
auto res = queue.push(ValueHelper<T>::make(i));
writer_results[i] += res;
};
for (int i = 0; i < writer_cnt; ++i)
threads.emplace_back(write_func, i);
std::this_thread::sleep_for(std::chrono::milliseconds(1));
queue.cancel();
for (int i = 0; i < writer_cnt; ++i)
{
threads[i].join();
ASSERT_EQ(writer_results[i], 0);
}
testCannotPop(queue);
testCannotPush(queue);
}
template <typename T>
void testPopAfterFinish(Int64 capacity)
{
MPMCQueue<T> queue(capacity);
testPushN<T>(queue, capacity, 0, true);
queue.finish();
testPopN<T>(queue, capacity, 0, true);
ASSERT_EQ(queue.size(), 0);
}
template <typename T>
void testConcurrentPush(Int64 capacity, int writer_cnt)
{
MPMCQueue<T> queue(capacity);
std::vector<std::thread> threads;
std::vector<int> reader_results;
std::vector<std::vector<int>> writer_results(writer_cnt);
auto read_func = [&] {
while (true)
{
T res;
if (queue.pop(res))
reader_results.push_back(ValueHelper<T>::extract(res));
else
break;
}
};
auto write_func = [&](int i) {
for (int x = i;; x += writer_cnt)
{
auto res = queue.push(ValueHelper<T>::make(x));
if (res)
writer_results[i].push_back(x);
else
break;
}
};
threads.emplace_back(read_func);
for (int i = 0; i < writer_cnt; ++i)
threads.emplace_back(write_func, i);
std::this_thread::sleep_for(std::chrono::milliseconds(10));
queue.finish();
for (auto & thread : threads)
thread.join();
ASSERT_EQ(queue.size(), 0);
std::vector<int> all_writer_results = collect(writer_results);
expectMonotonic(reader_results, writer_cnt);
expectEqualAfterSort(reader_results, all_writer_results);
}
template <typename T>
void testConcurrentPushPop(Int64 capacity, int reader_writer_cnt)
{
MPMCQueue<T> queue(capacity);
std::vector<std::thread> threads;
std::vector<std::vector<int>> reader_results(reader_writer_cnt);
std::vector<std::vector<int>> writer_results(reader_writer_cnt);
auto read_func = [&](int i) {
while (true)
{
T res;
if (queue.pop(res))
reader_results[i].push_back(ValueHelper<T>::extract(res));
else
break;
}
};
auto write_func = [&](int i) {
for (int x = i;; x += reader_writer_cnt)
{
auto res = queue.push(ValueHelper<T>::make(x));
if (res)
writer_results[i].push_back(x);
else
break;
}
};
for (int i = 0; i < reader_writer_cnt; ++i)
threads.emplace_back(read_func, i);
for (int i = 0; i < reader_writer_cnt; ++i)
threads.emplace_back(write_func, i);
std::this_thread::sleep_for(std::chrono::milliseconds(10));
queue.finish();
for (auto & thread : threads)
thread.join();
ASSERT_EQ(queue.size(), 0);
std::vector<int> all_reader_results = collect(reader_results);
std::vector<int> all_writer_results = collect(writer_results);
expectEqualAfterSort(all_reader_results, all_writer_results);
}
static std::vector<int> collect(const std::vector<std::vector<int>> & vs)
{
std::vector<int> res;
for (const auto & v : vs)
for (int x : v)
res.push_back(x);
return res;
}
static void expectMonotonic(const std::vector<int> & data, int stream_cnt)
{
std::vector<std::vector<int>> streams(stream_cnt);
for (int x : data)
{
int p = x % stream_cnt;
if (streams[p].empty())
ASSERT_EQ(x, p);
else
ASSERT_EQ(x, streams[p].back() + stream_cnt);
streams[p].push_back(x);
}
}
static void expectEqualAfterSort(std::vector<int> & a, std::vector<int> & b)
{
ASSERT_EQ(a.size(), b.size());
sort(begin(a), end(a));
sort(begin(b), end(b));
ASSERT_EQ(a, b);
}
struct ThrowInjectable
{
ThrowInjectable() = default;
ThrowInjectable(const ThrowInjectable &) = delete;
ThrowInjectable(ThrowInjectable && rhs)
{
throwOrMove(std::move(rhs));
}
ThrowInjectable & operator=(const ThrowInjectable &) = delete;
ThrowInjectable & operator=(ThrowInjectable && rhs)
{
if (this != &rhs)
throwOrMove(std::move(rhs));
return *this;
}
explicit ThrowInjectable(int /* just avoid potential overload resolution error */, bool throw_when_construct)
{
if (throw_when_construct)
throw TiFlashTestException("Throw when construct");
}
explicit ThrowInjectable(std::atomic<bool> * throw_when_move_)
: throw_when_move(throw_when_move_)
{
}
void throwOrMove(ThrowInjectable && rhs)
{
if (rhs.throw_when_move && rhs.throw_when_move->load())
throw TiFlashTestException("Throw when move");
throw_when_move = rhs.throw_when_move;
rhs.throw_when_move = nullptr;
}
std::atomic<bool> * throw_when_move = nullptr;
};
};
template <>
struct MPMCQueueTest::ValueHelper<int>
{
static int make(int v) { return v; }
static int extract(int v) { return v; }
};
template <>
struct MPMCQueueTest::ValueHelper<std::unique_ptr<int>>
{
static std::unique_ptr<int> make(int v) { return std::make_unique<int>(v); }
static int extract(std::unique_ptr<int> & v) { return *v; }
};
template <>
struct MPMCQueueTest::ValueHelper<std::shared_ptr<int>>
{
static std::shared_ptr<int> make(int v) { return std::make_shared<int>(v); }
static int extract(std::shared_ptr<int> & v) { return *v; }
};
#define ADD_TEST_FOR(type_name, type, test_name, ...) \
TEST_F(MPMCQueueTest, type_name##_##test_name) \
try \
{ \
test##test_name<type>(__VA_ARGS__); \
} \
CATCH
#define ADD_TEST(test_name, ...) \
ADD_TEST_FOR(Int, int, test_name, __VA_ARGS__) \
ADD_TEST_FOR(UniquePtr_Int, std::unique_ptr<int>, test_name, __VA_ARGS__) \
ADD_TEST_FOR(SharedPtr_Int, std::shared_ptr<int>, test_name, __VA_ARGS__)
ADD_TEST(Initialize, 10);
ADD_TEST(DuplicateFinishCancel);
ADD_TEST(SequentialPushPop, 100);
ADD_TEST(FinishEmpty, 100, 4);
ADD_TEST(ConcurrentPush, 2, 4);
ADD_TEST(ConcurrentPushPop, 2, 4);
ADD_TEST(PopAfterFinish, 100);
ADD_TEST(CancelEmpty, 4, 4);
ADD_TEST(CancelConcurrentPop, 4);
ADD_TEST(CancelConcurrentPush, 4);
TEST_F(MPMCQueueTest, ExceptionSafe)
try
{
MPMCQueue<ThrowInjectable> queue(10);
std::atomic<bool> throw_when_move = true;
ThrowInjectable x(&throw_when_move);
try
{
queue.push(std::move(x));
ASSERT_TRUE(false); // should throw
}
catch (const TiFlashTestException &)
{
}
ASSERT_EQ(queue.size(), 0);
throw_when_move.store(false);
queue.push(std::move(x));
ASSERT_EQ(queue.size(), 1);
throw_when_move.store(true);
try
{
ThrowInjectable res;
queue.pop(res);
ASSERT_TRUE(false); // should throw
}
catch (const TiFlashTestException &)
{
}
ASSERT_EQ(queue.size(), 1);
throw_when_move.store(false);
ThrowInjectable res;
bool ok = queue.pop(res);
ASSERT_TRUE(ok);
ASSERT_EQ(res.throw_when_move, &throw_when_move);
ASSERT_EQ(queue.size(), 0);
try
{
queue.emplace(0, true);
ASSERT_TRUE(false); // should throw
}
catch (const TiFlashTestException &)
{
}
ASSERT_EQ(queue.size(), 0);
queue.emplace(0, false);
ASSERT_EQ(queue.size(), 1);
}
CATCH
TEST_F(MPMCQueueTest, isNextOpNonBlocking)
try
{
MPMCQueue<int> q(2);
ASSERT_TRUE(q.isNextPushNonBlocking());
ASSERT_FALSE(q.isNextPopNonBlocking());
ASSERT_TRUE(q.push(1));
ASSERT_TRUE(q.isNextPushNonBlocking());
ASSERT_TRUE(q.isNextPopNonBlocking());
int val;
ASSERT_TRUE(q.pop(val));
ASSERT_TRUE(q.isNextPushNonBlocking());
ASSERT_FALSE(q.isNextPopNonBlocking());
ASSERT_TRUE(q.push(1));
ASSERT_TRUE(q.isNextPushNonBlocking());
ASSERT_TRUE(q.isNextPopNonBlocking());
ASSERT_TRUE(q.push(1));
ASSERT_FALSE(q.isNextPushNonBlocking());
ASSERT_TRUE(q.isNextPopNonBlocking());
ASSERT_TRUE(q.finish());
ASSERT_FALSE(q.finish());
//check isNextPush/PopNonBlocking after finish
ASSERT_TRUE(q.pop(val));
ASSERT_TRUE(q.isNextPushNonBlocking());
ASSERT_TRUE(q.isNextPopNonBlocking());
ASSERT_TRUE(q.pop(val));
ASSERT_TRUE(q.isNextPushNonBlocking());
ASSERT_TRUE(q.isNextPopNonBlocking());
}
CATCH
struct Counter
{
static int count;
Counter()
{
++count;
}
~Counter()
{
--count;
}
};
int Counter::count = 0;
TEST_F(MPMCQueueTest, objectsDestructed)
try
{
{
MPMCQueue<Counter> queue(100);
queue.emplace();
ASSERT_EQ(Counter::count, 1);
{
Counter cnt;
queue.pop(cnt);
}
ASSERT_EQ(Counter::count, 0);
queue.emplace();
ASSERT_EQ(Counter::count, 1);
}
ASSERT_EQ(Counter::count, 0);
}
CATCH
} // namespace
} // namespace DB::tests
| 28.504425
| 117
| 0.563748
|
solotzg
|
52ab3bfd4ba431d03548ff2c8617dc9bc8ea1cf3
| 3,846
|
cpp
|
C++
|
src/nod/aligndialog.cpp
|
astillich/nod
|
beb23c79684f277d8ee95d4c913e1981efe3941f
|
[
"MIT"
] | null | null | null |
src/nod/aligndialog.cpp
|
astillich/nod
|
beb23c79684f277d8ee95d4c913e1981efe3941f
|
[
"MIT"
] | 3
|
2018-02-21T23:36:41.000Z
|
2018-02-23T00:14:44.000Z
|
src/nod/aligndialog.cpp
|
astillich/nod
|
beb23c79684f277d8ee95d4c913e1981efe3941f
|
[
"MIT"
] | 1
|
2020-11-03T05:08:27.000Z
|
2020-11-03T05:08:27.000Z
|
// ----------------------------------------------------------------------------
#include <QButtonGroup>
#include <QCheckBox>
#include <QDialogButtonBox>
#include <QVariant>
#include <QVBoxLayout>
// ----------------------------------------------------------------------------
#include "nod/aligndialog.h"
// ----------------------------------------------------------------------------
namespace nod { namespace qgs {
// ----------------------------------------------------------------------------
AlignDialog::AlignDialog(QWidget *parent)
: QDialog(parent)
{
setWindowTitle(tr("Align Nodes"));
QVBoxLayout *vlayout = new QVBoxLayout(this);
QButtonGroup *group = new QButtonGroup(this);
QGridLayout *grid = new QGridLayout(this);
vlayout->addLayout(grid);
QCheckBox *tl = new QCheckBox(QObject::tr("Top Left"), this);
tl->setProperty("align", int(Qt::AlignLeft | Qt::AlignTop));
grid->addWidget(tl, 0, 0);
group->addButton(tl);
QCheckBox *t = new QCheckBox(QObject::tr("Top"), this);
t->setProperty("align", int(Qt::AlignHCenter | Qt::AlignTop));
grid->addWidget(t, 0, 1);
group->addButton(t);
QCheckBox *tr = new QCheckBox(QObject::tr("Top Right"), this);
tr->setProperty("align", int(Qt::AlignRight | Qt::AlignTop));
grid->addWidget(tr, 0, 2);
group->addButton(tr);
QCheckBox *l = new QCheckBox(QObject::tr("Left"), this);
l->setProperty("align", int(Qt::AlignLeft | Qt::AlignVCenter));
grid->addWidget(l, 1, 0);
group->addButton(l);
QCheckBox *c = new QCheckBox(QObject::tr("Center"), this);
c->setProperty("align", int(Qt::AlignHCenter | Qt::AlignVCenter));
grid->addWidget(c, 1, 1);
group->addButton(c);
QCheckBox *r = new QCheckBox(QObject::tr("Right"), this);
r->setProperty("align", int(Qt::AlignRight | Qt::AlignVCenter));
grid->addWidget(r, 1, 2);
group->addButton(r);
QCheckBox *bl = new QCheckBox(QObject::tr("Bottom Left"), this);
bl->setProperty("align", int(Qt::AlignLeft | Qt::AlignBottom));
grid->addWidget(bl, 2, 0);
group->addButton(bl);
QCheckBox *b = new QCheckBox(QObject::tr("Bottom"), this);
b->setProperty("align", int(Qt::AlignHCenter | Qt::AlignBottom));
grid->addWidget(b, 2, 1);
group->addButton(b);
QCheckBox *br = new QCheckBox(QObject::tr("Bottom Right"), this);
br->setProperty("align", int(Qt::AlignRight | Qt::AlignBottom));
grid->addWidget(br, 2, 2);
group->addButton(br);
auto buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, this);
vlayout->addWidget(buttons);
connect(buttons, &QDialogButtonBox::accepted, this, &AlignDialog::accept);
connect(buttons, &QDialogButtonBox::rejected, this, &AlignDialog::reject);
setLayout(vlayout);
}
// ----------------------------------------------------------------------------
void DefaultAlignDialog::accept()
{
auto items = findChildren<QCheckBox*>();
for (auto item : items)
{
if (item->isChecked())
{
mAlignment = Qt::Alignment(item->property("align").toInt());
break;
}
}
QDialog::accept();
}
// ----------------------------------------------------------------------------
void DefaultAlignDialog::setAlignment(Qt::Alignment alignment)
{
mAlignment = alignment;
auto items = findChildren<QCheckBox*>();
for (auto item : items)
{
auto item_alignment = Qt::Alignment(item->property("align").toInt());
if (item_alignment == alignment)
{
item->setChecked(true);
} else
item->setChecked(false);
}
}
// ----------------------------------------------------------------------------
} } // namespaces
// ----------------------------------------------------------------------------
| 30.283465
| 95
| 0.529121
|
astillich
|
52b51aa0539570bca0981eb7942e79e56d3f7640
| 69
|
cpp
|
C++
|
src/Table.cpp
|
Cloaked9000/FrSQL
|
e302ca6f0cfe087097df577b829601c063fda26e
|
[
"MIT"
] | null | null | null |
src/Table.cpp
|
Cloaked9000/FrSQL
|
e302ca6f0cfe087097df577b829601c063fda26e
|
[
"MIT"
] | null | null | null |
src/Table.cpp
|
Cloaked9000/FrSQL
|
e302ca6f0cfe087097df577b829601c063fda26e
|
[
"MIT"
] | null | null | null |
//
// Created by fred.nicolson on 11/03/2020.
//
#include "Table.h"
| 11.5
| 42
| 0.637681
|
Cloaked9000
|
52bc33f593ce286b83dd7281fd859d4aa73e5d06
| 8,721
|
cpp
|
C++
|
src/Water.cpp
|
jkortman/cg2017
|
fc66534584c2aff07da84319d06ed3b5ec8c61f7
|
[
"MIT"
] | null | null | null |
src/Water.cpp
|
jkortman/cg2017
|
fc66534584c2aff07da84319d06ed3b5ec8c61f7
|
[
"MIT"
] | null | null | null |
src/Water.cpp
|
jkortman/cg2017
|
fc66534584c2aff07da84319d06ed3b5ec8c61f7
|
[
"MIT"
] | null | null | null |
// Authorship: James Kortman (a1648090)
// Implementation of Water struct member functions.
#include "Water.hpp"
Water::Water(
int size, float edge, float level, Landscape* landscape,
glm::vec2 min, glm::vec2 max)
: model_matrix(glm::mat4(1.0f)),
size(size),
edge(edge),
level(level),
min(min),
max(max)
{
normal_matrix = glm::mat3(
glm::transpose(glm::inverse(model_matrix)));
positions.resize(size * size);
normals.resize(size * size);
colours.resize(size * size);
material.shininess = 50.0f;
// Generate palette.
base_colour = WATER_COLOUR;
palette = {{
glm::vec3(0.90f, 0.90f, 1.00f),
glm::vec3(0.75f, 0.75f, 1.00f),
glm::vec3(0.60f, 0.60f, 1.00f),
glm::vec3(0.30f, 0.30f, 1.00f),
glm::vec3(0.23f, 0.24f, 0.75f),
glm::vec3(0.16f, 0.16f, 0.5f),
glm::vec3(0.10f, 0.10f, 0.33f),
}};
initialize(landscape);
}
float Water::vert_dist()
{
return edge / size;
}
void Water::initialize(Landscape* landscape)
{
auto radius = [](float x, float y) { return std::sqrt(x*x + y*y); };
// Initialize positions and colours.
// Set the alpha on edge values
// Everything outside the edge radius has height 0.
const float edge_radius = 0.5 * edge - 0.5 * edge / size;
for (int row = 0; row < size; row += 1)
{
for (int col = 0; col < size; col += 1)
{
const float x = -edge / 2.0f + edge * float(row) / (size - 1);
const float z = -edge / 2.0f + edge * float(col) / (size - 1);
#if 1
const float height = level;
#else
// The water is a cap on a sphere. The height of the cap,
// 'h', is the default water level. The edge length of the cap
// (from the centre out to the edge circle) is a, or edge/2.
// ...
// . |h .
// .-------.
// . a .
const float h = level;
const float a = edge / 2.0f;
// The radius of the sphere.
const float R = (a*a + h*h) / (2.0f * h);
// In 3D space, the equation for the sphere is
// x^2 + y^2 + z^2 = R^2.
// As we are solving for the height y, we use:
// y = sqrt(R^2 - z^2 - x^2)
// But we want the height relative to the base plane of the cap:
// height = sqrt(R^2 - z^2 - x^2) - (R - h)
const float height = std::sqrt(R*R - z*z - x*x) - (R - h);
#endif
glm::vec3 position(
x,
(radius(x, z) > edge_radius) ? 0.0f : height,
z);
set_position(row, col, position);
set_colour(row, col, base_colour);
}
}
// Initialize normals.
calculate_normals();
// Initialize indices.
// For each vertex except the lowest row and furthest left column,
// connect positions into two triangles:
// current vertex r, c -> .___. <- r, c+1
// | /|
// | / |
// |/ |
// r+1,c -> .___. <- r+1, c+1
const float max_radius = 0.5 * edge;
for (int row = 0; row < size - 1; row += 1)
{
for (int col = 0; col < size - 1; col += 1)
{
// Count the number of verts outside of the max_radius provided.
int num_outside_radius = 0;
if (radius(get_position(row, col).x,
get_position(row, col).z)
> max_radius) num_outside_radius += 1;
if (radius(get_position(row, col + 1).x,
get_position(row, col + 1).z)
> max_radius) num_outside_radius += 1;
if (radius(get_position(row + 1, col).x,
get_position(row + 1, col).z)
> max_radius) num_outside_radius += 1;
if (radius(get_position(row + 1, col + 1).x,
get_position(row + 1, col + 1).z)
> max_radius) num_outside_radius += 1;
// Check if any verts are outside of the bounds provided.
auto in_bounds = [=](float x, float z)
{
return x >= min[0] && z >= min[1] && x <= max[0] && z <= max[1];
};
int num_outside_bounds = 0;
if (!in_bounds(get_position( row, col).x,
get_position( row, col).z)) num_outside_bounds += 1;
if (!in_bounds(get_position( row, col + 1).x,
get_position( row, col + 1).z)) num_outside_bounds += 1;
if (!in_bounds(get_position(row + 1, col).x,
get_position(row + 1, col).z)) num_outside_bounds += 1;
if (!in_bounds(get_position(row + 1, col + 1).x,
get_position(row + 1, col + 1).z)) num_outside_bounds += 1;
// Check if any verts are obscured by the landscape.
auto is_obscured = [=](int row, int col) {
float x = get_position(row, col).x;
float z = get_position(row, col).z;
// check if x,z is witho bounds for the landscape.
if (x <= -landscape->edge / 2.0
|| x >= landscape->edge / 2.0
|| z <= -landscape->edge / 2.0
|| z >= landscape->edge / 2.0) return false;
return landscape->get_pos_at(get_position(row, col)).y
> (level / 2.0) + get_position(row, col).y;
};
int num_obscured = 0;
if (landscape != nullptr)
{
if (is_obscured( row, col)) num_obscured += 1;
if (is_obscured( row, col + 1)) num_obscured += 1;
if (is_obscured(row + 1, col)) num_obscured += 1;
if (is_obscured(row + 1, col + 1)) num_obscured += 1;
}
// First triangle (upper-left on diagram).
if (num_outside_radius < 4
&& num_outside_bounds < 4
&& num_obscured < 4)
{
indices.push_back(std::array<unsigned int, 3>({{
(unsigned int)( row * size + col),
(unsigned int)( row * size + col + 1),
(unsigned int)((row + 1) * size + col),
}}));
// Second triangle (lower-right on diagram).
indices.push_back({{
(unsigned int)((row + 1) * size + col),
(unsigned int)( row * size + col + 1),
(unsigned int)((row + 1) * size + col + 1),
}});
}
}
}
}
void Water::calculate_normals()
{
for (int row = 0; row < size; row += 1)
{
for (int col = 0; col < size; col += 1)
{
glm::vec3 norm;
if (row == size-1) norm = get_normal( row, col-1);
else if (col == size-1) norm = get_normal(row-1, col-1);
else
{
// Get the points at, above, and to the right of the current point.
glm::vec3 at = get_position( row, col);
glm::vec3 below = get_position(row+1, col);
glm::vec3 right = get_position( row, col+1);
glm::vec3 downward = below - at;
glm::vec3 rightward = right - at;
norm = glm::normalize(glm::cross(rightward, downward));
}
set_normal(row, col, norm);
}
}
#if 0
for (int row = 0; row < size; row += 1)
{
for (int col = 0; col < size; col += 1)
{
glm::vec3 norm = get_normal(row, col);
printf("[%f %f %f] ", norm.x, norm.y, norm.z);
}
printf("\n");
}
#endif
}
// -- Data access functions --
// ---------------------------
glm::vec3 Water::get_position(int row, int col)
{
return positions[size * row + col];
}
glm::vec3 Water::get_normal(int row, int col)
{
return normals[size * row + col];
}
glm::vec3 Water::get_colour(int row, int col)
{
return colours[size * row + col];
}
void Water::set_position(int row, int col, glm::vec3 pos)
{
positions[size * row + col] = pos;
}
void Water::set_normal(int row, int col, glm::vec3 norm)
{
normals[size * row + col] = norm;
}
void Water::set_colour(int row, int col, glm::vec3 colour)
{
colours[size * row + col] = colour;
}
| 35.307692
| 86
| 0.469327
|
jkortman
|
52bcaf1d4f2f9a2d74696f5f8c6d6e09ebe09696
| 7,012
|
cpp
|
C++
|
src/core/Models/pendulummapmodel.cpp
|
jbuckmccready/staticpendulum_gui
|
8c14019e5903c531cca5cfefeeb22a1beca8b000
|
[
"MIT"
] | null | null | null |
src/core/Models/pendulummapmodel.cpp
|
jbuckmccready/staticpendulum_gui
|
8c14019e5903c531cca5cfefeeb22a1beca8b000
|
[
"MIT"
] | null | null | null |
src/core/Models/pendulummapmodel.cpp
|
jbuckmccready/staticpendulum_gui
|
8c14019e5903c531cca5cfefeeb22a1beca8b000
|
[
"MIT"
] | null | null | null |
/* ===========================================================================
* The MIT License (MIT)
*
* Copyright (c) 2016 Jedidiah Buck McCready <jbuckmccready@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
* ===========================================================================*/
#include "pendulummapmodel.h"
#include "DataStorage/jsonreader.h"
#include <QJsonObject>
#include <QJsonValue>
namespace staticpendulum {
PendulumMapModel::PendulumMapModel(QObject *parent)
: QObject(parent), m_xStart(-10.0), m_yStart(-10.0), m_xEnd(10.0),
m_yEnd(10.0), m_resolution(0.05), m_attractorPosThreshold(0.5),
m_midPosThreshold(0.1), m_convergeTimeThreshold(5.0),
m_midConvergeColor(QColor(0, 0, 0)),
m_outOfBoundsColor(QColor(255, 255, 255)) {}
const QString &PendulumMapModel::modelJsonKey()
{
static const QString key("pendulumMap");
return key;
}
const QString &PendulumMapModel::xStartJsonKey() {
static const QString key("xStart");
return key;
}
const QString &PendulumMapModel::yStartJsonKey() {
static const QString key("yStart");
return key;
}
const QString &PendulumMapModel::xEndJsonKey() {
static const QString key("xEnd");
return key;
}
const QString &PendulumMapModel::yEndJsonKey() {
static const QString key("yEnd");
return key;
}
const QString &PendulumMapModel::resolutionJsonKey() {
static const QString key("resolution");
return key;
}
const QString &PendulumMapModel::attractorPosThresholdJsonKey() {
static const QString key("attractorPosThreshold");
return key;
}
const QString &PendulumMapModel::midPosThresholdJsonKey() {
static const QString key("midPosThreshold");
return key;
}
const QString &PendulumMapModel::convergeTimeThresholdJsonKey() {
static const QString key("convergeTimeThreshold");
return key;
}
const QString &PendulumMapModel::midConvergeColorJsonKey() {
static const QString key("midConvergeColor");
return key;
}
const QString &PendulumMapModel::outOfBoundsColorJsonKey() {
static const QString key("outOfBoundsColor");
return key;
}
double PendulumMapModel::xStart() const { return m_xStart; }
double PendulumMapModel::yStart() const { return m_yStart; }
double PendulumMapModel::xEnd() const { return m_xEnd; }
double PendulumMapModel::yEnd() const { return m_yEnd; }
double PendulumMapModel::resolution() const { return m_resolution; }
double PendulumMapModel::attractorPosThreshold() const {
return m_attractorPosThreshold;
}
double PendulumMapModel::midPosThreshold() const { return m_midPosThreshold; }
double PendulumMapModel::convergeTimeThreshold() const {
return m_convergeTimeThreshold;
}
QColor PendulumMapModel::midConvergeColor() const { return m_midConvergeColor; }
QColor PendulumMapModel::outOfBoundsColor() const { return m_outOfBoundsColor; }
void PendulumMapModel::setXStart(double xStart) {
if (m_xStart == xStart)
return;
m_xStart = xStart;
emit xStartChanged(xStart);
}
void PendulumMapModel::setYStart(double yStart) {
if (m_yStart == yStart)
return;
m_yStart = yStart;
emit yStartChanged(yStart);
}
void PendulumMapModel::setXEnd(double xEnd) {
if (m_xEnd == xEnd)
return;
m_xEnd = xEnd;
emit xEndChanged(xEnd);
}
void PendulumMapModel::setYEnd(double yEnd) {
if (m_yEnd == yEnd)
return;
m_yEnd = yEnd;
emit yEndChanged(yEnd);
}
void PendulumMapModel::setResolution(double resolution) {
if (m_resolution == resolution)
return;
m_resolution = resolution;
emit resolutionChanged(resolution);
}
void PendulumMapModel::setAttractorPosThreshold(double attractorPositionTol) {
if (m_attractorPosThreshold == attractorPositionTol)
return;
m_attractorPosThreshold = attractorPositionTol;
emit attractorPosThresholdChanged(attractorPositionTol);
}
void PendulumMapModel::setMidPosThreshold(double midPositionTol) {
if (m_midPosThreshold == midPositionTol)
return;
m_midPosThreshold = midPositionTol;
emit midPosThresholdChanged(midPositionTol);
}
void PendulumMapModel::setConvergeTimeThreshold(double convergeTimeThreshold) {
if (m_convergeTimeThreshold == convergeTimeThreshold)
return;
m_convergeTimeThreshold = convergeTimeThreshold;
emit convergeTimeThresholdChanged(convergeTimeThreshold);
}
void PendulumMapModel::setMidConvergeColor(QColor midConvergeColor) {
if (m_midConvergeColor == midConvergeColor)
return;
m_midConvergeColor = midConvergeColor;
emit midConvergeColorChanged(midConvergeColor);
}
void PendulumMapModel::setOutOfBoundsColor(QColor outOfBoundsColor) {
if (m_outOfBoundsColor == outOfBoundsColor)
return;
m_outOfBoundsColor = outOfBoundsColor;
emit outOfBoundsColorChanged(outOfBoundsColor);
}
void PendulumMapModel::read(const QJsonObject &json) {
const JsonReader reader("pendulumMap", json);
setXStart(reader.readProperty(xStartJsonKey()).toDouble());
setYStart(reader.readProperty(yStartJsonKey()).toDouble());
setXEnd(reader.readProperty(xEndJsonKey()).toDouble());
setYEnd(reader.readProperty(yEndJsonKey()).toDouble());
setResolution(reader.readProperty(resolutionJsonKey()).toDouble());
setMidPosThreshold(reader.readProperty(midPosThresholdJsonKey()).toDouble());
setConvergeTimeThreshold(
reader.readProperty(convergeTimeThresholdJsonKey()).toDouble());
setMidConvergeColor(reader.readPropertyAsQColor(midConvergeColorJsonKey()));
setOutOfBoundsColor(reader.readPropertyAsQColor(outOfBoundsColorJsonKey()));
}
void PendulumMapModel::write(QJsonObject &json) const {
json[xStartJsonKey()] = xStart();
json[yStartJsonKey()] = yStart();
json[xEndJsonKey()] = xEnd();
json[yEndJsonKey()] = yEnd();
json[resolutionJsonKey()] = resolution();
json[midPosThresholdJsonKey()] = midPosThreshold();
json[convergeTimeThresholdJsonKey()] = convergeTimeThreshold();
json[midConvergeColorJsonKey()] = midConvergeColor().name();
json[outOfBoundsColorJsonKey()] = outOfBoundsColor().name();
}
} // namespace staticpendulum
| 31.443946
| 80
| 0.747576
|
jbuckmccready
|
52bd42af65aa765d2458ee5a394346de2610bbf3
| 1,115
|
hpp
|
C++
|
tests/test_utils/include/dml_test_utils/fill.hpp
|
hhb584520/DML
|
014eb9894e85334f03ec74435933c972f3d05b50
|
[
"MIT"
] | null | null | null |
tests/test_utils/include/dml_test_utils/fill.hpp
|
hhb584520/DML
|
014eb9894e85334f03ec74435933c972f3d05b50
|
[
"MIT"
] | null | null | null |
tests/test_utils/include/dml_test_utils/fill.hpp
|
hhb584520/DML
|
014eb9894e85334f03ec74435933c972f3d05b50
|
[
"MIT"
] | 1
|
2022-03-28T07:52:21.000Z
|
2022-03-28T07:52:21.000Z
|
/*******************************************************************************
* Copyright (C) 2021 Intel Corporation
*
* SPDX-License-Identifier: MIT
******************************************************************************/
#ifndef DML_TEST_UTILS_FILL_HPP
#define DML_TEST_UTILS_FILL_HPP
#include <dml_test_utils/data_generators.hpp>
#include <dml_test_utils/data_storage.hpp>
#include "gtest/gtest.h"
namespace dml::testing
{
struct fill
{
explicit fill(uint32_t seed, uint32_t length, uint32_t alignment = 64u):
seed(seed), length(length), pattern(0xFFFFDEADFFFFDEAD), dst(length, alignment), ref(length, alignment)
{
dst.generate(random_generator(seed));
ref.generate(fill_generator(pattern));
}
[[nodiscard]] bool check() const noexcept
{
return ref == dst;
}
const uint32_t seed;
const uint32_t length;
uint64_t pattern;
data_storage dst;
private:
data_storage ref;
};
} // namespace dml::testing
#endif //DML_TEST_UTILS_FILL_HPP
| 25.930233
| 115
| 0.550673
|
hhb584520
|
1ecb09834c3d3bead1da078fe7f2283cacf23232
| 13,423
|
cpp
|
C++
|
Marlin-BIQUBX_ALMOST_STOCK/Marlin/src/lcd/tft/images/confirm_64x64x4.cpp
|
Ejay-3D/Marlin-Biqu
|
bcf9d30c2fb998ca7d2ebf8c2cb917a96eb2d018
|
[
"MIT"
] | 6
|
2020-12-04T21:55:04.000Z
|
2022-02-02T20:49:45.000Z
|
Marlin-2.0.7_Stock_Board/Marlin/src/lcd/tft/images/confirm_64x64x4.cpp
|
kristapsdravnieks/Anycubic-Predator
|
879ea2af0b9cafc27ea85d966f9bc4699b3e8e25
|
[
"MIT"
] | 1
|
2021-06-16T09:37:24.000Z
|
2021-06-16T09:44:32.000Z
|
Marlin-2.0.7_Stock_Board/Marlin/src/lcd/tft/images/confirm_64x64x4.cpp
|
kristapsdravnieks/Anycubic-Predator
|
879ea2af0b9cafc27ea85d966f9bc4699b3e8e25
|
[
"MIT"
] | 3
|
2021-05-01T15:13:41.000Z
|
2022-02-11T01:15:30.000Z
|
/**
* Marlin 3D Printer Firmware
* Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
*
* Based on Sprinter and grbl.
* Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
*/
#include "../../../inc/MarlinConfigPre.h"
#if HAS_GRAPHICAL_TFT
extern const uint8_t confirm_64x64x4[2048] = {
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x87, 0x77, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x78, 0xa8, 0x78, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x87, 0x7c, 0xfc, 0x77, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x77, 0xcf, 0xff, 0xc7, 0x78, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x87, 0x7c, 0xff, 0xff, 0xfb, 0x77, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x77, 0xcf, 0xff, 0xff, 0xff, 0xb7, 0x78, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x87, 0x7c, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x77, 0xcf, 0xff, 0xff, 0xff, 0xff, 0xff, 0x87, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x87, 0x77, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x87, 0x7c, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfa, 0x55, 0x78, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x78, 0xa8, 0x78, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x78, 0xcf, 0xff, 0xff, 0xff, 0xff, 0xff, 0x94, 0x44, 0x68, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x87, 0x8d, 0xfb, 0x77, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x87, 0x7c, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfa, 0x44, 0x45, 0x78, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x78, 0xdf, 0xff, 0xb7, 0x78, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x77, 0xcf, 0xff, 0xff, 0xff, 0xff, 0xff, 0x94, 0x44, 0x57, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x87, 0x8d, 0xff, 0xff, 0xfb, 0x77, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x87, 0x7c, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf9, 0x44, 0x45, 0x78, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x78, 0xdf, 0xff, 0xff, 0xff, 0xb7, 0x78, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x77, 0xcf, 0xff, 0xff, 0xff, 0xff, 0xff, 0xa4, 0x44, 0x57, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x87, 0x8d, 0xff, 0xff, 0xff, 0xff, 0xfb, 0x77, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x87, 0x7c, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf9, 0x44, 0x45, 0x78, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x87, 0xbf, 0xff, 0xff, 0xff, 0xff, 0xff, 0xb7, 0x78, 0x88, 0x88, 0x88, 0x88, 0x88, 0x77, 0xcf, 0xff, 0xff, 0xff, 0xff, 0xff, 0xa4, 0x44, 0x57, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x87, 0x8c, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfb, 0x77, 0x88, 0x88, 0x88, 0x88, 0x87, 0x7c, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfa, 0x44, 0x45, 0x78, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x76, 0xaf, 0xff, 0xff, 0xff, 0xff, 0xff, 0xa7, 0x78, 0x88, 0x88, 0x88, 0x77, 0xcf, 0xff, 0xff, 0xff, 0xff, 0xff, 0xa4, 0x44, 0x57, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x86, 0x4b, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfb, 0x77, 0x88, 0x88, 0x87, 0x8c, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfa, 0x44, 0x45, 0x78, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x64, 0xbf, 0xff, 0xff, 0xff, 0xff, 0xff, 0xb7, 0x78, 0x88, 0x77, 0xcf, 0xff, 0xff, 0xff, 0xff, 0xff, 0xa4, 0x44, 0x57, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x86, 0x4b, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfb, 0x77, 0x87, 0x7c, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf9, 0x44, 0x45, 0x78, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x64, 0xbf, 0xff, 0xff, 0xff, 0xff, 0xff, 0xb7, 0x78, 0xcf, 0xff, 0xff, 0xff, 0xff, 0xff, 0xa4, 0x44, 0x57, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x86, 0x4b, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfb, 0x7c, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfa, 0x44, 0x45, 0x78, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x65, 0xbf, 0xff, 0xff, 0xff, 0xff, 0xff, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xff, 0x94, 0x44, 0x57, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x86, 0x5b, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfa, 0x44, 0x45, 0x78, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x64, 0xbf, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x94, 0x44, 0x57, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x86, 0x5b, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfa, 0x44, 0x45, 0x78, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x64, 0xbf, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x94, 0x44, 0x57, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x86, 0x4b, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf9, 0x44, 0x45, 0x78, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x65, 0xbf, 0xff, 0xff, 0xff, 0xff, 0xff, 0xa4, 0x44, 0x57, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x86, 0x4b, 0xff, 0xff, 0xff, 0xff, 0xfa, 0x44, 0x45, 0x78, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x65, 0xbf, 0xff, 0xff, 0xff, 0x94, 0x44, 0x57, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x86, 0x4b, 0xff, 0xff, 0xfa, 0x44, 0x45, 0x78, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x64, 0xbf, 0xff, 0x94, 0x44, 0x57, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x86, 0x4b, 0xfa, 0x44, 0x45, 0x78, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x65, 0x75, 0x44, 0x57, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x86, 0x44, 0x45, 0x78, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x65, 0x57, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x87, 0x78, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88
};
#endif // HAS_GRAPHICAL_TFT
| 141.294737
| 193
| 0.665351
|
Ejay-3D
|
1ece5af1f749599e18b93dbc5b403dfc33b4d520
| 1,684
|
hpp
|
C++
|
event-handling/event.hpp
|
beached/VariantTalk
|
da37b695369b23a9bcdfe5bce11d759a0b4c5470
|
[
"Apache-2.0",
"MIT"
] | 39
|
2018-11-15T23:38:27.000Z
|
2022-03-21T16:38:22.000Z
|
event-handling/event.hpp
|
beached/VariantTalk
|
da37b695369b23a9bcdfe5bce11d759a0b4c5470
|
[
"Apache-2.0",
"MIT"
] | 3
|
2018-11-30T10:52:04.000Z
|
2021-02-23T21:36:11.000Z
|
event-handling/event.hpp
|
beached/VariantTalk
|
da37b695369b23a9bcdfe5bce11d759a0b4c5470
|
[
"Apache-2.0",
"MIT"
] | 9
|
2019-01-18T05:43:35.000Z
|
2021-05-23T16:24:40.000Z
|
/* Copyright (C) 2018, Nikolai Wuttke. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#pragma once
#include <variant>
namespace variant_talk
{
enum class MouseButton
{
Left,
Middle,
Right,
Unknown
};
namespace event
{
struct MouseMoved
{
int x = 0;
int y = 0;
};
struct MouseButtonDown
{
MouseButton button;
};
struct MouseButtonUp
{
MouseButton button;
};
struct WindowResized
{
int newWidth = 0;
int newHeight = 0;
};
} // namespace event
using Event = std::variant<
event::MouseMoved,
event::MouseButtonDown,
event::MouseButtonUp,
event::WindowResized>;
} // namespace variant_talk
| 21.87013
| 80
| 0.736936
|
beached
|
1ee01cef660665df78cf927c12056d29a75c7acb
| 6,397
|
hpp
|
C++
|
grail/include/algorithm/CFG_TO_CNF.hpp
|
iambrosie/Grail-Plus
|
e102de735e86df241e4311394190ad39181f073b
|
[
"MIT"
] | null | null | null |
grail/include/algorithm/CFG_TO_CNF.hpp
|
iambrosie/Grail-Plus
|
e102de735e86df241e4311394190ad39181f073b
|
[
"MIT"
] | null | null | null |
grail/include/algorithm/CFG_TO_CNF.hpp
|
iambrosie/Grail-Plus
|
e102de735e86df241e4311394190ad39181f073b
|
[
"MIT"
] | 1
|
2020-07-14T03:58:19.000Z
|
2020-07-14T03:58:19.000Z
|
/*
* CFG_TO_CNF.hpp
*
* Created on: Feb 7, 2011
* Author: Peter Goodman
* Version: $Id$
*
* Copyright 2011 Peter Goodman, all rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef FLTL_CFG_TO_CNF_HPP_
#define FLTL_CFG_TO_CNF_HPP_
#include <cassert>
#include <set>
#include <map>
#include <utility>
#include "fltl/include/CFG.hpp"
#include "grail/include/algorithm/CFG_REMOVE_UNITS.hpp"
#include "grail/include/algorithm/CFG_REMOVE_EPSILON.hpp"
#include "grail/include/algorithm/CFG_TO_2CFG.hpp"
#include "grail/include/io/verbose.hpp"
namespace grail { namespace algorithm {
/// convert a context-free grammar into Chomsky Normal Form.
template <typename AlphaT>
class CFG_TO_CNF {
// take off the templates!
typedef fltl::CFG<AlphaT> CFG;
FLTL_CFG_USE_TYPES(CFG);
private:
// go look for productions with two symbols, if either of the symbols
// are terminals, then replace them with variables
inline static void clean_up_terminals(
CFG &cfg,
std::map<terminal_type, variable_type> &terminal_rules,
std::map<variable_type, variable_type> &vars_to_replace
) throw() {
production_type P;
symbol_string_type str;
variable_type A;
variable_type B;
terminal_type T;
generator_type pairs(cfg.search(~P, cfg._ --->* cfg._ + cfg._));
for(; pairs.match_next(); ) {
str = P.symbols();
const bool first_is_term(str.at(0).is_terminal());
const bool second_is_term(str.at(1).is_terminal());
if(first_is_term) {
T = str.at(0);
if(0 == terminal_rules.count(T)) {
A = cfg.add_variable();
cfg.add_production(A, T);
terminal_rules[T] = A;
} else {
A = terminal_rules[T];
}
}
if(second_is_term) {
T = str.at(1);
if(0 == terminal_rules.count(T)) {
B = cfg.add_variable();
cfg.add_production(B, T);
terminal_rules[T] = B;
} else {
B = terminal_rules[T];
}
}
// two terminals
if(first_is_term && second_is_term) {
cfg.remove_production(P);
cfg.add_production(P.variable(), A + B);
// first symbol is a terminal
} else if(first_is_term) {
cfg.remove_production(P);
B = str.at(1);
if(vars_to_replace.count(B)) {
B = vars_to_replace[B];
}
cfg.add_production(P.variable(), A + B);
// second symbol is a terminal
} else if(second_is_term) {
cfg.remove_production(P);
A = str.at(0);
if(vars_to_replace.count(A)) {
A = vars_to_replace[A];
}
cfg.add_production(P.variable(), A + B);
}
}
}
public:
/// convert a context-free grammar to chomsky normal form.
static void run(CFG &cfg) throw() {
if(0 == cfg.num_productions()) {
return;
}
io::verbose("Adding new start variable...\n");
// add a new start variable
variable_type old_start_var(cfg.get_start_variable());
variable_type new_start_var(cfg.add_variable());
cfg.set_start_variable(new_start_var);
cfg.add_production(new_start_var, old_start_var);
io::verbose("Shortening productions...\n");
CFG_TO_2CFG<AlphaT>::run(cfg);
io::verbose("Removing epsilon productions...\n");
CFG_REMOVE_EPSILON<AlphaT>::run(cfg);
io::verbose("Removing unit productions...\n");
CFG_REMOVE_UNITS<AlphaT>::run(cfg);
io::verbose("Moving terminals to their own variables...\n");
// keep track of those productions that only generate a terminal
std::map<terminal_type, variable_type> terminal_rules;
std::map<variable_type, variable_type> vars_to_replace;
terminal_type T;
production_type P;
variable_type A;
generator_type terminal_units(cfg.search(~P, (~A) --->* T));
for(; terminal_units.match_next(); ) {
if(1 == cfg.num_productions(A)) {
if(1 == terminal_rules.count(T)) {
vars_to_replace[A] = terminal_rules[T];
cfg.unsafe_remove_variable(A);
} else {
terminal_rules[T] = A;
}
}
}
io::verbose("Updating non-unit productions with terminals...\n");
clean_up_terminals(cfg, terminal_rules, vars_to_replace);
io::verbose("Done.\n");
}
};
}}
#endif /* FLTL_CFG_TO_CNF_HPP_ */
| 33.668421
| 80
| 0.550727
|
iambrosie
|
1ee11fb082db3bafc8210a65903187a16ea43112
| 3,820
|
hpp
|
C++
|
libraries/lib-app-base/include/polymer-app-base/glfw-app.hpp
|
ddiakopoulos/polymer
|
a052d6cea5c9714ca3a8f9200bf626eb2df85601
|
[
"BSD-3-Clause"
] | 256
|
2019-01-06T00:30:05.000Z
|
2022-03-12T15:41:04.000Z
|
libraries/lib-app-base/include/polymer-app-base/glfw-app.hpp
|
ddiakopoulos/polymer
|
a052d6cea5c9714ca3a8f9200bf626eb2df85601
|
[
"BSD-3-Clause"
] | 8
|
2019-01-06T01:46:43.000Z
|
2021-03-17T18:00:55.000Z
|
libraries/lib-app-base/include/polymer-app-base/glfw-app.hpp
|
ddiakopoulos/polymer
|
a052d6cea5c9714ca3a8f9200bf626eb2df85601
|
[
"BSD-3-Clause"
] | 22
|
2019-01-06T22:31:51.000Z
|
2022-01-27T02:13:21.000Z
|
#pragma once
#ifndef glfw_app_h
#define glfw_app_h
#include "polymer-core/util/util.hpp"
#include "polymer-core/math/math-core.hpp"
#include "polymer-gfx-gl/gl-api.hpp"
#include <thread>
#include <chrono>
#include <codecvt>
#include <string>
#define GLFW_INCLUDE_GLU
#include <GLFW/glfw3.h>
namespace polymer
{
// fixme - move to events file
struct app_update_event
{
double elapsed_s;
float timestep_ms;
float framesPerSecond;
uint64_t elapsedFrames;
};
// fixme - move to events file
struct app_input_event
{
enum Type { CURSOR, MOUSE, KEY, CHAR, SCROLL };
GLFWwindow * window;
int2 windowSize;
Type type;
int action;
int mods;
float2 cursor;
bool drag = false;
int2 value; // button, key, codepoint, scrollX, scrollY
bool is_down() const { return action != GLFW_RELEASE; }
bool is_up() const { return action == GLFW_RELEASE; }
bool using_shift_key() const { return mods & GLFW_MOD_SHIFT; };
bool using_control_key() const { return mods & GLFW_MOD_CONTROL; };
bool using_alt_key() const { return mods & GLFW_MOD_ALT; };
bool using_super_key() const { return mods & GLFW_MOD_SUPER; };
};
struct gl_context
{
GLFWwindow * hidden_window;
gl_context();
~gl_context();
};
class glfw_window
{
uint32_t drag_count { 0 };
void preprocess_input(app_input_event & event);
void consume_character(uint32_t codepoint);
void consume_key(int key, int action);
void consume_mousebtn(int button, int action);
void consume_cursor(double xpos, double ypos);
void consume_scroll(double xoffset, double yoffset);
protected:
GLFWwindow * window;
gl_context * gl_ctx;
public:
glfw_window(gl_context * context, int w, int h, const std::string title, int samples = 1);
virtual ~glfw_window();
int get_mods() const;
virtual void on_update(const app_update_event & e) { }
virtual void on_draw() { }
virtual void on_window_focus(bool focused) { }
virtual void on_window_resize(int2 size) { }
virtual void on_window_close() { }
virtual void on_input(const app_input_event & event) { }
virtual void on_drop(std::vector<std::string> names) { }
gl_context * get_shared_gl_context() const { return gl_ctx; }
GLFWwindow * get_window() const { return window; }
};
class polymer_app : public glfw_window
{
uint64_t elapsedFrames{ 0 };
double fps{ 0 };
double fpsTime{ 0 };
bool fullscreenState{ false };
void screenshot_impl();
static void enter_fullscreen(GLFWwindow * window, int2 & windowedSize, int2 & windowedPos);
static void exit_fullscreen(GLFWwindow * window, const int2 & windowedSize, const int2 & windowedPos);
int2 windowedSize, windowedPos;
std::string screenshotPath;
public:
polymer_app(int w, int h, const std::string windowTitle, int glfwSamples = 1);
~polymer_app();
void main_loop();
void exit();
void set_fullscreen(bool state);
bool get_fullscreen();
void request_screenshot(const std::string & filename);
};
extern int Main(int argc, char * argv[]);
} // end namespace polymer
#endif
#pragma warning(pop)
#define IMPLEMENT_MAIN(...) namespace polymer { int main(int argc, char * argv[]); } int main(int argc, char * argv[]) { return polymer::Main(argc, argv); } int polymer::Main(__VA_ARGS__)
| 29.612403
| 188
| 0.608901
|
ddiakopoulos
|
1ee1389bf8659cee47086590d92b3c79803d7351
| 3,931
|
cpp
|
C++
|
2000/arxlabs/lab09/lab9utils.cpp
|
kevinzhwl/ObjectARXMod
|
ef4c87db803a451c16213a7197470a3e9b40b1c6
|
[
"MIT"
] | 1
|
2021-06-25T02:58:47.000Z
|
2021-06-25T02:58:47.000Z
|
2000/arxlabs/lab09/lab9utils.cpp
|
kevinzhwl/ObjectARXMod
|
ef4c87db803a451c16213a7197470a3e9b40b1c6
|
[
"MIT"
] | null | null | null |
2000/arxlabs/lab09/lab9utils.cpp
|
kevinzhwl/ObjectARXMod
|
ef4c87db803a451c16213a7197470a3e9b40b1c6
|
[
"MIT"
] | 3
|
2020-05-23T02:47:44.000Z
|
2020-10-27T01:26:53.000Z
|
//
// (C) Copyright 1999 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
//
#include <dbents.h>
#include <dbsymtb.h>
#include <acdb.h>
#include <dbents.h>
#include <dbapserv.h>
#ifndef ACDBLIB
#include <actrans.h>
#include <adscodes.h>
#endif
#include "Lab9Utils.h"
//-----------------------------------------------------------------------------
Acad::ErrorStatus postToDatabase (AcDbEntity *pEnt, AcDbObjectId &idObj) {
//----- Purpose:
//----- Adds an entity to the MODEL_SPACE of the CURRENT database.
//----- Note:
//----- It could be generalized to add it to any block table record of
//----- any database, but why complicate it...
Acad::ErrorStatus es ;
AcDbBlockTable *pBlockTable ;
AcDbBlockTableRecord *pSpaceRecord ;
//----- Get a pointer to the current drawing
//----- and get the drawing's block table. Open it for read.
if ( (es =acdbHostApplicationServices()->workingDatabase()->getBlockTable (pBlockTable, AcDb::kForRead)) == Acad::eOk ) {
//----- Get the Model Space record and open it for write. This will be the owner of the new line.
if ( (es =pBlockTable->getAt (ACDB_MODEL_SPACE, pSpaceRecord, AcDb::kForWrite)) == Acad::eOk ) {
//----- Append pEnt to Model Space, then close it and the Model Space record.
if ( (es =pSpaceRecord->appendAcDbEntity (idObj, pEnt)) == Acad::eOk )
pEnt->close () ;
pSpaceRecord->close () ;
}
pBlockTable->close () ;
}
//----- It is good programming practice to return an error status
return (es) ;
}
//-----------------------------------------------------------------------------
Acad::ErrorStatus RTtoStatus (int rt) {
#ifndef ACDBLIB
//----- ObjectDBX does not have ADS functions and ADS error codes defined
//----- Description:
//----- Maps an ads return code to an Acad::ErrorStatus
//----- Note:
//----- I don't care about the performance hit that this
//----- extra function call introduces. ads_* functions, hopefully, can now
//----- be replaced by corresponding arx calls. Where they cannot be, they are
//----- usually in a user input context, therefore this performance penalty is
//----- not an issue.
//----- The mapping here is completely arbitrary. Change it if you don't like it.
switch ( rt ) {
case RTNORM: //----- 5100 - Request succeeded
return (Acad::eOk) ;
case RTERROR: //----- -5001 - Some other error
return (Acad::eUnrecoverableErrors) ;
case RTCAN: //----- -5002 - User cancelled request -- Ctl-C
return (Acad::eUserBreak) ;
case RTREJ: //----- -5003 - AutoCAD rejected request -- invalid
return (Acad::eInvalidInput) ;
case RTFAIL: //----- -5004 - Link failure -- Lisp probably died
return (Acad::eNotApplicable) ;
default:
//case RTKWORD: //----- -5005 - Keyword returned from getxxx() routine
//----- this function only intended to be called
//----- in an error checking situation. See ADSOK.
assert ( 0 ) ;
return (Acad::eOk) ;
}
#endif
return (Acad::eOk) ;
}
| 39.707071
| 123
| 0.639786
|
kevinzhwl
|
1ee1df8a7fe1b0c794c26328d9d38a933627953b
| 1,840
|
hpp
|
C++
|
server/test/ODBCTests.hpp
|
Velikss/Bus-Simulator
|
13bf0b66b9b44e3f4cb1375fc363720ea8f23e19
|
[
"MIT"
] | null | null | null |
server/test/ODBCTests.hpp
|
Velikss/Bus-Simulator
|
13bf0b66b9b44e3f4cb1375fc363720ea8f23e19
|
[
"MIT"
] | null | null | null |
server/test/ODBCTests.hpp
|
Velikss/Bus-Simulator
|
13bf0b66b9b44e3f4cb1375fc363720ea8f23e19
|
[
"MIT"
] | null | null | null |
#pragma once
#include <pch.hpp>
#include "../src/ODBC/ODBCInstance.hpp"
std::shared_ptr<cODBCInstance> poInstance;
string sUnicodeUTF8 = "おはようございます";
TEST(ODBCTests, Connect)
{
poInstance = std::make_shared<cODBCInstance>();
#if defined(WINDOWS)
EXPECT_TRUE(poInstance->Connect("driver=MariaDB ODBC 3.1 Driver;server=192.168.178.187;user=root;pwd=hiddenhand;database=test-windows;"));
#else
EXPECT_TRUE(poInstance->Connect("driver=MariaDB ODBC 3.1 Driver;server=192.168.178.187;user=root;pwd=hiddenhand;database=test-linux;"));
#endif
}
TEST(ODBCTests, Exe)
{
EXPECT_TRUE(poInstance->Exec("INSERT INTO UserTest (UserName, Password) VALUES('" + sUnicodeUTF8 + "', 'TEST');"));
}
/*TEST(ODBCTests, Unicode)
{
std::vector<SQLROW> aUsers;
EXPECT_TRUE(oInstance.Fetch("SELECT * FROM UserTest ORDER BY Id DESC LIMIT 1", &aUsers));
EXPECT_TRUE(aUsers.size() == 1);
string sFetchedUnicodeUTF8;
EXPECT_TRUE(aUsers[0]["UserName"]->GetValueStr(sFetchedUnicodeUTF8));
EXPECT_TRUE(sUnicodeUTF8.compare(sFetchedUnicodeUTF8));
}*/
TEST(ODBCTests, Fetch)
{
std::vector<SQLROW> aUsers;
EXPECT_TRUE(poInstance->Fetch("SELECT * FROM UserTest LIMIT 1", &aUsers));
EXPECT_TRUE(aUsers.size() == 1);
}
TEST(ODBCTests, SQLInjection)
{
string sString = "'; DROP TABLE *";
cODBCInstance::Escape(sString);
ASSERT_STREQ(sString.c_str(), "\\'; DROP TABLE *");
EXPECT_TRUE(poInstance->Exec("INSERT INTO UserTest (UserName, Password) VALUES('" + sString + "', 'TEST');"));
sString = "''; DROP TABLE *";
cODBCInstance::Escape(sString);
ASSERT_STREQ(sString.c_str(), "\\'\\'; DROP TABLE *");
EXPECT_TRUE(poInstance->Exec("INSERT INTO UserTest (UserName, Password) VALUES('" + sString + "', 'TEST');"));
}
TEST(ODBCTests, DisConnect)
{
EXPECT_TRUE(poInstance->Disconnect());
}
| 31.724138
| 142
| 0.695109
|
Velikss
|
1ee757c34d5fcab90bc8f5d0241c9a30bcd496f5
| 802
|
cpp
|
C++
|
Fiduccia-Mattheyses/src/nets.cpp
|
w4n9r3ntru3/Fiduccia-Mattheyses
|
d47013d315750dbfdc3e5ec7714e7ddbdc7e96b7
|
[
"MIT"
] | 1
|
2021-03-05T13:57:21.000Z
|
2021-03-05T13:57:21.000Z
|
Fiduccia-Mattheyses/src/nets.cpp
|
w4n9r3ntru3/Fiduccia-Mattheyses
|
d47013d315750dbfdc3e5ec7714e7ddbdc7e96b7
|
[
"MIT"
] | null | null | null |
Fiduccia-Mattheyses/src/nets.cpp
|
w4n9r3ntru3/Fiduccia-Mattheyses
|
d47013d315750dbfdc3e5ec7714e7ddbdc7e96b7
|
[
"MIT"
] | 1
|
2021-11-02T22:14:41.000Z
|
2021-11-02T22:14:41.000Z
|
#include "nets.h"
using namespace std;
Net::Net() : _true_count(0), _cells(vector<unsigned>()) {}
void Net::setCount(unsigned u) {
_true_count = u;
}
unsigned Net::true_count() const {
return _true_count;
}
unsigned Net::false_count() const {
return _cells.size() - _true_count;
}
unsigned Net::count(bool side) const {
if (side) {
return true_count();
} else {
return false_count();
}
}
void Net::inc_count(bool side) {
if (side) {
++_true_count;
} else {
--_true_count;
}
}
void Net::dec_count(bool side) {
inc_count(!side);
}
void Net::push_cell(unsigned cell) {
_cells.push_back(cell);
}
const vector<unsigned>& Net::cells() const {
return _cells;
}
unsigned Net::size() const {
return _cells.size();
}
| 16.04
| 58
| 0.613466
|
w4n9r3ntru3
|
1eed321b66fa85e27f0e4d59cdab37154ce992a2
| 822
|
hpp
|
C++
|
include/ftp_analyzer.hpp
|
Ksi0Na/3-4_cpp
|
38f53148ff522c48913bcff1b5895666bf1dab70
|
[
"MIT"
] | null | null | null |
include/ftp_analyzer.hpp
|
Ksi0Na/3-4_cpp
|
38f53148ff522c48913bcff1b5895666bf1dab70
|
[
"MIT"
] | null | null | null |
include/ftp_analyzer.hpp
|
Ksi0Na/3-4_cpp
|
38f53148ff522c48913bcff1b5895666bf1dab70
|
[
"MIT"
] | null | null | null |
// Copyright 2020 Olga Molchun olgamolchun5@gmail.com
#ifndef INCLUDE_FTP_ANALYZER_HPP_
#define INCLUDE_FTP_ANALYZER_HPP_
// broker stats
#include <broker_stats.hpp>
// STL headers
#include <map>
#include <ostream>
#include <regex>
#include <string>
// boost headers
#include <boost/filesystem.hpp>
class FtpAnalyzer final {
public:
explicit FtpAnalyzer(const std::string& root);
std::multimap<std::string, BrokerStats> analyze(std::ostream& os);
private:
std::string root_;
std::regex filter_;
std::multimap<std::string, BrokerStats> stats;
void analyzeImpl(const boost::filesystem::path& currPath,
std::ostream& os);
void insert(const std::string& broker, const std::string& id,
const std::string& date);
}; // class FtpAnalyzer
#endif // INCLUDE_FTP_ANALYZER_HPP_
| 27.4
| 70
| 0.717762
|
Ksi0Na
|
1ef3b91736f4fff72d38d534e6ac2300897e7f04
| 333
|
cpp
|
C++
|
BadMakeReturn.cpp
|
kfejes/cpp-security-examples
|
7b4646e3e86187696b796aed3ec323f629d57bc9
|
[
"MIT"
] | null | null | null |
BadMakeReturn.cpp
|
kfejes/cpp-security-examples
|
7b4646e3e86187696b796aed3ec323f629d57bc9
|
[
"MIT"
] | null | null | null |
BadMakeReturn.cpp
|
kfejes/cpp-security-examples
|
7b4646e3e86187696b796aed3ec323f629d57bc9
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <memory>
#include <string>
using namespace std;
int main() {
auto msgPtr = make_unique<string>("testMessage");
auto movedMsgPtr = move(msgPtr); // OK
auto found = movedMsgPtr->find("testMessage"); // OK
msgPtr->find("testMessage"); // Segmentation fault
return EXIT_SUCCESS;
}
| 22.2
| 57
| 0.66967
|
kfejes
|
1ef5d9ae99088ab810f7bfd4c3ed3628887e2340
| 818
|
cpp
|
C++
|
jp.atcoder/abc002/abc002_4/11335580.cpp
|
kagemeka/atcoder-submissions
|
91d8ad37411ea2ec582b10ba41b1e3cae01d4d6e
|
[
"MIT"
] | 1
|
2022-02-09T03:06:25.000Z
|
2022-02-09T03:06:25.000Z
|
jp.atcoder/abc002/abc002_4/11335580.cpp
|
kagemeka/atcoder-submissions
|
91d8ad37411ea2ec582b10ba41b1e3cae01d4d6e
|
[
"MIT"
] | 1
|
2022-02-05T22:53:18.000Z
|
2022-02-09T01:29:30.000Z
|
jp.atcoder/abc002/abc002_4/11335580.cpp
|
kagemeka/atcoder-submissions
|
91d8ad37411ea2ec582b10ba41b1e3cae01d4d6e
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, m;
cin >> n >> m;
vector<set<int>> g(n);
for (int i = 0; i < m; i++) {
int x, y;
cin >> x >> y;
x--; y--;
g[x].insert(y);
g[y].insert(x);
}
int res = 1;
for (int i = 0; i < (1 << n); i++) {
vector<int> group(0);
for (int j = 0; j < n; j++) {
if (i >> j & 1) group.push_back(j);
}
int k = group.size();
bool flag = false;
for (int a = 0; a < k - 1; a++) {
for (int b = a + 1; b < k; b++) {
int &x = group[a];
int &y = group[b];
if (g[x].find(y) != g[x].end()) continue;
flag = true;
break;
}
if (flag) break;
}
if (!flag) res = max(res, k);
}
cout << res << endl;
return 0;
}
| 20.45
| 50
| 0.391198
|
kagemeka
|
1ef879a886571ed8ef5a2a743a8cdbaaa5402543
| 5,627
|
cxx
|
C++
|
src/Cxx/CompositeData/OverlappingAMR.cxx
|
pavankumarbn/VTKExamples
|
884019ad7b3f39885b115ea8e800d5b4414605b2
|
[
"Apache-2.0"
] | 2
|
2019-01-19T17:51:00.000Z
|
2019-01-19T17:51:03.000Z
|
src/Cxx/CompositeData/OverlappingAMR.cxx
|
pavankumarbn/VTKExamples
|
884019ad7b3f39885b115ea8e800d5b4414605b2
|
[
"Apache-2.0"
] | null | null | null |
src/Cxx/CompositeData/OverlappingAMR.cxx
|
pavankumarbn/VTKExamples
|
884019ad7b3f39885b115ea8e800d5b4414605b2
|
[
"Apache-2.0"
] | null | null | null |
// Demonstrates how to create and populate a VTK's Overlapping AMR Grid
// type Data
#include <vtkAMRBox.h>
#include <vtkAMRUtilities.h>
#include <vtkContourFilter.h>
#include <vtkFloatArray.h>
#include <vtkCompositeDataGeometryFilter.h>
#include <vtkOutlineFilter.h>
#include <vtkOverlappingAMR.h>
#include <vtkPointData.h>
#include <vtkPolyDataMapper.h>
#include <vtkRenderer.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkSmartPointer.h>
#include <vtkSphere.h>
#include <vtkUniformGrid.h>
namespace
{
void MakeScalars(int dims[3], double origin[3], double spacing[3],
vtkFloatArray* scalars)
{
// Implicit function used to compute scalars
vtkSmartPointer<vtkSphere> sphere =
vtkSmartPointer<vtkSphere>::New();
sphere->SetRadius(3);
sphere->SetCenter(5, 5, 5);
scalars->SetNumberOfTuples(dims[0]*dims[1]*dims[2]);
for (int k=0; k<dims[2]; k++)
{
double z = origin[2] + spacing[2]*k;
for (int j=0; j<dims[1]; j++)
{
double y = origin[1] + spacing[1]*j;
for (int i=0; i<dims[0]; i++)
{
double x = origin[0] + spacing[0]*i;
scalars->SetValue(
k*dims[0]*dims[1] + j*dims[0] + i,
sphere->EvaluateFunction(x, y, z));
}
}
}
}
}
int main (int, char *[])
{
// Create and populate the AMR dataset
// The dataset should look like
// Level 0
// uniform grid, dimensions 11, 11, 11, AMR box (0, 0, 0) - (9, 9, 9)
// Level 1 - refinement ratio : 2
// uniform grid, dimensions 11, 11, 11, AMR box (0, 0, 0) - (9, 9, 9)
// uniform grid, dimensions 11, 11, 11, AMR box (10, 10, 10) - (19, 19, 19)
// Use MakeScalars() above to fill the scalar arrays
vtkSmartPointer<vtkOverlappingAMR> amr =
vtkSmartPointer<vtkOverlappingAMR>::New();
int blocksPerLevel[] = { 1, 2 };
amr->Initialize(2, blocksPerLevel);
double origin[3] = {0.0, 0.0, 0.0};
double spacing[3] = {1.0, 1.0, 1.0};
int dims[3] = {11, 11, 11};
vtkSmartPointer<vtkUniformGrid> ug1 =
vtkSmartPointer<vtkUniformGrid>::New();
// Geometry
ug1->SetOrigin(origin);
ug1->SetSpacing(spacing);
ug1->SetDimensions(dims);
// Data
vtkSmartPointer<vtkFloatArray> scalars =
vtkSmartPointer<vtkFloatArray>::New();
ug1->GetPointData()->SetScalars(scalars);
MakeScalars(dims, origin, spacing, scalars);
int lo[3] = {0, 0, 0};
int hi[3] = {9, 9, 9};
vtkAMRBox box1(lo, hi);
amr->SetAMRBox(0, 0, box1);
amr->SetDataSet(0, 0, ug1);
double spacing2[3] = {0.5, 0.5, 0.5};
vtkSmartPointer<vtkUniformGrid> ug2 =
vtkSmartPointer<vtkUniformGrid>::New();
// Geometry
ug2->SetOrigin(origin);
ug2->SetSpacing(spacing2);
ug2->SetDimensions(dims);
// Data
scalars = vtkSmartPointer<vtkFloatArray>::New();
ug2->GetPointData()->SetScalars(scalars);
MakeScalars(dims, origin, spacing2, scalars);
int lo2[3] = {0, 0, 0};
int hi2[3] = {9, 9, 9};
vtkAMRBox box2(lo2, hi2);
amr->SetAMRBox(1, 0, box2);
amr->SetDataSet(1, 0, ug2);
double origin3[3] = {5, 5, 5};
vtkSmartPointer<vtkUniformGrid> ug3 =
vtkSmartPointer<vtkUniformGrid>::New();
// Geometry
ug3->SetOrigin(origin3);
ug3->SetSpacing(spacing2);
ug3->SetDimensions(dims);
// Data
scalars = vtkSmartPointer<vtkFloatArray>::New();
ug3->GetPointData()->SetScalars(scalars);
MakeScalars(dims, origin3, spacing2, scalars);
int lo3[3] = {10, 10, 10};
int hi3[3] = {19, 19, 19};
vtkAMRBox box3(lo3, hi3);
amr->SetAMRBox(1, 1, box3);
amr->SetDataSet(1, 1, ug3);
amr->SetRefinementRatio(0, 2);
vtkAMRUtilities::BlankCells(amr);
// Render the amr data here
vtkSmartPointer<vtkOutlineFilter> of =
vtkSmartPointer<vtkOutlineFilter>::New();
of->SetInputData(amr);
vtkSmartPointer<vtkCompositeDataGeometryFilter> geomFilter =
vtkSmartPointer<vtkCompositeDataGeometryFilter>::New();
geomFilter->SetInputConnection(of->GetOutputPort());
// Create an iso-surface - at 10
vtkSmartPointer<vtkContourFilter> cf =
vtkSmartPointer<vtkContourFilter>::New();
cf->SetInputData(amr);
cf->SetNumberOfContours(1);
cf->SetValue(0, 10.0);
vtkSmartPointer<vtkCompositeDataGeometryFilter> geomFilter2 =
vtkSmartPointer<vtkCompositeDataGeometryFilter>::New();
geomFilter2->SetInputConnection(cf->GetOutputPort());
// create the render window, renderer, and interactor
vtkSmartPointer<vtkRenderer> aren =
vtkSmartPointer<vtkRenderer>::New();
vtkSmartPointer<vtkRenderWindow> renWin =
vtkSmartPointer<vtkRenderWindow>::New();
renWin->AddRenderer(aren);
vtkSmartPointer<vtkRenderWindowInteractor> iren =
vtkSmartPointer<vtkRenderWindowInteractor>::New();
iren->SetRenderWindow(renWin);
// associate the geometry with a mapper and the mapper to an actor
vtkSmartPointer<vtkPolyDataMapper> mapper =
vtkSmartPointer<vtkPolyDataMapper>::New();
mapper->SetInputConnection(geomFilter->GetOutputPort());
vtkSmartPointer<vtkActor> actor1 =
vtkSmartPointer<vtkActor>::New();
actor1->SetMapper(mapper);
// associate the geometry with a mapper and the mapper to an actor
vtkSmartPointer<vtkPolyDataMapper> mapper2 =
vtkSmartPointer<vtkPolyDataMapper>::New();
mapper2->SetInputConnection(geomFilter2->GetOutputPort());
vtkSmartPointer<vtkActor> actor2 =
vtkSmartPointer<vtkActor>::New();
actor2->SetMapper(mapper2);
// add the actor to the renderer and start handling events
aren->AddActor(actor1);
aren->AddActor(actor2);
renWin->Render();
iren->Start();
return EXIT_SUCCESS;
}
| 29.307292
| 79
| 0.674605
|
pavankumarbn
|
1efaee38e0cf3e4275fe2b100295eba433f765ec
| 3,022
|
hpp
|
C++
|
module/native/src/watch.hpp
|
cpoco/eyna
|
eed817c3cc90f82fdc05125138a4e303dd3fa098
|
[
"MIT"
] | null | null | null |
module/native/src/watch.hpp
|
cpoco/eyna
|
eed817c3cc90f82fdc05125138a4e303dd3fa098
|
[
"MIT"
] | null | null | null |
module/native/src/watch.hpp
|
cpoco/eyna
|
eed817c3cc90f82fdc05125138a4e303dd3fa098
|
[
"MIT"
] | null | null | null |
#ifndef NATIVE_WATCH
#define NATIVE_WATCH
#include "common.hpp"
// http://docs.libuv.org/en/v1.x/handle.html
// http://docs.libuv.org/en/v1.x/fs_event.html
class _watch_map
{
struct _data
{
uv_fs_event_t* event;
int32_t id;
std::filesystem::path path; // generic_path
v8::Persistent<v8::Function> callback;
};
std::map<int32_t, _data*> map;
public:
~_watch_map()
{
for (auto& [key, data] : map) {
uv_close((uv_handle_t*)data->event, &_watch_map::release);
}
}
void add(const int32_t _id, const _string_t& _path, const v8::Local<v8::Function>& _callback)
{
if (map.count(_id) != 0) {
remove(_id);
}
v8::HandleScope _(ISOLATE);
_data* data = new _data();
map.insert(std::make_pair(_id, data));
data->event = new uv_fs_event_t();
data->event->data = data;
data->id = _id;
data->path = generic_path(std::filesystem::path(_path));
data->callback.Reset(ISOLATE, _callback);
uv_fs_event_init(uv_default_loop(), data->event);
uv_fs_event_start(data->event, &_watch_map::callback, data->path.u8string().c_str(), UV_FS_EVENT_RECURSIVE);
}
void remove(const int32_t _id)
{
if (map.count(_id) == 0) {
return;
}
_data* data = map.at(_id);
map.erase(_id);
uv_fs_event_stop(data->event);
uv_close((uv_handle_t*)data->event, &_watch_map::release);
}
// uv_fs_event_cb
static void callback(uv_fs_event_t* _event, const char* _filename, int _events, int _status)
{
v8::HandleScope _(ISOLATE);
_data* data = static_cast<_data*>(_event->data);
if (_event != data->event || _filename == nullptr) {
return;
}
std::basic_string<char> u8filename(_filename);
#if _OS_WIN_
int depth = std::count(u8filename.cbegin(), u8filename.cend(), '\\');
#elif _OS_MAC_
int depth = std::count(u8filename.cbegin(), u8filename.cend(), '/');
#endif
const int argc = 3;
v8::Local<v8::Value> argv[argc] = {
v8::Number::New(ISOLATE, data->id),
v8::Number::New(ISOLATE, depth),
to_string(generic_path(data->path / std::filesystem::u8path(u8filename)))
};
data->callback.Get(ISOLATE)->Call(CONTEXT, v8::Undefined(ISOLATE), argc, argv);
}
// uv_close_cb
static void release(uv_handle_t* _event)
{
_data* data = static_cast<_data*>(_event->data);
data->callback.Reset();
delete data->event;
delete data;
}
} watch_map = _watch_map();
void watch(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::HandleScope _(ISOLATE);
if (info.Length() != 3
|| !info[0]->IsNumber()
|| !info[1]->IsString()
|| !info[2]->IsFunction())
{
return;
}
int32_t id = info[0]->Int32Value(CONTEXT).ToChecked();
_string_t path = to_string(info[1]->ToString(CONTEXT).ToLocalChecked());
watch_map.add(id, path, v8::Local<v8::Function>::Cast(info[2]));
}
void unwatch(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::HandleScope _(ISOLATE);
if (info.Length() != 1 || !info[0]->IsNumber()) {
return;
}
int32_t id = info[0]->Int32Value(CONTEXT).ToChecked();
watch_map.remove(id);
}
#endif // include guard
| 21.898551
| 110
| 0.665784
|
cpoco
|
1eff5a5e74faf465120046d77821f34ba81188f5
| 897
|
cpp
|
C++
|
Easy/67_Add_Binary.cpp
|
ShehabMMohamed/LeetCodeCPP
|
684340f29ac15c5e8fa9f6ef5c3f99d4c95ce780
|
[
"MIT"
] | 1
|
2021-03-15T10:02:10.000Z
|
2021-03-15T10:02:10.000Z
|
Easy/67_Add_Binary.cpp
|
ShehabMMohamed/LeetCodeCPP
|
684340f29ac15c5e8fa9f6ef5c3f99d4c95ce780
|
[
"MIT"
] | null | null | null |
Easy/67_Add_Binary.cpp
|
ShehabMMohamed/LeetCodeCPP
|
684340f29ac15c5e8fa9f6ef5c3f99d4c95ce780
|
[
"MIT"
] | null | null | null |
class Solution {
public:
string addBinary(string a, string b) {
reverse(a.begin(), a.end());
reverse(b.begin(), b.end());
string result = "";
bool carry = false;
for(int i = 0, j = 0; i < a.length() || j < b.length(); i++, j++) {
int binary_a = (i < a.length()) ? a[i] - '0' : 0;
int binary_b = (j < b.length()) ? b[j] - '0' : 0;
if (binary_a + binary_b > 1) {
result += (carry) ? '1' : '0';
carry = true;
}
else if(binary_a + binary_b > 0 && carry)
result += '0';
else {
result += (carry) ? '1' : (binary_a + binary_b) + '0';
carry = false;
}
}
if(carry) result += '1';
reverse(result.begin(), result.end());
return result;
}
};
| 32.035714
| 75
| 0.394649
|
ShehabMMohamed
|
480153aac26f98b51b815b1ac8d659baf797d486
| 2,167
|
cpp
|
C++
|
arvoes_b.cpp
|
PedroHenrique-git/data-structures
|
4252751328a6ab5e993ff1f58fa70c13ecbafed2
|
[
"MIT"
] | null | null | null |
arvoes_b.cpp
|
PedroHenrique-git/data-structures
|
4252751328a6ab5e993ff1f58fa70c13ecbafed2
|
[
"MIT"
] | null | null | null |
arvoes_b.cpp
|
PedroHenrique-git/data-structures
|
4252751328a6ab5e993ff1f58fa70c13ecbafed2
|
[
"MIT"
] | null | null | null |
#include<iostream>
using namespace std;
#define G 2
typedef struct tipo_no no;
typedef int tipo_dado;
struct tipo_no {
int nro_chaves;
int folha;
tipo_dado chaves[2*G-1];
tipo_no *apontadores[2*G];
};
void criar_arvore_B(no **A) {
no *Novo;
Novo = (no *)malloc(sizeof(no));
Novo->folha = 1;
Novo->nro_chaves = 0;
*A = Novo;
}
void repartir(no **Pai, int i) {
no *Ant, *Novo;
int k;
Ant = (*Pai)->apontadores[i];
Novo = (no *)malloc(sizeof(no));
Novo->folha = Ant->folha;
for(k = 0; k <= G-2; k++) {
Novo->chaves[k] = Ant->chaves[k+G];
}
if(Ant->folha == 0) {
for(k = 0; k <= G-1; k++) {
Novo->apontadores[k] = Ant->apontadores[k+G];
}
}
Novo->nro_chaves = Ant->nro_chaves = G-1;
for(k = (*Pai)->nro_chaves-1; k >= i; k--) {
(*Pai)->chaves[k+1] = (*Pai)->chaves[k];
}
(*Pai)->chaves[i] = Ant->chaves[G-1];
((*Pai)->nro_chaves)++;
for(k = ((*Pai)->nro_chaves); k >= i+1; k--) {
(*Pai)->apontadores[k+1] = (*Pai)->apontadores[k];
}
(*Pai)->apontadores[k+1] = Novo;
}
void inserir_chave_B(no **N, tipo_dado Ch) {
no *Aux;
int k;
k = (*N)->nro_chaves-1;
if((*N)->folha == 1) {
while(k >= 0 || Ch < (*N)->chaves[k]) {
(*N)->chaves[k+1] = (*N)->chaves[k];
k--;
}
(*N)->chaves[k+1] = Ch;
((*N)->nro_chaves)++;
} else {
while(k >= 0 || Ch < (*N)->chaves[k]) {
k--;
}
k++;
Aux = (*N)->apontadores[k];
if(Aux->nro_chaves == 2*G-1) {
repartir(&(*N)->chaves[k]) {
k++;
}
Aux = (*N)->apontadores[k];
}
inserir_chave_B(&Aux, Ch);
}
}
void inserir_B(no **A, tipo_dado Ch) {
no *Aux, *Novo;
Aux = *A;
if(Aux->nro_chaves == 2*G-1) {
Novo = (no *)malloc(sizeof(no));
Novo->folha = 0;
Novo->nro_chaves = 0;
Novo->apontadores[0] = Aux;
*A = Novo;
repartir(&Novo, 0);
inserir_chave_B(&Aux, Ch);
} else {
inserir_chave_B(&(*A), Ch);
}
}
| 23.301075
| 58
| 0.457776
|
PedroHenrique-git
|
4808e4e22cded8630250f27dc34fe6a99dd81843
| 3,407
|
cc
|
C++
|
src/engine/scripting/binding/utilities/ini.cc
|
hvonck/lambda-lilac
|
c4cf744356c2d2056e8f66da4f95d2268f7c25d0
|
[
"BSD-3-Clause"
] | 1
|
2019-05-28T16:39:19.000Z
|
2019-05-28T16:39:19.000Z
|
src/engine/scripting/binding/utilities/ini.cc
|
hvonck/lambda-lilac
|
c4cf744356c2d2056e8f66da4f95d2268f7c25d0
|
[
"BSD-3-Clause"
] | null | null | null |
src/engine/scripting/binding/utilities/ini.cc
|
hvonck/lambda-lilac
|
c4cf744356c2d2056e8f66da4f95d2268f7c25d0
|
[
"BSD-3-Clause"
] | 1
|
2019-05-28T16:39:06.000Z
|
2019-05-28T16:39:06.000Z
|
#include "ini.h"
#include <INIReader.h>
#include <utils/file_system.h>
#include <utils/console.h>
namespace lambda
{
namespace scripting
{
namespace utilities
{
namespace ini
{
UnorderedMap<uint64_t, INIReader> g_ini_readers;
uint64_t Load(const String& file_path)
{
String fp = FileSystem::GetBaseDir() + file_path;
uint64_t ini_id = hash(fp);
INIReader ini_reader(stlString(fp));
int error = ini_reader.ParseError();
String error_message = (error == -1 ? "Could not open file." : (error > 0 ? ("Line was unreadable: " + toString(error)) : ""));
if (false == error_message.empty())
{
foundation::Error("INI: '" + error_message + "' occurred while opening '" + file_path + "'");
}
g_ini_readers.insert(eastl::make_pair(ini_id, ini_reader));
return ini_id;
}
void Release(const uint64_t& ini_id)
{
g_ini_readers.erase(ini_id);
}
float GetVariableFloat(const uint64_t& ini_id, const String& section, const String& name)
{
return (float)g_ini_readers.at(ini_id).GetReal(stlString(section), stlString(name), 0.0);
}
double GetVariableDouble(const uint64_t& ini_id, const String& section, const String& name)
{
return g_ini_readers.at(ini_id).GetReal(stlString(section), stlString(name), 0.0);
}
bool GetVariableBool(const uint64_t& ini_id, const String& section, const String& name)
{
return g_ini_readers.at(ini_id).GetBoolean(stlString(section), stlString(name), false);
}
int32_t GetVariableInt(const uint64_t& ini_id, const String& section, const String& name)
{
return (int32_t)g_ini_readers.at(ini_id).GetInteger(stlString(section), stlString(name), 0);
}
String GetVariableString(const uint64_t& ini_id, const String& section, const String& name)
{
return lmbString(g_ini_readers.at(ini_id).Get(stlString(section), stlString(name), ""));
}
Map<lambda::String, void*> Bind(world::IWorld* world)
{
return Map<lambda::String, void*>{
{ "uint64 Violet_Utilities_Ini::Load(const String&in)", (void*)Load },
{ "void Violet_Utilities_Ini::Release(const uint64&in)", (void*)Release },
{ "bool Violet_Utilities_Ini::GetVariableBool(const uint64&in, const String&in, const String&in)", (void*)GetVariableBool },
{ "uint32 Violet_Utilities_Ini::GetVariableInt(const uint64&in, const String&in, const String&in)", (void*)GetVariableInt },
{ "float Violet_Utilities_Ini::GetVariableFloat(const uint64&in, const String&in, const String&in)", (void*)GetVariableFloat },
{ "double Violet_Utilities_Ini::GetVariableDouble(const uint64&in, const String&in, const String&in)", (void*)GetVariableDouble },
{ "String Violet_Utilities_Ini::GetVariableString(const uint64&in, const String&in, const String&in)", (void*)GetVariableString },
};
}
void Unbind()
{
g_ini_readers.clear();
}
}
}
}
}
| 45.426667
| 143
| 0.591136
|
hvonck
|
480e3492fe59f0ec6e8a6188891889855623ba39
| 1,000
|
hpp
|
C++
|
src/seq/fasta_sub_util.hpp
|
toppic-suite/toppic-suite
|
b5f0851f437dde053ddc646f45f9f592c16503ec
|
[
"Apache-2.0"
] | 8
|
2018-05-23T14:37:31.000Z
|
2022-02-04T23:48:38.000Z
|
src/seq/fasta_sub_util.hpp
|
toppic-suite/toppic-suite
|
b5f0851f437dde053ddc646f45f9f592c16503ec
|
[
"Apache-2.0"
] | 9
|
2019-08-31T08:17:45.000Z
|
2022-02-11T20:58:06.000Z
|
src/seq/fasta_sub_util.hpp
|
toppic-suite/toppic-suite
|
b5f0851f437dde053ddc646f45f9f592c16503ec
|
[
"Apache-2.0"
] | 4
|
2018-04-25T01:39:38.000Z
|
2020-05-20T19:25:07.000Z
|
//Copyright (c) 2014 - 2020, The Trustees of Indiana University.
//
//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.
#ifndef TOPPIC_SEQ_FASTA_SUB_UTIL_HPP_
#define TOPPIC_SEQ_FASTA_SUB_UTIL_HPP_
#include "seq/fasta_sub_seq.hpp"
namespace toppic {
namespace fasta_sub_util {
// break sequences into subsequences with length 2000
FastaSubSeqPtrVec breakSeq(FastaSeqPtr seq_ptr);
FastaSubSeqPtrVec breakSeq(FastaSeqPtr seq_ptr, int N);
} // namespace fasta_sub_util
} // namespace toppic
#endif
| 29.411765
| 74
| 0.777
|
toppic-suite
|
48103cb3435deee9e687e96ee9b71b2695e77a6a
| 213
|
cpp
|
C++
|
contest/AtCoder/abc032/B.cpp
|
not522/Competitive-Programming
|
be4a7d25caf5acbb70783b12899474a56c34dedb
|
[
"Unlicense"
] | 7
|
2018-04-14T14:55:51.000Z
|
2022-01-31T10:49:49.000Z
|
contest/AtCoder/abc032/B.cpp
|
not522/Competitive-Programming
|
be4a7d25caf5acbb70783b12899474a56c34dedb
|
[
"Unlicense"
] | 5
|
2018-04-14T14:28:49.000Z
|
2019-05-11T02:22:10.000Z
|
contest/AtCoder/abc032/B.cpp
|
not522/Competitive-Programming
|
be4a7d25caf5acbb70783b12899474a56c34dedb
|
[
"Unlicense"
] | null | null | null |
#include "set.hpp"
#include "string.hpp"
int main() {
String s(in);
int k(in);
Set<String> st;
for (int i = 0; i <= s.size() - k; ++i) {
st.emplace(s.substr(i, k));
}
cout << st.size() << endl;
}
| 16.384615
| 43
| 0.516432
|
not522
|
4810879cee3ee0761455d7929453ba30b5d1f69b
| 6,770
|
cp
|
C++
|
Obx/Mod/Buttons.cp
|
romiras/Blackbox-fw-playground
|
6de94dc65513e657a9b86c1772e2c07742b608a8
|
[
"BSD-2-Clause"
] | 1
|
2018-03-15T00:25:25.000Z
|
2018-03-15T00:25:25.000Z
|
Obx/Mod/Buttons.cps
|
Spirit-of-Oberon/LightBox
|
8a45ed11dcc02ae97e86f264dcee3e07c910ff9d
|
[
"BSD-2-Clause"
] | null | null | null |
Obx/Mod/Buttons.cps
|
Spirit-of-Oberon/LightBox
|
8a45ed11dcc02ae97e86f264dcee3e07c910ff9d
|
[
"BSD-2-Clause"
] | 1
|
2021-04-14T21:17:51.000Z
|
2021-04-14T21:17:51.000Z
|
MODULE ObxButtons;
(**
project = "BlackBox"
organization = "www.oberon.ch"
contributors = "Oberon microsystems"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "Docu/BB-License"
changes = ""
issues = ""
**)
IMPORT Dialog, Stores, Fonts, Ports, Views, Controllers, Properties, Controls;
CONST minVersion = 0; maxVersion = 0;
TYPE
View = POINTER TO RECORD (Views.View)
font: Fonts.Font;
color: INTEGER;
link: Dialog.String;
label: ARRAY 256 OF CHAR
END;
PROCEDURE (v: View) Internalize (VAR rd: Stores.Reader);
VAR version: INTEGER;
BEGIN
rd.ReadVersion(minVersion, maxVersion, version);
IF ~rd.cancelled THEN
Views.ReadFont(rd, v.font); rd.ReadInt(v.color); rd.ReadString(v.link); rd.ReadString(v.label)
END
END Internalize;
PROCEDURE (v: View) Externalize (VAR wr: Stores.Writer);
BEGIN
wr.WriteVersion(maxVersion);
Views.WriteFont(wr, v.font); wr.WriteInt(v.color); wr.WriteString(v.link); wr.WriteString(v.label)
END Externalize;
PROCEDURE (v: View) CopyFromSimpleView (source: Views.View);
BEGIN
WITH source: View DO
v.font := source.font; v.color := source.color; v.link := source.link; v.label := source.label
END
END CopyFromSimpleView;
PROCEDURE (v: View) Restore (f: Views.Frame; l, t, r, b: INTEGER);
VAR w, h, x, y, asc, dsc, fw: INTEGER;
BEGIN (* restore view at least in rectangle (l, t, r, b) *)
v.context.GetSize(w, h); (* the container context maintains the view's size *)
f.DrawRect(0, 0, w, h, f.dot, v.color); (* f.dot is close to one point, i.e. 1/72 inch *)
x := (w - v.font.StringWidth(v.label)) DIV 2;
v.font.GetBounds(asc, dsc, fw);
y := h DIV 2 + (asc + dsc) DIV 3;
f.DrawString(x, y, v.color, v.label, v.font)
END Restore;
PROCEDURE (v: View) HandleCtrlMsg (
f: Views.Frame; VAR msg: Controllers.Message; VAR focus: Views.View
);
VAR x, y, w, h, res: INTEGER; modifiers: SET; inside, isDown: BOOLEAN;
BEGIN
WITH msg: Controllers.TrackMsg DO (* mouse button was pressed *)
v.context.GetSize(w, h);
f.MarkRect(0, 0, w, h, Ports.fill, Ports.invert, Ports.show); inside := TRUE;
REPEAT (* mouse tracking loop *)
f.Input(x, y, modifiers, isDown);
IF inside # (x >= 0) & (y >= 0) & (x < w) & (y < h) THEN (* toggle state *)
inside := ~inside; f.MarkRect(0, 0, w, h, Ports.fill, Ports.invert, inside)
END
UNTIL ~isDown;
IF inside THEN (* mouse was released inside the control *)
f.MarkRect(0, 0, w, h, Ports.fill, Ports.invert, Ports.hide);
IF v.link # "" THEN
Dialog.Call(v.link, "", res) (* interpret and execute the string in v.link *)
END
END
ELSE (* ignore other messages *)
END
END HandleCtrlMsg;
PROCEDURE GetStdProp (v: View): Properties.Property;
VAR prop: Properties.StdProp;
BEGIN
NEW(prop);
prop.color.val := v.color;
prop.typeface := v.font.typeface;
prop.size := v.font.size;
prop.style.val := v.font.style;
prop.weight := v.font.weight;
prop.valid := {Properties.color..Properties.weight}; prop.known := prop.valid;
RETURN prop
END GetStdProp;
PROCEDURE SetStdProp (v: View; prop: Properties.StdProp);
VAR typeface: Fonts.Typeface; size: INTEGER; style: SET; weight: INTEGER;
BEGIN
IF Properties.color IN prop.valid THEN v.color := prop.color.val END;
typeface := v.font.typeface; size := v.font.size; style := v.font.style; weight := v.font.weight;
IF Properties.typeface IN prop.valid THEN typeface := prop.typeface END;
IF Properties.size IN prop.valid THEN size := prop.size END;
IF Properties.style IN prop.valid THEN style := prop.style.val END;
IF Properties.weight IN prop.valid THEN weight := prop.weight END;
v.font := Fonts.dir.This(typeface, size, style, weight);
END SetStdProp;
PROCEDURE (v: View) HandlePropMsg (VAR msg: Properties.Message);
CONST defaultWidth = 20 * Ports.mm; defaultHeight = 7 * Ports.mm;
VAR p: Controls.Prop; prop: Properties.Property;
BEGIN
WITH msg: Properties.FocusPref DO (* a button is a "hot focus", i.e. does not remain focused *)
msg.hotFocus := TRUE
| msg: Properties.SizePref DO (* return the default size of a button *)
IF msg.w = Views.undefined THEN msg.w := defaultWidth END;
IF msg.h = Views.undefined THEN msg.h := defaultHeight END
| msg: Properties.PollMsg DO (* return the standard font, color, and control properties *)
NEW(p);
p.link := v.link; p.label := v.label$;
p.valid := {Controls.link, Controls.label}; p.known := p.valid;
Properties.Insert(msg.prop, p);
Properties.Insert(msg.prop, GetStdProp(v))
| msg: Properties.SetMsg DO (* set the standard font, color, or control properties *)
prop := msg.prop;
WHILE prop # NIL DO
WITH prop: Controls.Prop DO (* standard control properties *)
Views.BeginModification(Views.notUndoable, v);
IF Controls.link IN prop.valid THEN v.link := prop.link; END;
IF Controls.label IN prop.valid THEN v.label := prop.label$ END;
Views.EndModification(Views.notUndoable, v);
Views.Update(v, Views.keepFrames) (* causes a delayed redrawing of the view *)
| prop: Properties.StdProp DO (* standard font and color properties *)
Views.BeginModification(Views.notUndoable, v);
SetStdProp(v, prop);
Views.EndModification(Views.notUndoable, v);
Views.Update(v, Views.keepFrames) (* causes a delayed redrawing of the view *)
ELSE
END;
prop := prop.next
END
ELSE (* ignore other messages *)
END
END HandlePropMsg;
PROCEDURE New* (): Views.View;
VAR v: View;
BEGIN (* create a new button *)
NEW(v); v.color := Ports.defaultColor; v.font := Fonts.dir.Default(); v.link := ""; v.label := ""; RETURN v
END New;
PROCEDURE Deposit*;
BEGIN
Views.Deposit(New())
END Deposit;
END ObxButtons.
| 42.578616
| 115
| 0.575185
|
romiras
|
4814bb617f0d67ad5eccebfd538aa306f040cbad
| 3,661
|
cpp
|
C++
|
examples/feature_showcase/source/polyline_drawing_test/polyline_drawing_test.cpp
|
mogemimi/pomdog
|
6dc6244d018f70d42e61c6118535cf94a9ee0618
|
[
"MIT"
] | 163
|
2015-03-16T08:42:32.000Z
|
2022-01-11T21:40:22.000Z
|
examples/feature_showcase/source/polyline_drawing_test/polyline_drawing_test.cpp
|
mogemimi/pomdog
|
6dc6244d018f70d42e61c6118535cf94a9ee0618
|
[
"MIT"
] | 17
|
2015-04-12T20:57:50.000Z
|
2020-10-10T10:51:45.000Z
|
examples/feature_showcase/source/polyline_drawing_test/polyline_drawing_test.cpp
|
mogemimi/pomdog
|
6dc6244d018f70d42e61c6118535cf94a9ee0618
|
[
"MIT"
] | 21
|
2015-04-12T20:45:11.000Z
|
2022-01-14T20:50:16.000Z
|
#include "polyline_drawing_test.hpp"
#include <pomdog/experimental/tween/easing_helper.hpp>
namespace feature_showcase {
PolylineDrawingTest::PolylineDrawingTest(const std::shared_ptr<GameHost>& gameHostIn)
: gameHost(gameHostIn)
, graphicsDevice(gameHostIn->GetGraphicsDevice())
, commandQueue(gameHostIn->GetGraphicsCommandQueue())
{
}
std::unique_ptr<Error> PolylineDrawingTest::Initialize()
{
auto assets = gameHost->GetAssetManager();
auto clock = gameHost->GetClock();
std::unique_ptr<Error> err;
// NOTE: Create graphics command list
std::tie(commandList, err) = graphicsDevice->CreateGraphicsCommandList();
if (err != nullptr) {
return errors::Wrap(std::move(err), "failed to create graphics command list");
}
lineBatch = std::make_shared<PolylineBatch>(graphicsDevice, *assets);
auto mouse = gameHost->GetMouse();
connect(mouse->ButtonDown, [this](MouseButtons button) {
if (button == MouseButtons::Left) {
polylineClosed = false;
}
if (button == MouseButtons::Right) {
path.clear();
}
});
connect(mouse->ButtonUp, [this](MouseButtons button) {
if (button == MouseButtons::Left) {
polylineClosed = true;
}
});
connect(mouse->ScrollWheel, [this](int32_t delta) {
lineWidth = std::clamp(lineWidth + static_cast<float>(delta) * 0.1f, 0.5f, 40.0f);
});
return nullptr;
}
void PolylineDrawingTest::Update()
{
const auto mouseState = gameHost->GetMouse()->GetState();
const auto width = gameHost->GetWindow()->GetClientBounds().Width;
const auto height = gameHost->GetWindow()->GetClientBounds().Height;
const auto pos = math::ToVector2(Point2D{mouseState.Position.X - (width / 2), (height / 2) - mouseState.Position.Y});
if (mouseState.LeftButton == ButtonState::Pressed) {
if (path.empty()) {
path.push_back(pos);
path.push_back(pos);
}
else if (math::DistanceSquared(pos, path[path.size() - 2]) > 10.0f) {
path.back() = pos;
path.push_back(pos);
}
}
if (!path.empty()) {
path.back() = pos;
}
}
void PolylineDrawingTest::Draw()
{
auto presentationParameters = graphicsDevice->GetPresentationParameters();
Viewport viewport = {0, 0, presentationParameters.BackBufferWidth, presentationParameters.BackBufferHeight};
RenderPass pass;
pass.RenderTargets[0] = {nullptr, Color::CornflowerBlue().ToVector4()};
pass.DepthStencilBuffer = nullptr;
pass.ClearDepth = 1.0f;
pass.ClearStencil = std::uint8_t(0);
pass.Viewport = viewport;
pass.ScissorRect = viewport.GetBounds();
commandList->Reset();
commandList->SetRenderPass(std::move(pass));
auto projectionMatrix = Matrix4x4::CreateOrthographicLH(
static_cast<float>(presentationParameters.BackBufferWidth),
static_cast<float>(presentationParameters.BackBufferHeight),
0.0f,
100.0f);
float thickness = lineWidth / static_cast<float>(presentationParameters.BackBufferWidth);
lineBatch->Begin(commandList, projectionMatrix);
lineBatch->DrawPath(path, polylineClosed, Color{255, 255, 255, 200}, thickness);
lineBatch->End();
commandList->Close();
constexpr bool isStandalone = false;
if constexpr (isStandalone) {
commandQueue->Reset();
commandQueue->PushbackCommandList(commandList);
commandQueue->ExecuteCommandLists();
commandQueue->Present();
}
else {
commandQueue->PushbackCommandList(commandList);
}
}
} // namespace feature_showcase
| 31.560345
| 121
| 0.662934
|
mogemimi
|
481815388b56e3ce5715b26d5cdb2c061ac79bc7
| 460
|
cpp
|
C++
|
Codechef/LECANDY.cpp
|
phileinSophos/programming
|
3d88de265f9ed087ce11347d53dc373edca75ac4
|
[
"MIT"
] | null | null | null |
Codechef/LECANDY.cpp
|
phileinSophos/programming
|
3d88de265f9ed087ce11347d53dc373edca75ac4
|
[
"MIT"
] | null | null | null |
Codechef/LECANDY.cpp
|
phileinSophos/programming
|
3d88de265f9ed087ce11347d53dc373edca75ac4
|
[
"MIT"
] | null | null | null |
/*
Problem Statement : Little Elephant and Candies
Link : https://www.codechef.com/problems/LECANDY
Score : accepted
*/
#include<iostream>
#include<vector>
#include<bits/stdc++.h>
using namespace std;
int main()
{
int test;
cin >>test;
for(int i=0;i<test;i++)
{
int N,C;
cin>>N>>C;
int A[N];
for(int x =0;x<N;x++)
{
cin>>A[x];
C = C - A[x];
}
if(C>=0)
{
cout<<"YES";
}
else
{
cout<<"NO";
}
}
return 0;
}
| 11.794872
| 51
| 0.543478
|
phileinSophos
|
481a4e2bcad429c2c65f4a4ebb48d49215d7fac9
| 838
|
cpp
|
C++
|
src/ec-task.cpp
|
ajis01/groot
|
c279574df7af599b7033c817a87b4e0768cb60d8
|
[
"MIT"
] | 58
|
2020-04-29T01:05:04.000Z
|
2022-03-28T15:17:34.000Z
|
src/ec-task.cpp
|
dns-groot/2020_SIGCOMM_Artifact_157
|
1170b7143568fdf456d2f20761b90f636382cc8f
|
[
"MIT"
] | 4
|
2020-05-11T16:09:55.000Z
|
2022-02-22T11:07:36.000Z
|
src/ec-task.cpp
|
dns-groot/2020_SIGCOMM_Artifact_157
|
1170b7143568fdf456d2f20761b90f636382cc8f
|
[
"MIT"
] | 5
|
2020-10-29T17:07:23.000Z
|
2022-01-06T12:40:31.000Z
|
#include "ec-task.h"
#include "job.h"
string ECTask::PrintTaskType()
{
return "EC Task";
}
void ECTask::Process(const Context &context, vector<boost::any> &variadic_arguments)
{
Job *current_job = boost::any_cast<Job *>(variadic_arguments[0]);
interpretation::Graph interpretation_graph_for_ec(ec_, context);
interpretation_graph_for_ec.CheckForLoops(current_job->json_queue);
// interpretation_graph_for_ec.GenerateDotFile("InterpretationGraph.dot");
current_job->attributes_queue.enqueue(
{static_cast<int>(num_vertices(interpretation_graph_for_ec)),
static_cast<int>(num_edges(interpretation_graph_for_ec))});
current_job->stats.ec_count++;
interpretation_graph_for_ec.CheckPropertiesOnEC(
current_job->path_functions, current_job->node_functions, current_job->json_queue);
}
| 38.090909
| 91
| 0.761337
|
ajis01
|
4820a280b3995512ef39fc16a26441d033047b1b
| 3,781
|
cpp
|
C++
|
src/dune/render_target.cpp
|
derkreature/dirtchamber
|
14fd7b9453288550b35689477a9b59274f3ff1da
|
[
"MIT",
"BSD-3-Clause"
] | 1
|
2018-10-01T02:27:25.000Z
|
2018-10-01T02:27:25.000Z
|
src/dune/render_target.cpp
|
derkreature/dirtchamber
|
14fd7b9453288550b35689477a9b59274f3ff1da
|
[
"MIT",
"BSD-3-Clause"
] | null | null | null |
src/dune/render_target.cpp
|
derkreature/dirtchamber
|
14fd7b9453288550b35689477a9b59274f3ff1da
|
[
"MIT",
"BSD-3-Clause"
] | null | null | null |
/*
* dune::render_target by Tobias Alexander Franke (tob@cyberhead.de) 2011
* For copyright and license see LICENSE
* http://www.tobias-franke.eu
*/
#include "render_target.h"
#include "d3d_tools.h"
#include "exception.h"
#include "texture_cache.h"
namespace dune
{
render_target::render_target() :
device_(nullptr),
rtview_(nullptr),
dsview_(nullptr),
cached_(false),
cached_copy_()
{
}
void render_target::do_create(ID3D11Device* device, D3D11_TEXTURE2D_DESC desc, D3D11_SUBRESOURCE_DATA* subresource)
{
rtview_ = nullptr;
dsview_ = nullptr;
device_ = device;
if (desc.Format == DXGI_FORMAT_R32_TYPELESS)
desc.BindFlags |= D3D11_BIND_DEPTH_STENCIL;
if (desc.BindFlags & D3D11_BIND_DEPTH_STENCIL)
{
tcout << "Target \"" << this->name.c_str() << "\" is technically not a render target but a depth stencil texture." << std::endl;
texture::do_create(device, desc, subresource);
D3D11_DEPTH_STENCIL_VIEW_DESC desc_dsv;
ZeroMemory(&desc_dsv, sizeof(desc_dsv));
desc_dsv.Format = DXGI_FORMAT_D32_FLOAT;
desc_dsv.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
desc_dsv.Flags = 0;
desc_dsv.Texture2D.MipSlice = 0;
assert_hr(device->CreateDepthStencilView(texture_, &desc_dsv, &dsview_));
}
else if (desc.Usage == D3D11_USAGE_DYNAMIC)
{
// target is dynamic and being "rendered" to from the outside via map/unmap/update/data()
texture::do_create(device, desc, subresource);
}
else
{
desc.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE;
texture::do_create(device, desc, subresource);
assert_hr(device->CreateRenderTargetView(texture_, nullptr, &rtview_));
}
if (cached_)
{
if (subresource)
{
size_t num_bytes = desc.Height * subresource->SysMemPitch;
cached_copy_.resize(num_bytes);
copy(reinterpret_cast<const BYTE*>(subresource->pSysMem), num_bytes);
}
else
{
// TODO: fixme
cached_copy_.resize(desc.Width * desc.Height * 4);
}
}
}
void render_target::resize(UINT width, UINT height)
{
if (width == size_.x &&
height == size_.y)
return;
// get old format
D3D11_TEXTURE2D_DESC desc;
texture_->GetDesc(&desc);
desc.Width = width;
desc.Height = height;
// save old device
auto device = device_;
destroy();
create(device, desc);
}
void render_target::destroy()
{
texture::destroy();
safe_release(rtview_);
safe_release(dsview_);
device_ = nullptr;
cached_ = false;
cached_copy_.clear();
}
void render_target::copy(const BYTE* data, size_t num_bytes)
{
std::memcpy(&cached_copy_[0], data, num_bytes);
}
void render_target::update(ID3D11DeviceContext* context)
{
void* p = map(context);
if (p)
{
BYTE* target = reinterpret_cast<BYTE*>(p);
std::memcpy(p, data<BYTE*>(), cached_copy_.size());
unmap(context);
}
}
void load_static_target(ID3D11Device* device, const tstring& filename, render_target& t)
{
t.enable_cached(true);
load_texture(device, filename, t);
}
}
| 28.428571
| 141
| 0.555938
|
derkreature
|
48211b79b6ee138126cb7b67ead6b21f7049f6ae
| 3,926
|
cpp
|
C++
|
libraries/chain/webassembly/infrablockchain/system_token_intrinsics.cpp
|
YosemiteLabs/infrablockchain
|
da05af17a9bfb1c02dafca9d8033c9e1b00e92b3
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
libraries/chain/webassembly/infrablockchain/system_token_intrinsics.cpp
|
YosemiteLabs/infrablockchain
|
da05af17a9bfb1c02dafca9d8033c9e1b00e92b3
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
libraries/chain/webassembly/infrablockchain/system_token_intrinsics.cpp
|
YosemiteLabs/infrablockchain
|
da05af17a9bfb1c02dafca9d8033c9e1b00e92b3
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
/**
* @file chain/webassembly/infrablockchain/system_token_intrinsics.cpp
* @author bezalel@infrablockchain.com
* @copyright defined in infrablockchain/LICENSE.txt
*/
#include <eosio/chain/webassembly/interface.hpp>
#include <eosio/chain/apply_context.hpp>
#include <infrablockchain/chain/standard_token_manager.hpp>
#include <infrablockchain/chain/system_token_list.hpp>
#include <vector>
#include <set>
namespace eosio { namespace chain { namespace webassembly {
///////////////////////////////////////////////////////////////
/// InfraBlockchain System Token Core API (Intrinsics)
/**
* Get System Token Count
* @brief get the number of active system tokens authorized by block producers and used as transaction fee payment token
*
* @return the number of system tokens
*/
uint32_t interface::get_system_token_count() const {
return context.control.get_standard_token_manager().get_system_token_count();
}
/**
* Get System Token List
* @brief Retrieve the system token list
*
* @param[out] packed_system_token_list - output buffer of the system token list (vector<infrablockchain_system_token>),
* output data retrieved only if the output buffer has sufficient size to hold the packed data.
*
* return the number of bytes copied to the buffer, or number of bytes required if the buffer is empty.
*/
uint32_t interface::get_system_token_list_packed( legacy_span<char> packed_system_token_list ) const {
std::vector<infrablockchain::chain::system_token> system_tokens = std::move(context.control.get_standard_token_manager().get_system_token_list().system_tokens);
auto s = fc::raw::pack_size( system_tokens );
if( packed_system_token_list.size() == 0 ) return s;
if ( s <= packed_system_token_list.size() ) {
datastream<char*> ds( packed_system_token_list.data(), s );
fc::raw::pack(ds, system_tokens);
return s;
}
return 0;
}
/**
* Set System Token List
* @brief set the list of system tokens (vector<infrablockchain_system_token>) used as transaction fee payment token.
* 2/3+ block producers have to sign any modification of system token list.
*
* @param packed_system_token_list - packed data of system_token vector in the appropriate system token order
*
* @return -1 if setting new system token list was unsuccessful, otherwise returns the version of the new system token list
*/
int64_t interface::set_system_token_list_packed( legacy_span<const char> packed_system_token_list ) {
//context.require_authorization(config::system_account_name);
datastream<const char*> ds( packed_system_token_list.data(), packed_system_token_list.size() );
std::vector<infrablockchain::chain::system_token> system_tokens;
fc::raw::unpack(ds, system_tokens);
EOS_ASSERT(system_tokens.size() <= infrablockchain::chain::max_system_tokens, wasm_execution_error, "System token list exceeds the maximum system token count for this chain");
// check that system tokens are unique
std::set<infrablockchain::chain::system_token_id_type> unique_sys_tokens;
for (const auto& sys_token : system_tokens) {
EOS_ASSERT( context.is_account(sys_token.token_id), wasm_execution_error, "system token list includes a nonexisting account" );
EOS_ASSERT( sys_token.valid(), wasm_execution_error, "system token list includes an invalid value" );
unique_sys_tokens.insert(sys_token.token_id);
}
EOS_ASSERT( system_tokens.size() == unique_sys_tokens.size(), wasm_execution_error, "duplicate system token id in system token list" );
return context.control.get_mutable_standard_token_manager().set_system_token_list( std::move(system_tokens) );
}
}}} /// eosio::chain::webassembly
| 45.651163
| 182
| 0.705298
|
YosemiteLabs
|
4822fb23ad0d6a7999edba66983e3c2199b0195d
| 3,587
|
cpp
|
C++
|
src/qt/qrax/assets/node.cpp
|
QRAX-LABS/QRAX
|
951ed45d473b7ab8c74bf35ff794e97169736d0c
|
[
"MIT"
] | 2
|
2021-12-29T14:10:03.000Z
|
2022-02-19T09:24:37.000Z
|
src/qt/qrax/assets/node.cpp
|
QRAX-LABS/QRAX
|
951ed45d473b7ab8c74bf35ff794e97169736d0c
|
[
"MIT"
] | null | null | null |
src/qt/qrax/assets/node.cpp
|
QRAX-LABS/QRAX
|
951ed45d473b7ab8c74bf35ff794e97169736d0c
|
[
"MIT"
] | null | null | null |
// Copyright (c) 2021 The QRAX developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "qt/guiutil.h"
#include "qt/qrax/qtutils.h"
#include "qt/walletmodel.h"
#include "qt/qrax/assets/graphicsscene.h"
#include "qt/qrax/assets/node.h"
#include <QGraphicsScene>
#include <QGraphicsSceneMouseEvent>
#include <QTransform>
class AssetsWidget;
class QmultiMiningTreeNode;
QmultiMiningTreeNode::QmultiMiningTreeNode()
{
setFlag(ItemIsMovable, false);
setFlag(ItemIsFocusable);
setFlag(ItemSendsGeometryChanges);
setCacheMode(DeviceCoordinateCache);
this->rx = 25;
this->ry = 25;
}
CKeyID QmultiMiningTreeNode::getKeyid() const
{
return keyid;
}
void QmultiMiningTreeNode::setKeyid(const CKeyID &value)
{
keyid = value;
}
CKeyID QmultiMiningTreeNode::getParentId() const
{
return parentId;
}
void QmultiMiningTreeNode::setParentId(const CKeyID &value)
{
parentId = value;
}
uint16_t QmultiMiningTreeNode::getChildCount() const
{
return childCount;
}
void QmultiMiningTreeNode::setChildCount(const uint16_t &value)
{
childCount = value;
}
QmultiMiningTreeNode *QmultiMiningTreeNode::getParentNode() const
{
return parentNode;
}
void QmultiMiningTreeNode::setParentNode(QmultiMiningTreeNode *value)
{
parentNode = value;
}
void QmultiMiningTreeNode::addChildNode(QmultiMiningTreeNode *value)
{
childNodes << value;
}
QVector<QmultiMiningTreeNode *> QmultiMiningTreeNode::getChildNodes() const
{
return childNodes;
}
QRectF QmultiMiningTreeNode::boundingRect() const
{
return QRectF(-30,-30,60,60);
}
void QmultiMiningTreeNode::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
QPainterPath circle_path;
painter->setBrush(Qt::darkBlue);
painter->setPen(QPen(Qt::darkGreen));
circle_path.addEllipse(-this->rx, -this->ry, this->rx * 2, this->ry * 2);
QFont myFont;
QPointF baseline(-this->rx / 3, this->ry / 4);
circle_path.addText(baseline, myFont, QString::fromStdString(this->keyid.ToString().substr(0, 4)));
painter->drawPath(circle_path);
Q_UNUSED(option);
Q_UNUSED(widget);
}
void QmultiMiningTreeNode::moveSiblingNodes(int direction)
{
if (scene()) {
QList<QGraphicsItem *> allItems = scene()->items(Qt::AscendingOrder);
QVector<QmultiMiningTreeNode *> nodes;
for (QGraphicsItem* item: allItems)
{
if (QmultiMiningTreeNode *nodeItem = dynamic_cast<QmultiMiningTreeNode*>(item)) {
if (nodeItem->getParentId() == getParentId()) {
if (direction > 0 && nodeItem->getPosition() > getPosition())
{
nodes << nodeItem;
} else if (direction < 0 && nodeItem->getPosition() < getPosition())
{
nodes << nodeItem;
}
}
}
}
for (QmultiMiningTreeNode * node: nodes) {
node->moveBy(1 * direction, 0);
}
}
}
QVariant QmultiMiningTreeNode::itemChange(GraphicsItemChange change, const QVariant &value)
{
switch (change) {
case ItemPositionHasChanged:
for (QAssetEdge *edge : qAsConst(edgeList))
edge->adjust();
for (QAssetEdge *edge : qAsConst(childEdges))
edge->moveChild();
break;
default:
break;
};
return QGraphicsItem::itemChange(change, value);
}
| 24.568493
| 108
| 0.65598
|
QRAX-LABS
|
48291704e20dc65acf660afa0194036151a3a51a
| 2,112
|
cc
|
C++
|
code/Treaps.cc
|
tulsyan/ACM-ICPC-Handbook
|
fbadfd66017991d264071af3f2fa8e050e4f8e40
|
[
"MIT"
] | 32
|
2017-12-24T20:00:47.000Z
|
2021-04-09T14:53:25.000Z
|
code/Treaps.cc
|
Zindastart/ACM-ICPC-Handbook
|
fbadfd66017991d264071af3f2fa8e050e4f8e40
|
[
"MIT"
] | null | null | null |
code/Treaps.cc
|
Zindastart/ACM-ICPC-Handbook
|
fbadfd66017991d264071af3f2fa8e050e4f8e40
|
[
"MIT"
] | 16
|
2017-12-13T14:35:27.000Z
|
2021-12-24T04:40:32.000Z
|
#include "template.h"
const int N = 100 * 1000;
struct node { int value, weight, ch[2], size; } T[ N+10 ] ; int nodes;
#define Child(x,c) T[x].ch[c]
#define Value(x) T[x].value
#define Weight(x) T[x].weight
#define Size(x) T[x].size
#define Left Child(x,0)
#define Right Child(x,1)
int update(int x) { if(!x)return 0; Size(x) = 1+Size(Left)+Size(Right); return x; }
int newnode(int value, int prio) {
T[++nodes]=(node){value,prio,0,0};
return update(nodes);
}
void split(int x, int by, int &L, int &R)
{
if(!x) { L=R=0; }
else if(Value(x) < Value(by)) { split(Right,by,Right,R); update(L=x); }
else { split(Left,by,L,Left); update(R=x); }
}
int merge(int L, int R)
{
if(!L) return R; if(!R) return L;
if(Weight(L)<Weight(R)) { Child(L,1) = merge(Child(L,1), R); return update(L);}
else { Child(R,0) = merge( L, Child(R, 0)); return update(R); }
}
int insert(int x, int n)
{
if(!x) { return update(n); }
if(Weight(n)<=Weight(x)) {split(x,n,Child(n,0),Child(n,1)); return update(n);}
else if(Value(n) < Value(x)) Left=insert(Left,n); else Right=insert(Right,n);
return update(x);
}
int del(int x, int value)
{
if(!x) return 0;
if(value == Value(x)) { int q = merge(Left,Right); return update(q); }
if(value < Value(x)) Left = del(Left,value); else Right = del(Right, value);
return update(x);
}
int find_GE(int x, int value) {
int ret=0;
while(x) { if(Value(x)==value)return x;
if(Value(x)>value) ret=x, x=Left; else x=Right; }
return ret;
}
int find(int x, int value) {
for(; x; x=Child(x,Value(x)<value)) if(Value(x)==value)return x;
return 0;
}
int findmin(int x) { for(;Left;x=Left); return x; }
int findmax(int x) { for(;Right;x=Right); return x; }
int findkth(int x, int k) {
while(x) {
if(k<=Size(Left)) x=Left;
else if(k==Size(Left)+1)return x;
else { k-=Size(Left)+1; x=Right; }
}
}
int queryrangekth(int &x, int a1, int a2, int k) {
a1 = find(x, a1); a2 = find(x, a2);
assert(a1 && a2);
int a,b,c; split(x,a1,a,b); split(b,a2,b,c);
int ret = findkth(b,k);
x = merge(a, merge(b,c));
return Value(ret);
}
int main(){
return 0;
}
| 30.171429
| 83
| 0.60322
|
tulsyan
|
482e8fc788836d6ab07b205f555a64c2447ea7a9
| 3,160
|
cpp
|
C++
|
third-party/Empirical/examples/math/stats.cpp
|
koellingh/empirical-p53-simulator
|
aa6232f661e8fc65852ab6d3e809339557af521b
|
[
"MIT"
] | null | null | null |
third-party/Empirical/examples/math/stats.cpp
|
koellingh/empirical-p53-simulator
|
aa6232f661e8fc65852ab6d3e809339557af521b
|
[
"MIT"
] | null | null | null |
third-party/Empirical/examples/math/stats.cpp
|
koellingh/empirical-p53-simulator
|
aa6232f661e8fc65852ab6d3e809339557af521b
|
[
"MIT"
] | null | null | null |
// This file is part of Empirical, https://github.com/devosoft/Empirical
// Copyright (C) Michigan State University, 2020.
// Released under the MIT Software license; see doc/LICENSE
//
//
// Some examples code for using vector_utils.h
#include <iostream>
#include <unordered_set>
#include "emp/base/vector.hpp"
#include "emp/math/stats.hpp"
#include "emp/tools/string_utils.hpp"
int main()
{
emp::vector<double> v1 = { 1.0, 2.0, 3.0, 4.0, 5.0, 6.0 };
const emp::vector<double> v2 = { 1.0, 5.0, 3.0, 4.0, 2.0, 6.0 };
emp::vector<size_t> v3 = { 4, 6, 8, 10, 12, 14 };
emp::vector<int> v4 = { -2, -1, 0, 1, 2, 4 };
std::set<double> s1 = { 1.0, 2.0, 3.0, 4.0, 5.0, 6.0 };
std::set<int> s4 = { -2, -1, 0, 1, 2, 3 };
int a=-2, b=-1, c=0, d=1, e=2, f=3;
emp::vector<int*> vp4 = { &a, &b, &c, &d, &e, &f };
std::cout << "v1 = " << emp::to_string(v1) << std::endl;
std::cout << "v2 = " << emp::to_string(v2) << std::endl;
std::cout << "v3 = " << emp::to_string(v3) << std::endl;
std::cout << "v4 = " << emp::to_string(v4) << std::endl;
std::cout << std::endl;
std::cout << "Sum(v1) = " << emp::Sum(v1)
<< " Mean(v1) = " << emp::Mean(v1)
<< " Var(v1) = " << emp::Variance(v1)
<< " StdDev(v1) = " << emp::StandardDeviation(v1)
<< std::endl;
std::cout << "Sum(v2) = " << emp::Sum(v2)
<< " Mean(v2) = " << emp::Mean(v2)
<< " Var(v2) = " << emp::Variance(v2)
<< " StdDev(v2) = " << emp::StandardDeviation(v2)
<< std::endl;
std::cout << "Sum(v3) = " << emp::Sum(v3)
<< " Mean(v3) = " << emp::Mean(v3)
<< " Var(v3) = " << emp::Variance(v3)
<< " StdDev(v3) = " << emp::StandardDeviation(v3)
<< std::endl;
std::cout << "Sum(v4) = " << emp::Sum(v4)
<< " Mean(v4) = " << emp::Mean(v4)
<< " Var(v4) = " << emp::Variance(v4)
<< " StdDev(v4) = " << emp::StandardDeviation(v4)
<< std::endl;
std::cout << "Sum(s1) = " << emp::Sum(s1)
<< " Mean(s1) = " << emp::Mean(s1)
<< " Var(s1) = " << emp::Variance(s1)
<< " StdDev(s1) = " << emp::StandardDeviation(s1)
<< std::endl;
std::cout << "Sum(s4) = " << emp::Sum(s4)
<< " Mean(s4) = " << emp::Mean(s4)
<< " Var(s4) = " << emp::Variance(s4)
<< " StdDev(s4) = " << emp::StandardDeviation(s4)
<< std::endl;
std::cout << "Sum(vp4) = " << emp::Sum(vp4)
<< " Mean(vp4) = " << emp::Mean(vp4)
<< " Var(vp4) = " << emp::Variance(vp4)
<< " StdDev(vp4) = " << emp::StandardDeviation(vp4)
<< std::endl;
std::cout << std::endl;
emp::vector<char> v5 = { 'a', 'b', 'c', 'a', 'a', 'b', 'c', 'a' };
char c1 = 'a', c2 = 'b', c3 = 'c', c4 = 'a';
emp::vector<char*> vp5 = { &c1, &c2, &c3, &c4, &c1, &c2, &c3, &c4 };
std::cout << "v5 = " << emp::to_string(v5) << std::endl;
std::cout << "ShannonEntropy(v5) = " << emp::ShannonEntropy(v5) << std::endl;
std::cout << "ShannonEntropy(vp5) = " << emp::ShannonEntropy(vp5) << std::endl;
}
| 39.5
| 81
| 0.464873
|
koellingh
|
483dc68da834b36651c4a2a4e573f8b9c0c0561e
| 14,128
|
cpp
|
C++
|
tests/TcpTest.cpp
|
bonnefoa/flowstats
|
64f3e2d4466596788174b508bc62838379162224
|
[
"MIT"
] | 4
|
2020-07-21T12:34:26.000Z
|
2020-12-09T16:51:33.000Z
|
tests/TcpTest.cpp
|
bonnefoa/flowstats
|
64f3e2d4466596788174b508bc62838379162224
|
[
"MIT"
] | null | null | null |
tests/TcpTest.cpp
|
bonnefoa/flowstats
|
64f3e2d4466596788174b508bc62838379162224
|
[
"MIT"
] | 1
|
2020-07-21T12:34:31.000Z
|
2020-07-21T12:34:31.000Z
|
#include "Collector.hpp"
#include "DnsStatsCollector.hpp"
#include "MainTest.hpp"
#include "TcpStatsCollector.hpp"
#include "Utils.hpp"
#include <catch2/catch.hpp>
using namespace flowstats;
TEST_CASE("Tcp simple", "[tcp]")
{
auto tester = Tester();
auto const& tcpStatsCollector = tester.getTcpStatsCollector();
SECTION("Tcp aggregated stats are computed")
{
tester.readPcap("tcp_simple.pcap", "port 53");
tester.readPcap("tcp_simple.pcap", "port 80", false);
auto tcpKey = AggregatedKey("google.com", {}, 80);
auto aggregatedMap = tcpStatsCollector.getAggregatedMap();
REQUIRE(aggregatedMap.size() == 1);
auto it = aggregatedMap.find(tcpKey);
REQUIRE(it != aggregatedMap.end());
auto const* aggregatedFlow = it->second;
CHECK(aggregatedFlow->getFieldStr(Field::SYN, FROM_CLIENT, 1, 0) == "1");
CHECK(aggregatedFlow->getFieldStr(Field::FIN, FROM_CLIENT, 1, 0) == "1");
CHECK(aggregatedFlow->getFieldStr(Field::CLOSE, FROM_CLIENT, 1, 0) == "1");
CHECK(aggregatedFlow->getFieldStr(Field::ACTIVE_CONNECTIONS, FROM_CLIENT, 1, 0) == "0");
CHECK(aggregatedFlow->getFieldStr(Field::CONN, FROM_CLIENT, 1, 0) == "1");
CHECK(aggregatedFlow->getFieldStr(Field::CONN_RATE, FROM_CLIENT, 1, 0) == "1");
CHECK(aggregatedFlow->getFieldStr(Field::CT_P99, FROM_CLIENT, 1, 0) == "50ms");
CHECK(aggregatedFlow->getFieldStr(Field::MTU, FROM_CLIENT, 1, 0) == "140");
CHECK(aggregatedFlow->getFieldStr(Field::MTU, FROM_SERVER, 1, 0) == "594");
auto flows = tcpStatsCollector.getTcpFlow();
CHECK(flows.size() == 1);
CHECK(flows.begin()->second.getGap() == 0);
AggregatedKey totalKey = AggregatedKey("Total", {}, 0);
std::map<Field, std::string> totalValues;
CHECK(aggregatedFlow->getFieldStr(Field::SYN, FROM_CLIENT, 1, 0) == "1");
}
}
TEST_CASE("Tcp sort", "[tcp]")
{
auto tester = Tester();
auto& tcpStatsCollector = tester.getTcpStatsCollector();
SECTION("Fqdn sort works")
{
tester.readPcap("testcom.pcap");
auto& ipToFqdn = tester.getIpToFqdn();
REQUIRE(ipToFqdn.getFlowFqdn(IPAddress(Tins::IPv4Address("35.155.52.1"))) == "Unknown");
auto const*aggregatedMap = tcpStatsCollector.getAggregatedMap();
REQUIRE(aggregatedMap->size() == 4);
auto flows = tcpStatsCollector.getAggregatedFlows();
CHECK(flows[0]->getFqdn() == "news.ycombinator.com");
CHECK(flows[1]->getFqdn() == "Unknown");
CHECK(flows[2]->getFqdn() == "www.test.com");
CHECK(flows[3]->getFqdn() == "www.test.com");
tcpStatsCollector.setSortField(Field::FQDN, true);
flows = tcpStatsCollector.getAggregatedFlows();
CHECK(flows[0]->getFqdn() == "www.test.com");
CHECK(flows[1]->getFqdn() == "www.test.com");
CHECK(flows[2]->getFqdn() == "Unknown");
CHECK(flows[3]->getFqdn() == "news.ycombinator.com");
tcpStatsCollector.setSortField(Field::PORT, false);
flows = tcpStatsCollector.getAggregatedFlows();
CHECK(flows[0]->getSrvPort() == 80);
CHECK(flows[1]->getSrvPort() == 443);
CHECK(flows[2]->getSrvPort() == 443);
CHECK(flows[3]->getSrvPort() == 443);
}
}
TEST_CASE("https pcap", "[tcp]")
{
auto tester = Tester();
auto const& tcpStatsCollector = tester.getTcpStatsCollector();
SECTION("Active connections are correctly counted")
{
auto tcpKey = AggregatedKey("Unknown", {}, 443);
tester.readPcap("https.pcap", "port 443", false);
auto aggregatedMap = tcpStatsCollector.getAggregatedMap();
REQUIRE(aggregatedMap.size() == 1);
auto const* aggregatedFlow = aggregatedMap[tcpKey];
CHECK(aggregatedFlow->getFieldStr(Field::SYN, FROM_CLIENT, 1, 0)== "1");
CHECK(aggregatedFlow->getFieldStr(Field::FIN, FROM_CLIENT, 1, 0)== "1");
CHECK(aggregatedFlow->getFieldStr(Field::CLOSE, FROM_CLIENT, 1, 0)== "1");
CHECK(aggregatedFlow->getFieldStr(Field::ACTIVE_CONNECTIONS, FROM_CLIENT, 1, 0)== "0");
CHECK(aggregatedFlow->getFieldStr(Field::CONN, FROM_CLIENT, 1, 0)== "1");
CHECK(aggregatedFlow->getFieldStr(Field::CT_P99, FROM_CLIENT, 1, 0)== "1ms");
auto flows = tcpStatsCollector.getTcpFlow();
REQUIRE(flows.size() == 1);
CHECK(flows.begin()->second.getGap() == 0);
}
}
TEST_CASE("Tcp gap connection", "[tcp]")
{
auto tester = Tester();
auto const& tcpStatsCollector = tester.getTcpStatsCollector();
SECTION("Connection time is not computed if there's a gap ")
{
tester.readPcap("connection_with_gap.pcap");
auto tcpKey = AggregatedKey("Unknown", {}, 443);
auto aggregatedMap = tcpStatsCollector.getAggregatedMap();
REQUIRE(aggregatedMap.size() == 1);
auto *aggregatedFlow = aggregatedMap[tcpKey];
CHECK(aggregatedFlow->getFieldStr(Field::CONN, FROM_CLIENT, 1, 0)== "0");
}
}
TEST_CASE("Tcp reused port", "[tcp]")
{
auto tester = Tester();
auto const& tcpStatsCollector = tester.getTcpStatsCollector();
SECTION("Reused connections")
{
tester.readPcap("reuse_port.pcap");
auto tcpKey = AggregatedKey("Unknown", {}, 1234);
auto aggregatedMap = tcpStatsCollector.getAggregatedMap();
REQUIRE(aggregatedMap.size() == 1);
auto *aggregatedFlow = aggregatedMap[tcpKey];
CHECK(aggregatedFlow->getFieldStr(Field::SYN, FROM_CLIENT, 1, 0) == "6");
CHECK(aggregatedFlow->getFieldStr(Field::FIN, FROM_CLIENT, 1, 0) == "5");
CHECK(aggregatedFlow->getFieldStr(Field::CLOSE, FROM_CLIENT, 1, 0) == "5");
CHECK(aggregatedFlow->getFieldStr(Field::ACTIVE_CONNECTIONS, FROM_CLIENT, 1, 0) == "0");
CHECK(aggregatedFlow->getFieldStr(Field::CONN, FROM_CLIENT, 1, 0) == "5");
CHECK(aggregatedFlow->getFieldStr(Field::CT_P99, FROM_CLIENT, 1, 0) == "0ms");
CHECK(aggregatedFlow->getFieldStr(Field::SRT_P99, FROM_CLIENT, 1, 0) == "0ms");
auto flows = tcpStatsCollector.getTcpFlow();
REQUIRE(flows.size() == 0);
}
}
TEST_CASE("Ssl stream ack + srt", "[tcp]")
{
auto tester = Tester();
auto const& tcpStatsCollector = tester.getTcpStatsCollector();
SECTION("Only payload from client starts SRT")
{
auto tcpKey = AggregatedKey("Unknown", {}, 443);
tester.readPcap("ssl_ack_srt.pcap");
auto aggregatedMap = tcpStatsCollector.getAggregatedMap();
REQUIRE(aggregatedMap.size() == 1);
auto const* aggregatedFlow = aggregatedMap[tcpKey];
REQUIRE(aggregatedFlow->getFieldStr(Field::SRT, FROM_CLIENT, 1, 0) == "2");
REQUIRE(aggregatedFlow->getFieldStr(Field::SRT_P99, FROM_CLIENT, 1, 0) == "2ms");
REQUIRE(aggregatedFlow->getFieldStr(Field::SRT_P95, FROM_CLIENT, 1, 0) == "2ms");
}
}
TEST_CASE("Ssl stream multiple srts", "[tcp]")
{
auto tester = Tester();
auto const& tcpStatsCollector = tester.getTcpStatsCollector();
SECTION("Srts are correctly computed from single flow")
{
auto tcpKey = AggregatedKey("Unknown", {}, 443);
tester.readPcap("tls_stream_extract.pcap");
auto aggregatedMap = tcpStatsCollector.getAggregatedMap();
REQUIRE(aggregatedMap.size() == 1);
auto const* aggregatedFlow = aggregatedMap[tcpKey];
REQUIRE(aggregatedFlow->getFieldStr(Field::SRT, FROM_CLIENT, 1, 0) == "11");
REQUIRE(aggregatedFlow->getFieldStr(Field::SRT_P99, FROM_CLIENT, 1, 0) == "9ms");
REQUIRE(aggregatedFlow->getFieldStr(Field::SRT_P95, FROM_CLIENT, 1, 0) == "3ms");
}
}
TEST_CASE("Tcp double", "[tcp]")
{
auto tester = Tester();
auto const& tcpStatsCollector = tester.getTcpStatsCollector();
SECTION("Srts are correctly computed from multiple flows")
{
auto tcpKey = AggregatedKey("Unknown", {}, 3834);
tester.readPcap("tcp_double.pcap");
auto aggregatedMap = tcpStatsCollector.getAggregatedMap();
REQUIRE(aggregatedMap.size() == 1);
auto const* aggregatedFlow = aggregatedMap[tcpKey];
CHECK(aggregatedFlow->getFieldStr(Field::SRT, FROM_CLIENT, 1, 0) == "2");
CHECK(aggregatedFlow->getFieldStr(Field::SRT_P99, FROM_CLIENT, 1, 0) == "499ms");
CHECK(aggregatedFlow->getFieldStr(Field::SRT_P95, FROM_CLIENT, 1, 0) == "499ms");
}
}
TEST_CASE("Tcp 0 win", "[tcp]")
{
auto tester = Tester(true);
auto const& tcpStatsCollector = tester.getTcpStatsCollector();
SECTION("0 wins are correctly counted")
{
tester.readPcap("0_win.pcap", "");
auto ipFlows = tcpStatsCollector.getAggregatedMap();
REQUIRE(ipFlows.size() == 1);
auto tcpKey = AggregatedKey("Unknown",
IPAddress(Tins::IPv4Address("127.0.0.1")), 443);
auto const* flow = ipFlows[tcpKey];
REQUIRE(flow != nullptr);
CHECK(flow->getFieldStr(Field::ZWIN, FROM_SERVER, 1, 0) == "3");
CHECK(flow->getFieldStr(Field::RST, FROM_SERVER, 1, 0) == "1");
}
}
TEST_CASE("Tcp rst", "[tcp]")
{
auto tester = Tester(true);
auto const& tcpStatsCollector = tester.getTcpStatsCollector();
auto& ipToFqdn = tester.getIpToFqdn();
Tins::IPv4Address ip("10.142.226.42");
ipToFqdn.updateFqdn("whatever", { ip }, {});
SECTION("Rst only close once")
{
tester.readPcap("rst_close.pcap", "");
auto ipFlows = tcpStatsCollector.getAggregatedMap();
REQUIRE(ipFlows.size() == 1);
auto tcpKey = AggregatedKey("whatever", IPAddress(ip), 3834);
auto const* flow = ipFlows[tcpKey];
CHECK(flow->getFieldStr(Field::RST, FROM_CLIENT, 1, 0) == "2");
CHECK(flow->getFieldStr(Field::CLOSE, FROM_CLIENT, 1, 0) == "1");
}
}
TEST_CASE("Inversed srt", "[tcp]")
{
auto tester = Tester();
auto const& tcpStatsCollector = tester.getTcpStatsCollector();
SECTION("We correctly detect the server")
{
auto tcpKey = AggregatedKey("Unknown", {}, 9000);
tester.readPcap("inversed_srv.pcap", "");
auto aggregatedMap = tcpStatsCollector.getAggregatedMap();
REQUIRE(aggregatedMap.size() == 1);
auto const* aggregatedFlow = aggregatedMap[tcpKey];
REQUIRE(aggregatedFlow != NULL);
REQUIRE(aggregatedFlow->getSrvIp().getAddrStr() == "10.8.109.46");
}
}
TEST_CASE("Request size", "[tcp]")
{
auto tester = Tester();
auto const& tcpStatsCollector = tester.getTcpStatsCollector();
SECTION("We correctly detect the server")
{
auto tcpKey = AggregatedKey("Unknown", {}, 9000);
tester.readPcap("6_sec_srt_extract.pcap", "");
auto aggregatedMap = tcpStatsCollector.getAggregatedMap();
REQUIRE(aggregatedMap.size() == 1);
auto const* flow = aggregatedMap[tcpKey];
REQUIRE(flow != nullptr);
REQUIRE(flow->getFieldStr(Field::DS_MAX, FROM_CLIENT, 1, 0) == "183 KB");
}
}
TEST_CASE("Srv port detection", "[tcp]")
{
auto tester = Tester();
auto const& tcpStatsCollector = tester.getTcpStatsCollector();
SECTION("We correctly detect srv port")
{
auto tcpKey = AggregatedKey("Unknown", {}, 9000);
tester.readPcap("port_detection.pcap", "", false);
auto aggregatedMap = tcpStatsCollector.getAggregatedMap();
REQUIRE(aggregatedMap.size() == 1);
auto const* flow = aggregatedMap[tcpKey];
REQUIRE(flow != nullptr);
REQUIRE(flow->getFieldStr(Field::ACTIVE_CONNECTIONS, FROM_CLIENT, 1, 0) == "3");
}
}
TEST_CASE("Gap in capture", "[tcp]")
{
auto tester = Tester();
auto const& tcpStatsCollector = tester.getTcpStatsCollector();
SECTION("We don't compute SRT on gap")
{
auto tcpKey = AggregatedKey("Unknown", {}, 80);
tester.readPcap("tcp_gap.pcap", "", false);
auto aggregatedMap = tcpStatsCollector.getAggregatedMap();
REQUIRE(aggregatedMap.size() == 1);
auto const* flow = aggregatedMap[tcpKey];
REQUIRE(flow != nullptr);
CHECK(flow->getFieldStr(Field::SRT, FROM_CLIENT, 1, 0) == "1");
CHECK(flow->getFieldStr(Field::SRT_P99, FROM_CLIENT, 1, 0) == "26ms");
auto flows = tcpStatsCollector.getTcpFlow();
CHECK(flows.size() == 1);
CHECK(flows.begin()->second.getGap() == 1);
}
}
TEST_CASE("Mtu is correctly computed", "[tcp]")
{
auto tester = Tester();
auto const& tcpStatsCollector = tester.getTcpStatsCollector();
tester.readPcap("tcp_mtu.pcap", "");
SECTION("We correctly compute mtu")
{
auto aggregatedMap = tcpStatsCollector.getAggregatedMap();
REQUIRE(aggregatedMap.size() == 1);
auto tcpKey = AggregatedKey("Unknown", {}, 80);
auto const* flow = aggregatedMap[tcpKey];
REQUIRE(flow != nullptr);
CHECK(flow->getFieldStr(Field::MTU, FROM_CLIENT, 1, 0) == "15346");
CHECK(flow->getFieldStr(Field::MTU, FROM_SERVER, 1, 0) == "413");
}
}
TEST_CASE("Ipv6", "[tcp]")
{
auto tester = Tester();
auto const& tcpStatsCollector = tester.getTcpStatsCollector();
auto const& dnsStatsCollector = tester.getDnsStatsCollector();
tester.readPcap("ipv6.pcap", "");
SECTION("We build ipv6 to fqdn mapping")
{
auto aggregatedMap = dnsStatsCollector.getAggregatedMap();
REQUIRE(aggregatedMap.size() == 2);
auto dnsKey = AggregatedKey::aggregatedDnsKey("google.fr",
Tins::DNS::AAAA, Transport::UDP);
auto const* flow = aggregatedMap[dnsKey];
REQUIRE(flow != nullptr);
}
SECTION("We correctly compute ipv6 tcp traffic")
{
auto aggregatedMap = tcpStatsCollector.getAggregatedMap();
REQUIRE(aggregatedMap.size() == 1);
auto tcpKey = AggregatedKey("google.fr", {}, 80);
auto const* flow = aggregatedMap[tcpKey];
REQUIRE(flow != nullptr);
CHECK(flow->getFieldStr(Field::BYTES, FROM_CLIENT, 1, 0) == "609 B");
CHECK(flow->getFieldStr(Field::BYTES, FROM_SERVER, 1, 0) == "886 B");
}
}
| 35.767089
| 96
| 0.632715
|
bonnefoa
|
c6182e56570d1824b723f276b61487c95caf4c28
| 1,748
|
cc
|
C++
|
Gurvich-Wirzt/trunk/nachos-unr21a/code/threads/lock.cc
|
swirzt/SistemasOoperativos2
|
2db49410837eb18a4b5afcabd229519f61a2e8ab
|
[
"MIT"
] | null | null | null |
Gurvich-Wirzt/trunk/nachos-unr21a/code/threads/lock.cc
|
swirzt/SistemasOoperativos2
|
2db49410837eb18a4b5afcabd229519f61a2e8ab
|
[
"MIT"
] | null | null | null |
Gurvich-Wirzt/trunk/nachos-unr21a/code/threads/lock.cc
|
swirzt/SistemasOoperativos2
|
2db49410837eb18a4b5afcabd229519f61a2e8ab
|
[
"MIT"
] | null | null | null |
/// Routines for synchronizing threads.
///
/// The implementation for this primitive does not come with base Nachos.
/// It is left to the student.
///
/// When implementing this module, keep in mind that any implementation of a
/// synchronization routine needs some primitive atomic operation. The
/// semaphore implementation, for example, disables interrupts in order to
/// achieve this; another way could be leveraging an already existing
/// primitive.
///
/// Copyright (c) 1992-1993 The Regents of the University of California.
/// 2016-2021 Docentes de la Universidad Nacional de Rosario.
/// All rights reserved. See `copyright.h` for copyright notice and
/// limitation of liability and disclaimer of warranty provisions.
#include "lock.hh"
#include "semaphore.hh"
#include "system.hh"
#include <string.h>
/// Dummy functions -- so we can compile our later assignments.
Lock::Lock(const char *debugName)
{
name = debugName;
sem = new Semaphore(debugName, 1);
holder = nullptr;
}
Lock::~Lock()
{
delete sem;
}
const char *
Lock::GetName() const
{
return name;
}
// 0 menos importante, COLAS-1 mas importante
void Lock::Acquire()
{
ASSERT(!IsHeldByCurrentThread());
int prio = currentThread->GetPrio();
if (holder != nullptr && holder->GetPrio() < prio)
{
holder->SetPrio(prio);
scheduler->UpdatePriority(holder);
}
sem->P();
holder = currentThread;
holderPriority = prio;
}
void Lock::Release()
{
ASSERT(IsHeldByCurrentThread());
currentThread->SetPrio(holderPriority);
scheduler->UpdatePriority(currentThread);
holder = nullptr;
sem->V();
}
bool Lock::IsHeldByCurrentThread() const
{
return holder == currentThread;
}
| 24.619718
| 76
| 0.689931
|
swirzt
|
c61b703a1600bd1c7573372b9f43bb3b7ba7d3bc
| 283
|
cpp
|
C++
|
Binary Search/Wolves of Wall Street/main.cpp
|
Code-With-Aagam/competitive-programming
|
610520cc396fb13a03c606b5fb6739cfd68cc444
|
[
"MIT"
] | 2
|
2022-02-08T12:37:41.000Z
|
2022-03-09T03:48:56.000Z
|
BinarySearch/Wolves of Wall Street/main.cpp
|
ShubhamJagtap2000/competitive-programming-1
|
3a9a2e3dd08f8fa8ab823f295cd020d08d3bff84
|
[
"MIT"
] | null | null | null |
BinarySearch/Wolves of Wall Street/main.cpp
|
ShubhamJagtap2000/competitive-programming-1
|
3a9a2e3dd08f8fa8ab823f295cd020d08d3bff84
|
[
"MIT"
] | null | null | null |
int solve(vector<int> &prices) {
if (prices.empty()) {
return 0;
}
int ans = 0, n = prices.size(), curr = prices[0];
for (int i = 1; i < n; i++) {
if (prices[i] > curr) {
ans += (prices[i] - curr);
curr = prices[i];
} else {
curr = prices[i];
}
}
return ans;
}
| 18.866667
| 50
| 0.512367
|
Code-With-Aagam
|
c61de46631d143ff2334ff7de840580ed51c0bfd
| 6,059
|
cpp
|
C++
|
verilator-4.016/src/V3GraphPathChecker.cpp
|
tcovert2015/fpga_competition
|
26b7a72959afbf8315eb962ec597ba14b4a73dbd
|
[
"BSD-3-Clause"
] | null | null | null |
verilator-4.016/src/V3GraphPathChecker.cpp
|
tcovert2015/fpga_competition
|
26b7a72959afbf8315eb962ec597ba14b4a73dbd
|
[
"BSD-3-Clause"
] | null | null | null |
verilator-4.016/src/V3GraphPathChecker.cpp
|
tcovert2015/fpga_competition
|
26b7a72959afbf8315eb962ec597ba14b4a73dbd
|
[
"BSD-3-Clause"
] | null | null | null |
// -*- mode: C++; c-file-style: "cc-mode" -*-
//*************************************************************************
// DESCRIPTION: Verilator: DAG Path Checking
//
// Code available from: http://www.veripool.org/verilator
//
//*************************************************************************
//
// Copyright 2003-2019 by Wilson Snyder. This program is free software; you can
// redistribute it and/or modify it under the terms of either the GNU
// Lesser General Public License Version 3 or the Perl Artistic License
// Version 2.0.
//
// Verilator is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
//*************************************************************************
#include "config_build.h"
#include "verilatedos.h"
#include "V3GraphStream.h"
#include "V3Global.h"
#include "V3GraphPathChecker.h"
//######################################################################
// GraphPCNode
struct GraphPCNode {
// User data for each node in GraphPathChecker.
//
// Like the LogicMTasks's, store before and after CPs for the nodes in
// the GraphPathChecker graph.
//
// Unlike the LogicMTasks's, we have no cost info for the generic graph
// accepted by GraphPathChecker, so assume each node has unit cost.
vluint32_t m_cp[GraphWay::NUM_WAYS];
// Detect if we've seen this node before in a given recursive
// operation. We'll use this in pathExistsInternal() to avoid checking
// the same node twice, and again in updateHalfCriticalPath() to assert
// there are no cycles.
vluint64_t m_seenAtGeneration;
// CONSTRUCTORS
GraphPCNode() : m_seenAtGeneration(0) {
for (int w = 0; w < GraphWay::NUM_WAYS; w++) m_cp[w] = 0;
}
~GraphPCNode() { }
};
//######################################################################
// GraphPathChecker implementation
GraphPathChecker::GraphPathChecker(const V3Graph* graphp, V3EdgeFuncP edgeFuncp)
: GraphAlg<const V3Graph>(graphp, edgeFuncp)
, m_generation(0) {
for (V3GraphVertex* vxp = graphp->verticesBeginp();
vxp; vxp = vxp->verticesNextp()) {
// Setup tracking structure for each node. If delete a vertex
// there would be a leak, but ok as accept only const V3Graph*'s.
vxp->userp(new GraphPCNode);
}
// Init critical paths in userp() for each vertex
initHalfCriticalPaths(GraphWay::FORWARD, false);
initHalfCriticalPaths(GraphWay::REVERSE, false);
}
GraphPathChecker::~GraphPathChecker() {
// Free every GraphPCNode
for (V3GraphVertex* vxp = m_graphp->verticesBeginp();
vxp; vxp = vxp->verticesNextp()) {
GraphPCNode* nodep = static_cast<GraphPCNode*>(vxp->userp());
delete nodep; VL_DANGLING(nodep);
vxp->userp(NULL);
}
}
void GraphPathChecker::initHalfCriticalPaths(GraphWay way, bool checkOnly) {
GraphStreamUnordered order(m_graphp, way);
GraphWay rev = way.invert();
while (const V3GraphVertex* vertexp = order.nextp()) {
unsigned critPathCost = 0;
for (V3GraphEdge* edgep = vertexp->beginp(rev);
edgep; edgep = edgep->nextp(rev)) {
if (!m_edgeFuncp(edgep)) continue;
V3GraphVertex* wrelativep = edgep->furtherp(rev);
GraphPCNode* wrelUserp = static_cast<GraphPCNode*>(wrelativep->userp());
critPathCost = std::max(critPathCost, wrelUserp->m_cp[way] + 1);
}
GraphPCNode* ourUserp = static_cast<GraphPCNode*>(vertexp->userp());
if (checkOnly) {
if (ourUserp->m_cp[way] != critPathCost) {
vertexp->v3fatalSrc("Validation of critical paths failed");
}
} else {
ourUserp->m_cp[way] = critPathCost;
}
}
}
bool GraphPathChecker::pathExistsInternal(const V3GraphVertex* ap,
const V3GraphVertex* bp,
unsigned* costp) {
GraphPCNode* auserp = static_cast<GraphPCNode*>(ap->userp());
GraphPCNode* buserp = static_cast<GraphPCNode*>(bp->userp());
// If have already searched this node on the current search, don't
// recurse through it again. Since we're still searching, we must not
// have found a path on the first go either.
if (auserp->m_seenAtGeneration == m_generation) {
if (costp) *costp = 0;
return false;
}
auserp->m_seenAtGeneration = m_generation;
if (costp) *costp = 1; // count 'a' toward the search cost
if (ap == bp) return true;
// Rule out an a->b path based on their CPs
if (auserp->m_cp[GraphWay::REVERSE] < buserp->m_cp[GraphWay::REVERSE] + 1) {
return false;
}
if (buserp->m_cp[GraphWay::FORWARD] < auserp->m_cp[GraphWay::FORWARD] + 1) {
return false;
}
// Slow path; visit some extended family
bool foundPath = false;
for (V3GraphEdge* edgep = ap->outBeginp();
edgep && !foundPath; edgep = edgep->outNextp()) {
if (!m_edgeFuncp(edgep)) continue;
unsigned childCost;
if (pathExistsInternal(edgep->top(), bp, &childCost)) {
foundPath = true;
}
if (costp) *costp += childCost;
}
return foundPath;
}
bool GraphPathChecker::pathExistsFrom(const V3GraphVertex* fromp,
const V3GraphVertex* top) {
incGeneration();
return pathExistsInternal(fromp, top);
}
bool GraphPathChecker::isTransitiveEdge(const V3GraphEdge* edgep) {
const V3GraphVertex* fromp = edgep->fromp();
const V3GraphVertex* top = edgep->top();
incGeneration();
for (const V3GraphEdge* fromOutp = fromp->outBeginp();
fromOutp; fromOutp = fromOutp->outNextp()) {
if (fromOutp == edgep) continue;
if (pathExistsInternal(fromOutp->top(), top)) {
return true;
}
}
return false;
}
| 36.065476
| 84
| 0.601584
|
tcovert2015
|
c61ebe48de6039fb25c617a57dc1cec030d8b092
| 4,632
|
cpp
|
C++
|
lib/duden/InfFile.cpp
|
nonwill/lsd2dsl
|
00e2a9832666dff03667b07815d73fab3fa8378e
|
[
"MIT"
] | 66
|
2015-01-17T16:57:38.000Z
|
2022-02-06T15:29:54.000Z
|
lib/duden/InfFile.cpp
|
nonwill/lsd2dsl
|
00e2a9832666dff03667b07815d73fab3fa8378e
|
[
"MIT"
] | 19
|
2015-02-08T15:35:12.000Z
|
2022-01-26T10:46:11.000Z
|
lib/duden/InfFile.cpp
|
nongeneric/lsd2dsl
|
4bf92b42b1ae47eee8e0b71bc04224dc037bd549
|
[
"MIT"
] | 18
|
2015-03-23T07:06:07.000Z
|
2022-01-15T21:03:04.000Z
|
#include "InfFile.h"
#include "Duden.h"
#include "LdFile.h"
#include "boost/algorithm/string.hpp"
namespace duden {
namespace {
std::string fixFileNameCase(const std::string& name, const CaseInsensitiveSet& files) {
if (name.empty())
return name;
auto it = files.find(fs::path(name));
if (it != end(files)) {
return it->filename().string();
}
return name;
}
} // namespace
std::vector<InfFile> parseInfFile(dictlsd::IRandomAccessStream* stream, IFileSystem* filesystem) {
std::string line;
uint32_t version = 0;
CaseInsensitiveSet files;
std::vector<std::string> lds;
const auto& fsFileSet = filesystem->files();
while (readLine(stream, line)) {
if (line.empty())
continue;
line = win1252toUtf8(line);
switch (line[0]) {
case 'V': version = std::stoi(line.substr(2), nullptr, 16); break;
case 'L': {
auto index = line.find(' ', 2);
if (index == std::string::npos)
throw std::runtime_error("INF file syntax error");
auto value = line.substr(index + 1);
boost::algorithm::trim_if(value, boost::algorithm::is_any_of("\r "));
lds.push_back(fixFileNameCase(value, fsFileSet));
} break;
case 'F': {
auto index = line.find(';');
if (index == std::string::npos)
throw std::runtime_error("INF file syntax error");
auto value = line.substr(index + 1);
boost::algorithm::trim_if(value, boost::algorithm::is_any_of("\r "));
files.insert(fs::path(fixFileNameCase(value, fsFileSet)));
} break;
}
}
std::vector<InfFile> infs;
auto findExt = [&](auto ext) {
return std::find_if(begin(files), end(files), [&](auto file) {
auto str = file.string();
boost::algorithm::to_lower(str);
return boost::algorithm::ends_with(str, ext);
});
};
for (auto& name : lds) {
auto ld = parseLdFile(filesystem->open(name).get());
InfFile inf;
inf.version = version;
inf.supported = true;
inf.ld = name;
inf.primary.hic = fixFileNameCase(ld.baseFileName + ".hic", files);
inf.primary.idx = fixFileNameCase(fs::path(name).stem().string() + ".idx", files);
inf.primary.bof = fixFileNameCase(fs::path(name).stem().string() + ".bof", files);
files.erase(inf.primary.bof);
files.erase(inf.primary.idx);
infs.push_back(inf);
}
ResourceArchive fsiResource;
auto fsi = findExt(".fsi");
if (fsi != end(files)) {
fsiResource.fsi = fsi->string();
auto bof = files.find(fsi->stem().string() + ".bof");
auto idx = files.find(fsi->stem().string() + ".idx");
if (bof == end(files) || idx == end(files)) {
fsiResource = {};
fsi = end(files);
} else {
fsiResource.bof = fixFileNameCase(bof->string(), files);
fsiResource.idx = fixFileNameCase(idx->string(), files);
files.erase(fs::path(fsiResource.bof));
}
}
auto filesCopy = files;
for (auto& inf : infs) {
if (!fsiResource.fsi.empty()) {
inf.resources.push_back(fsiResource);
}
for (;;) {
auto fsd = findExt(".fsd");
if (fsd != end(files)) {
ResourceArchive resource;
resource.fsd = fsd->string();
files.erase(fsd);
auto base = fs::path(resource.fsd).stem().string();
resource.fsi = fixFileNameCase(base + ".fsi", files);
if (files.find(resource.fsi) == end(files))
throw std::runtime_error("FSD blob doesn't have a corresponding FSI file");
inf.resources.push_back(resource);
continue;
}
auto bof = findExt(".bof");
if (bof == end(files))
break;
ResourceArchive resource;
resource.bof = bof->string();
files.erase(bof);
auto base = fs::path(resource.bof).stem().string();
resource.fsi = fixFileNameCase(base + ".fsi", files);
resource.idx = fixFileNameCase(base + ".idx", files);
if (files.find(resource.fsi) == end(files)) {
resource.fsi = "";
}
inf.resources.push_back(resource);
}
files = filesCopy;
}
return infs;
}
} // namespace duden
| 33.565217
| 98
| 0.530225
|
nonwill
|
c62c9a7ce11f06735a2977b442b494bf1bc1409f
| 1,088
|
hpp
|
C++
|
metro/include/metro/CholeskyStepper.hpp
|
gavinband/qctool
|
8d8adb45151c91f953fe4a9af00498073b1132ba
|
[
"BSL-1.0"
] | 3
|
2021-04-21T05:42:24.000Z
|
2022-01-26T14:59:43.000Z
|
metro/include/metro/CholeskyStepper.hpp
|
gavinband/qctool
|
8d8adb45151c91f953fe4a9af00498073b1132ba
|
[
"BSL-1.0"
] | 2
|
2020-04-09T16:11:04.000Z
|
2020-11-10T11:18:56.000Z
|
metro/include/metro/CholeskyStepper.hpp
|
gavinband/qctool
|
8d8adb45151c91f953fe4a9af00498073b1132ba
|
[
"BSL-1.0"
] | null | null | null |
// Copyright Gavin Band 2008 - 2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef METRO_CHOLESKY_STEPPER_HPP
#define METRO_CHOLESKY_STEPPER_HPP
#include <string>
#include <vector>
#include <Eigen/Core>
#include <Eigen/Cholesky>
#include "boost/function.hpp"
#include "metro/ModifiedCholesky.hpp"
#include "metro/SmoothFunction.hpp"
#include "metro/fit_model.hpp"
namespace metro {
struct CholeskyStepper: public Stepper {
public:
CholeskyStepper( double tolerance, int max_iterations, Tracer tracer = Tracer()) ;
bool step( Function& function, Vector* result ) ;
bool diverged() const ;
std::size_t number_of_iterations() const ;
void reset() ;
private:
double const m_tolerance ;
int const m_max_iterations ;
Tracer m_tracer ;
int m_iteration ;
metro::ModifiedCholesky< Matrix > m_solver ;
//Eigen::LDLT< Matrix > m_solver ;
//Eigen::ColPivHouseholderQR< Matrix > m_solver ;
double m_target_ll ;
} ;
}
#endif
| 25.302326
| 84
| 0.727022
|
gavinband
|
c62d8b0ae5dfda8f0df551a6992f7b3b9a26df7a
| 75
|
cpp
|
C++
|
0225proj/GV.cpp
|
Bidoumyouou/-Quick
|
98d58f4c66e7490c243b742d040a7e9c31d0696b
|
[
"Unlicense"
] | null | null | null |
0225proj/GV.cpp
|
Bidoumyouou/-Quick
|
98d58f4c66e7490c243b742d040a7e9c31d0696b
|
[
"Unlicense"
] | 1
|
2016-12-05T16:28:02.000Z
|
2016-12-05T16:29:58.000Z
|
0225proj/GV.cpp
|
Bidoumyouou/-Quick
|
98d58f4c66e7490c243b742d040a7e9c31d0696b
|
[
"Unlicense"
] | null | null | null |
#include "GV.h"
#include<DxLib.h>
unsigned int BLUE = GetColor(0, 0, 255);
| 18.75
| 40
| 0.68
|
Bidoumyouou
|
c631404eed5c057746b34bf48f4ea730f05a77bf
| 8,535
|
cc
|
C++
|
sparse_operation_kit/Deprecated/cc/kernels/v1/embedding_plugin_init.cc
|
marsmiao/HugeCTR
|
c9ff359a69565200fcc0c7aae291d9c297bea70e
|
[
"Apache-2.0"
] | null | null | null |
sparse_operation_kit/Deprecated/cc/kernels/v1/embedding_plugin_init.cc
|
marsmiao/HugeCTR
|
c9ff359a69565200fcc0c7aae291d9c297bea70e
|
[
"Apache-2.0"
] | null | null | null |
sparse_operation_kit/Deprecated/cc/kernels/v1/embedding_plugin_init.cc
|
marsmiao/HugeCTR
|
c9ff359a69565200fcc0c7aae291d9c297bea70e
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright (c) 2021, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "wrapper_variables.h"
#include "embedding_utils.hpp"
#include "tensorflow/core/framework/op_kernel.h"
#include "cuda_utils.h"
#include <memory>
#include <type_traits>
#include <iostream>
namespace tensorflow {
using GPUDevice = Eigen::GpuDevice;
using CPUDevice = Eigen::ThreadPoolDevice;
/*
This op is used to create part of HugeCTR's solver/session.
*/
template <typename Device>
class InitOp : public OpKernel {
public:
explicit InitOp(OpKernelConstruction* ctx) : OpKernel(ctx){
OP_REQUIRES_OK(ctx, ctx->GetAttr("seed", &seed_));
OP_REQUIRES_OK(ctx, ctx->GetAttr("key_type", &key_type));
OP_REQUIRES_OK(ctx, ctx->GetAttr("value_type", &value_type));
OP_REQUIRES(ctx, Utils::check_in_set(KEY_TYPE_SET, key_type),
errors::InvalidArgument("key_type must be {uint32, int64}."));
OP_REQUIRES(ctx, Utils::check_in_set(VALUE_TYPE_SET, value_type),
errors::InvalidArgument("value_type must be {float, half}."));
OP_REQUIRES_OK(ctx, ctx->GetAttr("batch_size", &batch_size_));
OP_REQUIRES(ctx, batch_size_ > 0, errors::InvalidArgument(__FILE__, ":", __LINE__, " ",
"batch_size should be > 0, but got ", batch_size_));
OP_REQUIRES_OK(ctx, ctx->GetAttr("batch_size_eval", &batch_size_eval_));
OP_REQUIRES(ctx, batch_size_eval_ > 0, errors::InvalidArgument(__FILE__, ":", __LINE__, " ",
"batch_size_eval should be > 0, but got ", batch_size_eval_));
}
void Compute(OpKernelContext* ctx) override {
/*vector<vector<int>> vvgpu*/
std::vector<std::vector<int>> vecvecgpu;
const Tensor* vvgpu = nullptr;
OP_REQUIRES_OK(ctx, ctx->input("visiable_gpus", &vvgpu));
/*check dims, should be {1, 2}*/
int dims = vvgpu->dims();
if (std::is_same<Device, CPUDevice>::value) {
switch (dims) {
case 1: { // vector
std::vector<int> vgpu;
auto vvgpu_flat = vvgpu->flat<int32>();
for (long int i = 0; i < vvgpu_flat.size(); ++i) {
int gpu = vvgpu_flat(i);
OP_REQUIRES(ctx, gpu >= 0, errors::InvalidArgument("Input tensor vvgpus's elements ",
"should be >= 0, but get ", gpu));
vgpu.push_back(gpu);
}
vecvecgpu.push_back(vgpu);
break;
}
case 2: { // vector<vector>
auto vvgpu_flat = vvgpu->flat<int32>();
size_t dim_size_0 = vvgpu->dim_size(0);
size_t dim_size_1 = vvgpu->dim_size(1);
for (size_t dim_0 = 0; dim_0 < dim_size_0; ++dim_0) {
std::vector<int> vgpu;
vgpu.clear();
for (size_t dim_1 = 0; dim_1 < dim_size_1; ++dim_1) {
int gpu = vvgpu_flat(dim_0 * dim_size_1 + dim_1);
OP_REQUIRES(ctx, gpu >= 0, errors::InvalidArgument("Input tensor vvgpus's elements ",
"should be >= 0, but get ", gpu));
vgpu.push_back(gpu);
}
vecvecgpu.push_back(vgpu);
}
break;
}
default: {
ctx->SetStatus(errors::InvalidArgument("The dims of input tensor 'vvgpu' should be {1, 2}, but get ",
dims));
return;
}
}
} else if (std::is_same<Device, GPUDevice>::value) {
switch (dims) {
case 1: {
auto vvgpu_flat = vvgpu->flat<int32>();
std::vector<int> vgpu(vvgpu_flat.size(), 0);
PLUGIN_CUDA_CHECK(ctx, cudaMemcpy(vgpu.data(), vvgpu_flat.data(),
vvgpu_flat.size() * sizeof(int), cudaMemcpyDeviceToHost));
vecvecgpu.push_back(vgpu);
break;
}
case 2: {
auto vvgpu_flat = vvgpu->flat<int32>();
size_t dim_size_0 = vvgpu->dim_size(0);
size_t dim_size_1 = vvgpu->dim_size(1);
for (size_t dim_0 = 0; dim_0 < dim_size_0; ++dim_0) {
std::vector<int> vgpu(dim_size_1, 0);
PLUGIN_CUDA_CHECK(ctx, cudaMemcpy(vgpu.data(), vvgpu_flat.data() + dim_0 * dim_size_1,
dim_size_1 * sizeof(int), cudaMemcpyDeviceToHost));
vecvecgpu.push_back(vgpu);
}
break;
}
default: {
ctx->SetStatus(errors::InvalidArgument("The dims of input tensor 'vvgpu' should be {1, 2}, but get ",
dims));
return;
}
}
} // if device
/*check devices are unique*/
std::string show_gpus = "";
int before = -1;
for (auto vec : vecvecgpu) {
for (auto gpu : vec) {
if (gpu > before) {
show_gpus += (std::to_string(gpu) + ",");
before = gpu;
} else {
ctx->SetStatus(errors::InvalidArgument(__FILE__, ":", __LINE__, " ",
"visiable_gpus for embedding plugin is not valid. They must be in ascending order",
" and without repetition."));
return;
}
}
}
LOG(INFO) << "visiable_gpus for embedding plugin: " << show_gpus;
/*create wrapper instance*/
if (wrapper) {
ctx->SetStatus(errors::AlreadyExists("An wrapper instance already exists. Maybe you called hugectr.init() ",
"more than once."));
return;
} else {
if ("uint32" == key_type) {
if ("float" == value_type) {
wrapper.reset(new HugeCTR::EmbeddingWrapper<unsigned int, float>(vecvecgpu,
static_cast<unsigned long long>(seed_),
batch_size_, batch_size_eval_));
} else if ("half" == value_type) {
wrapper.reset(new HugeCTR::EmbeddingWrapper<unsigned int, __half>(vecvecgpu,
static_cast<unsigned long long>(seed_),
batch_size_, batch_size_eval_));
}
} else if ("int64" == key_type) {
if ("float" == value_type) {
wrapper.reset(new HugeCTR::EmbeddingWrapper<long long, float>(vecvecgpu,
static_cast<unsigned long long>(seed_),
batch_size_, batch_size_eval_));
} else if ("half" == value_type) {
wrapper.reset(new HugeCTR::EmbeddingWrapper<long long, __half>(vecvecgpu,
static_cast<unsigned long long>(seed_),
batch_size_, batch_size_eval_));
}
}
}
}
private:
long long seed_;
long long batch_size_;
long long batch_size_eval_;
};
REGISTER_KERNEL_BUILDER(Name("HugectrInit").Device(DEVICE_CPU), InitOp<CPUDevice>);
REGISTER_KERNEL_BUILDER(Name("HugectrInit").Device(DEVICE_GPU), InitOp<GPUDevice>);
} // namespace tensorflow
| 45.887097
| 122
| 0.500879
|
marsmiao
|
c6327228ea9b887176426fd248c225b7919a34fd
| 23,539
|
hpp
|
C++
|
src/Event.hpp
|
epicbrownie/Epic
|
c54159616b899bb24c6d59325d582e73f2803ab6
|
[
"MIT"
] | null | null | null |
src/Event.hpp
|
epicbrownie/Epic
|
c54159616b899bb24c6d59325d582e73f2803ab6
|
[
"MIT"
] | 29
|
2016-08-01T14:50:12.000Z
|
2017-12-17T20:28:27.000Z
|
src/Event.hpp
|
epicbrownie/Epic
|
c54159616b899bb24c6d59325d582e73f2803ab6
|
[
"MIT"
] | null | null | null |
//////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2016 Ronnie Brohn (EpicBrownie)
//
// Distributed under The MIT License (MIT).
// (See accompanying file License.txt or copy at
// https://opensource.org/licenses/MIT)
//
// Please report any bugs, typos, or suggestions to
// https://github.com/epicbrownie/Epic/issues
//
//////////////////////////////////////////////////////////////////////////////
#pragma once
#include <Epic/StringHash.hpp>
#include <Epic/Memory/Default.hpp>
#include <Epic/STL/Vector.hpp>
#include <Epic/TMP/Sequence.hpp>
#include <boost/preprocessor.hpp>
#include <cstdint>
#include <functional>
#include <tuple>
//////////////////////////////////////////////////////////////////////////////
namespace Epic
{
namespace detail
{
template<class R, class... Args>
class EventBase;
}
template<typename Signature>
class Event;
template<typename Signature>
class PolledEvent;
}
//////////////////////////////////////////////////////////////////////////////
// The following macros are used with the boost preprocessor library to allow for automatic parameter
// binding when binding member function pointers to events. Set BMFP_COUNT to a number that is
// less-than or equal to the number of std::placeholders defined for your system.
#define BMFP_COUNT 20
#define BMFP_PH_DECL(z, n, text) BOOST_PP_COMMA() BOOST_PP_CAT(std::placeholders::_, BOOST_PP_ADD(n, 1))
#define BMFP_N_DECL(z, n, text) \
template<class T, class This> \
struct BMFP< ## n ##, T, This> \
{ \
static inline DelegateType Bind(const This* pThis, R(T::* fn)(Args...) const) noexcept \
{ return std::bind(fn, pThis BOOST_PP_REPEAT(n, BMFP_PH_DECL, ~)); } \
static inline DelegateType Bind(This* pThis, R(T::* fn)(Args...)) noexcept \
{ return std::bind(fn, pThis BOOST_PP_REPEAT(n, BMFP_PH_DECL, ~)); } \
};
//////////////////////////////////////////////////////////////////////////////
// EventBase
template<class R, class... Args>
class Epic::detail::EventBase
{
public:
using Type = Epic::detail::EventBase<R, Args...>;
using DelegateType = std::function<R(Args...)>;
protected:
struct EventHandler
{
using HandleType = uint32_t;
using InstanceType = intptr_t;
HandleType handle;
InstanceType instance;
};
struct MutateQueueEntry
{
enum eMutateCommand
{
Subscribe,
Unsubscribe,
UnsubscribeHandle,
UnsubscribeInstance,
UnsubscribeAll
};
MutateQueueEntry(eMutateCommand cmd)
: command{ cmd }, handler{ 0, 0 }, delegate{}
{ }
MutateQueueEntry(eMutateCommand cmd, const EventHandler& hand, const DelegateType fn)
: command{ cmd }, handler{ hand }, delegate{ fn }
{ }
DelegateType delegate;
EventHandler handler;
eMutateCommand command;
};
protected:
using Listener = std::pair<EventHandler, DelegateType>;
using ListenerList = Epic::STLVector<Listener>;
using MutateQueue = Epic::SmallVector<MutateQueueEntry, 2>;
protected:
ListenerList m_Listeners;
MutateQueue m_MutateQueue;
bool m_IsSuspended;
public:
inline EventBase() noexcept
: m_IsSuspended(false)
{ }
inline EventBase(Type& other) noexcept
: m_IsSuspended(false),
m_Listeners(other.m_Listeners),
m_MutateQueue(other.m_MutateQueue)
{ }
inline EventBase(Type&& other) noexcept
: m_IsSuspended(std::move(other.m_IsSuspended)),
m_Listeners(std::move(other.m_Listeners)),
m_MutateQueue(std::move(other.m_MutateQueue))
{ }
public:
Type& operator = (const Type& other) = delete;
Type& operator = (Type&& other) = delete;
public:
explicit inline operator bool() const noexcept
{
return !m_Listeners.empty();
}
protected:
// Subscribe listener without instance or handle
// If the listener list is currently being processed, the subscription will be queued
// and processed during the next Flush operation
inline void Subscribe(const DelegateType& delegate) noexcept
{
Subscribe(delegate, 0, 0);
}
// Subscribe listener with instance (null handle)
inline void Subscribe(const DelegateType& delegate, const typename EventHandler::InstanceType instance) noexcept
{
Subscribe(delegate, instance, 0);
}
// Subscribe listener with handle (null instance)
inline void Subscribe(const DelegateType& delegate, const typename EventHandler::HandleType handle) noexcept
{
Subscribe(delegate, 0, handle);
}
// Subscribe listener with instance and handle
void Subscribe(const DelegateType& delegate,
const typename EventHandler::InstanceType instance,
const typename EventHandler::HandleType handle) noexcept
{
if (!m_IsSuspended)
{
if ((instance == 0 && handle == 0) || !HasInstanceAndHandle(instance, handle))
m_Listeners.emplace_back(EventHandler{ handle, instance }, delegate);
}
else
{
m_MutateQueue.emplace_back(MutateQueueEntry::Subscribe, EventHandler{ handle, instance }, delegate);
}
}
// Unsubscribe listener with instance (null handle)
inline void Unsubscribe(const typename EventHandler::InstanceType instance) noexcept
{
Unsubscribe(instance, 0);
}
// Unsubscribe all listeners with handle
void Unsubscribe(const typename EventHandler::HandleType handle) noexcept
{
if (!m_IsSuspended)
{
// Multiple listeners can match this handle; unsubscribe all of them.
m_Listeners.erase(std::remove_if(
std::begin(m_Listeners),
std::end(m_Listeners),
[&](const auto& o) { return o.first.handle == handle; }
), std::end(m_Listeners));
}
else
{
// Queue the unsubscription
m_MutateQueue.emplace_back(MutateQueueEntry::UnsubscribeHandle, EventHandler{ handle, 0 }, DelegateType());
}
}
// Unsubscribe one listener with instance and handle
void Unsubscribe(const typename EventHandler::InstanceType instance, const typename EventHandler::HandleType handle) noexcept
{
if (!m_IsSuspended)
{
// There can only be one listener that has both this instance and this handle
auto it = std::find_if(std::begin(m_Listeners), std::end(m_Listeners),
[&](const auto& o) { return o.first.instance == instance && o.first.handle == handle; });
if (it != std::end(m_Listeners))
m_Listeners.erase(it);
}
else
{
// Queue the unsubscription
m_MutateQueue.emplace_back(MutateQueueEntry::Unsubscribe, EventHandler{ handle, instance }, DelegateType());
}
}
// Unsubscribe all listeners with instance
void UnsubscribeAll(const typename EventHandler::InstanceType instance) noexcept
{
if (!m_IsSuspended)
{
// Unsubscribe all listeners that match this instance
m_Listeners.erase(std::remove_if(
std::begin(m_Listeners),
std::end(m_Listeners),
[&](const auto& o) { return o.first.instance == instance; }
), std::end(m_Listeners));
}
else
{
// Queue the unsubscription
m_MutateQueue.emplace_back(MutateQueueEntry::UnsubscribeInstance, EventHandler{ 0, instance }, DelegateType());
}
}
// Unsubscribe all listeners
void UnsubscribeAll() noexcept
{
if (!m_IsSuspended)
{
// Unsubscribe every listener
m_Listeners.clear();
}
else
{
// Queue the unsubscription
m_MutateQueue.emplace_back(MutateQueueEntry::UnsubscribeAll);
}
}
// Iterate through listeners to determine if one can be found with the provided instance and handle
inline bool HasInstanceAndHandle(const typename EventHandler::InstanceType instance, const typename EventHandler::HandleType handle) noexcept
{
return std::find_if(std::begin(m_Listeners), std::end(m_Listeners),
[&](const auto& o)
{
return o.first.instance == instance && o.first.handle == handle;
}) != std::end(m_Listeners);
}
// Suspend or resume subscribing/unsubscribing new listeners freely
inline void Suspend(bool shouldSuspend) noexcept
{
m_IsSuspended = shouldSuspend;
}
// Process mutate queue
void Flush() noexcept
{
Suspend(false);
while (!m_MutateQueue.empty())
{
// Get the next queue item
auto entry = std::move(m_MutateQueue.back());
m_MutateQueue.pop_back();
switch (entry.command)
{
default:
break;
case MutateQueueEntry::Subscribe:
Subscribe(entry.delegate, entry.handler.instance, entry.handler.handle);
break;
case MutateQueueEntry::Unsubscribe:
Unsubscribe(entry.handler.instance, entry.handler.handle);
break;
case MutateQueueEntry::UnsubscribeHandle:
Unsubscribe(entry.handler.handle);
break;
case MutateQueueEntry::UnsubscribeInstance:
UnsubscribeAll(entry.handler.instance);
break;
case MutateQueueEntry::UnsubscribeAll:
UnsubscribeAll();
break;
}
}
}
public:
// Returns the number of listeners subscribed to this event
inline auto GetListenerCount() const noexcept
{
return std::size(m_Listeners);
}
public:
// Connect a function handler
inline void Connect(const DelegateType& delegate) noexcept
{
Subscribe(delegate);
}
// Connect a function handler with a handle
inline void Connect(const DelegateType& delegate, Epic::StringHash handle) noexcept
{
Subscribe(delegate, typename EventHandler::HandleType(handle));
}
// Connect a function object handler
template<class Function>
inline void Connect(const Function& fn) noexcept
{
Subscribe(DelegateType(fn));
}
// Connect a function object handler with a handle
template<class Function>
inline void Connect(const Function& fn, Epic::StringHash handle) noexcept
{
Subscribe(DelegateType(fn), typename EventHandler::HandleType(handle));
}
// Connect a static function pointer handler
inline void Connect(R(*fn)(Args...)) noexcept
{
Subscribe(DelegateType(fn), reinterpret_cast<EventHandler::InstanceType>(fn));
}
// Connect a static function pointer handler with a handle
inline void Connect(R(*fn)(Args...), Epic::StringHash handle) noexcept
{
Subscribe(DelegateType(fn),
reinterpret_cast<EventHandler::InstanceType>(fn),
typename EventHandler::HandleType(handle));
}
// Connect a member function pointer handler
template<class T, class This>
inline void Connect(This* pThis, R(T::* fn)(Args...)) noexcept
{
Subscribe(BMFP<sizeof...(Args), T, This>::Bind(pThis, fn),
reinterpret_cast<EventHandler::InstanceType>(pThis));
}
// Connect a const member function pointer handler
template<class T, class This>
inline void Connect(const This* pThis, R(T::* fn)(Args...) const) noexcept
{
Subscribe(BMFP<sizeof...(Args), T, This>::Bind(pThis, fn),
reinterpret_cast<EventHandler::InstanceType>(pThis));
}
// Connect a member function pointer handler with a handle
template<class T, class This>
inline void Connect(This* pThis, R(T::* fn)(Args...), Epic::StringHash handle) noexcept
{
Subscribe(BMFP<sizeof...(Args), T, This>::Bind(pThis, fn),
reinterpret_cast<EventHandler::InstanceType>(pThis),
typename EventHandler::HandleType>(handle));
}
// Connect a const member function pointer handler with a handle
template<class T, class This>
inline void Connect(const This* pThis, R(T::* fn)(Args...) const, Epic::StringHash handle) noexcept
{
Subscribe(BMFP<sizeof...(Args), T, This>::Bind(pThis, fn),
reinterpret_cast<EventHandler::InstanceType>(pThis),
typename EventHandler::HandleType>(handle));
}
// Disconnect all handlers with the supplied handle
template<size_t N>
inline void Disconnect(const char(&cstr)[N]) noexcept
{
Unsubscribe(typename EventHandler::HandleType(Epic::Hash(cstr)));
}
// Disconnect all handlers with the supplied handle
inline void Disconnect(Epic::StringHash handle) noexcept
{
Unsubscribe(typename EventHandler::HandleType(handle));
}
// Disconnect a static function pointer handler (this will NOT disconnect listeners that provided a handle)
inline void Disconnect(R(*fn)(Args...)) noexcept
{
Unsubscribe(reinterpret_cast<EventHandler::InstanceType>(fn));
}
// Disconnect a static function pointer handler with a handle
inline void Disconnect(R(*fn)(Args...), Epic::StringHash handle) noexcept
{
Unsubscribe(reinterpret_cast<EventHandler::InstanceType>(fn), typename EventHandler::HandleType(handle));
}
// Disconnect a member function pointer handler (this will NOT disconnect listeners that provided a handle)
template<class This>
inline void Disconnect(const This* pThis) noexcept
{
Unsubscribe(reinterpret_cast<EventHandler::InstanceType>(pThis));
}
// Disconnect a member function pointer handler with a handle
template<class This>
inline void Disconnect(const This* pThis, Epic::StringHash handle) noexcept
{
Unsubscribe(reinterpret_cast<EventHandler::InstanceType>(pThis),
typename EventHandler::HandleType(handle));
}
// Disconnect all static function pointer handlers with this address (even listeners that provided a handle)
inline void DisconnectAll(R(*fn)(Args...)) noexcept
{
UnsubscribeAll(reinterpret_cast<EventHandler::InstanceType>(fn));
}
// Disconnect all member function pointer handlers with this instance address (even listeners that provided a handle)
template<class This>
inline void DisconnectAll(const This* pThis) noexcept
{
UnsubscribeAll(reinterpret_cast<EventHandler::InstanceType>(pThis));
}
// Disconnect all listeners
inline void DisconnectAll() noexcept
{
UnsubscribeAll();
}
public:
// Alias: Connect a standard function handler
inline Type& operator += (const DelegateType& delegate) noexcept
{
Connect(delegate);
return *this;
}
// Alias: Connect a function object handler
template<class Function>
inline Type& operator += (const Function& fn) noexcept
{
Connect<Function>(fn);
return *this;
}
// Alias: Connect a static function pointer handler
inline Type& operator += (R(*fn)(Args...)) noexcept
{
Connect(fn);
return *this;
}
// Alias: Disconnect all handlers with the supplied handle
template<size_t N>
inline Type& operator -= (const char(&cstr)[N]) noexcept
{
Disconnect(typename EventHandler::HandleType(Epic::Hash(cstr)));
return *this;
}
// Alias: Disconnect all handlers with the supplied handle
inline Type& operator -= (Epic::StringHash handle) noexcept
{
Disconnect(handle);
return *this;
}
// Alias: Disconnect a static function pointer handler (this will NOT disconnect listeners that provided a handle)
inline Type& operator -= (R(*fn)(Args...)) noexcept
{
Disconnect(fn);
return *this;
}
// Alias: Disconnect a member function pointer handler (this will NOT disconnect listeners that provided a handle)
template<class This>
inline Type& operator -= (const This* pThis) noexcept
{
Disconnect(pThis);
return *this;
}
private:
template<size_t argc, class T, class This>
struct BMFP
{
static inline DelegateType Bind(const This* /* pThis */, R(T::* /* fn */)(Args...) const) noexcept
{
static_assert(false, "Unable to bind member function pointer! Are you trying to bind more than BMFP_COUNT parameters?");
}
static inline DelegateType Bind(This* /* pThis */, R(T::* /* fn */)(Args...)) noexcept
{
static_assert(false, "Unable to bind member function pointer! Are you trying to bind more than BMFP_COUNT parameters?");
}
};
BOOST_PP_REPEAT(BMFP_COUNT, BMFP_N_DECL, ~);
};
//////////////////////////////////////////////////////////////////////////////
// PolledEvent<Signature>
template<class R, class... Args>
class Epic::PolledEvent<R(Args...)> : public Epic::detail::EventBase<R, Args...>
{
using Type = Epic::PolledEvent<R(Args...)>;
using Base = Epic::detail::EventBase<R, Args...>;
public:
using Base::Base;
private:
template<class EventType>
struct ScopeSuspend
{
ScopeSuspend(EventType& evt)
: _event(evt)
{
_event.Suspend(true);
}
~ScopeSuspend()
{
_event.Flush();
}
EventType& _event;
};
template<class EventType>
friend struct ScopeSuspend;
private:
template<class S>
friend class Event;
protected:
using Invocation = std::tuple<Args...>;
using InvocationQueue = Epic::STLVector<Invocation>;
private:
InvocationQueue m_Invocations;
public:
// Buffer an invocation of the event
inline void operator() (Args... args) noexcept
{
m_Invocations.emplace_back(std::forward<Args>(args)...);
}
// Buffer an invocation of the event
inline void Invoke(Args... args) noexcept
{
this->operator() (std::forward<Args>(args)...);
}
private:
template<size_t... Is>
void DoInvoke(Invocation& invocation, std::integer_sequence<size_t, Is...>)
{
for (auto& listener : m_Listeners)
listener.second(std::get<Is>(invocation)...);
}
template<class Return>
inline Return ForwardedInvoke(Args... args) noexcept
{
Invoke(std::forward<Args>(args)...);
return Return();
}
public:
// Invoke all pending event invocations
void Poll()
{
ScopeSuspend<Type> _suspend(*this);
for(auto& argPack : m_Invocations)
DoInvoke(argPack, Epic::TMP::MakeSequence<size_t, sizeof...(Args)>());
}
};
//////////////////////////////////////////////////////////////////////////////
// Event<Signature>
template<class R, class... Args>
class Epic::Event<R(Args...)> : public Epic::detail::EventBase<R, Args...>
{
using Type = Epic::Event<R(Args...)>;
using Base = Epic::detail::EventBase<R, Args...>;
public:
using Base::Base;
private:
template<typename EventType>
struct ScopeSuspend
{
ScopeSuspend(EventType& evt)
: _event(evt)
{
_event.Suspend(true);
}
~ScopeSuspend()
{
_event.Flush();
}
EventType& _event;
};
template<typename EventType>
friend struct ScopeSuspend;
public:
// Import base Connect overloads
using Base::Connect;
// Connect an event as a handler to this event
template<class Return>
inline void Connect(Event<Return(Args...)>& event) noexcept
{
Base::Connect(&event, &Event<Return(Args...)>::ForwardedInvoke<R>);
}
// Connect an event as a handler to this event with a handle
template<class Return>
inline void Connect(Event<Return(Args...)>& event, Epic::StringHash handle) noexcept
{
Base::Connect(&event, &Event<Return(Args...)>::ForwardedInvoke<R>, handle);
}
// Connect a polled event as a handler to this event
template<class Return>
inline void Connect(PolledEvent<Return(Args...)>& event) noexcept
{
Base::Connect(&event, &PolledEvent<Return(Args...)>::ForwardedInvoke<R>);
}
// Connect a polled event as a handler to this event with a handle
template<class Return>
inline void Connect(PolledEvent<Return(Args...)>& event, Epic::StringHash handle) noexcept
{
Base::Connect(&event, &PolledEvent<Return(Args...)>::ForwardedInvoke<R>, handle);
}
// Import base Disconnect overloads
using Base::Disconnect;
// Disconnect an event handler
template<class Return>
inline void Disconnect(const Event<Return(Args...)>& event) noexcept
{
Base::Disconnect(&event);
}
// Disconnect an event handler with a handle
template<class Return>
inline void Disconnect(const Event<Return(Args...)>& event, Epic::StringHash handle) noexcept
{
Base::Disconnect(&event, handle);
}
// Disconnect a polled event handler
template<class Return>
inline void Disconnect(const PolledEvent<Return(Args...)>& event) noexcept
{
Base::Disconnect(&event);
}
// Disconnect a polled event handler with a handle
template<class Return>
inline void Disconnect(const PolledEvent<Return(Args...)>& event, Epic::StringHash handle) noexcept
{
Base::Disconnect(&event, handle);
}
public:
// Import Connect/Disconnect operators
using Base::operator +=;
using Base::operator -=;
// Alias: Connect an event as a handler to this event
template<class Return>
inline Type& operator += (Event<Return(Args...)>& event) noexcept
{
Connect(event);
return *this;
}
// Alias: Connect a polled event as a handler to this event
template<class Return>
inline Type& operator += (PolledEvent<Return(Args...)>& event) noexcept
{
Connect(event);
return *this;
}
// Alias: Disconnect an event as a handler to this event
template<class Return>
inline Type& operator -= (Event<Return(Args...)>& event) noexcept
{
Disconnect(event);
return *this;
}
// Alias: Disconnect a polled event as a handler to this event
template<class Return>
inline Type& operator -= (PolledEvent<Return(Args...)>& event) noexcept
{
Disconnect(event);
return *this;
}
public:
// Invoke the event (handler return values are ignored)
void operator() (Args... args)
{
ScopeSuspend<Type> _suspend(*this);
for (auto& listener : m_Listeners)
listener.second(std::forward<Args>(args)...);
}
// Invoke the event (handler return values are ignored)
inline void Invoke(Args... args)
{
this->operator() (std::forward<Args>(args)...);
}
// Invoke the event and store listener return values into an accumulator
template<class Accumulator = Epic::STLVector<R>>
Accumulator InvokeAccumulate(Args... args)
{
ScopeSuspend<Type> _suspend(*this);
Accumulator accum;
for (auto& listener : m_Listeners)
accum.emplace_back(listener.second(std::forward<Args>(args)...));
return accum;
}
// Invoke the event and store listener return values into the supplied iterator
template<class OutIter>
void InvokeAccumulate(OutIter dest, Args... args)
{
ScopeSuspend<Type> _suspend(*this);
for (auto& listener : m_Listeners)
*dest++ = listener.second(std::forward<Args>(args)...);
}
// Listeners will be invoked and their return value fed to the predicate.
// This loop will continue until the predicate evaluates to true.
// Returns true if predicate ever evaluated to true.
template<class Predicate>
bool InvokeUntil(Predicate& predicate, Args... args)
{
ScopeSuspend<Type> _suspend(*this);
for (auto& listener : m_Listeners)
{
if (predicate(listener.second(std::forward<Args>(args)...)))
return true;
}
return false;
}
// Invoke the event until a listener returns the parameter value
// This function returns whether or not a delegate returned the parameter value
template<typename RV = std::enable_if_t<!std::is_void<R>::value, R>>
bool InvokeUntil(const RV& value, Args... args)
{
ScopeSuspend<Type> _suspend(*this);
for (auto& listener : m_Listeners)
{
if (value == listener.second(std::forward<Args>(args)...))
return true;
}
return false;
}
// Listeners will be invoked and their return value fed to the predicate.
// This loop will continue while the predicate evaluates to true.
// Returns true if all listeners were invoked and predicate always evaluated to true.
template<class Predicate>
bool InvokeWhile(Predicate& predicate, Args... args)
{
ScopeSuspend<Type> _suspend(*this);
for (auto& listener : m_Listeners)
{
if (!predicate(listener.second(std::forward<Args>(args)...)))
return false;
}
return true;
}
// Invoke the event while delegates return the parameter value
// This function returns true if all listeners returned 'value'
template<typename RV = std::enable_if_t<!std::is_void<R>::value, R>>
bool InvokeWhile(const RV& value, Args... args)
{
ScopeSuspend<Type> _suspend(*this);
for (auto& listener : m_Listeners)
{
if (value != listener.second(std::forward<Args>(args)...))
return false;
}
return true;
}
private:
template<class Return>
inline Return ForwardedInvoke(Args... args) noexcept
{
Invoke(std::forward<Args>(args)...);
return Return();
}
};
//////////////////////////////////////////////////////////////////////////////
// Undefine the preprocessor macros (clean up)
#undef BMFP_N_DECL
#undef BMFP_PH_DECL
#undef BMFP_COUNT
| 27.402794
| 142
| 0.692553
|
epicbrownie
|
c63d83bd6a9915eca7d8939be76c2f9837bcdbed
| 402
|
hpp
|
C++
|
cs1410/projects/maze/Maze.hpp
|
McKayRansom/CourseMaterials
|
976552ffca4d9d6e822c74a19bc108f3435bdab1
|
[
"MIT"
] | 6
|
2017-04-07T17:57:48.000Z
|
2020-02-01T22:26:43.000Z
|
cs1410/projects/maze/Maze.hpp
|
McKayRansom/CourseMaterials
|
976552ffca4d9d6e822c74a19bc108f3435bdab1
|
[
"MIT"
] | 20
|
2017-03-29T22:26:47.000Z
|
2019-12-01T05:58:12.000Z
|
cs1410/projects/maze/Maze.hpp
|
McKayRansom/CourseMaterials
|
976552ffca4d9d6e822c74a19bc108f3435bdab1
|
[
"MIT"
] | 91
|
2017-03-29T00:23:21.000Z
|
2021-01-10T14:19:02.000Z
|
#ifndef CS1410_MAZE_HPP
#define CS1410_MAZE_HPP
#include <string>
#include <vector>
class Maze
{
public:
Maze();
void read(std::string filename);
void solve();
void display();
private:
enum MazeCell
{
WALL,
VISITED,
EMPTY,
ON_PATH,
START,
END
};
std::vector<std::vector<MazeCell>> cells;
void display(MazeCell);
};
#endif
| 13.4
| 45
| 0.589552
|
McKayRansom
|
c63df9ba10a1bff3149d26757ba6811a71cb1137
| 487
|
hpp
|
C++
|
scenegraph/include/ren/database_model.hpp
|
wobakj/VulkanFramework
|
960628dbc9743f0d74bc13b7d990d0795e32a542
|
[
"MIT"
] | null | null | null |
scenegraph/include/ren/database_model.hpp
|
wobakj/VulkanFramework
|
960628dbc9743f0d74bc13b7d990d0795e32a542
|
[
"MIT"
] | null | null | null |
scenegraph/include/ren/database_model.hpp
|
wobakj/VulkanFramework
|
960628dbc9743f0d74bc13b7d990d0795e32a542
|
[
"MIT"
] | null | null | null |
#ifndef DATABASE_MODEL_HPP
#define DATABASE_MODEL_HPP
#include "ren/database.hpp"
#include "ren/model.hpp"
class ModelDatabase : public Database<Model> {
public:
ModelDatabase();
// ModelDatabase(Transferrer& transferrer);
ModelDatabase(ModelDatabase && dev);
ModelDatabase(ModelDatabase const&) = delete;
ModelDatabase& operator=(ModelDatabase const&) = delete;
ModelDatabase& operator=(ModelDatabase&& dev);
// void store(std::string const& tex_path);
};
#endif
| 23.190476
| 58
| 0.743326
|
wobakj
|
c63ec85d13c15d8719baac32634717c593941fb5
| 4,283
|
hpp
|
C++
|
src/awt/x11/XToolkit.hpp
|
krzydyn/jacpp
|
ab9b5bfcca1774198c05d9187e5891de1fdf4759
|
[
"Apache-2.0"
] | 5
|
2019-01-01T14:55:58.000Z
|
2021-01-31T14:55:59.000Z
|
src/awt/x11/XToolkit.hpp
|
krzydyn/jacpp
|
ab9b5bfcca1774198c05d9187e5891de1fdf4759
|
[
"Apache-2.0"
] | null | null | null |
src/awt/x11/XToolkit.hpp
|
krzydyn/jacpp
|
ab9b5bfcca1774198c05d9187e5891de1fdf4759
|
[
"Apache-2.0"
] | null | null | null |
#ifndef __AWT_X11_XTOOLKIT_HPP
#define __AWT_X11_XTOOLKIT_HPP
#include <awt/Window.hpp>
#include <lang/Number.hpp>
#include <lang/Thread.hpp>
#include <nio/ByteBuffer.hpp>
namespace awt { namespace x11 {
// http://www.grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/sun/awt/X11GraphicsEnvironment.java
// iX11GraphicsEnvironment -> SunGraphicsEnvironment -> GraphicsEnvironment
class X11GraphicsEnvironment : extends GraphicsEnvironment {
public:
X11GraphicsEnvironment();
Array<GraphicsDevice*>& getScreenDevices();
GraphicsDevice& getDefaultScreenDevice();
boolean isDisplayLocal() {return true;}
};
class XDataWrapper : extends Object {
protected:
Shared<nio::ByteBuffer> pData;
XDataWrapper(int size) {
pData = nio::ByteBuffer::allocate(size);
pData->order(nio::ByteOrder::LITTLE_ENDIAN);
}
XDataWrapper(Shared<nio::ByteBuffer> buf) {
pData = buf;
pData->order(nio::ByteOrder::LITTLE_ENDIAN);
}
boolean getBool(int offs) const { return pData->get(offs) != 0; }
void putBool(int offs, boolean b) { pData->put(offs, b?1:0); }
static int getLongSize() {return 8;}
public:
long getPData() { return (long)&(pData->array()[0]); }
void dispose() { pData.reset(); }
};
class XAnyEvent : extends XDataWrapper {
public:
static int getSize() { return 40; }
XAnyEvent(Shared<nio::ByteBuffer> buf) : XDataWrapper(buf) {}
long get_window() const { return pData->getLong(32); }
};
// in Xlib.h this union
class XEvent : extends XDataWrapper {
public:
static int getSize() { return 192; }
XEvent() : XDataWrapper(getSize()) { }
XEvent(Shared<nio::ByteBuffer> buf) : XDataWrapper(buf) {}
int get_type() const { return pData->getInt(0); }
XAnyEvent get_xany() { return XAnyEvent(pData); }
};
interface DisplayChangedListener : Interface {
};
class X11GraphicsConfig;
class X11GraphicsDevice : extends awt::GraphicsDevice {
private:
int screen;
X11GraphicsConfig *defaultConfig = null;
public:
X11GraphicsDevice(int screennum) : screen(screennum) {}
awt::GraphicsConfiguration& getDefaultConfiguration();
int getScreen() { return screen; }
//long getDisplay();
void addDisplayChangedListener(DisplayChangedListener* client);
};
class AwtGraphicsConfigData;
class X11GraphicsConfig : extends awt::GraphicsConfiguration {
private:
AwtGraphicsConfigData *aData;
void init(int visualNum, int screen);
protected:
X11GraphicsDevice* screen;
int visual;
int depth;
int colormap;
boolean doubleBuffer;
public:
X11GraphicsConfig(X11GraphicsDevice* device, int visualnum, int depth, int colormap, boolean doubleBuffer);
//deprecated, replaced by device->getDefaultConfig(), TODO by device->getConfig(v,d,cm,type)
//static X11GraphicsConfig& getConfig(X11GraphicsDevice* device, int visualnum, int depth, int colormap, int type);
GraphicsDevice& getDevice();
ColorModel getColorModel() const;
ColorModel getColorModel(int transparency) const;
//virtual AffineTransform getDefaultTransform();
//virtual AffineTransform getNormalizingTransform();
Rectangle getBounds() const;
boolean isTranslucencyCapable() const {return false;}
AwtGraphicsConfigData *getAData() { return aData; }
};
class XBaseWindow;
class XToolkit : extends Toolkit, implements Runnable {
private:
void init();
long getNextTaskTime();
public:
static void awtLock();
static void awtUnlock();
static long getDisplay();
static long getDefaultRootWindow();
static boolean getSunAwtDisableGrab();
static void addToWinMap(long window, XBaseWindow* xwin);
static void removeFromWinMap(long window, XBaseWindow* xwin);
static XBaseWindow* windowToXWindow(long window);
//static void addEventDispatcher(long window, XEventDispatcher dispatcher);
static String getCorrectXIDString(const String& val);
static String getEnv(const String& key);
XToolkit();
awt::ButtonPeer* createButton(awt::Button* target);
awt::FramePeer* createLightweightFrame(awt::LightweightFrame* target);
awt::FramePeer* createFrame(awt::Frame* target);
awt::LightweightPeer* createComponent(awt::Component* target);
awt::WindowPeer* createWindow(awt::Window* target);
awt::DialogPeer* createDialog(awt::Dialog* target);
awt::EventQueue& getSystemEventQueueImpl();
awt::MouseInfoPeer& getMouseInfoPeer();
void run();
void run(boolean loop);
};
}}
#endif
| 30.81295
| 122
| 0.761149
|
krzydyn
|
c63f59121d4058485002e4059c1f72b491b9d9a9
| 1,280
|
hpp
|
C++
|
Real-Time Corruptor/BizHawk_RTC/waterbox/libsnes/bsnes/nall/stdint.hpp
|
redscientistlabs/Bizhawk50X-Vanguard
|
96e0f5f87671a1230784c8faf935fe70baadfe48
|
[
"MIT"
] | 1,414
|
2015-06-28T09:57:51.000Z
|
2021-10-14T03:51:10.000Z
|
Real-Time Corruptor/BizHawk_RTC/waterbox/libsnes/bsnes/nall/stdint.hpp
|
redscientistlabs/Bizhawk50X-Vanguard
|
96e0f5f87671a1230784c8faf935fe70baadfe48
|
[
"MIT"
] | 2,369
|
2015-06-25T01:45:44.000Z
|
2021-10-16T08:44:18.000Z
|
Real-Time Corruptor/BizHawk_RTC/waterbox/libsnes/bsnes/nall/stdint.hpp
|
redscientistlabs/Bizhawk50X-Vanguard
|
96e0f5f87671a1230784c8faf935fe70baadfe48
|
[
"MIT"
] | 430
|
2015-06-29T04:28:58.000Z
|
2021-10-05T18:24:17.000Z
|
#ifndef NALL_STDINT_HPP
#define NALL_STDINT_HPP
#if defined(_MSC_VER)
typedef signed char int8_t;
typedef signed short int16_t;
typedef signed int int32_t;
typedef signed long long int64_t;
typedef int64_t intmax_t;
#if defined(_WIN64)
typedef int64_t intptr_t;
#else
typedef int32_t intptr_t;
#endif
typedef unsigned char uint8_t;
typedef unsigned short uint16_t;
typedef unsigned int uint32_t;
typedef unsigned long long uint64_t;
typedef uint64_t uintmax_t;
#if defined(_WIN64)
typedef uint64_t uintptr_t;
#else
typedef uint32_t uintptr_t;
#endif
#else
#include <stdint.h>
#endif
namespace nall {
static_assert(sizeof(int8_t) == 1, "int8_t is not of the correct size" );
static_assert(sizeof(int16_t) == 2, "int16_t is not of the correct size");
static_assert(sizeof(int32_t) == 4, "int32_t is not of the correct size");
static_assert(sizeof(int64_t) == 8, "int64_t is not of the correct size");
static_assert(sizeof(uint8_t) == 1, "int8_t is not of the correct size" );
static_assert(sizeof(uint16_t) == 2, "int16_t is not of the correct size");
static_assert(sizeof(uint32_t) == 4, "int32_t is not of the correct size");
static_assert(sizeof(uint64_t) == 8, "int64_t is not of the correct size");
}
#endif
| 29.767442
| 77
| 0.73125
|
redscientistlabs
|
c6468061e9d93883b5d5b9fd527882afb0692e96
| 5,583
|
cc
|
C++
|
lite/model_parser/flatbuffers/program_desc_test.cc
|
yangsong02/Paddle-Lite
|
70b71336c7a4641f45725d87a9395bcf2a35eef6
|
[
"Apache-2.0"
] | null | null | null |
lite/model_parser/flatbuffers/program_desc_test.cc
|
yangsong02/Paddle-Lite
|
70b71336c7a4641f45725d87a9395bcf2a35eef6
|
[
"Apache-2.0"
] | null | null | null |
lite/model_parser/flatbuffers/program_desc_test.cc
|
yangsong02/Paddle-Lite
|
70b71336c7a4641f45725d87a9395bcf2a35eef6
|
[
"Apache-2.0"
] | null | null | null |
// Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "lite/model_parser/flatbuffers/program_desc.h"
#include <gtest/gtest.h>
#include <string>
namespace paddle {
namespace lite {
namespace fbs {
namespace {
std::vector<char> GenerateProgramCache() {
/* --------- Set Program --------- */
ProgramDesc program;
program.SetVersion(1000600);
/* --------- Set Block A --------- */
BlockDesc block_a(program.AddBlock<proto::BlockDescT>());
VarDesc var_a2(block_a.AddVar<proto::VarDescT>());
var_a2.SetType(paddle::lite::VarDataType::LOD_TENSOR);
var_a2.SetName("var_a2");
var_a2.SetShape({2, 2, 1});
VarDesc var_a0(block_a.AddVar<proto::VarDescT>());
var_a0.SetType(paddle::lite::VarDataType::LOD_TENSOR);
var_a0.SetName("var_a0");
var_a0.SetShape({1, 2});
OpDesc op_a0(block_a.AddOp<proto::OpDescT>());
op_a0.SetType("Type");
op_a0.SetInput("X", {"var_a0"});
op_a0.SetOutput("Y0", {"var_a0", "var_a1"});
op_a0.SetOutput("Y1", {"var_a2"});
op_a0.SetAttr<std::string>("Attr5", "attr_5");
op_a0.SetAttr<std::vector<std::string>>("Attr2", {"attr_2"});
op_a0.SetAttr<float>("Attr1", 0.98f);
op_a0.SetAttr<int32_t>("Attr0", 16);
/* --------- Set Block B --------- */
BlockDesc block_b(program.AddBlock<proto::BlockDescT>());
VarDesc var_b0(block_b.AddVar<proto::VarDescT>());
var_b0.SetName("var_b0");
var_b0.SetShape({-1, 1});
OpDesc op_b0(block_b.AddOp<proto::OpDescT>());
op_b0.SetType("Type0");
op_b0.SetInput("X", {"var_b0"});
op_b0.SetOutput("Y1", {"var_b0"});
op_b0.SetAttr<std::string>("Attr5", "attr_5");
OpDesc op_b1(block_b.AddOp<proto::OpDescT>());
op_b1.SetType("Type1");
op_b1.SetInput("X", {"var_b0"});
op_b1.SetOutput("Y1", {"var_b0"});
op_b1.SetAttr<std::string>("Attr5", "attr_5");
op_b1.SetAttr<std::vector<std::string>>("Attr2", {"attr_2"});
op_b1.SetAttr<bool>("Attr1", true);
/* --------- Cache Program ---------- */
std::vector<char> cache;
cache.resize(program.buf_size());
std::memcpy(cache.data(), program.data(), program.buf_size());
return cache;
}
} // namespace
TEST(ProgramDesc, LoadTest) {
ProgramDesc program(GenerateProgramCache());
CHECK_EQ(program.Version(), 1000600);
CHECK_EQ(program.BlocksSize(), static_cast<size_t>(2));
/* --------- Check Block A --------- */
auto block_a = BlockDesc(program.GetBlock<proto::BlockDescT>(0));
CHECK_EQ(block_a.OpsSize(), 1);
CHECK_EQ(block_a.VarsSize(), 2);
auto var_a2 = VarDesc(block_a.GetVar<proto::VarDescT>(0));
CHECK(var_a2.GetShape() == std::vector<int64_t>({2, 2, 1}));
auto op_a0 = OpDesc(block_a.GetOp<proto::OpDescT>(0));
CHECK_EQ(op_a0.Type(), std::string("Type"));
CHECK(op_a0.Input("X") == std::vector<std::string>({"var_a0"}));
CHECK(op_a0.Output("Y0") == std::vector<std::string>({"var_a0", "var_a1"}));
CHECK(op_a0.Output("Y1") == std::vector<std::string>({"var_a2"}));
CHECK_EQ(op_a0.GetAttr<float>("Attr1"), 0.98f);
CHECK_EQ(op_a0.GetAttr<int32_t>("Attr0"), 16);
CHECK_EQ(op_a0.GetAttr<std::string>("Attr5"), std::string("attr_5"));
CHECK(op_a0.GetAttr<std::vector<std::string>>("Attr2") ==
std::vector<std::string>({"attr_2"}));
/* --------- Check Block B --------- */
auto block_b = BlockDesc(program.GetBlock<proto::BlockDescT>(1));
CHECK_EQ(block_b.OpsSize(), 2);
CHECK_EQ(block_b.VarsSize(), 1);
auto op_b0 = OpDesc(block_b.GetOp<proto::OpDescT>(1));
CHECK_EQ(op_b0.GetAttr<bool>("Attr1"), true);
CHECK_EQ(op_b0.HasAttr("Attr4"), false);
}
TEST(ProgramDescView, LoadTest) {
const ProgramDescView program(GenerateProgramCache());
CHECK_EQ(program.Version(), 1000600);
CHECK_EQ(program.BlocksSize(), static_cast<size_t>(2));
/* --------- Check Block A --------- */
const auto& block_a = *program.GetBlock<BlockDescView>(0);
CHECK_EQ(block_a.OpsSize(), 1);
CHECK_EQ(block_a.VarsSize(), 2);
const auto& var_a2 = *block_a.GetVar<VarDescView>(0);
CHECK(var_a2.GetShape() == std::vector<int64_t>({2, 2, 1}));
const auto& op_a0 = *block_a.GetOp<OpDescView>(0);
CHECK_EQ(op_a0.Type(), std::string("Type"));
CHECK(op_a0.Input("X") == std::vector<std::string>({"var_a0"}));
CHECK(op_a0.Output("Y0") == std::vector<std::string>({"var_a0", "var_a1"}));
CHECK(op_a0.Output("Y1") == std::vector<std::string>({"var_a2"}));
CHECK_EQ(op_a0.GetAttr<float>("Attr1"), 0.98f);
CHECK_EQ(op_a0.GetAttr<int32_t>("Attr0"), 16);
CHECK_EQ(op_a0.GetAttr<std::string>("Attr5"), std::string("attr_5"));
CHECK(static_cast<std::vector<std::string>>(
op_a0.GetAttr<std::vector<std::string>>("Attr2")) ==
std::vector<std::string>({"attr_2"}));
/* --------- Check Block B --------- */
const auto& block_b = *program.GetBlock<BlockDescView>(1);
CHECK_EQ(block_b.OpsSize(), 2);
CHECK_EQ(block_b.VarsSize(), 1);
const auto& op_b0 = *block_b.GetOp<OpDescView>(1);
CHECK_EQ(op_b0.GetAttr<bool>("Attr1"), true);
CHECK_EQ(op_b0.HasAttr("Attr4"), false);
}
} // namespace fbs
} // namespace lite
} // namespace paddle
| 36.97351
| 78
| 0.658606
|
yangsong02
|
c64faf70bbf6332e7739f0ea9e5172475a44acd3
| 1,545
|
cpp
|
C++
|
GV/CE_RenderPass.cpp
|
EavanKim/E_Flow_Dev
|
a8b076df8f748d4cc2f0d6da2ee01e7601f860b8
|
[
"MIT"
] | null | null | null |
GV/CE_RenderPass.cpp
|
EavanKim/E_Flow_Dev
|
a8b076df8f748d4cc2f0d6da2ee01e7601f860b8
|
[
"MIT"
] | null | null | null |
GV/CE_RenderPass.cpp
|
EavanKim/E_Flow_Dev
|
a8b076df8f748d4cc2f0d6da2ee01e7601f860b8
|
[
"MIT"
] | null | null | null |
#include "CVulkan_Core.h"
CE_RenderPass::CE_RenderPass(const char* _Name)
: GV_Module(_Name)
{
}
CE_RenderPass::CE_RenderPass(std::string _Name)
: GV_Module(_Name)
{
}
void CE_RenderPass::createRenderPass(CE_VDevice* _Device, std::string _Path, std::string _ShaderName, VkShaderStageFlagBits _bit)
{
std::vector<char> ShaderCode = readFile(_Path);
VkShaderModule ShaderModule = createShaderModel(_Device, ShaderCode);
VkPipelineShaderStageCreateInfo ShaderStageInfo = {};
ShaderStageInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
ShaderStageInfo.stage = _bit;
ShaderStageInfo.module = ShaderModule;
ShaderStageInfo.pName = _ShaderName.c_str();
m_PipelineInfos.push_back(ShaderStageInfo);
}
VkShaderModule CE_RenderPass::createShaderModel(CE_VDevice* _Device, const std::vector<char>& _code)
{
VkShaderModuleCreateInfo ShaderInfo = {};
ShaderInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
ShaderInfo.codeSize = _code.size();
ShaderInfo.pCode = reinterpret_cast<const uint32_t*>(_code.data());
VkShaderModule shaderModule;
if (vkCreateShaderModule(_Device->GetDevice(), &ShaderInfo, nullptr, &shaderModule) != VK_SUCCESS)
throw std::runtime_error("failed to create shader module!");
return shaderModule;
}
VkPipelineShaderStageCreateInfo* CE_RenderPass::GetInfo()
{
return m_PipelineInfos.data();
}
void CE_RenderPass::DestroyInstance(VkDevice _device)
{
for (VkPipelineShaderStageCreateInfo Iterator : m_PipelineInfos)
vkDestroyShaderModule(_device, Iterator.module, nullptr);
}
| 28.090909
| 129
| 0.799353
|
EavanKim
|
c64fc79357aabdc831a672af0f68cf5207199935
| 348
|
cpp
|
C++
|
src/ros/service_server.cpp
|
Xamla/torch-ros
|
1f42cd4863d68bc4f9134bd1932988c1d5d1e7ca
|
[
"BSD-3-Clause"
] | 26
|
2016-03-16T06:21:16.000Z
|
2021-01-04T05:37:07.000Z
|
src/ros/service_server.cpp
|
Xamla/torch-ros
|
1f42cd4863d68bc4f9134bd1932988c1d5d1e7ca
|
[
"BSD-3-Clause"
] | 15
|
2016-04-04T21:31:29.000Z
|
2021-08-20T05:27:34.000Z
|
src/ros/service_server.cpp
|
Xamla/torch-ros
|
1f42cd4863d68bc4f9134bd1932988c1d5d1e7ca
|
[
"BSD-3-Clause"
] | 10
|
2016-04-04T21:07:43.000Z
|
2018-05-17T12:54:27.000Z
|
#include "torch-ros.h"
#include <ros/service_server.h>
ROSIMP(void, ServiceServer, delete)(ros::ServiceServer *ptr) {
delete ptr;
}
ROSIMP(void, ServiceServer, shutdown)(ros::ServiceServer *self) {
self->shutdown();
}
ROSIMP(void, ServiceServer, getService)(ros::ServiceServer *self, std::string *result) {
*result = self->getService();
}
| 23.2
| 88
| 0.715517
|
Xamla
|
c6560a5f1709335b30bb26d8573e2852533d7c17
| 848
|
cpp
|
C++
|
ROS-nodes/jetbot_stats/src/jetbot_stats.cpp
|
Skammi/ROS-cpp-for-Jetbot
|
25bd461ca44f387ce3d86e95651004242f78270e
|
[
"BSD-3-Clause"
] | null | null | null |
ROS-nodes/jetbot_stats/src/jetbot_stats.cpp
|
Skammi/ROS-cpp-for-Jetbot
|
25bd461ca44f387ce3d86e95651004242f78270e
|
[
"BSD-3-Clause"
] | null | null | null |
ROS-nodes/jetbot_stats/src/jetbot_stats.cpp
|
Skammi/ROS-cpp-for-Jetbot
|
25bd461ca44f387ce3d86e95651004242f78270e
|
[
"BSD-3-Clause"
] | null | null | null |
/*
* file : jetbot_stats.cpp
* Project : jetbot
* Created on : 10 Nov 2020
* Last edit : 10 Nov 2020
* Author : jacob
*
* Version Date Comment
* ------- ---- -------
* 0.0.1 201110 initial version
*
* Needs to be started with a launch file, which has to set the jetbot_stat specific parameters
* Start:
* roslaunch jetbot_stats jetbot_stats.launch
*
*/
// Include the class header file
#include <jetbot_stats/jetbot_stats_class.h>
int main(int argc, char** argv)
{
// ROS set-ups:
ros::init(argc, argv, "jetbot_stats");
ros::NodeHandle nh;
ROS_INFO("jetbot_stats: instantiating an object of type JetbotStats");
JetbotStats jbs(&nh); // instantiate a JetbotStats object
ROS_INFO("jetbot_stats: Going to spin.");
ros::spin(); // Let the call-backs do the work
return 0;
}
//****[ eof jetbot_stats.cpp ]****//
| 22.918919
| 95
| 0.666274
|
Skammi
|
c664e5e7f5bfa40eacef4f3a5457a67569f66aae
| 9,420
|
cpp
|
C++
|
frameworks/render/modules/osg/dmzRenderModuleCoreOSGBasic.cpp
|
tongli/dmz
|
f2242027a17ea804259f9412b07d69f719a527c5
|
[
"MIT"
] | 1
|
2016-05-08T22:02:35.000Z
|
2016-05-08T22:02:35.000Z
|
frameworks/render/modules/osg/dmzRenderModuleCoreOSGBasic.cpp
|
tongli/dmz
|
f2242027a17ea804259f9412b07d69f719a527c5
|
[
"MIT"
] | null | null | null |
frameworks/render/modules/osg/dmzRenderModuleCoreOSGBasic.cpp
|
tongli/dmz
|
f2242027a17ea804259f9412b07d69f719a527c5
|
[
"MIT"
] | null | null | null |
#include "dmzRenderModuleCoreOSGBasic.h"
#include <dmzObjectModule.h>
#include <dmzObjectAttributeMasks.h>
#include <dmzRenderObjectDataOSG.h>
#include <dmzRuntimeConfig.h>
#include <dmzRuntimeConfigToTypesBase.h>
#include <dmzRuntimeConfigToPathContainer.h>
#include <dmzRuntimePluginFactoryLinkSymbol.h>
#include <dmzRuntimePluginInfo.h>
#include <dmzRuntimeLoadPlugins.h>
#include <dmzSystem.h>
#include <dmzSystemFile.h>
#include <osg/DeleteHandler>
#include <osg/Referenced>
#include <osgDB/Registry>
dmz::RenderModuleCoreOSGBasic::RenderModuleCoreOSGBasic (
const PluginInfo &Info,
Config &local,
Config &global) :
Plugin (Info),
TimeSlice (Info),
ObjectObserverUtil (Info, local),
RenderModuleCoreOSG (Info),
_log (Info),
_defaultHandle (0),
_dirtyObjects (0) {
_scene = new osg::Group;
_overlay = new osg::Group;
_scene->addChild (_overlay.get ());
_isect = new osg::Group;
_scene->addChild (_isect.get ());
_staticObjects = new osg::Group;
_isect->addChild (_staticObjects.get ());
_dynamicObjects = new osg::Group;
_dynamicObjects->setDataVariance (osg::Object::DYNAMIC);
_isect->addChild (_dynamicObjects.get ());
_init (local, global);
}
dmz::RenderModuleCoreOSGBasic::~RenderModuleCoreOSGBasic () {
_extensions.remove_plugins ();
_objectTable.empty ();
_portalTable.empty ();
osg::DeleteHandler *dh (osg::Referenced::getDeleteHandler ());
if (dh) { dh->flush (); }
}
// Plugin Interface
void
dmz::RenderModuleCoreOSGBasic::update_plugin_state (
const PluginStateEnum State,
const UInt32 Level) {
if (State == PluginStateStart) {
_extensions.start_plugins ();
}
else if (State == PluginStateStop) {
_extensions.stop_plugins ();
}
else if (State == PluginStateShutdown) {
_extensions.shutdown_plugins ();
}
}
void
dmz::RenderModuleCoreOSGBasic::discover_plugin (
const PluginDiscoverEnum Mode,
const Plugin *PluginPtr) {
if (Mode == PluginDiscoverAdd) {
_extensions.discover_external_plugin (PluginPtr);
}
else if (Mode == PluginDiscoverRemove) {
_extensions.remove_external_plugin (PluginPtr);
}
}
// Time Slice Interface
void
dmz::RenderModuleCoreOSGBasic::update_time_slice (const Float64 DeltaTime) {
while (_dirtyObjects) {
ObjectStruct *os (_dirtyObjects);
_dirtyObjects = os->next;
os->transform->setMatrix (to_osg_matrix (os->ori, os->pos));
if (os->destroyed) {
if (_dynamicObjects.valid ()) {
_dynamicObjects->removeChild (os->transform.get ());
}
delete os; os = 0;
}
else { os->next = 0; os->dirty = False; }
}
}
// Object Observer Interface
void
dmz::RenderModuleCoreOSGBasic::destroy_object (
const UUID &Identity,
const Handle ObjectHandle) {
ObjectStruct *os (_objectTable.remove (ObjectHandle));
if (os) {
if (os->dirty) { os->destroyed = True; }
else {
if (_dynamicObjects.valid ()) {
_dynamicObjects->removeChild (os->transform.get ());
}
delete os; os = 0;
}
}
}
void
dmz::RenderModuleCoreOSGBasic::update_object_position (
const UUID &Identity,
const Handle ObjectHandle,
const Handle AttributeHandle,
const Vector &Value,
const Vector *PreviousValue) {
ObjectStruct *os (_objectTable.lookup (ObjectHandle));
if (os) {
os->pos = Value;
if (!os->dirty) {
os->dirty = True;
os->next = _dirtyObjects;
_dirtyObjects = os;
}
}
}
void
dmz::RenderModuleCoreOSGBasic::update_object_orientation (
const UUID &Identity,
const Handle ObjectHandle,
const Handle AttributeHandle,
const Matrix &Value,
const Matrix *PreviousValue) {
ObjectStruct *os (_objectTable.lookup (ObjectHandle));
if (os) {
os->ori = Value;
if (!os->dirty) {
os->dirty = True;
os->next = _dirtyObjects;
_dirtyObjects = os;
}
}
}
osg::Group *
dmz::RenderModuleCoreOSGBasic::get_scene () { return _scene.get (); }
osg::Group *
dmz::RenderModuleCoreOSGBasic::get_overlay () { return _overlay.get (); }
osg::Group *
dmz::RenderModuleCoreOSGBasic::get_isect () { return _isect.get (); }
osg::Group *
dmz::RenderModuleCoreOSGBasic::get_static_objects () { return _staticObjects.get (); }
osg::Group *
dmz::RenderModuleCoreOSGBasic::get_dynamic_objects () { return _dynamicObjects.get (); }
osg::Group *
dmz::RenderModuleCoreOSGBasic::create_dynamic_object (const Handle ObjectHandle) {
osg::Group *result (0);
ObjectStruct *os (_objectTable.lookup (ObjectHandle));
if (!os) {
os = new ObjectStruct;
if (os && !_objectTable.store (ObjectHandle, os)) { delete os; os = 0; }
if (os) {
os->transform->setUserData (new RenderObjectDataOSG (ObjectHandle));
os->transform->setDataVariance (osg::Object::DYNAMIC);
ObjectModule *objMod (get_object_module ());
if (objMod) {
objMod->lookup_position (ObjectHandle, _defaultHandle, os->pos);
objMod->lookup_orientation (ObjectHandle, _defaultHandle, os->ori);
os->dirty = True;
os->next = _dirtyObjects;
_dirtyObjects = os;
}
}
}
if (os) {
result = os->transform.get ();
if (_dynamicObjects.valid ()) {
_dynamicObjects->addChild (result);
}
}
return result;
}
osg::Group *
dmz::RenderModuleCoreOSGBasic::lookup_dynamic_object (const Handle ObjectHandle) {
osg::Group *result (0);
ObjectStruct *os (_objectTable.lookup (ObjectHandle));
if (os) { result = os->transform.get (); }
return result;
}
dmz::Boolean
dmz::RenderModuleCoreOSGBasic::add_camera (
const String &PortalName,
osg::Camera *camera) {
Boolean result (False);
PortalStruct *ps = _get_portal_struct (PortalName);
if (ps && camera) {
if (!(ps->camera.valid ())) {
ps->camera = camera;
result = True;
}
}
return result;
}
osg::Camera *
dmz::RenderModuleCoreOSGBasic::lookup_camera (const String &PortalName) {
osg::Camera *result = 0;
PortalStruct *ps = _portalTable.lookup (PortalName);
if (ps) {
result = ps->camera.get ();
}
return result;
}
osg::Camera *
dmz::RenderModuleCoreOSGBasic::remove_camera (const String &PortalName) {
osg::Camera *result = 0;
PortalStruct *ps = _portalTable.lookup (PortalName);
if (ps) {
result = ps->camera.get ();
ps->camera = 0;
}
return result;
}
dmz::Boolean
dmz::RenderModuleCoreOSGBasic::add_camera_manipulator (
const String &PortalName,
dmz::RenderCameraManipulatorOSG *manipulator) {
Boolean result(False);
PortalStruct *ps = _get_portal_struct (PortalName);
if (ps && manipulator) {
if (!(ps->cameraManipulator.valid ())) {
ps->cameraManipulator = manipulator;
result = True;
}
}
return result;
}
dmz::RenderCameraManipulatorOSG *
dmz::RenderModuleCoreOSGBasic::lookup_camera_manipulator (const String &PortalName) {
RenderCameraManipulatorOSG *result = 0;
PortalStruct *ps = _portalTable.lookup (PortalName);
if (ps) {
result = ps->cameraManipulator.get ();
}
return result;
}
dmz::RenderCameraManipulatorOSG *
dmz::RenderModuleCoreOSGBasic::remove_camera_manipulator (const String &PortalName) {
RenderCameraManipulatorOSG *result = 0;
PortalStruct *ps = _portalTable.lookup (PortalName);
if (ps) {
result = ps->cameraManipulator.get ();
ps->cameraManipulator = 0;
}
return result;
}
dmz::RenderModuleCoreOSGBasic::PortalStruct *
dmz::RenderModuleCoreOSGBasic::_get_portal_struct (const String &PortalName) {
PortalStruct *ps = _portalTable.lookup (PortalName);
if (!ps) {
ps = new PortalStruct (PortalName);
if (!_portalTable.store (PortalName, ps)) { delete ps; ps = 0; }
}
return ps;
}
void
dmz::RenderModuleCoreOSGBasic::_init (Config &local, Config &global) {
Config pluginList;
if (local.lookup_all_config ("plugins.plugin", pluginList)) {
RuntimeContext *context (get_plugin_runtime_context ());
if (dmz::load_plugins (context, pluginList, local, global, _extensions, &_log)) {
_extensions.discover_plugins ();
_extensions.discover_external_plugin (this);
}
}
osgDB::Registry *reg = osgDB::Registry::instance ();
Config pathList;
if (reg && local.lookup_all_config ("loader.path", pathList)) {
osgDB::FilePathList &fpl = reg->getLibraryFilePathList ();
ConfigIterator it;
Config path;
while (pathList.get_next_config (it, path)) {
String pathStr = config_to_string ("value", path);
if (get_absolute_path (pathStr, pathStr)) {
fpl.push_back (pathStr.get_buffer ());
}
}
}
_defaultHandle = activate_default_object_attribute (
ObjectDestroyMask | ObjectPositionMask | ObjectOrientationMask);
}
extern "C" {
DMZ_PLUGIN_FACTORY_LINK_SYMBOL dmz::Plugin *
create_dmzRenderModuleCoreOSGBasic (
const dmz::PluginInfo &Info,
dmz::Config &local,
dmz::Config &global) {
return new dmz::RenderModuleCoreOSGBasic (Info, local, global);
}
};
| 21.026786
| 88
| 0.651486
|
tongli
|
c66c5c48941d6f9feaef0c4d0b9f3858f9cd2de8
| 1,183
|
cpp
|
C++
|
AEngine/src/Utils/Logger.cpp
|
alife1029/aengine
|
6d5bf28604f32610a1a60fb6f2bc297bd972d3c7
|
[
"MIT"
] | 1
|
2022-01-17T19:01:14.000Z
|
2022-01-17T19:01:14.000Z
|
AEngine/src/Utils/Logger.cpp
|
alife1029/AEngine
|
ecf181948fc90690c7fe2fba7792f29441b445d7
|
[
"MIT"
] | null | null | null |
AEngine/src/Utils/Logger.cpp
|
alife1029/AEngine
|
ecf181948fc90690c7fe2fba7792f29441b445d7
|
[
"MIT"
] | null | null | null |
#include "AEngine/Utils/Logger.hpp"
#include <fstream>
#include <chrono>
namespace aengine
{
void Logger::LogToFile(const std::string& data, const std::string& file, LogType type)
{
std::ofstream ofs(file, std::ios::app);
if (ofs.is_open())
{
// Calculate current time
time_t currentTime = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
std::string currentTimeStr = std::string(ctime(¤tTime));
// Print current time
ofs << "[" << currentTimeStr.substr(0, currentTimeStr.size() - 1) << "] ";
// Print log type
switch (type)
{
case LogType::Info:
ofs << "[INFO]\t";
break;
case LogType::Warning:
ofs << "[WARNING]\t";
break;
case LogType::Error:
ofs << "[ERROR]\t";
break;
default:
ofs << "[LOG]\t";
break;
}
// Print log message
ofs << data << std::endl;
}
ofs.close();
}
}
| 26.288889
| 104
| 0.459848
|
alife1029
|
c66f79810622e2a48a141514099da111480a81bb
| 2,310
|
hpp
|
C++
|
include/ast/NullableTypeNode.hpp
|
aviralg/tastr
|
184e6324de86831c1e4162112d446f537ad8f50c
|
[
"Apache-2.0"
] | 1
|
2021-03-25T04:05:35.000Z
|
2021-03-25T04:05:35.000Z
|
include/ast/NullableTypeNode.hpp
|
aviralg/tastr
|
184e6324de86831c1e4162112d446f537ad8f50c
|
[
"Apache-2.0"
] | null | null | null |
include/ast/NullableTypeNode.hpp
|
aviralg/tastr
|
184e6324de86831c1e4162112d446f537ad8f50c
|
[
"Apache-2.0"
] | null | null | null |
#ifndef TASTR_AST_NULLABLE_TYPE_NODE_HPP
#define TASTR_AST_NULLABLE_TYPE_NODE_HPP
#include "ast/OperatorNode.hpp"
#include "ast/TypeNode.hpp"
#include <memory>
namespace tastr {
namespace ast {
class NullableTypeNode final: public TypeNode {
public:
explicit NullableTypeNode(OperatorNodeUPtr op,
std::unique_ptr<TypeNode> inner_type)
: TypeNode(), op_(std::move(op)), inner_type_(std::move(inner_type)) {
}
~NullableTypeNode() = default;
NullableTypeNode(const NullableTypeNode& node)
: TypeNode(node)
, op_(node.op_->clone())
, inner_type_(node.inner_type_->clone()) {
}
NullableTypeNode(NullableTypeNode&& node)
: TypeNode(std::move(node))
, op_(std::move(node.op_))
, inner_type_(std::move(node.inner_type_)) {
}
NullableTypeNode& operator=(const NullableTypeNode& node) {
if (&node == this) {
return *this;
}
TypeNode::operator=(node);
op_ = node.op_->clone();
inner_type_ = node.inner_type_->clone();
return *this;
}
NullableTypeNode& operator=(NullableTypeNode&& node) {
TypeNode::operator=(std::move(node));
op_ = std::move(node.op_);
inner_type_ = std::move(node.inner_type_);
return *this;
}
void accept(tastr::visitor::ConstNodeVisitor& visitor) const override final;
void accept(tastr::visitor::MutableNodeVisitor& visitor) override final;
const tastr::ast::TypeNode& get_inner_type() const {
return *inner_type_.get();
}
const OperatorNode& get_operator() const {
return *op_.get();
}
std::unique_ptr<NullableTypeNode> clone() const {
return std::unique_ptr<NullableTypeNode>(this->clone_impl());
}
Kind get_kind() const override final {
return kind_;
}
private:
virtual NullableTypeNode* clone_impl() const override final {
return new NullableTypeNode(*this);
};
OperatorNodeUPtr op_;
std::unique_ptr<TypeNode> inner_type_;
static const Kind kind_;
};
using NullableTypeNodePtr = NullableTypeNode*;
using NullableTypeNodeUPtr = std::unique_ptr<NullableTypeNode>;
} // namespace ast
} // namespace tastr
#endif /* TASTR_AST_NULLABLE_TYPE_NODE_HPP */
| 26.25
| 80
| 0.651082
|
aviralg
|
c674f1a3d61ea7c385a9b87eb5b2044e3524861e
| 185
|
hpp
|
C++
|
drivers/servo/TestServo.hpp
|
jpmorris33/syntheyes3
|
36b0312616145e8da44868897f231cbe7702a64f
|
[
"BSD-3-Clause"
] | 2
|
2022-01-24T23:00:43.000Z
|
2022-03-01T01:39:08.000Z
|
drivers/servo/TestServo.hpp
|
jpmorris33/syntheyes3
|
36b0312616145e8da44868897f231cbe7702a64f
|
[
"BSD-3-Clause"
] | null | null | null |
drivers/servo/TestServo.hpp
|
jpmorris33/syntheyes3
|
36b0312616145e8da44868897f231cbe7702a64f
|
[
"BSD-3-Clause"
] | null | null | null |
#include "../ServoDriver.hpp"
class TestServo : public ServoDriver {
public:
void init(int defaultAngle, const char *param);
void update();
private:
void write(int angle);
};
| 16.818182
| 49
| 0.697297
|
jpmorris33
|
c68176abe97be10557dd97e0f40f515afcb925b9
| 10,490
|
cpp
|
C++
|
src/lib/analysis/advisor/GPUInstruction.cpp
|
GVProf/hpctoolkit
|
baf45028ead83ceba3e952bb8d0b14caf9ea5f78
|
[
"BSD-3-Clause"
] | null | null | null |
src/lib/analysis/advisor/GPUInstruction.cpp
|
GVProf/hpctoolkit
|
baf45028ead83ceba3e952bb8d0b14caf9ea5f78
|
[
"BSD-3-Clause"
] | null | null | null |
src/lib/analysis/advisor/GPUInstruction.cpp
|
GVProf/hpctoolkit
|
baf45028ead83ceba3e952bb8d0b14caf9ea5f78
|
[
"BSD-3-Clause"
] | 2
|
2021-11-30T18:24:10.000Z
|
2022-02-13T18:13:17.000Z
|
//************************* System Include Files ****************************
#include <iostream>
#include <fstream>
#include <string>
#include <climits>
#include <cstring>
#include <cstdio>
#include <typeinfo>
#include <unordered_map>
#include <algorithm>
#include <sys/stat.h>
//*************************** User Include Files ****************************
#include <include/uint.h>
#include <include/gcc-attr.h>
#include <include/gpu-metric-names.h>
#include "GPUInstruction.hpp"
#include "GPUAdvisor.hpp"
using std::string;
#include <lib/prof/CCT-Tree.hpp>
#include <lib/prof/Struct-Tree.hpp>
#include <lib/prof/Metric-Mgr.hpp>
#include <lib/prof/Metric-ADesc.hpp>
#include <lib/profxml/XercesUtil.hpp>
#include <lib/profxml/PGMReader.hpp>
#include <lib/prof-lean/hpcrun-metric.h>
#include <lib/binutils/LM.hpp>
#include <lib/binutils/VMAInterval.hpp>
#include <lib/xml/xml.hpp>
#include <lib/support/diagnostics.h>
#include <lib/support/Logic.hpp>
#include <lib/support/IOUtil.hpp>
#include <lib/support/StrUtil.hpp>
#include <lib/cuda/AnalyzeInstruction.hpp>
#include <vector>
#include <iostream>
#define DEBUG_CALLPATH_CUDAINSTRUCTION 0
namespace Analysis {
namespace CallPath {
static std::vector<size_t> gpu_issue_index;
struct VMAStmt {
VMA lm_ip;
Prof::CCT::ANode *node;
VMAStmt(VMA lm_ip, Prof::CCT::ANode *node) :
lm_ip(lm_ip), node(node) {}
bool operator < (const VMAStmt &other) const {
return this->lm_ip < other.lm_ip;
}
};
static inline std::string
getLMfromInst(const std::string &inst_file) {
char resolved_path[PATH_MAX];
realpath(inst_file.c_str(), resolved_path);
std::string file = std::string(resolved_path);
// xxxx/structs/xxxx/xxxx.cubin.inst
auto dot_pos = file.rfind(".");
std::string cubin_file = file.substr(0, dot_pos);
auto slash_pos0 = cubin_file.rfind("/structs");
auto slash_pos1 = cubin_file.rfind("/");
cubin_file.replace(slash_pos0, slash_pos1 - slash_pos0, "/cubins");
std::cout << cubin_file << std::endl;
return cubin_file;
}
static void
createMetrics(const std::vector<CudaParse::InstructionStat *> &inst_stats,
MetricNameProfMap &metric_name_prof_map, Prof::Metric::Mgr &mgr) {
// Create new metrics in hpcprof
// raw_id-><inclusive id, exclusive id>
// Existing metric names
for (auto *inst_stat : inst_stats) {
auto &metric_name = inst_stat->op;
auto metric_ids = metric_name_prof_map.metric_ids(metric_name);
if (metric_ids.size() == 0) {
if (metric_name_prof_map.add(metric_name)) {
if (DEBUG_CALLPATH_CUDAINSTRUCTION) {
metric_ids = metric_name_prof_map.metric_ids(metric_name);
for (auto id : metric_ids) {
std::cout << "Create metric " << metric_name <<
" inclusive id " << id << std::endl;
}
}
}
} else {
// we already have raw_id-><inclusive id, exclusive id> mappings
if (DEBUG_CALLPATH_CUDAINSTRUCTION) {
metric_ids = metric_name_prof_map.metric_ids(metric_name);
for (auto id : metric_ids) {
std::cout << "Existing metric " << metric_name <<
" inclusive id " << id << std::endl;
}
}
}
}
}
static void
gatherStmts(const Prof::LoadMap::LMId_t lm_id, int inst_pc_front, int inst_pc_back,
const Prof::CCT::ANode *prof_root, std::vector<VMAStmt> &vma_stmts,
std::vector<int> &gpu_kernel_index,
std::set<Prof::CCT::ADynNode *> &gpu_kernels) {
if (DEBUG_CALLPATH_CUDAINSTRUCTION) {
std::cout << "inst pc range: [0x" << std::hex << inst_pc_front <<
", 0x" << inst_pc_back << "]" << std::dec << std::endl;
}
// Get all the stmt nodes
Prof::CCT::ANodeIterator prof_it(prof_root, NULL/*filter*/, false/*leavesOnly*/,
IteratorStack::PreOrder);
for (Prof::CCT::ANode *n = NULL; (n = prof_it.current()); ++prof_it) {
Prof::CCT::ADynNode* n_dyn = dynamic_cast<Prof::CCT::ADynNode*>(n);
if (n_dyn) {
Prof::LoadMap::LMId_t n_lm_id = n_dyn->lmId(); // ok if LoadMap::LMId_NULL
VMA n_lm_ip = n_dyn->lmIP();
// filter out
if (n_lm_id != lm_id || n_lm_ip < static_cast<VMA>(inst_pc_front) || n_lm_ip > static_cast<VMA>(inst_pc_back)) {
continue;
}
// Use the first pc as the gpu_kernel node
for (auto index : gpu_kernel_index) {
if (n_dyn->demandMetric(index) != 0) {
gpu_kernels.insert(n_dyn);
break;
}
}
if (DEBUG_CALLPATH_CUDAINSTRUCTION) {
std::cout << "Find CCT node vma: 0x" << std::hex << n_lm_ip << std::dec << std::endl;
}
vma_stmts.emplace_back(n_lm_ip, n);
}
}
// Sort stmt nodes O(nlogn)
std::sort(vma_stmts.begin(), vma_stmts.end());
}
static void
associateInstStmts(const std::vector<VMAStmt> &vma_stmts,
const std::vector<CudaParse::InstructionStat *> &inst_stats,
MetricNameProfMap &metric_name_prof_map) {
size_t cur_stmt_index = 0;
auto issue_metric_ids = metric_name_prof_map.metric_ids(GPU_INST_METRIC_NAME":STL_NONE");
// Lay metrics over prof tree O(n)
for (auto *inst_stat : inst_stats) {
// while lm_ip < inst_stat->pc
while (cur_stmt_index < vma_stmts.size() && static_cast<VMA>(inst_stat->pc) > vma_stmts[cur_stmt_index].lm_ip) {
if (DEBUG_CALLPATH_CUDAINSTRUCTION) {
std::cout << "inst_stat->pc: 0x" << std::hex << inst_stat->pc << ", vma: 0x" <<
vma_stmts[cur_stmt_index].lm_ip << std::dec << std::endl;
}
++cur_stmt_index;
}
if (cur_stmt_index == vma_stmts.size()) {
break;
}
if (static_cast<VMA>(inst_stat->pc) != vma_stmts[cur_stmt_index].lm_ip) {
continue;
}
auto cur_vma = vma_stmts[cur_stmt_index].lm_ip;
auto *node = vma_stmts[cur_stmt_index].node;
auto in_metric_ids = metric_name_prof_map.metric_ids(inst_stat->op, true);
auto ex_metric_ids = metric_name_prof_map.metric_ids(inst_stat->op, false);
if (in_metric_ids.size() != ex_metric_ids.size()) {
if (DEBUG_CALLPATH_CUDAINSTRUCTION) {
std::cout << "Inclusive and exclusive metrics not match: " << inst_stat->op << std::endl;
}
continue;
}
for (size_t i = 0; i < issue_metric_ids.size(); ++i) {
double sum_insts_f = node->demandMetric(issue_metric_ids[i]);
auto in_metric_id = in_metric_ids[i];
auto ex_metric_id = ex_metric_ids[i];
// Calculate estimate number of executed instructions
node->demandMetric(in_metric_id) += sum_insts_f;
node->demandMetric(ex_metric_id) += sum_insts_f;
if (DEBUG_CALLPATH_CUDAINSTRUCTION) {
auto in_count = node->metric(in_metric_id);
auto ex_count = node->metric(ex_metric_id);
std::cout << "Associate pc: 0x" << std::hex << inst_stat->pc <<
" with vma: " << cur_vma << std::dec <<
" inclusive id " << in_metric_id <<
" name " << metric_name_prof_map.name(in_metric_id) << " count " << in_count <<
" exclusive id " << ex_metric_id <<
" name " << metric_name_prof_map.name(ex_metric_id) << " count " << ex_count << std::endl;
}
}
}
}
std::vector<GPUAdvisor::AdviceTuple>
overlayGPUInstructionsMain(Prof::CallPath::Profile &prof,
const std::vector<std::string> &instruction_files) {
auto *mgr = prof.metricMgr();
MetricNameProfMap metric_name_prof_map(mgr);
metric_name_prof_map.init();
// Check if prof contains gpu metrics
// Skip non-gpu prof
if (metric_name_prof_map.metric_ids(GPU_INST_METRIC_NAME":STL_NONE").size() == 0) {
if (DEBUG_CALLPATH_CUDAINSTRUCTION) {
std::cout << "Skip non-gpu prof" << std::endl;
}
return std::vector<GPUAdvisor::AdviceTuple>();
}
GPUAdvisor gpu_advisor(&prof, &metric_name_prof_map);
gpu_advisor.init();
// Read instruction files
for (auto &file: instruction_files) {
if (DEBUG_CALLPATH_CUDAINSTRUCTION) {
std::cout << std::endl;
std::cout << "-------------------------------------------------" << std::endl;
std::cout << "Read instruction file " << file << std::endl;
std::cout << "-------------------------------------------------" << std::endl;
}
std::string lm_name = getLMfromInst(file);
Prof::LoadMap::LMSet_nm::iterator lm_iter;
if ((lm_iter = prof.loadmap()->lm_find(lm_name)) == prof.loadmap()->lm_end_nm()) {
if (DEBUG_CALLPATH_CUDAINSTRUCTION) {
std::cout << "Instruction file module " << lm_name << " not found " << std::endl;
}
continue;
}
Prof::LoadMap::LMId_t lm_id = (*lm_iter)->id();
// Step 1: Read metrics
std::vector<CudaParse::Function *> functions;
CudaParse::readCudaInstructions(file, functions);
// Step 2: Sort the instructions by PC
// Assign absolute addresses to instructions
CudaParse::relocateCudaInstructionStats(functions);
std::vector<CudaParse::InstructionStat *> inst_stats;
// Put instructions to a vector
CudaParse::flatCudaInstructionStats(functions, inst_stats);
// Step 3: Find new metric names and insert new mappings between from name to prof metric ids
createMetrics(inst_stats, metric_name_prof_map, *mgr);
// Step 4: Gather all CCT nodes with lm_id and find GPU roots
std::vector<VMAStmt> vma_stmts;
std::set<Prof::CCT::ADynNode *> gpu_kernels;
std::vector<int> gpu_kernel_index = metric_name_prof_map.metric_ids(GPU_KERNEL_METRIC_NAME);
auto *prof_root = prof.cct()->root();
gatherStmts(lm_id, inst_stats.front()->pc, inst_stats.back()->pc,
prof_root, vma_stmts, gpu_kernel_index, gpu_kernels);
// Step 5: Lay metrics over prof tree
associateInstStmts(vma_stmts, inst_stats, metric_name_prof_map);
gpu_advisor.configInst(lm_name, functions);
// Step 6: Make advise
// Find each GPU calling context, make recommendation for each calling context
for (auto *gpu_kernel : gpu_kernels) {
auto *gpu_root = dynamic_cast<Prof::CCT::ADynNode *>(gpu_kernel->parent());
// Pass current gpu root
gpu_advisor.configGPURoot(gpu_root, gpu_kernel);
// <mpi_rank, <thread_id, <blames>>>
CCTBlames cct_blames;
// Blame latencies
gpu_advisor.blame(cct_blames);
// Make advise for the calling context and cache result
gpu_advisor.advise(cct_blames);
}
if (DEBUG_CALLPATH_CUDAINSTRUCTION) {
std::cout << "Finish reading instruction file " << file << std::endl;
}
}
return gpu_advisor.get_advice();
}
} // namespace CallPath
} // namespace Analysis
| 32.47678
| 118
| 0.651001
|
GVProf
|
c686549e94075ae2bd3e6826340080d0b6c3b779
| 230
|
hpp
|
C++
|
src/Client/Engine/ColorRGBA8.hpp
|
fqhd/BuildBattle
|
f85ec857aa232313f4678514aa317af73c37de10
|
[
"MIT"
] | 10
|
2021-08-17T20:55:52.000Z
|
2022-03-28T00:45:14.000Z
|
src/Client/Engine/ColorRGBA8.hpp
|
fqhd/BuildBattle
|
f85ec857aa232313f4678514aa317af73c37de10
|
[
"MIT"
] | null | null | null |
src/Client/Engine/ColorRGBA8.hpp
|
fqhd/BuildBattle
|
f85ec857aa232313f4678514aa317af73c37de10
|
[
"MIT"
] | 2
|
2021-07-05T18:49:56.000Z
|
2021-07-10T22:03:17.000Z
|
#pragma once
struct ColorRGBA8 {
ColorRGBA8(){}
ColorRGBA8(GLubyte _r, GLubyte _g, GLubyte _b, GLubyte _a){
r = _r;
g = _g;
b = _b;
a = _a;
}
GLubyte r = 255;
GLubyte g = 255;
GLubyte b = 255;
GLubyte a = 255;
};
| 13.529412
| 60
| 0.6
|
fqhd
|
c68f67f41bd3d3996a1bd1f105b18fd3fbc53d39
| 216
|
cpp
|
C++
|
EndScaneHook.cpp
|
Sanceilaks/LemiGMOD
|
60a605527c870648b73de3f94feb37c0e933088d
|
[
"Apache-2.0"
] | 2
|
2021-06-21T14:20:12.000Z
|
2021-09-02T01:47:50.000Z
|
EndScaneHook.cpp
|
Sanceilaks/LemiGMOD
|
60a605527c870648b73de3f94feb37c0e933088d
|
[
"Apache-2.0"
] | 1
|
2020-10-23T02:38:21.000Z
|
2020-12-14T03:57:30.000Z
|
EndScaneHook.cpp
|
Sanceilaks/LemiGMOD
|
60a605527c870648b73de3f94feb37c0e933088d
|
[
"Apache-2.0"
] | null | null | null |
#include "EndScaneHook.h"
#include "Render.h"
void __stdcall MyHooks::EndScane(IDirect3DDevice9* device)
{
if (!isInit)
{
Render::Get().Init(device);
isInit = true;
}
else
Render::Get().NewFrame(device);
}
| 16.615385
| 58
| 0.685185
|
Sanceilaks
|
c69635a5f73054eddae6b8bc3f87881a0ef7ce1d
| 1,212
|
cpp
|
C++
|
codechef/dementia/c.cpp
|
xenowits/cp
|
963b3c7df65b5328d5ce5ef894a46691afefb98c
|
[
"MIT"
] | null | null | null |
codechef/dementia/c.cpp
|
xenowits/cp
|
963b3c7df65b5328d5ce5ef894a46691afefb98c
|
[
"MIT"
] | null | null | null |
codechef/dementia/c.cpp
|
xenowits/cp
|
963b3c7df65b5328d5ce5ef894a46691afefb98c
|
[
"MIT"
] | null | null | null |
#include<bits/stdc++.h>
using namespace std;
#define fori(i,a,b) for (long int i = a; i <= b ; ++i)
#define ford(i,a,b) for(long int i = a;i >= b ; --i)
#define mk make_pair
#define mod 1000000007
#define pb push_back
#define ll long long
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n;
cin >> n;
long a[n+1];
fori(i,0,n-1)
cin >> a[i];
if (n == 1)
{
cout << 1 << endl << "L";
return 0;
}
string s = "";
int j = n-1,temp = -1;
for(int i = 0; i < n && i <= j;)
{
if (a[i] > temp && a[j] > temp)
{
if ((a[i]-temp) < (a[j]-temp))
{
temp = a[i];
s += 'L';
i += 1;
//cout << "yeah" << endl;
}
else
{
temp = a[j];
s += 'R';
j -= 1;
//cout << "wahha" << endl;
}
}
else if (a[j] > temp)
{
s += 'R';
temp = a[j];
j -= 1;
//cout << "kaha" << endl;
}
else if (a[i] > temp)
{
s += 'L';
temp = a[i];
i += 1;
//cout << "jaha" << endl;
}
else
{
//cout << "chutiye" << i << j << temp << endl;
break;
}
}
cout << s.length() << endl << s;
return 0;
}
| 17.565217
| 54
| 0.39604
|
xenowits
|
578d31e26ac74af8205c2605ddafaba6e273609c
| 786
|
hxx
|
C++
|
source/lib/public/LibPtv/TypeMemberPadding.hxx
|
selmentdev/pdb-type-viewer
|
d348aaeb04a8f15c2f09dbda95f5010f1d6709e1
|
[
"MIT"
] | 12
|
2019-06-19T05:22:34.000Z
|
2022-01-18T10:55:37.000Z
|
source/lib/public/LibPtv/TypeMemberPadding.hxx
|
selmentdev/pdb-type-viewer
|
d348aaeb04a8f15c2f09dbda95f5010f1d6709e1
|
[
"MIT"
] | 14
|
2019-06-22T14:12:24.000Z
|
2020-04-14T14:02:55.000Z
|
source/lib/public/LibPtv/TypeMemberPadding.hxx
|
selmentdev/pdb-type-viewer
|
d348aaeb04a8f15c2f09dbda95f5010f1d6709e1
|
[
"MIT"
] | 2
|
2021-03-13T02:21:16.000Z
|
2021-03-13T03:23:44.000Z
|
#pragma once
#include <LibPtv/BaseTypeMember.hxx>
namespace LibPdb
{
class TypeMemberPadding : public BaseTypeMember
{
private:
bool m_IsSpurious;
public:
TypeMemberPadding(
uint64_t size,
uint64_t offset
) noexcept
: BaseTypeMember{ size, offset }
, m_IsSpurious{ false }
{
}
virtual ~TypeMemberPadding() noexcept = default;
public:
virtual MemberType GetMemberType() const noexcept override
{
return MemberType::Padding;
}
void SetSpurious(bool value) noexcept
{
m_IsSpurious = value;
}
bool IsSpurious() const noexcept
{
return m_IsSpurious;
}
};
}
| 19.65
| 66
| 0.548346
|
selmentdev
|
578ea0d6edbd2fb994a449755c12776b2b7ea7f2
| 2,031
|
cpp
|
C++
|
test/burst/integer/to_unsigned.cpp
|
izvolov/thrust
|
399e12eed54131d731c4c5ef40512b17107bca56
|
[
"BSL-1.0"
] | 85
|
2015-11-25T14:05:42.000Z
|
2021-11-15T11:47:19.000Z
|
test/burst/integer/to_unsigned.cpp
|
izvolov/burst
|
399e12eed54131d731c4c5ef40512b17107bca56
|
[
"BSL-1.0"
] | 147
|
2015-01-11T08:36:53.000Z
|
2021-11-04T09:03:36.000Z
|
test/burst/integer/to_unsigned.cpp
|
izvolov/thrust
|
399e12eed54131d731c4c5ef40512b17107bca56
|
[
"BSL-1.0"
] | 6
|
2016-06-02T17:28:26.000Z
|
2020-04-05T11:16:16.000Z
|
#include <burst/integer/to_unsigned.hpp>
#include <doctest/doctest.h>
#include <boost/mpl/vector.hpp>
#include <limits>
#include <type_traits>
TEST_SUITE("to_unsigned")
{
TEST_CASE_TEMPLATE("Сдвигает область знакового целого так, чтобы она совпадала с областью "
"равного по размеру беззнакового целого", signed_integer_type,
char, signed char, short, int, long, long long)
{
using unsigned_integer_type = std::make_unsigned_t<signed_integer_type>;
CHECK
(
burst::to_unsigned(std::numeric_limits<signed_integer_type>::min()) ==
std::numeric_limits<unsigned_integer_type>::min()
);
CHECK
(
burst::to_unsigned(std::numeric_limits<signed_integer_type>::max()) ==
std::numeric_limits<unsigned_integer_type>::max()
);
CHECK
(
burst::to_unsigned(signed_integer_type{0}) ==
std::numeric_limits<unsigned_integer_type>::max() / 2 + 1
);
}
TEST_CASE_TEMPLATE("Беззнаковые целые оставляются без изменений", unsigned_integer_type,
unsigned char, unsigned short, unsigned, unsigned long, unsigned long long)
{
CHECK
(
burst::to_unsigned(std::numeric_limits<unsigned_integer_type>::min()) ==
std::numeric_limits<unsigned_integer_type>::min()
);
CHECK
(
burst::to_unsigned(std::numeric_limits<unsigned_integer_type>::max()) ==
std::numeric_limits<unsigned_integer_type>::max()
);
CHECK
(
burst::to_unsigned(unsigned_integer_type{0}) ==
unsigned_integer_type{0}
);
CHECK
(
burst::to_unsigned(unsigned_integer_type{1}) ==
unsigned_integer_type{1}
);
}
TEST_CASE("Может быть вычислена на этапе компиляции")
{
constexpr auto r = burst::to_unsigned(-1);
static_assert(r == std::numeric_limits<unsigned>::max () / 2, "");
}
}
| 31.246154
| 95
| 0.60906
|
izvolov
|
5790661be8c6fa562ee284d41470e7d0421ae79c
| 332
|
hpp
|
C++
|
Triforce - Index Buffers/VAO.hpp
|
Yaboi-Gengarboi/OpenGL-Projects
|
17171a5e7e6344b97346c2d9c1a4a5d7c165f480
|
[
"Unlicense"
] | null | null | null |
Triforce - Index Buffers/VAO.hpp
|
Yaboi-Gengarboi/OpenGL-Projects
|
17171a5e7e6344b97346c2d9c1a4a5d7c165f480
|
[
"Unlicense"
] | null | null | null |
Triforce - Index Buffers/VAO.hpp
|
Yaboi-Gengarboi/OpenGL-Projects
|
17171a5e7e6344b97346c2d9c1a4a5d7c165f480
|
[
"Unlicense"
] | null | null | null |
// OpenGL-Projects
// Triforce - Index Buffers
// VAO.hpp
// File created on 2021-09-24 by Justyn Durnford
// File last modified on 2021-09-24 by Justyn Durnford
#pragma once
#include "VBO.hpp"
class VAO
{
public:
GLuint id;
VAO();
void linkVBO(VBO vbo, GLuint layout);
void bind();
void unbind();
void destroy();
};
| 12.769231
| 54
| 0.677711
|
Yaboi-Gengarboi
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.