hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
9d1fcdede8b9ede7c6c9b8b9361fb2bc24a93702
30,733
cc
C++
src/test/libcephfs/recordlock.cc
rpratap-bot/ceph
9834961a66927ae856935591f2fd51082e2ee484
[ "MIT" ]
4
2020-04-08T03:42:02.000Z
2020-10-01T20:34:48.000Z
src/test/libcephfs/recordlock.cc
rpratap-bot/ceph
9834961a66927ae856935591f2fd51082e2ee484
[ "MIT" ]
93
2020-03-26T14:29:14.000Z
2020-11-12T05:54:55.000Z
src/test/libcephfs/recordlock.cc
rpratap-bot/ceph
9834961a66927ae856935591f2fd51082e2ee484
[ "MIT" ]
23
2020-03-24T10:28:44.000Z
2020-09-24T09:42:19.000Z
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2011 New Dream Network * 2016 Red Hat * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include <pthread.h> #include "gtest/gtest.h" #ifndef GTEST_IS_THREADSAFE #error "!GTEST_IS_THREADSAFE" #endif #include "include/cephfs/libcephfs.h" #include <errno.h> #include <sys/fcntl.h> #include <unistd.h> #include <sys/file.h> #include <sys/types.h> #include <sys/stat.h> #include <dirent.h> #include <sys/xattr.h> #include <stdlib.h> #include <semaphore.h> #include <time.h> #include <sys/mman.h> #ifdef __linux__ #include <limits.h> #endif #include "include/ceph_assert.h" // Startup common: create and mount ceph fs #define STARTUP_CEPH() do { \ ASSERT_EQ(0, ceph_create(&cmount, NULL)); \ ASSERT_EQ(0, ceph_conf_read_file(cmount, NULL)); \ ASSERT_EQ(0, ceph_conf_parse_env(cmount, NULL)); \ ASSERT_EQ(0, ceph_mount(cmount, NULL)); \ } while(0) // Cleanup common: unmount and release ceph fs #define CLEANUP_CEPH() do { \ ASSERT_EQ(0, ceph_unmount(cmount)); \ ASSERT_EQ(0, ceph_release(cmount)); \ } while(0) static const mode_t fileMode = S_IRWXU | S_IRWXG | S_IRWXO; // Default wait time for normal and "slow" operations // (5" should be enough in case of network congestion) static const long waitMs = 10; static const long waitSlowMs = 5000; // Get the absolute struct timespec reference from now + 'ms' milliseconds static const struct timespec* abstime(struct timespec &ts, long ms) { if (clock_gettime(CLOCK_REALTIME, &ts) == -1) { ceph_abort(); } ts.tv_nsec += ms * 1000000; ts.tv_sec += ts.tv_nsec / 1000000000; ts.tv_nsec %= 1000000000; return &ts; } /* Basic locking */ TEST(LibCephFS, BasicRecordLocking) { struct ceph_mount_info *cmount = NULL; STARTUP_CEPH(); char c_file[1024]; sprintf(c_file, "recordlock_test_%d", getpid()); Fh *fh = NULL; Inode *root = NULL, *inode = NULL; struct ceph_statx stx; int rc; struct flock lock1, lock2; UserPerm *perms = ceph_mount_perms(cmount); // Get the root inode rc = ceph_ll_lookup_root(cmount, &root); ASSERT_EQ(rc, 0); // Get the inode and Fh corresponding to c_file rc = ceph_ll_create(cmount, root, c_file, fileMode, O_RDWR | O_CREAT, &inode, &fh, &stx, 0, 0, perms); ASSERT_EQ(rc, 0); // write lock twice lock1.l_type = F_WRLCK; lock1.l_whence = SEEK_SET; lock1.l_start = 0; lock1.l_len = 1024; lock1.l_pid = getpid(); ASSERT_EQ(0, ceph_ll_setlk(cmount, fh, &lock1, 42, false)); lock2.l_type = F_WRLCK; lock2.l_whence = SEEK_SET; lock2.l_start = 0; lock2.l_len = 1024; lock2.l_pid = getpid(); ASSERT_EQ(-EAGAIN, ceph_ll_setlk(cmount, fh, &lock2, 43, false)); // Now try a conflicting read lock lock2.l_type = F_RDLCK; lock2.l_whence = SEEK_SET; lock2.l_start = 100; lock2.l_len = 100; lock2.l_pid = getpid(); ASSERT_EQ(-EAGAIN, ceph_ll_setlk(cmount, fh, &lock2, 43, false)); // Now do a getlk ASSERT_EQ(0, ceph_ll_getlk(cmount, fh, &lock2, 43)); ASSERT_EQ(lock2.l_type, F_WRLCK); ASSERT_EQ(lock2.l_start, 0); ASSERT_EQ(lock2.l_len, 1024); ASSERT_EQ(lock2.l_pid, getpid()); // Extend the range of the write lock lock1.l_type = F_WRLCK; lock1.l_whence = SEEK_SET; lock1.l_start = 1024; lock1.l_len = 1024; lock1.l_pid = getpid(); ASSERT_EQ(0, ceph_ll_setlk(cmount, fh, &lock1, 42, false)); // Now do a getlk lock2.l_type = F_RDLCK; lock2.l_whence = SEEK_SET; lock2.l_start = 100; lock2.l_len = 100; lock2.l_pid = getpid(); ASSERT_EQ(0, ceph_ll_getlk(cmount, fh, &lock2, 43)); ASSERT_EQ(lock2.l_type, F_WRLCK); ASSERT_EQ(lock2.l_start, 0); ASSERT_EQ(lock2.l_len, 2048); ASSERT_EQ(lock2.l_pid, getpid()); // Now release part of the range lock1.l_type = F_UNLCK; lock1.l_whence = SEEK_SET; lock1.l_start = 512; lock1.l_len = 1024; lock1.l_pid = getpid(); ASSERT_EQ(0, ceph_ll_setlk(cmount, fh, &lock1, 42, false)); // Now do a getlk to check 1st part lock2.l_type = F_RDLCK; lock2.l_whence = SEEK_SET; lock2.l_start = 100; lock2.l_len = 100; lock2.l_pid = getpid(); ASSERT_EQ(0, ceph_ll_getlk(cmount, fh, &lock2, 43)); ASSERT_EQ(lock2.l_type, F_WRLCK); ASSERT_EQ(lock2.l_start, 0); ASSERT_EQ(lock2.l_len, 512); ASSERT_EQ(lock2.l_pid, getpid()); // Now do a getlk to check 2nd part lock2.l_type = F_RDLCK; lock2.l_whence = SEEK_SET; lock2.l_start = 2000; lock2.l_len = 100; lock2.l_pid = getpid(); ASSERT_EQ(0, ceph_ll_getlk(cmount, fh, &lock2, 43)); ASSERT_EQ(lock2.l_type, F_WRLCK); ASSERT_EQ(lock2.l_start, 1536); ASSERT_EQ(lock2.l_len, 512); ASSERT_EQ(lock2.l_pid, getpid()); // Now do a getlk to check released part lock2.l_type = F_RDLCK; lock2.l_whence = SEEK_SET; lock2.l_start = 512; lock2.l_len = 1024; lock2.l_pid = getpid(); ASSERT_EQ(0, ceph_ll_getlk(cmount, fh, &lock2, 43)); ASSERT_EQ(lock2.l_type, F_UNLCK); ASSERT_EQ(lock2.l_start, 512); ASSERT_EQ(lock2.l_len, 1024); ASSERT_EQ(lock2.l_pid, getpid()); // Now downgrade the 1st part of the lock lock1.l_type = F_RDLCK; lock1.l_whence = SEEK_SET; lock1.l_start = 0; lock1.l_len = 512; lock1.l_pid = getpid(); ASSERT_EQ(0, ceph_ll_setlk(cmount, fh, &lock1, 42, false)); // Now do a getlk to check 1st part lock2.l_type = F_WRLCK; lock2.l_whence = SEEK_SET; lock2.l_start = 100; lock2.l_len = 100; lock2.l_pid = getpid(); ASSERT_EQ(0, ceph_ll_getlk(cmount, fh, &lock2, 43)); ASSERT_EQ(lock2.l_type, F_RDLCK); ASSERT_EQ(lock2.l_start, 0); ASSERT_EQ(lock2.l_len, 512); ASSERT_EQ(lock2.l_pid, getpid()); // Now upgrade the 1st part of the lock lock1.l_type = F_WRLCK; lock1.l_whence = SEEK_SET; lock1.l_start = 0; lock1.l_len = 512; lock1.l_pid = getpid(); ASSERT_EQ(0, ceph_ll_setlk(cmount, fh, &lock1, 42, false)); // Now do a getlk to check 1st part lock2.l_type = F_WRLCK; lock2.l_whence = SEEK_SET; lock2.l_start = 100; lock2.l_len = 100; lock2.l_pid = getpid(); ASSERT_EQ(0, ceph_ll_getlk(cmount, fh, &lock2, 43)); ASSERT_EQ(lock2.l_type, F_WRLCK); ASSERT_EQ(lock2.l_start, 0); ASSERT_EQ(lock2.l_len, 512); ASSERT_EQ(lock2.l_pid, getpid()); ASSERT_EQ(0, ceph_ll_close(cmount, fh)); ASSERT_EQ(0, ceph_ll_unlink(cmount, root, c_file, perms)); CLEANUP_CEPH(); } /* Locking in different threads */ // Used by ConcurrentLocking test struct str_ConcurrentRecordLocking { const char *file; struct ceph_mount_info *cmount; // !NULL if shared sem_t sem[2]; sem_t semReply[2]; void sem_init(int pshared) { ASSERT_EQ(0, ::sem_init(&sem[0], pshared, 0)); ASSERT_EQ(0, ::sem_init(&sem[1], pshared, 0)); ASSERT_EQ(0, ::sem_init(&semReply[0], pshared, 0)); ASSERT_EQ(0, ::sem_init(&semReply[1], pshared, 0)); } void sem_destroy() { ASSERT_EQ(0, ::sem_destroy(&sem[0])); ASSERT_EQ(0, ::sem_destroy(&sem[1])); ASSERT_EQ(0, ::sem_destroy(&semReply[0])); ASSERT_EQ(0, ::sem_destroy(&semReply[1])); } }; // Wakeup main (for (N) steps) #define PING_MAIN(n) ASSERT_EQ(0, sem_post(&s.sem[n%2])) // Wait for main to wake us up (for (RN) steps) #define WAIT_MAIN(n) \ ASSERT_EQ(0, sem_timedwait(&s.semReply[n%2], abstime(ts, waitSlowMs))) // Wakeup worker (for (RN) steps) #define PING_WORKER(n) ASSERT_EQ(0, sem_post(&s.semReply[n%2])) // Wait for worker to wake us up (for (N) steps) #define WAIT_WORKER(n) \ ASSERT_EQ(0, sem_timedwait(&s.sem[n%2], abstime(ts, waitSlowMs))) // Worker shall not wake us up (for (N) steps) #define NOT_WAIT_WORKER(n) \ ASSERT_EQ(-1, sem_timedwait(&s.sem[n%2], abstime(ts, waitMs))) // Do twice an operation #define TWICE(EXPR) do { \ EXPR; \ EXPR; \ } while(0) /* Locking in different threads */ // Used by ConcurrentLocking test static void thread_ConcurrentRecordLocking(str_ConcurrentRecordLocking& s) { struct ceph_mount_info *const cmount = s.cmount; Fh *fh = NULL; Inode *root = NULL, *inode = NULL; struct ceph_statx stx; struct flock lock1; int rc; struct timespec ts; // Get the root inode rc = ceph_ll_lookup_root(cmount, &root); ASSERT_EQ(rc, 0); // Get the inode and Fh corresponding to c_file rc = ceph_ll_create(cmount, root, s.file, fileMode, O_RDWR | O_CREAT, &inode, &fh, &stx, 0, 0, ceph_mount_perms(cmount)); ASSERT_EQ(rc, 0); lock1.l_type = F_WRLCK; lock1.l_whence = SEEK_SET; lock1.l_start = 0; lock1.l_len = 1024; lock1.l_pid = getpid(); ASSERT_EQ(-EAGAIN, ceph_ll_setlk(cmount, fh, &lock1, pthread_self(), false)); PING_MAIN(1); // (1) lock1.l_type = F_WRLCK; lock1.l_whence = SEEK_SET; lock1.l_start = 0; lock1.l_len = 1024; lock1.l_pid = getpid(); ASSERT_EQ(0, ceph_ll_setlk(cmount, fh, &lock1, pthread_self(), true)); PING_MAIN(2); // (2) lock1.l_type = F_UNLCK; lock1.l_whence = SEEK_SET; lock1.l_start = 0; lock1.l_len = 1024; lock1.l_pid = getpid(); ASSERT_EQ(0, ceph_ll_setlk(cmount, fh, &lock1, pthread_self(), false)); PING_MAIN(3); // (3) lock1.l_type = F_RDLCK; lock1.l_whence = SEEK_SET; lock1.l_start = 0; lock1.l_len = 1024; lock1.l_pid = getpid(); ASSERT_EQ(0, ceph_ll_setlk(cmount, fh, &lock1, pthread_self(), true)); PING_MAIN(4); // (4) WAIT_MAIN(1); // (R1) lock1.l_type = F_UNLCK; lock1.l_whence = SEEK_SET; lock1.l_start = 0; lock1.l_len = 1024; lock1.l_pid = getpid(); ASSERT_EQ(0, ceph_ll_setlk(cmount, fh, &lock1, pthread_self(), false)); PING_MAIN(5); // (5) WAIT_MAIN(2); // (R2) lock1.l_type = F_WRLCK; lock1.l_whence = SEEK_SET; lock1.l_start = 0; lock1.l_len = 1024; lock1.l_pid = getpid(); ASSERT_EQ(0, ceph_ll_setlk(cmount, fh, &lock1, pthread_self(), true)); PING_MAIN(6); // (6) WAIT_MAIN(3); // (R3) lock1.l_type = F_UNLCK; lock1.l_whence = SEEK_SET; lock1.l_start = 0; lock1.l_len = 1024; lock1.l_pid = getpid(); ASSERT_EQ(0, ceph_ll_setlk(cmount, fh, &lock1, pthread_self(), false)); PING_MAIN(7); // (7) ASSERT_EQ(0, ceph_ll_close(cmount, fh)); } // Used by ConcurrentRecordLocking test static void* thread_ConcurrentRecordLocking_(void *arg) { str_ConcurrentRecordLocking *const s = reinterpret_cast<str_ConcurrentRecordLocking*>(arg); thread_ConcurrentRecordLocking(*s); return NULL; } TEST(LibCephFS, ConcurrentRecordLocking) { const pid_t mypid = getpid(); struct ceph_mount_info *cmount; STARTUP_CEPH(); char c_file[1024]; sprintf(c_file, "recordlock_test_%d", mypid); Fh *fh = NULL; Inode *root = NULL, *inode = NULL; struct ceph_statx stx; struct flock lock1; int rc; UserPerm *perms = ceph_mount_perms(cmount); // Get the root inode rc = ceph_ll_lookup_root(cmount, &root); ASSERT_EQ(rc, 0); // Get the inode and Fh corresponding to c_file rc = ceph_ll_create(cmount, root, c_file, fileMode, O_RDWR | O_CREAT, &inode, &fh, &stx, 0, 0, perms); ASSERT_EQ(rc, 0); // Lock lock1.l_type = F_WRLCK; lock1.l_whence = SEEK_SET; lock1.l_start = 0; lock1.l_len = 1024; lock1.l_pid = getpid(); ASSERT_EQ(0, ceph_ll_setlk(cmount, fh, &lock1, pthread_self(), true)); // Start locker thread pthread_t thread; struct timespec ts; str_ConcurrentRecordLocking s = { c_file, cmount }; s.sem_init(0); ASSERT_EQ(0, pthread_create(&thread, NULL, thread_ConcurrentRecordLocking_, &s)); // Synchronization point with thread (failure: thread is dead) WAIT_WORKER(1); // (1) // Shall not have lock immediately NOT_WAIT_WORKER(2); // (2) // Unlock lock1.l_type = F_UNLCK; lock1.l_whence = SEEK_SET; lock1.l_start = 0; lock1.l_len = 1024; lock1.l_pid = getpid(); ASSERT_EQ(0, ceph_ll_setlk(cmount, fh, &lock1, pthread_self(), false)); // Shall have lock // Synchronization point with thread (failure: thread is dead) WAIT_WORKER(2); // (2) // Synchronization point with thread (failure: thread is dead) WAIT_WORKER(3); // (3) // Wait for thread to share lock WAIT_WORKER(4); // (4) lock1.l_type = F_WRLCK; lock1.l_whence = SEEK_SET; lock1.l_start = 0; lock1.l_len = 1024; lock1.l_pid = getpid(); ASSERT_EQ(-EAGAIN, ceph_ll_setlk(cmount, fh, &lock1, pthread_self(), false)); lock1.l_type = F_RDLCK; lock1.l_whence = SEEK_SET; lock1.l_start = 0; lock1.l_len = 1024; lock1.l_pid = getpid(); ASSERT_EQ(0, ceph_ll_setlk(cmount, fh, &lock1, pthread_self(), false)); // Wake up thread to unlock shared lock PING_WORKER(1); // (R1) WAIT_WORKER(5); // (5) // Now we can lock exclusively // Upgrade to exclusive lock (as per POSIX) lock1.l_type = F_WRLCK; lock1.l_whence = SEEK_SET; lock1.l_start = 0; lock1.l_len = 1024; lock1.l_pid = getpid(); ASSERT_EQ(0, ceph_ll_setlk(cmount, fh, &lock1, pthread_self(), true)); // Wake up thread to lock shared lock PING_WORKER(2); // (R2) // Shall not have lock immediately NOT_WAIT_WORKER(6); // (6) // Release lock ; thread will get it lock1.l_type = F_UNLCK; lock1.l_whence = SEEK_SET; lock1.l_start = 0; lock1.l_len = 1024; lock1.l_pid = getpid(); ASSERT_EQ(0, ceph_ll_setlk(cmount, fh, &lock1, pthread_self(), false)); WAIT_WORKER(6); // (6) // We no longer have the lock lock1.l_type = F_WRLCK; lock1.l_whence = SEEK_SET; lock1.l_start = 0; lock1.l_len = 1024; lock1.l_pid = getpid(); ASSERT_EQ(-EAGAIN, ceph_ll_setlk(cmount, fh, &lock1, pthread_self(), false)); lock1.l_type = F_RDLCK; lock1.l_whence = SEEK_SET; lock1.l_start = 0; lock1.l_len = 1024; lock1.l_pid = getpid(); ASSERT_EQ(-EAGAIN, ceph_ll_setlk(cmount, fh, &lock1, pthread_self(), false)); // Wake up thread to unlock exclusive lock PING_WORKER(3); // (R3) WAIT_WORKER(7); // (7) // We can lock it again lock1.l_type = F_WRLCK; lock1.l_whence = SEEK_SET; lock1.l_start = 0; lock1.l_len = 1024; lock1.l_pid = getpid(); ASSERT_EQ(0, ceph_ll_setlk(cmount, fh, &lock1, pthread_self(), false)); lock1.l_type = F_UNLCK; lock1.l_whence = SEEK_SET; lock1.l_start = 0; lock1.l_len = 1024; lock1.l_pid = getpid(); ASSERT_EQ(0, ceph_ll_setlk(cmount, fh, &lock1, pthread_self(), false)); // Cleanup void *retval = (void*) (uintptr_t) -1; ASSERT_EQ(0, pthread_join(thread, &retval)); ASSERT_EQ(NULL, retval); s.sem_destroy(); ASSERT_EQ(0, ceph_ll_close(cmount, fh)); ASSERT_EQ(0, ceph_ll_unlink(cmount, root, c_file, perms)); CLEANUP_CEPH(); } TEST(LibCephFS, ThreesomeRecordLocking) { const pid_t mypid = getpid(); struct ceph_mount_info *cmount; STARTUP_CEPH(); char c_file[1024]; sprintf(c_file, "recordlock_test_%d", mypid); Fh *fh = NULL; Inode *root = NULL, *inode = NULL; struct ceph_statx stx; struct flock lock1; int rc; UserPerm *perms = ceph_mount_perms(cmount); // Get the root inode rc = ceph_ll_lookup_root(cmount, &root); ASSERT_EQ(rc, 0); // Get the inode and Fh corresponding to c_file rc = ceph_ll_create(cmount, root, c_file, fileMode, O_RDWR | O_CREAT, &inode, &fh, &stx, 0, 0, perms); ASSERT_EQ(rc, 0); // Lock lock1.l_type = F_WRLCK; lock1.l_whence = SEEK_SET; lock1.l_start = 0; lock1.l_len = 1024; lock1.l_pid = getpid(); ASSERT_EQ(0, ceph_ll_setlk(cmount, fh, &lock1, pthread_self(), true)); // Start locker thread pthread_t thread[2]; struct timespec ts; str_ConcurrentRecordLocking s = { c_file, cmount }; s.sem_init(0); ASSERT_EQ(0, pthread_create(&thread[0], NULL, thread_ConcurrentRecordLocking_, &s)); ASSERT_EQ(0, pthread_create(&thread[1], NULL, thread_ConcurrentRecordLocking_, &s)); // Synchronization point with thread (failure: thread is dead) TWICE(WAIT_WORKER(1)); // (1) // Shall not have lock immediately NOT_WAIT_WORKER(2); // (2) // Unlock lock1.l_type = F_UNLCK; lock1.l_whence = SEEK_SET; lock1.l_start = 0; lock1.l_len = 1024; lock1.l_pid = getpid(); ASSERT_EQ(0, ceph_ll_setlk(cmount, fh, &lock1, pthread_self(), false)); // Shall have lock TWICE(// Synchronization point with thread (failure: thread is dead) WAIT_WORKER(2); // (2) // Synchronization point with thread (failure: thread is dead) WAIT_WORKER(3)); // (3) // Wait for thread to share lock TWICE(WAIT_WORKER(4)); // (4) lock1.l_type = F_WRLCK; lock1.l_whence = SEEK_SET; lock1.l_start = 0; lock1.l_len = 1024; lock1.l_pid = getpid(); ASSERT_EQ(-EAGAIN, ceph_ll_setlk(cmount, fh, &lock1, pthread_self(), false)); lock1.l_type = F_RDLCK; lock1.l_whence = SEEK_SET; lock1.l_start = 0; lock1.l_len = 1024; lock1.l_pid = getpid(); ASSERT_EQ(0, ceph_ll_setlk(cmount, fh, &lock1, pthread_self(), false)); // Wake up thread to unlock shared lock TWICE(PING_WORKER(1); // (R1) WAIT_WORKER(5)); // (5) // Now we can lock exclusively // Upgrade to exclusive lock (as per POSIX) lock1.l_type = F_WRLCK; lock1.l_whence = SEEK_SET; lock1.l_start = 0; lock1.l_len = 1024; lock1.l_pid = getpid(); ASSERT_EQ(0, ceph_ll_setlk(cmount, fh, &lock1, pthread_self(), true)); TWICE( // Wake up thread to lock shared lock PING_WORKER(2); // (R2) // Shall not have lock immediately NOT_WAIT_WORKER(6)); // (6) // Release lock ; thread will get it lock1.l_type = F_UNLCK; lock1.l_whence = SEEK_SET; lock1.l_start = 0; lock1.l_len = 1024; lock1.l_pid = getpid(); ASSERT_EQ(0, ceph_ll_setlk(cmount, fh, &lock1, pthread_self(), false)); TWICE(WAIT_WORKER(6); // (6) // We no longer have the lock lock1.l_type = F_WRLCK; lock1.l_whence = SEEK_SET; lock1.l_start = 0; lock1.l_len = 1024; lock1.l_pid = getpid(); ASSERT_EQ(-EAGAIN, ceph_ll_setlk(cmount, fh, &lock1, pthread_self(), false)); lock1.l_type = F_RDLCK; lock1.l_whence = SEEK_SET; lock1.l_start = 0; lock1.l_len = 1024; lock1.l_pid = getpid(); ASSERT_EQ(-EAGAIN, ceph_ll_setlk(cmount, fh, &lock1, pthread_self(), false)); // Wake up thread to unlock exclusive lock PING_WORKER(3); // (R3) WAIT_WORKER(7); // (7) ); // We can lock it again lock1.l_type = F_WRLCK; lock1.l_whence = SEEK_SET; lock1.l_start = 0; lock1.l_len = 1024; lock1.l_pid = getpid(); ASSERT_EQ(0, ceph_ll_setlk(cmount, fh, &lock1, pthread_self(), false)); lock1.l_type = F_UNLCK; lock1.l_whence = SEEK_SET; lock1.l_start = 0; lock1.l_len = 1024; lock1.l_pid = getpid(); ASSERT_EQ(0, ceph_ll_setlk(cmount, fh, &lock1, pthread_self(), false)); // Cleanup void *retval = (void*) (uintptr_t) -1; ASSERT_EQ(0, pthread_join(thread[0], &retval)); ASSERT_EQ(NULL, retval); ASSERT_EQ(0, pthread_join(thread[1], &retval)); ASSERT_EQ(NULL, retval); s.sem_destroy(); ASSERT_EQ(0, ceph_ll_close(cmount, fh)); ASSERT_EQ(0, ceph_ll_unlink(cmount, root, c_file, perms)); CLEANUP_CEPH(); } /* Locking in different processes */ #define PROCESS_SLOW_MS() \ static const long waitMs = 100; \ (void) waitMs // Used by ConcurrentLocking test static void process_ConcurrentRecordLocking(str_ConcurrentRecordLocking& s) { const pid_t mypid = getpid(); PROCESS_SLOW_MS(); struct ceph_mount_info *cmount = NULL; struct timespec ts; Fh *fh = NULL; Inode *root = NULL, *inode = NULL; struct ceph_statx stx; int rc; struct flock lock1; STARTUP_CEPH(); s.cmount = cmount; // Get the root inode rc = ceph_ll_lookup_root(cmount, &root); ASSERT_EQ(rc, 0); // Get the inode and Fh corresponding to c_file rc = ceph_ll_create(cmount, root, s.file, fileMode, O_RDWR | O_CREAT, &inode, &fh, &stx, 0, 0, ceph_mount_perms(cmount)); ASSERT_EQ(rc, 0); WAIT_MAIN(1); // (R1) lock1.l_type = F_WRLCK; lock1.l_whence = SEEK_SET; lock1.l_start = 0; lock1.l_len = 1024; lock1.l_pid = getpid(); ASSERT_EQ(-EAGAIN, ceph_ll_setlk(cmount, fh, &lock1, mypid, false)); PING_MAIN(1); // (1) lock1.l_type = F_WRLCK; lock1.l_whence = SEEK_SET; lock1.l_start = 0; lock1.l_len = 1024; lock1.l_pid = getpid(); ASSERT_EQ(0, ceph_ll_setlk(cmount, fh, &lock1, mypid, true)); PING_MAIN(2); // (2) lock1.l_type = F_UNLCK; lock1.l_whence = SEEK_SET; lock1.l_start = 0; lock1.l_len = 1024; lock1.l_pid = getpid(); ASSERT_EQ(0, ceph_ll_setlk(cmount, fh, &lock1, mypid, false)); PING_MAIN(3); // (3) lock1.l_type = F_RDLCK; lock1.l_whence = SEEK_SET; lock1.l_start = 0; lock1.l_len = 1024; lock1.l_pid = getpid(); ASSERT_EQ(0, ceph_ll_setlk(cmount, fh, &lock1, mypid, true)); PING_MAIN(4); // (4) WAIT_MAIN(2); // (R2) lock1.l_type = F_UNLCK; lock1.l_whence = SEEK_SET; lock1.l_start = 0; lock1.l_len = 1024; lock1.l_pid = getpid(); ASSERT_EQ(0, ceph_ll_setlk(cmount, fh, &lock1, mypid, false)); PING_MAIN(5); // (5) WAIT_MAIN(3); // (R3) lock1.l_type = F_WRLCK; lock1.l_whence = SEEK_SET; lock1.l_start = 0; lock1.l_len = 1024; lock1.l_pid = getpid(); ASSERT_EQ(0, ceph_ll_setlk(cmount, fh, &lock1, mypid, true)); PING_MAIN(6); // (6) WAIT_MAIN(4); // (R4) lock1.l_type = F_UNLCK; lock1.l_whence = SEEK_SET; lock1.l_start = 0; lock1.l_len = 1024; lock1.l_pid = getpid(); ASSERT_EQ(0, ceph_ll_setlk(cmount, fh, &lock1, mypid, false)); PING_MAIN(7); // (7) ASSERT_EQ(0, ceph_ll_close(cmount, fh)); CLEANUP_CEPH(); s.sem_destroy(); exit(EXIT_SUCCESS); } // Disabled because of fork() issues (http://tracker.ceph.com/issues/16556) TEST(LibCephFS, DISABLED_InterProcessRecordLocking) { PROCESS_SLOW_MS(); // Process synchronization char c_file[1024]; const pid_t mypid = getpid(); sprintf(c_file, "recordlock_test_%d", mypid); Fh *fh = NULL; Inode *root = NULL, *inode = NULL; struct ceph_statx stx; struct flock lock1; int rc; // Note: the semaphores MUST be on a shared memory segment str_ConcurrentRecordLocking *const shs = reinterpret_cast<str_ConcurrentRecordLocking*> (mmap(0, sizeof(*shs), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0)); str_ConcurrentRecordLocking &s = *shs; s.file = c_file; s.sem_init(1); // Start locker process const pid_t pid = fork(); ASSERT_GE(pid, 0); if (pid == 0) { process_ConcurrentRecordLocking(s); exit(EXIT_FAILURE); } struct timespec ts; struct ceph_mount_info *cmount; STARTUP_CEPH(); UserPerm *perms = ceph_mount_perms(cmount); // Get the root inode rc = ceph_ll_lookup_root(cmount, &root); ASSERT_EQ(rc, 0); // Get the inode and Fh corresponding to c_file rc = ceph_ll_create(cmount, root, c_file, fileMode, O_RDWR | O_CREAT, &inode, &fh, &stx, 0, 0, perms); ASSERT_EQ(rc, 0); // Lock lock1.l_type = F_WRLCK; lock1.l_whence = SEEK_SET; lock1.l_start = 0; lock1.l_len = 1024; lock1.l_pid = getpid(); ASSERT_EQ(0, ceph_ll_setlk(cmount, fh, &lock1, mypid, true)); // Synchronization point with process (failure: process is dead) PING_WORKER(1); // (R1) WAIT_WORKER(1); // (1) // Shall not have lock immediately NOT_WAIT_WORKER(2); // (2) // Unlock lock1.l_type = F_UNLCK; lock1.l_whence = SEEK_SET; lock1.l_start = 0; lock1.l_len = 1024; lock1.l_pid = getpid(); ASSERT_EQ(0, ceph_ll_setlk(cmount, fh, &lock1, mypid, false)); // Shall have lock // Synchronization point with process (failure: process is dead) WAIT_WORKER(2); // (2) // Synchronization point with process (failure: process is dead) WAIT_WORKER(3); // (3) // Wait for process to share lock WAIT_WORKER(4); // (4) lock1.l_type = F_WRLCK; lock1.l_whence = SEEK_SET; lock1.l_start = 0; lock1.l_len = 1024; lock1.l_pid = getpid(); ASSERT_EQ(-EAGAIN, ceph_ll_setlk(cmount, fh, &lock1, mypid, false)); lock1.l_type = F_RDLCK; lock1.l_whence = SEEK_SET; lock1.l_start = 0; lock1.l_len = 1024; lock1.l_pid = getpid(); ASSERT_EQ(0, ceph_ll_setlk(cmount, fh, &lock1, mypid, false)); // Wake up process to unlock shared lock PING_WORKER(2); // (R2) WAIT_WORKER(5); // (5) // Now we can lock exclusively // Upgrade to exclusive lock (as per POSIX) lock1.l_type = F_WRLCK; lock1.l_whence = SEEK_SET; lock1.l_start = 0; lock1.l_len = 1024; lock1.l_pid = getpid(); ASSERT_EQ(0, ceph_ll_setlk(cmount, fh, &lock1, mypid, true)); // Wake up process to lock shared lock PING_WORKER(3); // (R3) // Shall not have lock immediately NOT_WAIT_WORKER(6); // (6) // Release lock ; process will get it lock1.l_type = F_UNLCK; lock1.l_whence = SEEK_SET; lock1.l_start = 0; lock1.l_len = 1024; lock1.l_pid = getpid(); ASSERT_EQ(0, ceph_ll_setlk(cmount, fh, &lock1, mypid, false)); WAIT_WORKER(6); // (6) // We no longer have the lock lock1.l_type = F_WRLCK; lock1.l_whence = SEEK_SET; lock1.l_start = 0; lock1.l_len = 1024; lock1.l_pid = getpid(); ASSERT_EQ(-EAGAIN, ceph_ll_setlk(cmount, fh, &lock1, mypid, false)); lock1.l_type = F_RDLCK; lock1.l_whence = SEEK_SET; lock1.l_start = 0; lock1.l_len = 1024; lock1.l_pid = getpid(); ASSERT_EQ(-EAGAIN, ceph_ll_setlk(cmount, fh, &lock1, mypid, false)); // Wake up process to unlock exclusive lock PING_WORKER(4); // (R4) WAIT_WORKER(7); // (7) // We can lock it again lock1.l_type = F_WRLCK; lock1.l_whence = SEEK_SET; lock1.l_start = 0; lock1.l_len = 1024; lock1.l_pid = getpid(); ASSERT_EQ(0, ceph_ll_setlk(cmount, fh, &lock1, mypid, false)); lock1.l_type = F_UNLCK; lock1.l_whence = SEEK_SET; lock1.l_start = 0; lock1.l_len = 1024; lock1.l_pid = getpid(); ASSERT_EQ(0, ceph_ll_setlk(cmount, fh, &lock1, mypid, false)); // Wait pid int status; ASSERT_EQ(pid, waitpid(pid, &status, 0)); ASSERT_EQ(EXIT_SUCCESS, status); // Cleanup s.sem_destroy(); ASSERT_EQ(0, munmap(shs, sizeof(*shs))); ASSERT_EQ(0, ceph_ll_close(cmount, fh)); ASSERT_EQ(0, ceph_ll_unlink(cmount, root, c_file, perms)); CLEANUP_CEPH(); } // Disabled because of fork() issues (http://tracker.ceph.com/issues/16556) TEST(LibCephFS, DISABLED_ThreesomeInterProcessRecordLocking) { PROCESS_SLOW_MS(); // Process synchronization char c_file[1024]; const pid_t mypid = getpid(); sprintf(c_file, "recordlock_test_%d", mypid); Fh *fh = NULL; Inode *root = NULL, *inode = NULL; struct ceph_statx stx; struct flock lock1; int rc; // Note: the semaphores MUST be on a shared memory segment str_ConcurrentRecordLocking *const shs = reinterpret_cast<str_ConcurrentRecordLocking*> (mmap(0, sizeof(*shs), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0)); str_ConcurrentRecordLocking &s = *shs; s.file = c_file; s.sem_init(1); // Start locker processes pid_t pid[2]; pid[0] = fork(); ASSERT_GE(pid[0], 0); if (pid[0] == 0) { process_ConcurrentRecordLocking(s); exit(EXIT_FAILURE); } pid[1] = fork(); ASSERT_GE(pid[1], 0); if (pid[1] == 0) { process_ConcurrentRecordLocking(s); exit(EXIT_FAILURE); } struct timespec ts; struct ceph_mount_info *cmount; STARTUP_CEPH(); // Get the root inode rc = ceph_ll_lookup_root(cmount, &root); ASSERT_EQ(rc, 0); // Get the inode and Fh corresponding to c_file UserPerm *perms = ceph_mount_perms(cmount); rc = ceph_ll_create(cmount, root, c_file, fileMode, O_RDWR | O_CREAT, &inode, &fh, &stx, 0, 0, perms); ASSERT_EQ(rc, 0); // Lock lock1.l_type = F_WRLCK; lock1.l_whence = SEEK_SET; lock1.l_start = 0; lock1.l_len = 1024; lock1.l_pid = getpid(); ASSERT_EQ(0, ceph_ll_setlk(cmount, fh, &lock1, mypid, true)); // Synchronization point with process (failure: process is dead) TWICE(PING_WORKER(1)); // (R1) TWICE(WAIT_WORKER(1)); // (1) // Shall not have lock immediately NOT_WAIT_WORKER(2); // (2) // Unlock lock1.l_type = F_UNLCK; lock1.l_whence = SEEK_SET; lock1.l_start = 0; lock1.l_len = 1024; lock1.l_pid = getpid(); ASSERT_EQ(0, ceph_ll_setlk(cmount, fh, &lock1, mypid, false)); // Shall have lock TWICE(// Synchronization point with process (failure: process is dead) WAIT_WORKER(2); // (2) // Synchronization point with process (failure: process is dead) WAIT_WORKER(3)); // (3) // Wait for process to share lock TWICE(WAIT_WORKER(4)); // (4) lock1.l_type = F_WRLCK; lock1.l_whence = SEEK_SET; lock1.l_start = 0; lock1.l_len = 1024; lock1.l_pid = getpid(); ASSERT_EQ(-EAGAIN, ceph_ll_setlk(cmount, fh, &lock1, mypid, false)); lock1.l_type = F_RDLCK; lock1.l_whence = SEEK_SET; lock1.l_start = 0; lock1.l_len = 1024; lock1.l_pid = getpid(); ASSERT_EQ(0, ceph_ll_setlk(cmount, fh, &lock1, mypid, false)); // Wake up process to unlock shared lock TWICE(PING_WORKER(2); // (R2) WAIT_WORKER(5)); // (5) // Now we can lock exclusively // Upgrade to exclusive lock (as per POSIX) lock1.l_type = F_WRLCK; lock1.l_whence = SEEK_SET; lock1.l_start = 0; lock1.l_len = 1024; lock1.l_pid = getpid(); ASSERT_EQ(0, ceph_ll_setlk(cmount, fh, &lock1, mypid, true)); TWICE( // Wake up process to lock shared lock PING_WORKER(3); // (R3) // Shall not have lock immediately NOT_WAIT_WORKER(6)); // (6) // Release lock ; process will get it lock1.l_type = F_UNLCK; lock1.l_whence = SEEK_SET; lock1.l_start = 0; lock1.l_len = 1024; lock1.l_pid = getpid(); ASSERT_EQ(0, ceph_ll_setlk(cmount, fh, &lock1, mypid, false)); TWICE(WAIT_WORKER(6); // (6) // We no longer have the lock lock1.l_type = F_WRLCK; lock1.l_whence = SEEK_SET; lock1.l_start = 0; lock1.l_len = 1024; lock1.l_pid = getpid(); ASSERT_EQ(-EAGAIN, ceph_ll_setlk(cmount, fh, &lock1, pthread_self(), false)); lock1.l_type = F_RDLCK; lock1.l_whence = SEEK_SET; lock1.l_start = 0; lock1.l_len = 1024; lock1.l_pid = getpid(); ASSERT_EQ(-EAGAIN, ceph_ll_setlk(cmount, fh, &lock1, pthread_self(), false)); // Wake up process to unlock exclusive lock PING_WORKER(4); // (R4) WAIT_WORKER(7); // (7) ); // We can lock it again lock1.l_type = F_WRLCK; lock1.l_whence = SEEK_SET; lock1.l_start = 0; lock1.l_len = 1024; lock1.l_pid = getpid(); ASSERT_EQ(0, ceph_ll_setlk(cmount, fh, &lock1, mypid, false)); lock1.l_type = F_UNLCK; lock1.l_whence = SEEK_SET; lock1.l_start = 0; lock1.l_len = 1024; lock1.l_pid = getpid(); ASSERT_EQ(0, ceph_ll_setlk(cmount, fh, &lock1, mypid, false)); // Wait pids int status; ASSERT_EQ(pid[0], waitpid(pid[0], &status, 0)); ASSERT_EQ(EXIT_SUCCESS, status); ASSERT_EQ(pid[1], waitpid(pid[1], &status, 0)); ASSERT_EQ(EXIT_SUCCESS, status); // Cleanup s.sem_destroy(); ASSERT_EQ(0, munmap(shs, sizeof(*shs))); ASSERT_EQ(0, ceph_ll_close(cmount, fh)); ASSERT_EQ(0, ceph_ll_unlink(cmount, root, c_file, perms)); CLEANUP_CEPH(); }
28.118024
86
0.674682
rpratap-bot
9d20aa453c56549918d0fad19824216d238fc4d3
8,650
cpp
C++
Engine/Source/Runtime/AudioMixer/Private/Effects/AudioMixerSubmixEffectEQ.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
1
2022-01-29T18:36:12.000Z
2022-01-29T18:36:12.000Z
Engine/Source/Runtime/AudioMixer/Private/Effects/AudioMixerSubmixEffectEQ.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
Engine/Source/Runtime/AudioMixer/Private/Effects/AudioMixerSubmixEffectEQ.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #include "SubmixEffects/AudioMixerSubmixEffectEQ.h" #include "Misc/ScopeLock.h" #include "AudioMixer.h" static int32 DisableSubmixEffectEQCvar = 0; FAutoConsoleVariableRef CVarDisableSubmixEQ( TEXT("au.DisableSubmixEffectEQ"), DisableSubmixEffectEQCvar, TEXT("Disables the eq submix.\n") TEXT("0: Not Disabled, 1: Disabled"), ECVF_Default); static bool IsEqual(const FSubmixEffectSubmixEQSettings& Left, const FSubmixEffectSubmixEQSettings& Right) { // return false if the number of bands changed if (Left.EQBands.Num() != Right.EQBands.Num()) { return false; } for (int32 i = 0; i < Right.EQBands.Num(); ++i) { const FSubmixEffectEQBand& OtherBand = Right.EQBands[i]; const FSubmixEffectEQBand& ThisBand = Left.EQBands[i]; if (OtherBand.bEnabled != ThisBand.bEnabled) { return false; } if (!FMath::IsNearlyEqual(OtherBand.Bandwidth, ThisBand.Bandwidth)) { return false; } if (!FMath::IsNearlyEqual(OtherBand.Frequency, ThisBand.Frequency)) { return false; } if (!FMath::IsNearlyEqual(OtherBand.GainDb, ThisBand.GainDb)) { return false; } } // If we made it this far these are equal return true; } FSubmixEffectSubmixEQ::FSubmixEffectSubmixEQ() : SampleRate(0) , NumOutputChannels(2) { FMemory::Memzero((void*)ScratchInBuffer, sizeof(float) * 2); FMemory::Memzero((void*)ScratchOutBuffer, sizeof(float) * 2); } void FSubmixEffectSubmixEQ::Init(const FSoundEffectSubmixInitData& InitData) { SampleRate = InitData.SampleRate; // Assume 8 channels (max supported channels) NumOutputChannels = 8; const int32 NumFilters = NumOutputChannels / 2; for (int32 i = 0; i < NumFilters; ++i) { int32 Index = FiltersPerChannel.Add(FEQ()); } bEQSettingsSet = false; } // Called when an audio effect preset is changed void FSubmixEffectSubmixEQ::OnPresetChanged() { GET_EFFECT_SETTINGS(SubmixEffectSubmixEQ); // Don't make any changes if this is the exact same parameters if (!IsEqual(GameThreadEQSettings, Settings)) { GameThreadEQSettings = Settings; PendingSettings.SetParams(GameThreadEQSettings); } } void FSubmixEffectSubmixEQ::OnProcessAudio(const FSoundEffectSubmixInputData& InData, FSoundEffectSubmixOutputData& OutData) { SCOPE_CYCLE_COUNTER(STAT_AudioMixerMasterEQ); // Update parameters that may have been set from game thread UpdateParameters(InData.NumChannels); Audio::AlignedFloatBuffer& InAudioBuffer = *InData.AudioBuffer; Audio::AlignedFloatBuffer& OutAudioBuffer = *OutData.AudioBuffer; if (bEQSettingsSet && !DisableSubmixEffectEQCvar && RenderThreadEQSettings.EQBands.Num() > 0) { // Feed every other channel through the EQ filters int32 NumFilters = InData.NumChannels / 2; for (int32 FilterIndex = 0; FilterIndex < NumFilters; ++FilterIndex) { FEQ& EQFilter = FiltersPerChannel[FilterIndex]; const int32 ChannelOffset = FilterIndex * 2; for (int32 FrameIndex = 0; FrameIndex < InData.NumFrames; ++FrameIndex) { // Get the sample index of this frame for this filter const int32 SampleIndex = FrameIndex * InData.NumChannels + ChannelOffset; // Copy the audio from the input buffer for this frame ScratchInBuffer[0] = InAudioBuffer[SampleIndex]; ScratchInBuffer[1] = InAudioBuffer[SampleIndex + 1]; const int32 NumBands = EQFilter.Bands.Num(); for (int32 BandIndex = 0; BandIndex < NumBands; ++BandIndex) { EQFilter.Bands[BandIndex].ProcessAudioFrame(ScratchInBuffer, ScratchOutBuffer); // Copy the output of this band into the input for sequential processing for (int32 Channel = 0; Channel < 2; ++Channel) { ScratchInBuffer[Channel] = ScratchOutBuffer[Channel]; } } // Copy the results of this frame to the output buffer OutAudioBuffer[SampleIndex] = ScratchOutBuffer[0]; OutAudioBuffer[SampleIndex + 1] = ScratchOutBuffer[1]; } } } else { // pass through for (int32 i = 0; i < InAudioBuffer.Num(); ++i) { OutAudioBuffer[i] = InAudioBuffer[i]; } } } static float GetClampedGain(const float InGain) { // These are clamped to match XAudio2 FXEQ_MIN_GAIN and FXEQ_MAX_GAIN return FMath::Clamp(InGain, 0.001f, 7.94f); } static float GetClampedBandwidth(const float InBandwidth) { // These are clamped to match XAudio2 FXEQ_MIN_BANDWIDTH and FXEQ_MAX_BANDWIDTH return FMath::Clamp(InBandwidth, 0.1f, 2.0f); } static float GetClampedFrequency(const float InFrequency) { // These are clamped to match XAudio2 FXEQ_MIN_FREQUENCY_CENTER and FXEQ_MAX_FREQUENCY_CENTER return FMath::Clamp(InFrequency, 20.0f, 20000.0f); } void FSubmixEffectSubmixEQ::SetEffectParameters(const FAudioEQEffect& InEQEffectParameters) { // This function maps the old audio engine eq effect params to the new eq effect. // Note that this is always a 4-band EQ and not flexible w/ respect. FSubmixEffectSubmixEQSettings NewSettings; FSubmixEffectEQBand Band; Band.bEnabled = true; Band.Frequency = GetClampedFrequency(InEQEffectParameters.FrequencyCenter0); Band.Bandwidth = GetClampedBandwidth(InEQEffectParameters.Bandwidth0); Band.GainDb = Audio::ConvertToDecibels(GetClampedGain(InEQEffectParameters.Gain0)); NewSettings.EQBands.Add(Band); Band.bEnabled = true; Band.Frequency = GetClampedFrequency(InEQEffectParameters.FrequencyCenter1); Band.Bandwidth = GetClampedBandwidth(InEQEffectParameters.Bandwidth1); Band.GainDb = Audio::ConvertToDecibels(GetClampedGain(InEQEffectParameters.Gain1)); NewSettings.EQBands.Add(Band); Band.bEnabled = true; Band.Frequency = GetClampedFrequency(InEQEffectParameters.FrequencyCenter2); Band.Bandwidth = GetClampedBandwidth(InEQEffectParameters.Bandwidth2); Band.GainDb = Audio::ConvertToDecibels(GetClampedGain(InEQEffectParameters.Gain2)); NewSettings.EQBands.Add(Band); Band.bEnabled = true; Band.Frequency = GetClampedFrequency(InEQEffectParameters.FrequencyCenter3); Band.Bandwidth = GetClampedBandwidth(InEQEffectParameters.Bandwidth3); Band.GainDb = Audio::ConvertToDecibels(GetClampedGain(InEQEffectParameters.Gain3)); NewSettings.EQBands.Add(Band); // Don't make any changes if this is the exact same parameters if (!IsEqual(GameThreadEQSettings, NewSettings)) { GameThreadEQSettings = NewSettings; PendingSettings.SetParams(GameThreadEQSettings); } } void FSubmixEffectSubmixEQ::UpdateParameters(const int32 InNumOutputChannels) { // We need to update parameters if the output channel count changed bool bParamsChanged = false; // Also need to update if new settings have been applied FSubmixEffectSubmixEQSettings NewSettings; if (PendingSettings.GetParams(&NewSettings)) { bParamsChanged = true; RenderThreadEQSettings = NewSettings; } if (bParamsChanged || !bEQSettingsSet) { bEQSettingsSet = true; const int32 NumBandsInSetting = RenderThreadEQSettings.EQBands.Num(); const int32 CurrentFilterCount = FiltersPerChannel.Num(); // Now loop through all the bands and set them up on all the filters. for (int32 FilterIndex = 0; FilterIndex < CurrentFilterCount; ++FilterIndex) { FEQ& EqFilter = FiltersPerChannel[FilterIndex]; EqFilter.bEnabled = true; // Create more bands as needed const int32 NumCurrentBands = EqFilter.Bands.Num(); if (NumCurrentBands < NumBandsInSetting) { // Create and initialize the biquad filters per band for (int32 BandIndex = NumCurrentBands; BandIndex < NumBandsInSetting; ++BandIndex) { // Create new filter instance int32 BiquadIndex = EqFilter.Bands.Add(Audio::FBiquadFilter()); // Initialize it EqFilter.Bands[BiquadIndex].Init(SampleRate, 2, Audio::EBiquadFilter::ParametricEQ); } } // Disable bands as needed else if (NumCurrentBands > NumBandsInSetting) { // Disable all filters that are greater than the number of bands in the new setting for (int32 BandIndex = NumBandsInSetting; BandIndex < NumCurrentBands; ++BandIndex) { EqFilter.Bands[BandIndex].SetEnabled(false); } } // Now copy the settings over to the specific EQ filter check(NumBandsInSetting <= EqFilter.Bands.Num()); for (int32 BandIndex = 0; BandIndex < NumBandsInSetting; ++BandIndex) { const FSubmixEffectEQBand& EQBandSetting = RenderThreadEQSettings.EQBands[BandIndex]; EqFilter.Bands[BandIndex].SetEnabled(EQBandSetting.bEnabled); EqFilter.Bands[BandIndex].SetParams(Audio::EBiquadFilter::ParametricEQ, EQBandSetting.Frequency, EQBandSetting.Bandwidth, EQBandSetting.GainDb); } } } } void USubmixEffectSubmixEQPreset::SetSettings(const FSubmixEffectSubmixEQSettings& InSettings) { UpdateSettings(InSettings); }
31.569343
148
0.755491
windystrife
9d21cbc19933311185e0a14a66c22b7520831d8d
7,517
cc
C++
test/realm/memspeed.cc
chuckatkins/legion
ba0cda94372a21f42ad60e7edef99de5951d21b0
[ "Apache-2.0" ]
null
null
null
test/realm/memspeed.cc
chuckatkins/legion
ba0cda94372a21f42ad60e7edef99de5951d21b0
[ "Apache-2.0" ]
null
null
null
test/realm/memspeed.cc
chuckatkins/legion
ba0cda94372a21f42ad60e7edef99de5951d21b0
[ "Apache-2.0" ]
null
null
null
#include "realm/realm.h" #include <cstdio> #include <cstdlib> #include <cassert> #include <cstring> #include <csignal> #include <cmath> #include <time.h> #include <unistd.h> using namespace Realm; using namespace LegionRuntime::Accessor; Logger log_app("app"); // Task IDs, some IDs are reserved so start at first available number enum { TOP_LEVEL_TASK = Processor::TASK_ID_FIRST_AVAILABLE+0, MEMSPEED_TASK, }; struct SpeedTestArgs { Memory mem; RegionInstance inst; size_t elements; int reps; Machine::AffinityDetails affinity; }; static size_t buffer_size = 64 << 20; // should be bigger than any cache in system void memspeed_cpu_task(const void *args, size_t arglen, const void *userdata, size_t userlen, Processor p) { const SpeedTestArgs& cargs = *(const SpeedTestArgs *)args; RegionAccessor<AccessorType::Generic> ra_untyped = cargs.inst.get_accessor(); RegionAccessor<AccessorType::Affine<1>, void *> ra = ra_untyped.typeify<void *>().convert<AccessorType::Affine<1> >(); // sequential write test double seqwr_bw = 0; { long long t1 = Clock::current_time_in_nanoseconds(); for(int j = 0; j < cargs.reps; j++) for(size_t i = 0; i < cargs.elements; i++) ra[i] = 0; long long t2 = Clock::current_time_in_nanoseconds(); seqwr_bw = 1.0 * cargs.reps * cargs.elements * sizeof(void *) / (t2 - t1); } // sequential read test double seqrd_bw = 0; { long long t1 = Clock::current_time_in_nanoseconds(); int errors = 0; for(int j = 0; j < cargs.reps; j++) for(size_t i = 0; i < cargs.elements; i++) { void *ptr = *(void * volatile *)&ra[i]; if(ptr != 0) errors++; } long long t2 = Clock::current_time_in_nanoseconds(); assert(errors == 0); seqrd_bw = 1.0 * cargs.reps * cargs.elements * sizeof(void *) / (t2 - t1); } // random write test double rndwr_bw = 0; std::vector<void *> last_ptrs; // for checking latency test { // run on many fewer elements... size_t count = cargs.elements >> 8; // quadratic stepping via "acceleration" and "velocity" size_t a = 548191; size_t v = 24819; size_t p = 0; long long t1 = Clock::current_time_in_nanoseconds(); for(int j = 0; j < cargs.reps; j++) { for(size_t i = 0; i < count; i++) { size_t prev = p; p = (p + v) % cargs.elements; v = (v + a) % cargs.elements; // wrapping would be bad assert(p != 0); ra[prev] = &ra[p]; } last_ptrs.push_back(&ra[p]); } long long t2 = Clock::current_time_in_nanoseconds(); rndwr_bw = 1.0 * cargs.reps * count * sizeof(void *) / (t2 - t1); } // random read test double rndrd_bw = 0; { // run on many fewer elements... size_t count = cargs.elements >> 8; // quadratic stepping via "acceleration" and "velocity" size_t a = 548191; size_t v = 24819; size_t p = 0; long long t1 = Clock::current_time_in_nanoseconds(); int errors = 0; for(int j = 0; j < cargs.reps; j++) for(size_t i = 0; i < count; i++) { size_t prev = p; p = (p + v) % cargs.elements; v = (v + a) % cargs.elements; // wrapping would be bad assert(p != 0); void *exp = &ra[p]; void *act = ra[prev]; if(exp != act) errors++; } long long t2 = Clock::current_time_in_nanoseconds(); assert(errors == 0); rndrd_bw = 1.0 * cargs.reps * count * sizeof(void *) / (t2 - t1); } // latency test double latency = 0; { // run on many fewer elements... size_t count = cargs.elements >> 8; // quadratic stepping via "acceleration" and "velocity" long long t1 = Clock::current_time_in_nanoseconds(); int errors = 0; void **ptr = &ra[0]; for(int j = 0; j < cargs.reps; j++) { for(size_t i = 0; i < count; i++) ptr = (void **)*ptr; assert(ptr == last_ptrs[j]); } long long t2 = Clock::current_time_in_nanoseconds(); assert(errors == 0); latency = 1.0 * (t2 - t1) / (cargs.reps * count); } log_app.info() << " on proc " << p << " seqwr:" << seqwr_bw << " seqrd:" << seqrd_bw; log_app.info() << " on proc " << p << " rndwr:" << rndwr_bw << " rndrd:" << rndrd_bw; log_app.info() << " on proc " << p << " latency:" << latency; } void top_level_task(const void *args, size_t arglen, const void *userdata, size_t userlen, Processor p) { log_app.print() << "Realm memory speed test"; size_t elements = buffer_size / sizeof(void *); Domain d = Domain::from_rect<1>(Rect<1>(0, elements - 1)); // iterate over memories, create and instance, and then let each processor beat on it Machine machine = Machine::get_machine(); for(Machine::MemoryQuery::iterator it = Machine::MemoryQuery(machine).begin(); it; ++it) { Memory m = *it; size_t capacity = m.capacity(); if(capacity < buffer_size) { log_app.info() << "skipping memory " << m << " (kind=" << m.kind() << ") - insufficient capacity"; continue; } if(m.kind() == Memory::GLOBAL_MEM) { log_app.info() << "skipping memory " << m << " (kind=" << m.kind() << ") - slow global memory"; continue; } log_app.print() << "Memory: " << m << " Kind:" << m.kind() << " Capacity: " << capacity; std::vector<size_t> field_sizes(1, sizeof(void *)); RegionInstance inst = d.create_instance(m, std::vector<size_t>(1, sizeof(void *)), elements); assert(inst.exists()); // clear the instance first - this should also take care of faulting it in void *fill_value = 0; std::vector<Domain::CopySrcDstField> sdf(1); sdf[0].inst = inst; sdf[0].offset = 0; sdf[0].size = sizeof(void *); d.fill(sdf, &fill_value, sizeof(fill_value)).wait(); Machine::ProcessorQuery pq = Machine::ProcessorQuery(machine).has_affinity_to(m); for(Machine::ProcessorQuery::iterator it2 = pq.begin(); it2; ++it2) { Processor p = *it2; SpeedTestArgs cargs; cargs.mem = m; cargs.inst = inst; cargs.elements = elements; cargs.reps = 8; bool ok = machine.has_affinity(p, m, &cargs.affinity); assert(ok); Event e = p.spawn(MEMSPEED_TASK, &cargs, sizeof(cargs)); e.wait(); } inst.destroy(); } } int main(int argc, char **argv) { Runtime rt; rt.init(&argc, &argv); for(int i = 1; i < argc; i++) { if(!strcmp(argv[i], "-b")) { buffer_size = strtoll(argv[++i], 0, 10); continue; } } rt.register_task(TOP_LEVEL_TASK, top_level_task); Processor::register_task_by_kind(Processor::LOC_PROC, false /*!global*/, MEMSPEED_TASK, CodeDescriptor(memspeed_cpu_task), ProfilingRequestSet(), 0, 0).wait(); Processor::register_task_by_kind(Processor::UTIL_PROC, false /*!global*/, MEMSPEED_TASK, CodeDescriptor(memspeed_cpu_task), ProfilingRequestSet(), 0, 0).wait(); Processor::register_task_by_kind(Processor::IO_PROC, false /*!global*/, MEMSPEED_TASK, CodeDescriptor(memspeed_cpu_task), ProfilingRequestSet(), 0, 0).wait(); // select a processor to run the top level task on Processor p = Machine::ProcessorQuery(Machine::get_machine()) .only_kind(Processor::LOC_PROC) .first(); assert(p.exists()); // collective launch of a single task - everybody gets the same finish event Event e = rt.collective_spawn(p, TOP_LEVEL_TASK, 0, 0); // request shutdown once that task is complete rt.shutdown(e); // now sleep this thread until that shutdown actually happens rt.wait_for_shutdown(); return 0; }
29.594488
120
0.620194
chuckatkins
9d23a9e6f4494c8b88e7306cdc073a67128bbefd
2,503
hpp
C++
src/managers/draw_manager.hpp
Romop5/holoinjector
db11922e6c57b4664beeec31199385a4877e1619
[ "MIT" ]
2
2021-04-12T06:09:57.000Z
2021-05-20T11:56:01.000Z
src/managers/draw_manager.hpp
Romop5/holoinjector
db11922e6c57b4664beeec31199385a4877e1619
[ "MIT" ]
null
null
null
src/managers/draw_manager.hpp
Romop5/holoinjector
db11922e6c57b4664beeec31199385a4877e1619
[ "MIT" ]
null
null
null
/***************************************************************************** * * PROJECT: HoloInjector - https://github.com/Romop5/holoinjector * LICENSE: See LICENSE in the top level directory * FILE: managers/draw_manager.hpp * *****************************************************************************/ #ifndef HI_DRAW_MANAGER_HPP #define HI_DRAW_MANAGER_HPP #include <functional> namespace hi { class Context; namespace pipeline { class PerspectiveProjectionParameters; } namespace managers { class DrawManager { public: void draw(Context& context, const std::function<void(void)>& code); void setInjectorDecodedProjection(Context& context, GLuint program, const hi::pipeline::PerspectiveProjectionParameters& projection); private: /// Decide if current draw call is dispached in suitable settings bool shouldSkipDrawCall(Context& context); /// Decide which draw methods should be used void drawGeneric(Context& context, const std::function<void(void)>& code); /// Draw without support of GS, or when shaderless fixed-pipeline is used void drawLegacy(Context& context, const std::function<void(void)>& code); /// Draw when Geometry Shader has been injected into program void drawWithGeometryShader(Context& context, const std::function<void(void)>& code); /// Draw without, just using Vertex Shader + repeating void drawWithVertexShader(Context& context, const std::function<void(void)>& code); std::string dumpDrawContext(Context& context) const; // TODO: Replace setters with separate class, devoted for intershader communication void setInjectorShift(Context& context, const glm::mat4& viewSpaceTransform, float projectionAdjust = 0.0); void resetInjectorShift(Context& context); void setInjectorIdentity(Context& context); void pushFixedPipelineProjection(Context& context, const glm::mat4& viewSpaceTransform, float projectionAdjust = 0.0); void popFixedPipelineProjection(Context& context); // Legacy OpenGL - Create single-view FBO from current FBO GLuint createSingleViewFBO(Context& contex, size_t layer); /* Context queries */ bool isSingleViewPossible(Context& context); bool isRepeatingSuitable(Context& context); void setInjectorUniforms(size_t shaderID, Context& context); }; } // namespace managers } // namespace hi #endif
37.924242
141
0.666001
Romop5
9d251642791f2f121d991d49d8b0c8a5e9a3d761
1,375
hpp
C++
hardware_interface_extensions/include/hardware_interface_extensions/sensor_state_interface.hpp
smilerobotics/ros_control_extensions
1eee21217708dcee80aa3d91b2c6415c1f4feffa
[ "MIT" ]
null
null
null
hardware_interface_extensions/include/hardware_interface_extensions/sensor_state_interface.hpp
smilerobotics/ros_control_extensions
1eee21217708dcee80aa3d91b2c6415c1f4feffa
[ "MIT" ]
null
null
null
hardware_interface_extensions/include/hardware_interface_extensions/sensor_state_interface.hpp
smilerobotics/ros_control_extensions
1eee21217708dcee80aa3d91b2c6415c1f4feffa
[ "MIT" ]
1
2021-10-14T06:37:36.000Z
2021-10-14T06:37:36.000Z
#ifndef HARDWARE_INTERFACE_EXTENSIONS_SENSOR_STATE_INTERFACE_HPP #define HARDWARE_INTERFACE_EXTENSIONS_SENSOR_STATE_INTERFACE_HPP #include <string> #include <hardware_interface/internal/hardware_resource_manager.h> #include <ros/common.h> // for ROS_ASSERT() #include <sensor_msgs/BatteryState.h> namespace hardware_interface_extensions { // // sensor state handles // template < typename DataT > class SensorStateHandle { public: typedef DataT Data; public: SensorStateHandle() : name_(), data_(NULL) {} SensorStateHandle(const std::string &name, const Data *const data) : name_(name), data_(data) {} virtual ~SensorStateHandle() {} std::string getName() const { return name_; } ros::Time getStamp() const { ROS_ASSERT(data_); return data_->header.stamp; } const Data &getData() const { ROS_ASSERT(data_); return *data_; } const Data *getDataPtr() const { return data_; } private: std::string name_; const Data *data_; }; typedef SensorStateHandle< sensor_msgs::BatteryState > BatteryStateHandle; // // sensor state interfaces // template < typename HandleT > class SensorStateInterface : public hardware_interface::HardwareResourceManager< HandleT > { public: typedef HandleT Handle; }; typedef SensorStateInterface< BatteryStateHandle > BatteryStateInterface; } // namespace hardware_interface_extensions #endif
22.177419
98
0.755636
smilerobotics
9d275d4dba99ff3fedd5cfd20edba6314d2d2064
18,262
cpp
C++
vipss/src/Solver.cpp
jpanetta/VIPSS
34491070a49047f8071f1670139ffe01d38598a4
[ "MIT" ]
38
2019-05-18T05:22:40.000Z
2022-03-25T15:40:11.000Z
vipss/src/Solver.cpp
jpanetta/VIPSS
34491070a49047f8071f1670139ffe01d38598a4
[ "MIT" ]
3
2020-03-25T01:34:28.000Z
2021-07-29T15:15:31.000Z
vipss/src/Solver.cpp
jpanetta/VIPSS
34491070a49047f8071f1670139ffe01d38598a4
[ "MIT" ]
10
2019-05-18T05:22:29.000Z
2021-06-19T11:50:58.000Z
#include "Solver.h" #include <ctime> #include <chrono> #include <iomanip> //#include <eigen3/Eigen/CholmodSupport> //#include <gurobi_c++.h> typedef std::chrono::high_resolution_clock Clock; //static GRBModel static_model; void LinearVec::set_label(int label){ this->label = label; } void LinearVec::set_ab(double a, double b){ this->a = a; this->b = b; } void LinearVec::clear(){ ts.clear(); ws.clear(); } void LinearVec::push_back(int t, double w){ ts.push_back(t); ws.push_back(w); } void QuadraticVec::push_back(int i,int j,double val){ ts.push_back(triple(i,j,val)); } void QuadraticVec::clear(){ ts.clear(); } void QuadraticVec::set_b(double b){ this->b = b; } void Solution_Struct::init(int n){ solveval.reserve(n); Statue = 0; } int optwrapper(vector<double>&para, vector<double>&lowerbound, vector<double>&upperbound, void *funcPara, double (*optfunc)(const vector<double>&,vector<double>&,void *), double (*constraintfunc)(const vector<double>&,vector<double>&,void *), double tor, int maxIter, double &finEnergy ){ nlopt::result result; try{ int numOfPara = para.size(); //nlopt::opt myopt(nlopt::LD_CCSAQ,uint(numOfPara)); //nlopt::opt myopt(nlopt::LD_SLSQP,uint(numOfPara)); nlopt::opt myopt(nlopt::LD_LBFGS,uint(numOfPara)); myopt.set_ftol_rel(tor); //myopt.set_ftol_abs(tor); //myopt.set_xtol_abs(1e-6); //myopt.set_xtol_rel(1e-7); myopt.set_maxeval(maxIter); //myopt.set_initial_step(0.001); myopt.set_lower_bounds(lowerbound); myopt.set_upper_bounds(upperbound); myopt.set_min_objective(optfunc,funcPara); //myopt.set_precond_min_objective(optfuncModify, pre, &funcPara); //myopt.set_min_objective(optfunc, &funcPara); myopt.add_equality_constraint(constraintfunc,funcPara,tor); result = myopt.optimize(para, finEnergy); std::cout << "Obj: "<< std::setprecision(10) << finEnergy << std::endl; } catch(std::exception &e) { std::cout << "nlopt failed: " << e.what() << std::endl; } return result; } int Solver::nloptwrapper(vector<double>&lowerbound, vector<double>&upperbound, nlopt::vfunc optfunc, void *funcPara, vector<NLOptConstraint>&nl_constraints, double tor, int maxIter, Solution_Struct &sol ){ nlopt::result result; sol.Statue=0; vector<double>tmp_grad(0); sol.init_energy = optfunc(sol.solveval,tmp_grad,funcPara); try{ int numOfPara = lowerbound.size(); //nlopt::opt myopt(nlopt::LD_CCSAQ,uint(numOfPara)); nlopt::opt myopt(nlopt::LD_SLSQP,uint(numOfPara)); //nlopt::opt myopt(nlopt::LD_VAR2,uint(numOfPara)); myopt.set_ftol_rel(tor); //myopt.set_ftol_abs(tor); //myopt.set_xtol_abs(1e-6); //myopt.set_xtol_rel(1e-7); myopt.set_maxeval(maxIter); //myopt.set_initial_step(0.001); myopt.set_lower_bounds(lowerbound); myopt.set_upper_bounds(upperbound); myopt.set_min_objective(optfunc,funcPara); //myopt.set_precond_min_objective(optfuncModify, pre, &funcPara); //myopt.set_min_objective(optfunc, &funcPara); for(auto &a:nl_constraints){ if(a.mt==CM_EQUAL){ myopt.add_equality_constraint(a.constraintfunc,a.data,tor); }else { myopt.add_inequality_constraint(a.constraintfunc,a.data,tor); } } auto t1 = Clock::now(); result = myopt.optimize(sol.solveval, sol.energy); auto t2 = Clock::now(); cout << "nlopt time: " << (sol.time = std::chrono::nanoseconds(t2 - t1).count()/1e9) <<endl; sol.Statue = (result >= nlopt::SUCCESS); cout<<"Statu: "<<result<<endl; std::cout << "Obj: "<< std::setprecision(10) << sol.energy << std::endl; } catch(std::exception &e) { std::cout << "nlopt failed: " << e.what() << std::endl; } return result; } int Solver::nloptwrapper(vector<double>&lowerbound, vector<double>&upperbound, nlopt::vfunc optfunc, void *funcPara, double tor, int maxIter, Solution_Struct &sol ){ nlopt::result result; sol.Statue=0; vector<double>tmp_grad(0); sol.init_energy = optfunc(sol.solveval,tmp_grad,funcPara); try{ int numOfPara = lowerbound.size(); //nlopt::opt myopt(nlopt::LD_VAR1,uint(numOfPara)); //nlopt::opt myopt(nlopt::LD_CCSAQ,uint(numOfPara)); //nlopt::opt myopt(nlopt::LD_SLSQP,uint(numOfPara)); nlopt::opt myopt(nlopt::LD_LBFGS,uint(numOfPara)); myopt.set_ftol_rel(tor); //myopt.set_ftol_abs(tor); //myopt.set_xtol_abs(1e-6); //myopt.set_xtol_rel(1e-7); myopt.set_maxeval(maxIter); //myopt.set_initial_step(0.001); myopt.set_lower_bounds(lowerbound); myopt.set_upper_bounds(upperbound); myopt.set_min_objective(optfunc,funcPara); //myopt.set_precond_min_objective(optfuncModify, pre, &funcPara); //myopt.set_min_objective(optfunc, &funcPara); auto t1 = Clock::now(); result = myopt.optimize(sol.solveval, sol.energy); auto t2 = Clock::now(); cout << "nlopt time: " << (sol.time = std::chrono::nanoseconds(t2 - t1).count()/1e9) <<endl; sol.Statue = (result >= nlopt::SUCCESS); cout<<"Statu: "<<result<<endl; std::cout << "Obj: "<< std::setprecision(10) << sol.init_energy << " -> " <<sol.energy << std::endl; } catch(std::exception &e) { std::cout << "nlopt failed: " << e.what() << std::endl; } return result; } //int solveQuadraticProgramming_Core(GRBModel &model, vector<GRBVar>&vars, Solution_Struct &sol, bool suppressinfo = false){ // int n = vars.size(); // try{ // auto t1 = Clock::now(); // model.optimize(); // auto t2 = Clock::now(); // if(!suppressinfo)cout << "Total opt time: " << (sol.time = std::chrono::nanoseconds(t2 - t1).count()/1e9) <<endl<<endl; // if(!suppressinfo)cout << "Status: " << model.get(GRB_IntAttr_Status) << endl; // //cout<<"0"<<endl; // if (sol.Statue = (model.get(GRB_IntAttr_Status) == GRB_OPTIMAL)) { // sol.solveval.resize(n); // //cout<<"1"<<endl; // sol.energy = model.get(GRB_DoubleAttr_ObjVal); // if(!suppressinfo)cout << "Obj: " << sol.energy << endl; // //cout<<"2"<<endl; // for(int i=0;i<n;++i)sol.solveval[i] = vars[i].get(GRB_DoubleAttr_X); // //for(int i=0;i<n;++i)cout<<sol.solveval[i]<<' ';cout<<endl; // } // }catch (GRBException e) { // cout << "Error code = " << e.getErrorCode() << endl; // cout << e.getMessage() << endl; // } catch (...) { // cout << "Exception during optimization" << endl; // } // return model.get(GRB_IntAttr_Status); // //return time; //} //int Solver::solveQuadraticProgramming(vector<triple> &M, vector<triple> &Ab, int n, vector<double>&solveval){ // vector<GRBVar>vars(n); // try{ // GRBEnv env = GRBEnv(); // //cout << "optimize 0" << endl; // GRBModel model = GRBModel(env); // model.getEnv().set(GRB_IntParam_OutputFlag, 0); // for(int i=0;i<n;++i)vars[i] = model.addVar(-GRB_INFINITY, GRB_INFINITY, 0, GRB_CONTINUOUS,to_string(i)); // //cout << "optimize 1" << endl; // GRBQuadExpr obj = 0; // for(int i=0;i<M.size();++i){ // obj += vars[M[i].i] * vars[M[i].j] * M[i].val; // } // // cout << "optimize 2 " <<codeer<< endl; // model.setObjective(obj, GRB_MINIMIZE); // //model.update(); // for(int i=0;i<Ab.size();++i){ // model.addConstr(vars[Ab[i].i] - vars[Ab[i].j] >= Ab[i].val); // } // auto t1 = Clock::now(); // model.optimize(); // auto t2 = Clock::now(); // cout << "Total opt time: " << std::chrono::nanoseconds(t2 - t1).count()/1e9<< endl<< endl; // //cout << "Status: " << model.get(GRB_IntAttr_Status) << endl; // if (model.get(GRB_IntAttr_Status) == GRB_OPTIMAL) { // solveval.resize(n); // cout << "Obj: " << model.get(GRB_DoubleAttr_ObjVal) << endl; // for(int i=0;i<n;++i)solveval[i] = vars[i].get(GRB_DoubleAttr_X) ; // } // }catch (GRBException e) { // cout << "Error code = " << e.getErrorCode() << endl; // cout << e.getMessage() << endl; // } catch (...) { // cout << "Exception during optimization" << endl; // } // return 1; //} //int Solver::solveQuadraticProgramming(vector<triple> &M, vector<LinearVec> &Ab, int n, vector<double>&solveval){ // vector<GRBVar>vars(n); // try{ // GRBEnv env = GRBEnv(); // //cout << "optimize 0" << endl; // GRBModel model = GRBModel(env); // model.getEnv().set(GRB_IntParam_OutputFlag, 0); // for(int i=0;i<n;++i)vars[i] = model.addVar(-GRB_INFINITY, GRB_INFINITY, 0, GRB_CONTINUOUS,to_string(i)); // //cout << "optimize 1" << endl; // GRBQuadExpr obj = 0; // for(int i=0;i<M.size();++i){ // obj += vars[M[i].i] * vars[M[i].j] * M[i].val; // } // // cout << "optimize 2 " <<codeer<< endl; // model.setObjective(obj, GRB_MINIMIZE); // //model.update(); // for(int i=0;i<Ab.size();++i){ // auto &a = Ab[i]; // GRBLinExpr cons = 0; // for(int i=0;i<a.ts.size();++i)cons += vars[a.ts[i]] * a.ws[i]; // if(a.label == 0)model.addConstr(cons == a.b); // else if(a.label == -1)model.addConstr(cons <= a.b); // else if(a.label == 1)model.addConstr(cons >= a.b); // } // auto t1 = Clock::now(); // model.optimize(); // auto t2 = Clock::now(); // cout << "Total opt time: " << std::chrono::nanoseconds(t2 - t1).count()/1e9<< endl<< endl; // //cout << "Status: " << model.get(GRB_IntAttr_Status) << endl; // if (model.get(GRB_IntAttr_Status) == GRB_OPTIMAL) { // solveval.resize(n); // cout << "Obj: " << model.get(GRB_DoubleAttr_ObjVal) << endl; // for(int i=0;i<n;++i)solveval[i] = vars[i].get(GRB_DoubleAttr_X) ; // } // }catch (GRBException e) { // cout << "Error code = " << e.getErrorCode() << endl; // cout << e.getMessage() << endl; // } catch (...) { // cout << "Exception during optimization" << endl; // } // return 1; //} //int Solver::solveQuadraticProgramming(arma::mat &M, vector<LinearVec> &Ab, int n, Solution_Struct &sol){ // vector<GRBVar>vars(n); // int re; // sol.init(n); // try{ // GRBEnv env = GRBEnv(); // //cout << "optimize 0" << endl; // GRBModel model = GRBModel(env); // model.getEnv().set(GRB_IntParam_OutputFlag, 0); // for(int i=0;i<n;++i)vars[i] = model.addVar(-GRB_INFINITY, GRB_INFINITY, 0, GRB_CONTINUOUS,to_string(i)); // //cout << "optimize 1" << endl; // GRBQuadExpr obj = 0; // int mm = M.n_rows; // for(int i=0;i<mm;++i)for(int j=0;j<mm;++j){ // obj += vars[i] * vars[j] * M(i,j); // } // // cout << "optimize 2 " <<codeer<< endl; // model.setObjective(obj, GRB_MINIMIZE); // int ec = 0, iec = 0; // for(int i=0;i<Ab.size();++i){ // auto &a = Ab[i]; // GRBLinExpr cons = 0; // for(int i=0;i<a.ts.size();++i)cons += vars[a.ts[i]] * a.ws[i]; // //cout<<a.ts.size()<<endl; // if(a.a == a.b){model.addConstr(cons == a.b);ec++;} // else {model.addConstr(cons >= a.a);model.addConstr(cons <= a.b);iec+=2;} // } // cout<<ec<<' '<<iec<<endl; // cout<<"Begin Solve"<<endl; // re = solveQuadraticProgramming_Core(model, vars, sol); // if(0){ // for(int i=0;i<Ab.size();++i){ // auto &a = Ab[i]; // double cons = 0; // for(int i=0;i<a.ts.size();++i)cons += vars[a.ts[i]].get(GRB_DoubleAttr_X) * a.ws[i]; // cout<<cons<<endl; // } // } // }catch (GRBException e) { // cout << "Error code = " << e.getErrorCode() << endl; // cout << e.getMessage() << endl; // } catch (...) { // cout << "Exception during optimization" << endl; // } // return re; //} //int Solver::solveLinearLS(vector<triple> &M, vector<double> &b, int n, vector<double>&solveval){ // return -1; //} //int Solver::solveQCQP(arma::mat &M, vector<LinearVec> &Ab, vector<QuadraticVec> &Cb, int n, Solution_Struct &sol){ // vector<GRBVar>vars(n); // int re; // sol.init(n); // try{ // GRBEnv env = GRBEnv(); // //cout << "optimize 0" << endl; // GRBModel model = GRBModel(env); // model.getEnv().set(GRB_IntParam_OutputFlag, 0); // //model.getEnv().set(GRB_INT_PAR_DUALREDUCTIONS, 0); // for(int i=0;i<n;++i)vars[i] = model.addVar(-GRB_INFINITY, GRB_INFINITY, 0, GRB_CONTINUOUS,to_string(i)); // //cout << "optimize 1" << endl; // GRBQuadExpr obj = 0; // int mm = M.n_rows; // for(int i=0;i<mm;++i)for(int j=0;j<mm;++j){ // obj += vars[i] * vars[j] * M(i,j); // } // // cout << "optimize 2 " <<codeer<< endl; // //model.setObjective(obj, GRB_MINIMIZE); // model.set(GRB_IntParam_DualReductions, 0); // model.setObjective(obj, GRB_MAXIMIZE); // //cout<<"model.set(GRB_INT_PAR_DUALREDUCTIONS,0): "<<model.get(GRB_IntA)<<endl; // int ec = 0, iec = 0; // for(int i=0;i<Ab.size();++i){ // auto &a = Ab[i]; // GRBLinExpr cons = 0; // for(int i=0;i<a.ts.size();++i)cons += vars[a.ts[i]] * a.ws[i]; // model.addConstr(cons <= a.a); // //cout<<a.ts.size()<<endl; // if(a.mt == CM_EQUAL){model.addConstr(cons == a.a);ec++;} // else if(a.mt == CM_LESS){model.addConstr(cons <= a.b);iec++;} // else if(a.mt == CM_GREATER){model.addConstr(cons >= a.a);iec++;} // else if(a.mt == CM_RANGE){model.addConstr(cons >= a.a);model.addConstr(cons <= a.b);iec+=2;} // } // cout<<"equalc & inequalc: "<<ec<<' '<<iec<<endl; // for(int i=0;i<Cb.size();++i){ // QuadraticVec &a = Cb[i]; // GRBQuadExpr cons = 0; // for(int i=0;i<a.ts.size();++i)cons += vars[a.ts[i].i] * vars[a.ts[i].j] * a.ts[i].val; // if(a.mt == CM_EQUAL){model.addQConstr(cons == a.b);ec++;} // else if(a.mt == CM_LESS){model.addQConstr(cons <= a.b);iec++;} // else if(a.mt == CM_GREATER){model.addQConstr(cons >= a.b);iec++;} // } // cout<<"equalc & inequalc: "<<ec<<' '<<iec<<endl; // cout<<"Begin Solve"<<endl; // re = solveQuadraticProgramming_Core(model, vars, sol); // if(0){ // for(int i=0;i<Ab.size();++i){ // auto &a = Ab[i]; // double cons = 0; // for(int i=0;i<a.ts.size();++i)cons += vars[a.ts[i]].get(GRB_DoubleAttr_X) * a.ws[i]; // cout<<cons<<endl; // } // } // }catch (GRBException e) { // cout << "Error code = " << e.getErrorCode() << endl; // cout << e.getMessage() << endl; // } catch (...) { // cout << "Exception during optimization" << endl; // } // return re; //} //int Solver::solveQP_multiupdata_main( Solution_Struct &sol, vector<LinearVec> &Ab, int n, bool suppressinfo){ // vector<GRBVar>vars(n); // int re; // sol.init(n); // try{ // //cout << "optimize 0" << endl; // GRBModel model(objmodel); // //cout << "optimize 1" << endl; // GRBVar *pVar = model.getVars(); // for(int i=0;i<n;++i){ // vars[i] = pVar[i]; // } // //model.update(); // //cout<<"Begin Cons"<<endl; // int ec = 0, iec = 0; // for(int i=0;i<Ab.size();++i){ // auto &a = Ab[i]; // GRBLinExpr cons = 0; // for(int i=0;i<a.ts.size();++i)cons += vars[a.ts[i]] * a.ws[i]; // //cout<<a.ts.size()<<endl; // if(a.a == a.b){model.addConstr(cons == a.b);ec++;} // else {model.addConstr(cons >= a.a);model.addConstr(cons <= a.b);iec+=2;} // } // //cout<<ec<<' '<<iec<<endl; // //cout<<"Begin Solve"<<endl; // re = solveQuadraticProgramming_Core(model, vars, sol, suppressinfo); // if(0){ // for(int i=0;i<Ab.size();++i){ // auto &a = Ab[i]; // double cons = 0; // for(int i=0;i<a.ts.size();++i)cons += vars[a.ts[i]].get(GRB_DoubleAttr_X) * a.ws[i]; // cout<<cons<<endl; // } // } // }catch (GRBException e) { // cout << "Error code = " << e.getErrorCode() << endl; // cout << e.getMessage() << endl; // } catch (...) { // cout << "Exception during optimization" << endl; // } // return re; //} //int Solver::solveQP_multiupdata_init(arma::mat &M, int n){ // c_vars.resize(n); // for(int i=0;i<n;++i)c_vars[i] = objmodel.addVar(-GRB_INFINITY, GRB_INFINITY, 0, GRB_CONTINUOUS,to_string(i)); // //cout << "optimize 1" << endl; // GRBQuadExpr obj = 0; // int mm = M.n_rows; // for(int i=0;i<mm;++i)for(int j=0;j<mm;++j){ // obj += c_vars[i] * c_vars[j] * M(i,j); // } // // cout << "optimize 2 " <<codeer<< endl; // objmodel.setObjective(obj, GRB_MINIMIZE); // objmodel.update(); // cout<<"solveQP_multiupdata_init"<<endl; //}
27.216095
129
0.521301
jpanetta
9d2d64a79f0feb23f8b0038cde54e2ddf8b476ba
520
tcc
C++
src/Arduino.tcc
lawyiu/2d-robot-simulator
864af5074a597c7505df29a5ab81aa4fe331f45c
[ "MIT" ]
1
2022-03-25T12:37:07.000Z
2022-03-25T12:37:07.000Z
src/Arduino.tcc
lawyiu/2d-robot-simulator
864af5074a597c7505df29a5ab81aa4fe331f45c
[ "MIT" ]
3
2021-09-20T20:52:03.000Z
2021-09-26T06:14:07.000Z
src/Arduino.tcc
lawyiu/2D-robot-simulator
864af5074a597c7505df29a5ab81aa4fe331f45c
[ "MIT" ]
null
null
null
template <typename T> std::string SerialPort::formatVal(T val, int type) { std::ostringstream os; switch (type) { case BIN: { std::bitset<8 * sizeof(val)> bits(val); os << bits; break; } case HEX: { os << std::hex << val; break; } case OCT: { os << std::oct << val; break; } default: { os << val; break; } } return os.str(); }
17.931034
74
0.388462
lawyiu
9d2ee29e2cdeeeb7cf4cc24a7a95dc7e7fb60797
14,264
cpp
C++
testapp/scenes/scenemanager.cpp
ColinGilbert/d-collide
8adb354d52e7ee49705ca2853d50a6a879f3cd49
[ "BSD-3-Clause" ]
6
2015-12-08T05:38:03.000Z
2021-04-09T13:45:59.000Z
testapp/scenes/scenemanager.cpp
ColinGilbert/d-collide
8adb354d52e7ee49705ca2853d50a6a879f3cd49
[ "BSD-3-Clause" ]
null
null
null
testapp/scenes/scenemanager.cpp
ColinGilbert/d-collide
8adb354d52e7ee49705ca2853d50a6a879f3cd49
[ "BSD-3-Clause" ]
null
null
null
/******************************************************************************* * Copyright (C) 2007 by the members of PG 510, University of Dortmund: * * d-collide-devel@lists.sourceforge.net * * * Andreas Beckermann, Christian Bode, Marcel Ens, Sebastian Ens, * * Martin Fassbach, Maximilian Hegele, Daniel Haus, Oliver Horst, * * Gregor Jochmann, Timo Loist, Marcel Nienhaus and Marc Schulz * * * * All rights reserved. * * * * Redistribution and use in source and binary forms, with or without * * modification, are permitted provided that the following conditions are met:* * - Redistributions of source code must retain the above copyright * * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * * notice, this list of conditions and the following disclaimer in the * * documentation and/or other materials provided with the distribution. * * - Neither the name of the PG510 nor the names of its contributors may be * * used to endorse or promote products derived from this software without * * specific prior written permission. * * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE * *******************************************************************************/ #include "scenemanager.h" #include "dcollide-config_testapp.h" #include "deformable/deforming.h" #include "deformable/deformablescene.h" #include "deformable/deformablescenecollisions.h" #include "deformable/deformablescenespheres.h" #include "deformable/spherecloth.h" #include "general/collisionstopscene.h" #include "general/dcollidescene.h" #include "general/penetrationdepthscene.h" #include "general/specificationscene.h" #ifndef DCOLLIDE_BUILD_RELEASE_VERSION # include "general/devtest.h" #endif #include "physics/boxstackscene.h" #include "physics/clothbox.h" #include "physics/rotatingcloth.h" #include "physics/collisionresponse.h" #include "physics/rampscene.h" #include "physics/snookerscene.h" #include "physics/dominoday.h" #include "physics/wallscene.h" #include "physics/shakescene.h" #include "physics/marblerun.h" #include "physics/hangingclothscene.h" #include "rigid/manymovingboxes.h" #include "rigid/movingbunny.h" #include "rigid/tworigidhelicopters.h" #include "rigid/tworigidhelicoptersingrid.h" #include "benchmark/mixed.h" #include "benchmark/deformable.h" #include <d-collide/debug.h> #include <iostream> SceneManager* SceneManager::mSceneManager = 0; std::string SceneManager::mDefaultSceneId = "general"; SceneManager::SceneManager() { mSceneTitles.insert(std::make_pair("general", "General Testscene [general]")); mSceneTitles.insert(std::make_pair("surfacehierarchyply", "SurfaceHierarchy Demo (.ply model) [surfacehierarchyply]")); mSceneTitles.insert(std::make_pair("surfacehierarchycloth", "SurfaceHierarchy Demo (triangle grid) [surfacehierarchycloth]")); mSceneTitles.insert(std::make_pair("shcollisions", "SurfaceHierarchy CollisionTest [shcollisions]")); mSceneTitles.insert(std::make_pair("collisionstop", "Stop On Collision Scene [collisionstop]")); mSceneTitles.insert(std::make_pair("penetrationdepth", "Penetration depth for different shapes [penetrationdepth]")); mSceneTitles.insert(std::make_pair("copters", "Two Helicopters [copters]")); mSceneTitles.insert(std::make_pair("coptersgrid", "Two Helicopters in a grid of Boxes [coptersgrid]")); mSceneTitles.insert(std::make_pair("parallelboxes", "Moving Parallel Boxes [parallelboxes]")); mSceneTitles.insert(std::make_pair("spherecloth", "SpatialHash Demo [spherecloth]")); mSceneTitles.insert(std::make_pair("movingbunny", "Moving Bunny [movingbunny]")); mSceneTitles.insert(std::make_pair("snooker", "Physics Demo: Snooker Table [snooker]")); mSceneTitles.insert(std::make_pair("ramp", "Physics Demo: Rolling and Sliding on a Ramp [ramp]")); mSceneTitles.insert(std::make_pair("boxstack", "Physics Demo: [boxstack]")); mSceneTitles.insert(std::make_pair("response", "Physics Demo: All combinations of collisions in a physic scene [response]")); mSceneTitles.insert(std::make_pair("dominoday", "Physics Demo: Lots of fun with domino bricks [dominoday]")); mSceneTitles.insert(std::make_pair("clothbox", "Physics Demo: A cloth falling down onto a box [clothbox]")); mSceneTitles.insert(std::make_pair("rotatingcloth", "Physics Demo: A cloth falling down onto a rotating sphere [rotatingcloth]")); mSceneTitles.insert(std::make_pair("specification", "Exact specifications [specificationscene]")); mSceneTitles.insert(std::make_pair("wall", "Physics Demo: A wall of boxes and some cannonballs [wall]")); mSceneTitles.insert(std::make_pair("shake", "Physics Test: One body on two others [shake]")); mSceneTitles.insert(std::make_pair("marblerun", "Physics Demo: Marble in a maze [marblerun]")); mSceneTitles.insert(std::make_pair("hangingcloth", "Physics Demo: Cloth fixed at some points [hangingcloth]")); mSceneTitles.insert(std::make_pair("deforming", "Deforming objects [deforming]")); mSceneTitles.insert(std::make_pair("mixedbenchmark", "Benchmarking Scene (Mixed) [mixedbenchmark]")); mSceneTitles.insert(std::make_pair("deformablebenchmark", "Benchmarking Scene (Deformable) [deformablebenchmark]")); #ifndef DCOLLIDE_BUILD_RELEASE_VERSION mSceneTitles.insert(std::make_pair("devtest", "DEVELOPER SCENE [devtest]")); #endif } SceneManager::~SceneManager() { for (std::map<std::string, SceneBase*>::iterator it = mScenes.begin(); it != mScenes.end(); ++it) { delete (*it).second; } } /*! * Create the global scene manager object. This function must be called at most * once, multiple calls are not allowed (SceneManager is a singleton). */ void SceneManager::createSceneManager() { if (mSceneManager) { std::cerr << dc_funcinfo << "scenemanager already created" << std::endl; return; } mSceneManager = new SceneManager(); } /*! * \return The global SceneManager object or NULL if \ref createSceneManager was * not yet called. */ SceneManager* SceneManager::getSceneManager() { return mSceneManager; } /*! * Delete the global SceneManager object that was created by \ref * createSceneManager */ void SceneManager::deleteSceneManager() { delete mSceneManager; mSceneManager = 0; } /*! * Set the scene ID of the class that is used as "default scene", i.e. which is * created when the ID "default" is used in \ref createScene. * * This method is in particular meant to be used as a very early statment in the * main() function: you could easily create multiple test programs that are all * exactly equal (i.e. use exactly the same sources, except for main.cpp), * except for the default scene id that is used. */ void SceneManager::setDefaultSceneId(const std::string& id) { mDefaultSceneId = id; } /*! * \return The scene ID of the class that is created for the ID string * "default". See also \ref setDefaultSceneId */ const std::string& SceneManager::getDefaultSceneId() { return mDefaultSceneId; } /*! * Create a new scene as specified by \p id and returns a pointer to it. * * This class keeps ownership of the created scene and deletes it on * destruction. */ SceneBase* SceneManager::createScene(const std::string& id, Ogre::Root* root) { if (id == "default") { return createScene(getDefaultSceneId(), root); } if (mScenes.find(id) != mScenes.end()) { // no need to create a new scene, we already created one return (*mScenes.find(id)).second; } SceneBase* scene = 0; // note: also add new scenes to getAvailableSceneIds() ! if (id == "general") { scene = new DCollideScene(root); } else if (id == "surfacehierarchyply") { scene = new DeformableScene(root); } else if (id == "surfacehierarchycloth") { scene = new DeformableSceneSpheres(root); } else if (id == "shcollisions") { scene = new DeformableSceneCollisions(root); } else if (id == "collisionstop") { scene = new CollisionStopScene(root); } else if (id == "penetrationdepth") { scene = new PenetrationDepthScene(root); } else if (id == "copters") { scene = new TwoRigidHelicopters(root); } else if (id == "coptersgrid") { scene = new TwoRigidHelicoptersInGrid(root); } else if (id == "parallelboxes") { scene = new ManyMovingBoxes(root); } else if (id == "spherecloth") { scene = new SphereCloth(root); } else if (id == "movingbunny") { scene = new MovingBunny(root); } else if (id == "snooker") { scene = new SnookerScene(root); } else if (id == "ramp") { scene = new RampScene(root); } else if (id == "boxstack") { scene = new BoxstackScene(root); } else if (id == "response") { scene = new CollisionResponse(root); } else if (id == "dominoday") { scene = new DominoDay(root); } else if (id == "clothbox") { scene = new ClothBox(root); } else if (id == "rotatingcloth") { scene = new RotatingCloth(root); } else if (id == "specification") { scene = new SpecificationScene(root); } else if (id == "wall") { scene = new WallScene(root); } else if (id == "shake") { scene = new ShakeScene(root); } else if (id == "marblerun") { scene = new MarblerunScene(root); } else if (id == "deforming") { scene = new Deforming(root); } else if (id == "hangingcloth") { scene = new HangingClothScene(root); } else if (id == "mixedbenchmark") { scene = new MixedBenchmark(root); } else if (id == "deformablebenchmark") { scene = new DeformableBenchmark(root); } #ifndef DCOLLIDE_BUILD_RELEASE_VERSION else if (id == "devtest") { scene = new DevTestScene(root); } #endif if (!scene) { std::cerr << dc_funcinfo << "unknown identifier " << id << std::endl; return 0; } mScenes.insert(make_pair(id, scene)); return scene; } /*! * \brief scene titles * * these titles are displayed in the scene-chooser combobox * used format is [SceneID] short Title */ std::list<std::string> SceneManager::getAvailableSceneTitles() const { std::list<std::string> sceneTitles; for (std::map<std::string, std::string>::const_iterator iter = mSceneTitles.begin(); iter != mSceneTitles.end(); ++iter) { sceneTitles.push_back((*iter).second); } return sceneTitles; } std::list<std::string> SceneManager::getAvailableSceneIds() const { std::list<std::string> sceneIds; for (std::map<std::string, std::string>::const_iterator iter = mSceneTitles.begin(); iter != mSceneTitles.end(); ++iter) { sceneIds.push_back((*iter).first); } return sceneIds; } std::string SceneManager::getSceneTitle(const std::string& sceneId) const{ std::map<std::string, std::string>::const_iterator findIter = mSceneTitles.find(sceneId); if (findIter != mSceneTitles.end()) { return (*findIter).second; } return "n.A."; } /*! * Deletes the scene \p scene from the internal list, as well as the \p scene * object itself. */ void SceneManager::deleteScene(SceneBase* scene) { for (std::map<std::string, SceneBase*>::iterator it = mScenes.begin(); it != mScenes.end(); ++it) { if ((*it).second == scene) { delete scene; scene = 0; mScenes.erase(it); break; } } delete scene; // in case it was not in the map } /*! * \return The scene ID of a \p scene that was created using \ref createScene, * or an empty string if \p scene is not known to the SceneManager */ std::string SceneManager::getSceneId(SceneBase* scene) const { for (std::map<std::string, SceneBase*>::const_iterator it = mScenes.begin(); it != mScenes.end(); ++it) { if ((*it).second == scene) { return (*it).first; } } return ""; } /* * vim: et sw=4 ts=4 */
44.436137
161
0.609296
ColinGilbert
9d359e9a7e2c6b30b4f10d972a6ff2c0afe86528
20,386
cpp
C++
Source/ThirdParty/NewtonDynamics/include/packages/dContainers/dCRC.cpp
nigeyuk/HevEn
0dc970d6ecd0e5fd5512441562e2fdb4620214f0
[ "CC-BY-3.0" ]
15
2017-03-15T15:41:13.000Z
2022-01-11T01:15:12.000Z
Source/ThirdParty/NewtonDynamics/include/packages/dContainers/dCRC.cpp
nigeyuk/HevEn
0dc970d6ecd0e5fd5512441562e2fdb4620214f0
[ "CC-BY-3.0" ]
null
null
null
Source/ThirdParty/NewtonDynamics/include/packages/dContainers/dCRC.cpp
nigeyuk/HevEn
0dc970d6ecd0e5fd5512441562e2fdb4620214f0
[ "CC-BY-3.0" ]
3
2017-03-17T12:28:48.000Z
2020-03-19T19:32:02.000Z
/* Copyright (c) <2003-2016> <Newton Game Dynamics> * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely */ #include "dContainersStdAfx.h" #include "dCRC.h" /* static dCRCTYPE randBits0[] = { 7266447313870364031ULL, 4946485549665804864ULL, 16945909448695747420ULL, 16394063075524226720ULL, 4873882236456199058ULL, 14877448043947020171ULL, 6740343660852211943ULL, 13857871200353263164ULL, 5249110015610582907ULL, 10205081126064480383ULL, 1235879089597390050ULL, 17320312680810499042ULL, 16489141110565194782ULL, 8942268601720066061ULL, 13520575722002588570ULL, 14226945236717732373ULL, 9383926873555417063ULL, 15690281668532552105ULL, 11510704754157191257ULL, 15864264574919463609ULL, 6489677788245343319ULL, 5112602299894754389ULL, 10828930062652518694ULL, 15942305434158995996ULL, 15445717675088218264ULL, 4764500002345775851ULL, 14673753115101942098ULL, 236502320419669032ULL, 13670483975188204088ULL, 14931360615268175698ULL, 8904234204977263924ULL, 12836915408046564963ULL, 12120302420213647524ULL, 15755110976537356441ULL, 5405758943702519480ULL, 10951858968426898805ULL, 17251681303478610375ULL, 4144140664012008120ULL, 18286145806977825275ULL, 13075804672185204371ULL, 10831805955733617705ULL, 6172975950399619139ULL, 12837097014497293886ULL, 12903857913610213846ULL, 560691676108914154ULL, 1074659097419704618ULL, 14266121283820281686ULL, 11696403736022963346ULL, 13383246710985227247ULL, 7132746073714321322ULL, 10608108217231874211ULL, 9027884570906061560ULL, 12893913769120703138ULL, 15675160838921962454ULL, 2511068401785704737ULL, 14483183001716371453ULL, 3774730664208216065ULL, 5083371700846102796ULL, 9583498264570933637ULL, 17119870085051257224ULL, 5217910858257235075ULL, 10612176809475689857ULL, 1924700483125896976ULL, 7171619684536160599ULL, 10949279256701751503ULL, 15596196964072664893ULL, 14097948002655599357ULL, 615821766635933047ULL, 5636498760852923045ULL, 17618792803942051220ULL, 580805356741162327ULL, 425267967796817241ULL, 8381470634608387938ULL, 13212228678420887626ULL, 16993060308636741960ULL, 957923366004347591ULL, 6210242862396777185ULL, 1012818702180800310ULL, 15299383925974515757ULL, 17501832009465945633ULL, 17453794942891241229ULL, 15807805462076484491ULL, 8407189590930420827ULL, 974125122787311712ULL, 1861591264068118966ULL, 997568339582634050ULL, 18046771844467391493ULL, 17981867688435687790ULL, 3809841506498447207ULL, 9460108917638135678ULL, 16172980638639374310ULL, 958022432077424298ULL, 4393365126459778813ULL, 13408683141069553686ULL, 13900005529547645957ULL, 15773550354402817866ULL, 16475327524349230602ULL, 6260298154874769264ULL, 12224576659776460914ULL, 6405294864092763507ULL, 7585484664713203306ULL, 5187641382818981381ULL, 12435998400285353380ULL, 13554353441017344755ULL, 646091557254529188ULL, 11393747116974949255ULL, 16797249248413342857ULL, 15713519023537495495ULL, 12823504709579858843ULL, 4738086532119935073ULL, 4429068783387643752ULL, 585582692562183870ULL, 1048280754023674130ULL, 6788940719869959076ULL, 11670856244972073775ULL, 2488756775360218862ULL, 2061695363573180185ULL, 6884655301895085032ULL, 3566345954323888697ULL, 12784319933059041817ULL, 4772468691551857254ULL, 6864898938209826895ULL, 7198730565322227090ULL, 2452224231472687253ULL, 13424792606032445807ULL, 10827695224855383989ULL, 11016608897122070904ULL, 14683280565151378358ULL, 7077866519618824360ULL, 17487079941198422333ULL, 3956319990205097495ULL, 5804870313319323478ULL, 8017203611194497730ULL, 3310931575584983808ULL, 5009341981771541845ULL, 11772020174577005930ULL, 3537640779967351792ULL, 6801855569284252424ULL, 17687268231192623388ULL, 12968358613633237218ULL, 1429775571144180123ULL, 10427377732172208413ULL, 12155566091986788996ULL, 16465954421598296115ULL, 12710429690464359999ULL, 9547226351541565595ULL, 12156624891403410342ULL, 2985938688676214686ULL, 18066917785985010959ULL, 5975570403614438776ULL, 11541343163022500560ULL, 11115388652389704592ULL, 9499328389494710074ULL, 9247163036769651820ULL, 3688303938005101774ULL, 2210483654336887556ULL, 15458161910089693228ULL, 6558785204455557683ULL, 1288373156735958118ULL, 18433986059948829624ULL, 3435082195390932486ULL, 16822351800343061990ULL, 3120532877336962310ULL, 16681785111062885568ULL, 7835551710041302304ULL, 2612798015018627203ULL, 15083279177152657491ULL, 6591467229462292195ULL, 10592706450534565444ULL, 7438147750787157163ULL, 323186165595851698ULL, 7444710627467609883ULL, 8473714411329896576ULL, 2782675857700189492ULL, 3383567662400128329ULL, 3200233909833521327ULL, 12897601280285604448ULL, 3612068790453735040ULL, 8324209243736219497ULL, 15789570356497723463ULL, 1083312926512215996ULL, 4797349136059339390ULL, 5556729349871544986ULL, 18266943104929747076ULL, 1620389818516182276ULL, 172225355691600141ULL, 3034352936522087096ULL, 1266779576738385285ULL, 3906668377244742888ULL, 6961783143042492788ULL, 17159706887321247572ULL, 4676208075243319061ULL, 10315634697142985816ULL, 13435140047933251189ULL, 716076639492622016ULL, 13847954035438697558ULL, 7195811275139178570ULL, 10815312636510328870ULL, 6214164734784158515ULL, 16412194511839921544ULL, 3862249798930641332ULL, 1005482699535576005ULL, 4644542796609371301ULL, 17600091057367987283ULL, 4209958422564632034ULL, 5419285945389823940ULL, 11453701547564354601ULL, 9951588026679380114ULL, 7425168333159839689ULL, 8436306210125134906ULL, 11216615872596820107ULL, 3681345096403933680ULL, 5770016989916553752ULL, 11102855936150871733ULL, 11187980892339693935ULL, 396336430216428875ULL, 6384853777489155236ULL, 7551613839184151117ULL, 16527062023276943109ULL, 13429850429024956898ULL, 9901753960477271766ULL, 9731501992702612259ULL, 5217575797614661659ULL, 10311708346636548706ULL, 15111747519735330483ULL, 4353415295139137513ULL, 1845293119018433391ULL, 11952006873430493561ULL, 3531972641585683893ULL, 16852246477648409827ULL, 15956854822143321380ULL, 12314609993579474774ULL, 16763911684844598963ULL, 16392145690385382634ULL, 1545507136970403756ULL, 17771199061862790062ULL, 12121348462972638971ULL, 12613068545148305776ULL, 954203144844315208ULL, 1257976447679270605ULL, 3664184785462160180ULL, 2747964788443845091ULL, 15895917007470512307ULL, 15552935765724302120ULL, 16366915862261682626ULL, 8385468783684865323ULL, 10745343827145102946ULL, 2485742734157099909ULL, 916246281077683950ULL, 15214206653637466707ULL, 12895483149474345798ULL, 1079510114301747843ULL, 10718876134480663664ULL, 1259990987526807294ULL, 8326303777037206221ULL, 14104661172014248293ULL, }; */ static dCRCTYPE randBits0[] = { static_cast<long long>(7266447313870364031ULL), static_cast<long long>(4946485549665804864ULL), static_cast<long long>(16945909448695747420ULL), static_cast<long long>(16394063075524226720ULL), static_cast<long long>(4873882236456199058ULL), static_cast<long long>(14877448043947020171ULL), static_cast<long long>(6740343660852211943ULL), static_cast<long long>(13857871200353263164ULL), static_cast<long long>(5249110015610582907ULL), static_cast<long long>(10205081126064480383ULL), static_cast<long long>(1235879089597390050ULL), static_cast<long long>(17320312680810499042ULL), static_cast<long long>(16489141110565194782ULL), static_cast<long long>(8942268601720066061ULL), static_cast<long long>(13520575722002588570ULL), static_cast<long long>(14226945236717732373ULL), static_cast<long long>(9383926873555417063ULL), static_cast<long long>(15690281668532552105ULL), static_cast<long long>(11510704754157191257ULL), static_cast<long long>(15864264574919463609ULL), static_cast<long long>(6489677788245343319ULL), static_cast<long long>(5112602299894754389ULL), static_cast<long long>(10828930062652518694ULL), static_cast<long long>(15942305434158995996ULL), static_cast<long long>(15445717675088218264ULL), static_cast<long long>(4764500002345775851ULL), static_cast<long long>(14673753115101942098ULL), static_cast<long long>(236502320419669032ULL), static_cast<long long>(13670483975188204088ULL), static_cast<long long>(14931360615268175698ULL), static_cast<long long>(8904234204977263924ULL), static_cast<long long>(12836915408046564963ULL), static_cast<long long>(12120302420213647524ULL), static_cast<long long>(15755110976537356441ULL), static_cast<long long>(5405758943702519480ULL), static_cast<long long>(10951858968426898805ULL), static_cast<long long>(17251681303478610375ULL), static_cast<long long>(4144140664012008120ULL), static_cast<long long>(18286145806977825275ULL), static_cast<long long>(13075804672185204371ULL), static_cast<long long>(10831805955733617705ULL), static_cast<long long>(6172975950399619139ULL), static_cast<long long>(12837097014497293886ULL), static_cast<long long>(12903857913610213846ULL), static_cast<long long>(560691676108914154ULL), static_cast<long long>(1074659097419704618ULL), static_cast<long long>(14266121283820281686ULL), static_cast<long long>(11696403736022963346ULL), static_cast<long long>(13383246710985227247ULL), static_cast<long long>(7132746073714321322ULL), static_cast<long long>(10608108217231874211ULL), static_cast<long long>(9027884570906061560ULL), static_cast<long long>(12893913769120703138ULL), static_cast<long long>(15675160838921962454ULL), static_cast<long long>(2511068401785704737ULL), static_cast<long long>(14483183001716371453ULL), static_cast<long long>(3774730664208216065ULL), static_cast<long long>(5083371700846102796ULL), static_cast<long long>(9583498264570933637ULL), static_cast<long long>(17119870085051257224ULL), static_cast<long long>(5217910858257235075ULL), static_cast<long long>(10612176809475689857ULL), static_cast<long long>(1924700483125896976ULL), static_cast<long long>(7171619684536160599ULL), static_cast<long long>(10949279256701751503ULL), static_cast<long long>(15596196964072664893ULL), static_cast<long long>(14097948002655599357ULL), static_cast<long long>(615821766635933047ULL), static_cast<long long>(5636498760852923045ULL), static_cast<long long>(17618792803942051220ULL), static_cast<long long>(580805356741162327ULL), static_cast<long long>(425267967796817241ULL), static_cast<long long>(8381470634608387938ULL), static_cast<long long>(13212228678420887626ULL), static_cast<long long>(16993060308636741960ULL), static_cast<long long>(957923366004347591ULL), static_cast<long long>(6210242862396777185ULL), static_cast<long long>(1012818702180800310ULL), static_cast<long long>(15299383925974515757ULL), static_cast<long long>(17501832009465945633ULL), static_cast<long long>(17453794942891241229ULL), static_cast<long long>(15807805462076484491ULL), static_cast<long long>(8407189590930420827ULL), static_cast<long long>(974125122787311712ULL), static_cast<long long>(1861591264068118966ULL), static_cast<long long>(997568339582634050ULL), static_cast<long long>(18046771844467391493ULL), static_cast<long long>(17981867688435687790ULL), static_cast<long long>(3809841506498447207ULL), static_cast<long long>(9460108917638135678ULL), static_cast<long long>(16172980638639374310ULL), static_cast<long long>(958022432077424298ULL), static_cast<long long>(4393365126459778813ULL), static_cast<long long>(13408683141069553686ULL), static_cast<long long>(13900005529547645957ULL), static_cast<long long>(15773550354402817866ULL), static_cast<long long>(16475327524349230602ULL), static_cast<long long>(6260298154874769264ULL), static_cast<long long>(12224576659776460914ULL), static_cast<long long>(6405294864092763507ULL), static_cast<long long>(7585484664713203306ULL), static_cast<long long>(5187641382818981381ULL), static_cast<long long>(12435998400285353380ULL), static_cast<long long>(13554353441017344755ULL), static_cast<long long>(646091557254529188ULL), static_cast<long long>(11393747116974949255ULL), static_cast<long long>(16797249248413342857ULL), static_cast<long long>(15713519023537495495ULL), static_cast<long long>(12823504709579858843ULL), static_cast<long long>(4738086532119935073ULL), static_cast<long long>(4429068783387643752ULL), static_cast<long long>(585582692562183870ULL), static_cast<long long>(1048280754023674130ULL), static_cast<long long>(6788940719869959076ULL), static_cast<long long>(11670856244972073775ULL), static_cast<long long>(2488756775360218862ULL), static_cast<long long>(2061695363573180185ULL), static_cast<long long>(6884655301895085032ULL), static_cast<long long>(3566345954323888697ULL), static_cast<long long>(12784319933059041817ULL), static_cast<long long>(4772468691551857254ULL), static_cast<long long>(6864898938209826895ULL), static_cast<long long>(7198730565322227090ULL), static_cast<long long>(2452224231472687253ULL), static_cast<long long>(13424792606032445807ULL), static_cast<long long>(10827695224855383989ULL), static_cast<long long>(11016608897122070904ULL), static_cast<long long>(14683280565151378358ULL), static_cast<long long>(7077866519618824360ULL), static_cast<long long>(17487079941198422333ULL), static_cast<long long>(3956319990205097495ULL), static_cast<long long>(5804870313319323478ULL), static_cast<long long>(8017203611194497730ULL), static_cast<long long>(3310931575584983808ULL), static_cast<long long>(5009341981771541845ULL), static_cast<long long>(11772020174577005930ULL), static_cast<long long>(3537640779967351792ULL), static_cast<long long>(6801855569284252424ULL), static_cast<long long>(17687268231192623388ULL), static_cast<long long>(12968358613633237218ULL), static_cast<long long>(1429775571144180123ULL), static_cast<long long>(10427377732172208413ULL), static_cast<long long>(12155566091986788996ULL), static_cast<long long>(16465954421598296115ULL), static_cast<long long>(12710429690464359999ULL), static_cast<long long>(9547226351541565595ULL), static_cast<long long>(12156624891403410342ULL), static_cast<long long>(2985938688676214686ULL), static_cast<long long>(18066917785985010959ULL), static_cast<long long>(5975570403614438776ULL), static_cast<long long>(11541343163022500560ULL), static_cast<long long>(11115388652389704592ULL), static_cast<long long>(9499328389494710074ULL), static_cast<long long>(9247163036769651820ULL), static_cast<long long>(3688303938005101774ULL), static_cast<long long>(2210483654336887556ULL), static_cast<long long>(15458161910089693228ULL), static_cast<long long>(6558785204455557683ULL), static_cast<long long>(1288373156735958118ULL), static_cast<long long>(18433986059948829624ULL), static_cast<long long>(3435082195390932486ULL), static_cast<long long>(16822351800343061990ULL), static_cast<long long>(3120532877336962310ULL), static_cast<long long>(16681785111062885568ULL), static_cast<long long>(7835551710041302304ULL), static_cast<long long>(2612798015018627203ULL), static_cast<long long>(15083279177152657491ULL), static_cast<long long>(6591467229462292195ULL), static_cast<long long>(10592706450534565444ULL), static_cast<long long>(7438147750787157163ULL), static_cast<long long>(323186165595851698ULL), static_cast<long long>(7444710627467609883ULL), static_cast<long long>(8473714411329896576ULL), static_cast<long long>(2782675857700189492ULL), static_cast<long long>(3383567662400128329ULL), static_cast<long long>(3200233909833521327ULL), static_cast<long long>(12897601280285604448ULL), static_cast<long long>(3612068790453735040ULL), static_cast<long long>(8324209243736219497ULL), static_cast<long long>(15789570356497723463ULL), static_cast<long long>(1083312926512215996ULL), static_cast<long long>(4797349136059339390ULL), static_cast<long long>(5556729349871544986ULL), static_cast<long long>(18266943104929747076ULL), static_cast<long long>(1620389818516182276ULL), static_cast<long long>(172225355691600141ULL), static_cast<long long>(3034352936522087096ULL), static_cast<long long>(1266779576738385285ULL), static_cast<long long>(3906668377244742888ULL), static_cast<long long>(6961783143042492788ULL), static_cast<long long>(17159706887321247572ULL), static_cast<long long>(4676208075243319061ULL), static_cast<long long>(10315634697142985816ULL), static_cast<long long>(13435140047933251189ULL), static_cast<long long>(716076639492622016ULL), static_cast<long long>(13847954035438697558ULL), static_cast<long long>(7195811275139178570ULL), static_cast<long long>(10815312636510328870ULL), static_cast<long long>(6214164734784158515ULL), static_cast<long long>(16412194511839921544ULL), static_cast<long long>(3862249798930641332ULL), static_cast<long long>(1005482699535576005ULL), static_cast<long long>(4644542796609371301ULL), static_cast<long long>(17600091057367987283ULL), static_cast<long long>(4209958422564632034ULL), static_cast<long long>(5419285945389823940ULL), static_cast<long long>(11453701547564354601ULL), static_cast<long long>(9951588026679380114ULL), static_cast<long long>(7425168333159839689ULL), static_cast<long long>(8436306210125134906ULL), static_cast<long long>(11216615872596820107ULL), static_cast<long long>(3681345096403933680ULL), static_cast<long long>(5770016989916553752ULL), static_cast<long long>(11102855936150871733ULL), static_cast<long long>(11187980892339693935ULL), static_cast<long long>(396336430216428875ULL), static_cast<long long>(6384853777489155236ULL), static_cast<long long>(7551613839184151117ULL), static_cast<long long>(16527062023276943109ULL), static_cast<long long>(13429850429024956898ULL), static_cast<long long>(9901753960477271766ULL), static_cast<long long>(9731501992702612259ULL), static_cast<long long>(5217575797614661659ULL), static_cast<long long>(10311708346636548706ULL), static_cast<long long>(15111747519735330483ULL), static_cast<long long>(4353415295139137513ULL), static_cast<long long>(1845293119018433391ULL), static_cast<long long>(11952006873430493561ULL), static_cast<long long>(3531972641585683893ULL), static_cast<long long>(16852246477648409827ULL), static_cast<long long>(15956854822143321380ULL), static_cast<long long>(12314609993579474774ULL), static_cast<long long>(16763911684844598963ULL), static_cast<long long>(16392145690385382634ULL), static_cast<long long>(1545507136970403756ULL), static_cast<long long>(17771199061862790062ULL), static_cast<long long>(12121348462972638971ULL), static_cast<long long>(12613068545148305776ULL), static_cast<long long>(954203144844315208ULL), static_cast<long long>(1257976447679270605ULL), static_cast<long long>(3664184785462160180ULL), static_cast<long long>(2747964788443845091ULL), static_cast<long long>(15895917007470512307ULL), static_cast<long long>(15552935765724302120ULL), static_cast<long long>(16366915862261682626ULL), static_cast<long long>(8385468783684865323ULL), static_cast<long long>(10745343827145102946ULL), static_cast<long long>(2485742734157099909ULL), static_cast<long long>(916246281077683950ULL), static_cast<long long>(15214206653637466707ULL), static_cast<long long>(12895483149474345798ULL), static_cast<long long>(1079510114301747843ULL), static_cast<long long>(10718876134480663664ULL), static_cast<long long>(1259990987526807294ULL), static_cast<long long>(8326303777037206221ULL), static_cast<long long>(14104661172014248293ULL), }; dCRCTYPE dCombineCRC (dCRCTYPE a, dCRCTYPE b) { return (a << 8) ^ b; } // calculate a 32 bit crc of a string dCRCTYPE dCRC64 (const char* const name, dCRCTYPE crcAcc) { if (name) { const int bitshift = (sizeof (dCRCTYPE)<<3) - 8; for (int i = 0; name[i]; i ++) { char c = name[i]; dCRCTYPE val = randBits0[((crcAcc >> bitshift) ^ c) & 0xff]; crcAcc = (crcAcc << 8) ^ val; } } return crcAcc; } dCRCTYPE dCRC64 (const void* const buffer, int size, dCRCTYPE crcAcc) { const unsigned char* const ptr = (unsigned char*)buffer; const int bitshift = (sizeof (dCRCTYPE)<<3) - 8; for (int i = 0; i < size; i ++) { char c = ptr[i]; dCRCTYPE val = randBits0[((crcAcc >> bitshift) ^ c) & 0xff]; crcAcc = (crcAcc << 8) ^ val; } return crcAcc; }
92.663636
199
0.842882
nigeyuk
9d37efdd720fdf2095dc30e105835c774a216a57
2,592
cpp
C++
source/GUI/GUIButton.cpp
badbrainz/pme
1c8e6f3d154cc59613f5ef3f2f8293f488c64b28
[ "WTFPL" ]
null
null
null
source/GUI/GUIButton.cpp
badbrainz/pme
1c8e6f3d154cc59613f5ef3f2f8293f488c64b28
[ "WTFPL" ]
null
null
null
source/GUI/GUIButton.cpp
badbrainz/pme
1c8e6f3d154cc59613f5ef3f2f8293f488c64b28
[ "WTFPL" ]
null
null
null
#include "GUIButton.h" #include "GUIAlphaElement.h" #include "GUIClippedRectangle.h" #include "../Tools/Logger.h" GUIButton::GUIButton(const char *cbs) : GUIAlphaElement(cbs), GUIClippedRectangle() { setBordersColor(0.0f, 0.0f, 0.0f); setDimensions(40, 22); setPosition(0.5, 0.5); setColor(100, 150, 190); widgetType = BUTTON; drawBackground = true; drawBounds = true; bounce = true; } bool GUIButton::loadXMLSettings(XMLElement *element) { if (!element || element->getName() != "Button") return Logger::writeErrorLog("Need a Button node in the xml file"); XMLElement *child = NULL; if (child = element->getChildByName("bounce")) enableBounce((child->getValue() == "true")); return GUIAlphaElement::loadXMLSettings(element) && GUIClippedRectangle::loadXMLClippedRectangleInfo(element); } void GUIButton::enableBounce(bool bounce_) { bounce = bounce_; } bool GUIButton::bounceEnabled() { return bounce; } void GUIButton::render(float clockTick) { if (!parent || !visible) return; modifyCurrentAlpha(clockTick); bgColor = color; Tuple3f tempColor = label.getColor(); float displacement = 2.0f*(pressed || clicked)*bounce; int xCenter = (windowBounds.x + windowBounds.z)/2, yCenter = (windowBounds.y + windowBounds.w)/2; glTranslatef(displacement, displacement, 0.0); renderClippedBounds(); label.printCenteredXY(xCenter, yCenter); glTranslatef(-displacement, -displacement, 0.0f); } const void GUIButton::computeWindowBounds() { if (parent && update) { GUIRectangle::computeWindowBounds(); label.computeDimensions(); int width = windowBounds.z - windowBounds.x, height = windowBounds.w - windowBounds.y; if (width <= label.getWidth() + 2*clipSize) { if (anchor == CENTER) { width = (label.getWidth() - width)/2 + clipSize + 2; windowBounds.x -=width; windowBounds.z +=width; } if ((anchor == CORNERLU) || (anchor == CORNERLD)) { width = (label.getWidth() - width)/2 + clipSize + 2; windowBounds.z +=2*width; } } if (height + 2*clipSize < label.getHeight()) { height = (label.getHeight() - height)/2 + clipSize + 2; windowBounds.y -= height; windowBounds.w += height; } computeClippedBounds(windowBounds); } }
26.44898
84
0.59375
badbrainz
9d39f3f0190f081772a317fb4aa185c5196469bb
3,669
cpp
C++
src/packet.cpp
caseycs/pinba2
931a820e12cbc41fd5c19e87bdbfd9811c7a969b
[ "BSD-3-Clause" ]
108
2018-11-02T08:41:11.000Z
2022-02-17T22:27:23.000Z
src/packet.cpp
caseycs/pinba2
931a820e12cbc41fd5c19e87bdbfd9811c7a969b
[ "BSD-3-Clause" ]
19
2018-11-02T06:54:37.000Z
2021-09-02T15:45:40.000Z
src/packet.cpp
caseycs/pinba2
931a820e12cbc41fd5c19e87bdbfd9811c7a969b
[ "BSD-3-Clause" ]
17
2018-11-08T14:14:31.000Z
2021-12-16T15:57:38.000Z
#include <cmath> #include "pinba/globals.h" #include "pinba/limits.h" #include "pinba/dictionary.h" #include "pinba/packet.h" #include "pinba/bloom.h" #include "proto/pinba.pb-c.h" //////////////////////////////////////////////////////////////////////////////////////////////// request_validate_result_t pinba_validate_request(Pinba__Request *r) { if (r->status >= PINBA_INTERNAL___STATUS_MAX) return request_validate_result::status_is_too_large; if (r->n_timer_value != r->n_timer_hit_count) // all timers have hit counts return request_validate_result::bad_hit_count; if (r->n_timer_value != r->n_timer_tag_count) // all timers have tag counts return request_validate_result::bad_tag_count; // NOTE(antoxa): some clients don't send rusage at all, let them // if (r->n_timer_value != r->n_timer_ru_utime) // return request_validate_result::bad_timer_ru_utime_count; // if (r->n_timer_value != r->n_timer_ru_stime) // return request_validate_result::bad_timer_ru_stime_count; // all timer hit counts are > 0 for (unsigned i = 0; i < r->n_timer_hit_count; i++) { if (r->timer_hit_count[i] <= 0) return request_validate_result::bad_timer_hit_count; } auto const total_tag_count = [&]() { size_t result = 0; for (unsigned i = 0; i < r->n_timer_tag_count; i++) { result += r->timer_tag_count[i]; } return result; }(); if (total_tag_count != r->n_timer_tag_name) // all tags have names return request_validate_result::not_enough_tag_names; if (total_tag_count != r->n_timer_tag_value) // all tags have values return request_validate_result::not_enough_tag_values; // request_time should be > 0, reset to 0 when < 0 { switch (std::fpclassify(r->request_time)) { case FP_ZERO: break; case FP_NORMAL: break; default: return request_validate_result::bad_float_request_time; } if (std::signbit(r->request_time)) r->request_time = 0; } // NOTE(antoxa): this should not happen, but happens A LOT // so just reset them to zero if negative { switch (std::fpclassify(r->ru_utime)) { case FP_ZERO: break; case FP_NORMAL: break; default: return request_validate_result::bad_float_ru_utime; } if (std::signbit(r->ru_utime)) r->ru_utime = 0; } { switch (std::fpclassify(r->ru_stime)) { case FP_ZERO: break; case FP_NORMAL: break; default: return request_validate_result::bad_float_ru_stime; } if (std::signbit(r->ru_stime)) r->ru_stime = 0; } // timer values must be >= 0 for (unsigned i = 0; i < r->n_timer_value; i++) { switch (std::fpclassify(r->timer_value[i])) { case FP_ZERO: break; case FP_NORMAL: break; default: return request_validate_result::bad_float_timer_value; } if (std::signbit(r->timer_value[i])) return request_validate_result::negative_float_timer_value; } // NOTE(antoxa): same as r->ru_utime, r->ru_stime // negative values happen, just make them zero for (unsigned i = 0; i < r->n_timer_ru_utime; i++) { switch (std::fpclassify(r->timer_ru_utime[i])) { case FP_ZERO: break; case FP_NORMAL: break; default: return request_validate_result::bad_float_timer_ru_utime; } if (std::signbit(r->timer_ru_utime[i])) r->timer_ru_utime[i] = 0; } for (unsigned i = 0; i < r->n_timer_ru_stime; i++) { switch (std::fpclassify(r->timer_ru_stime[i])) { case FP_ZERO: break; case FP_NORMAL: break; default: return request_validate_result::bad_float_timer_ru_stime; } if (std::signbit(r->timer_ru_stime[i])) r->timer_ru_stime[i] = 0; } return request_validate_result::okay; }
27.795455
96
0.668029
caseycs
9d3b307777eab0216ffa4b6eecbf69b5361b2fcb
5,091
cpp
C++
framework/tlvf/AutoGenerated/src/tlvf/wfa_map/tlvBackhaulSteeringResponse.cpp
SWRT-dev/easymesh
12d902edde77599e074c0535f7256499b08f7494
[ "BSD-3-Clause", "BSD-2-Clause-Patent", "MIT" ]
85
2018-10-24T22:18:35.000Z
2022-02-24T09:11:56.000Z
framework/tlvf/AutoGenerated/src/tlvf/wfa_map/tlvBackhaulSteeringResponse.cpp
SWRT-dev/easymesh
12d902edde77599e074c0535f7256499b08f7494
[ "BSD-3-Clause", "BSD-2-Clause-Patent", "MIT" ]
1,105
2018-10-03T14:04:58.000Z
2020-08-14T21:22:55.000Z
framework/tlvf/AutoGenerated/src/tlvf/wfa_map/tlvBackhaulSteeringResponse.cpp
orenvor/prplMesh
aebd37e7e194acd9fefa3cdd64fb84a8c9f733bd
[ "BSD-3-Clause", "BSD-2-Clause-Patent", "MIT" ]
43
2018-11-12T22:51:40.000Z
2021-12-26T07:40:39.000Z
/////////////////////////////////////// // AUTO GENERATED FILE - DO NOT EDIT // /////////////////////////////////////// /* SPDX-License-Identifier: BSD-2-Clause-Patent * * SPDX-FileCopyrightText: 2016-2020 the prplMesh contributors (see AUTHORS.md) * * This code is subject to the terms of the BSD+Patent license. * See LICENSE file for more details. */ #include <tlvf/wfa_map/tlvBackhaulSteeringResponse.h> #include <tlvf/tlvflogging.h> using namespace wfa_map; tlvBackhaulSteeringResponse::tlvBackhaulSteeringResponse(uint8_t* buff, size_t buff_len, bool parse) : BaseClass(buff, buff_len, parse) { m_init_succeeded = init(); } tlvBackhaulSteeringResponse::tlvBackhaulSteeringResponse(std::shared_ptr<BaseClass> base, bool parse) : BaseClass(base->getBuffPtr(), base->getBuffRemainingBytes(), parse){ m_init_succeeded = init(); } tlvBackhaulSteeringResponse::~tlvBackhaulSteeringResponse() { } const eTlvTypeMap& tlvBackhaulSteeringResponse::type() { return (const eTlvTypeMap&)(*m_type); } const uint16_t& tlvBackhaulSteeringResponse::length() { return (const uint16_t&)(*m_length); } sMacAddr& tlvBackhaulSteeringResponse::backhaul_station_mac() { return (sMacAddr&)(*m_backhaul_station_mac); } sMacAddr& tlvBackhaulSteeringResponse::target_bssid() { return (sMacAddr&)(*m_target_bssid); } tlvBackhaulSteeringResponse::eResultCode& tlvBackhaulSteeringResponse::result_code() { return (eResultCode&)(*m_result_code); } void tlvBackhaulSteeringResponse::class_swap() { tlvf_swap(16, reinterpret_cast<uint8_t*>(m_length)); m_backhaul_station_mac->struct_swap(); m_target_bssid->struct_swap(); tlvf_swap(8*sizeof(eResultCode), reinterpret_cast<uint8_t*>(m_result_code)); } bool tlvBackhaulSteeringResponse::finalize() { if (m_parse__) { TLVF_LOG(DEBUG) << "finalize() called but m_parse__ is set"; return true; } if (m_finalized__) { TLVF_LOG(DEBUG) << "finalize() called for already finalized class"; return true; } if (!isPostInitSucceeded()) { TLVF_LOG(ERROR) << "post init check failed"; return false; } if (m_inner__) { if (!m_inner__->finalize()) { TLVF_LOG(ERROR) << "m_inner__->finalize() failed"; return false; } auto tailroom = m_inner__->getMessageBuffLength() - m_inner__->getMessageLength(); m_buff_ptr__ -= tailroom; *m_length -= tailroom; } class_swap(); m_finalized__ = true; return true; } size_t tlvBackhaulSteeringResponse::get_initial_size() { size_t class_size = 0; class_size += sizeof(eTlvTypeMap); // type class_size += sizeof(uint16_t); // length class_size += sizeof(sMacAddr); // backhaul_station_mac class_size += sizeof(sMacAddr); // target_bssid class_size += sizeof(eResultCode); // result_code return class_size; } bool tlvBackhaulSteeringResponse::init() { if (getBuffRemainingBytes() < get_initial_size()) { TLVF_LOG(ERROR) << "Not enough available space on buffer. Class init failed"; return false; } m_type = reinterpret_cast<eTlvTypeMap*>(m_buff_ptr__); if (!m_parse__) *m_type = eTlvTypeMap::TLV_BACKHAUL_STEERING_RESPONSE; if (!buffPtrIncrementSafe(sizeof(eTlvTypeMap))) { LOG(ERROR) << "buffPtrIncrementSafe(" << std::dec << sizeof(eTlvTypeMap) << ") Failed!"; return false; } m_length = reinterpret_cast<uint16_t*>(m_buff_ptr__); if (!m_parse__) *m_length = 0; if (!buffPtrIncrementSafe(sizeof(uint16_t))) { LOG(ERROR) << "buffPtrIncrementSafe(" << std::dec << sizeof(uint16_t) << ") Failed!"; return false; } m_backhaul_station_mac = reinterpret_cast<sMacAddr*>(m_buff_ptr__); if (!buffPtrIncrementSafe(sizeof(sMacAddr))) { LOG(ERROR) << "buffPtrIncrementSafe(" << std::dec << sizeof(sMacAddr) << ") Failed!"; return false; } if(m_length && !m_parse__){ (*m_length) += sizeof(sMacAddr); } if (!m_parse__) { m_backhaul_station_mac->struct_init(); } m_target_bssid = reinterpret_cast<sMacAddr*>(m_buff_ptr__); if (!buffPtrIncrementSafe(sizeof(sMacAddr))) { LOG(ERROR) << "buffPtrIncrementSafe(" << std::dec << sizeof(sMacAddr) << ") Failed!"; return false; } if(m_length && !m_parse__){ (*m_length) += sizeof(sMacAddr); } if (!m_parse__) { m_target_bssid->struct_init(); } m_result_code = reinterpret_cast<eResultCode*>(m_buff_ptr__); if (!buffPtrIncrementSafe(sizeof(eResultCode))) { LOG(ERROR) << "buffPtrIncrementSafe(" << std::dec << sizeof(eResultCode) << ") Failed!"; return false; } if(m_length && !m_parse__){ (*m_length) += sizeof(eResultCode); } if (m_parse__) { class_swap(); } if (m_parse__) { if (*m_type != eTlvTypeMap::TLV_BACKHAUL_STEERING_RESPONSE) { TLVF_LOG(ERROR) << "TLV type mismatch. Expected value: " << int(eTlvTypeMap::TLV_BACKHAUL_STEERING_RESPONSE) << ", received value: " << int(*m_type); return false; } } return true; }
35.354167
161
0.666077
SWRT-dev
9d3c414ae86ce3ada2ef92da5938d299d3d93a6e
1,218
cpp
C++
example.cpp
LTU-CEG/libserialpipe
0000e0466581b68c4674ac87cc358f27f430c872
[ "BSL-1.0" ]
null
null
null
example.cpp
LTU-CEG/libserialpipe
0000e0466581b68c4674ac87cc358f27f430c872
[ "BSL-1.0" ]
null
null
null
example.cpp
LTU-CEG/libserialpipe
0000e0466581b68c4674ac87cc358f27f430c872
[ "BSL-1.0" ]
null
null
null
// Copyright Emil Fresk 2015-2017. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE.md or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <iostream> #include "serialpipe.hpp" using namespace std; void test(const std::vector<uint8_t> &data); int main() { /* Create serial pipe */ serialpipe::bridge sp("/dev/ttyUSB0", 57600, 10, true); /* serialpipe usage: * * serialpipe("port", * baudrate, * timeout (in ms), (optional, 1000 default) * string data (true / false) (optional, true default) * string termination); (optional, "\n" default) */ /* Register a callback */ sp.registerCallback(test); /* Open the serial port */ sp.openPort(); /* Transmit some data... */ sp.serialTransmit("test test test"); cin.get(); /* Close port */ sp.closePort(); return 0; } /* Print incoming data... */ void test(const std::vector<uint8_t> &data) { cout << "Data received: "; for (const uint8_t &ch : data) { cout << static_cast<char>( ch ); } cout << endl; }
21.75
72
0.560755
LTU-CEG
9d3cac6432e83e261a760582a2b9344d8228faee
1,081
cpp
C++
hihocoder/calculate_strength.cpp
qiaotian/CodeInterview
294c1ba86d8ace41a121c5ada4ba4c3765ccc17d
[ "WTFPL" ]
5
2016-10-29T09:28:11.000Z
2019-10-19T23:02:48.000Z
hihocoder/calculate_strength.cpp
qiaotian/CodeInterview
294c1ba86d8ace41a121c5ada4ba4c3765ccc17d
[ "WTFPL" ]
null
null
null
hihocoder/calculate_strength.cpp
qiaotian/CodeInterview
294c1ba86d8ace41a121c5ada4ba4c3765ccc17d
[ "WTFPL" ]
null
null
null
/* Description 小Hi在虚拟世界中有一只小宠物小P。小P有K种属性,每种属性的初始值为Ai。小Ho送给了小Hi若干颗药丸,每颗药丸可以提高小P指定属性1点。通过属性值,我们可以计算小P的强力值=(C1(1/B1))*(C2(1/B2))*...*(CK(1/BK)),其中Ci为小P第i项属性的最终值(Ai+药丸增加的属性)。 已知小Ho送给小Hi的药丸一共有N颗,问小P的强力值最高能够达到多少? Input 第一行包含两个整数N,K,分别表示药丸数和属性种数。 第二行为K个整数A1 - AK,意义如前文所述。 第三行为K个整数B1 - BK,意义如前文所述。 对于30%的数据,满足1<=N<=10, 1<=K<=3 对于100%的数据,满足1<=N<=100000, 1<=K<=10 对于100%的数据,满足1<=Ai<=100, 1<=Bi<=10 Output 输出小P能够达到的最高的强力值。 只要你的结果与正确答案之间的相对或绝对误差不超过千分之一,都被是为正确的输出。 Sample Input 5 2 1 1 3 2 Sample Output 2.88 */ #include <iostream> #include <vector> using namespace std; double calVal(vector<int>& base, vector<int>& exp) { double ans = 1.0; for(int i=0; i<base.size(); i++) { ans*=(pow(base[i], 1.0/exp[i])); } return ans; } int calMaxPower(vector<int>& base, vector<int>& exp, int N) { // maxval[i] 是第i颗药丸分配给K种属性以后得到的最强力 // base表示当前各项属性值 // exp表示各项属性值的指数倒数,即B1,B2,B3... vector<double> maxval(N+1, 0); if(N<=0) return 0; maxval[0] = calVal(base, exp); for(int i=1; i<N+1; i++) { } } int main(void) { return 0; }
19.303571
191
0.653099
qiaotian
9d3ce8ce3c664643eac9a0d1abe018b8d79c7184
2,787
cpp
C++
TerrainApps/VTBuilder/PrefDlg.cpp
nakijun/vtp
7bd2b2abd3a3f778a32ba30be099cfba9b892922
[ "MIT" ]
4
2019-02-08T13:51:26.000Z
2021-12-07T13:11:06.000Z
TerrainApps/VTBuilder/PrefDlg.cpp
nakijun/vtp
7bd2b2abd3a3f778a32ba30be099cfba9b892922
[ "MIT" ]
null
null
null
TerrainApps/VTBuilder/PrefDlg.cpp
nakijun/vtp
7bd2b2abd3a3f778a32ba30be099cfba9b892922
[ "MIT" ]
7
2017-12-03T10:13:17.000Z
2022-03-29T09:51:18.000Z
// // Name: PrefDlg.cpp // // Copyright (c) 2007-2011 Virtual Terrain Project // Free for all uses, see license.txt for details. // // For compilers that support precompilation, includes "wx/wx.h". #include "wx/wxprec.h" #include "PrefDlg.h" #include "vtui/AutoDialog.h" // WDR: class implementations //---------------------------------------------------------------------------- // PrefDlg //---------------------------------------------------------------------------- // WDR: event table for PrefDlg BEGIN_EVENT_TABLE(PrefDlg, PrefDlgBase) EVT_INIT_DIALOG (PrefDlg::OnInitDialog) EVT_BUTTON( wxID_OK, PrefDlg::OnOK ) EVT_RADIOBUTTON( ID_RADIO1, PrefDlg::OnRadio ) EVT_RADIOBUTTON( ID_RADIO2, PrefDlg::OnRadio ) EVT_RADIOBUTTON( ID_RADIO3, PrefDlg::OnRadio ) EVT_RADIOBUTTON( ID_RADIO4, PrefDlg::OnRadio ) EVT_RADIOBUTTON( ID_RADIO5, PrefDlg::OnRadio ) EVT_RADIOBUTTON( ID_RADIO6, PrefDlg::OnRadio ) EVT_RADIOBUTTON( ID_RADIO7, PrefDlg::OnRadio ) EVT_RADIOBUTTON( ID_RADIO8, PrefDlg::OnRadio ) EVT_RADIOBUTTON( ID_RADIO9, PrefDlg::OnRadio ) EVT_RADIOBUTTON( ID_RADIO10, PrefDlg::OnRadio ) EVT_RADIOBUTTON( ID_RADIO11, PrefDlg::OnRadio ) EVT_CHECKBOX( ID_BLACK_TRANSP, PrefDlg::OnCheck ) EVT_CHECKBOX( ID_DEFLATE_TIFF, PrefDlg::OnCheck ) EVT_CHECKBOX( ID_DELAY_LOAD, PrefDlg::OnCheck ) END_EVENT_TABLE() PrefDlg::PrefDlg( wxWindow *parent, wxWindowID id, const wxString &title, const wxPoint &position, const wxSize& size, long style ) : PrefDlgBase( parent, id, title, position, size, style ) { AddValidator(this, ID_RADIO1, &b1); AddValidator(this, ID_RADIO2, &b2); AddValidator(this, ID_RADIO3, &b3); AddValidator(this, ID_RADIO4, &b4); AddValidator(this, ID_RADIO5, &b5); AddValidator(this, ID_RADIO6, &b6); AddValidator(this, ID_RADIO7, &b7); AddValidator(this, ID_RADIO8, &b8); AddValidator(this, ID_RADIO9, &b9); AddValidator(this, ID_RADIO10, &b10); AddValidator(this, ID_RADIO11, &b11); AddValidator(this, ID_BLACK_TRANSP, &b12); AddValidator(this, ID_DEFLATE_TIFF, &b13); AddValidator(this, ID_BT_GZIP, &b14); AddValidator(this, ID_DELAY_LOAD, &b15); AddNumValidator(this, ID_SAMPLING_N, &i1); AddNumValidator(this, ID_MAX_MEGAPIXELS, &i2); AddNumValidator(this, ID_ELEV_MAX_SIZE, &i3); AddNumValidator(this, ID_MAX_MEM_GRID, &i4); GetSizer()->SetSizeHints(this); } void PrefDlg::UpdateEnable() { FindWindow(ID_MAX_MEM_GRID)->Enable(b15); } // WDR: handler implementations for PrefDlg void PrefDlg::OnInitDialog(wxInitDialogEvent& event) { UpdateEnable(); } void PrefDlg::OnRadio( wxCommandEvent &event ) { TransferDataFromWindow(); } void PrefDlg::OnCheck( wxCommandEvent &event ) { TransferDataFromWindow(); UpdateEnable(); } void PrefDlg::OnOK( wxCommandEvent &event ) { TransferDataFromWindow(); event.Skip(); }
28.438776
78
0.712235
nakijun
9d448b9fdd492c99e5c1be08761c8fa7348e0a24
10,821
cpp
C++
Wind_API/Wind_strike.cpp
FlyingOE/q_Wind
03317f18128e95da63d897c0818cbdb833f45e48
[ "Apache-2.0" ]
93
2015-03-06T03:35:59.000Z
2022-02-10T10:13:36.000Z
Wind_API/Wind_strike.cpp
linggen/q_Wind
03317f18128e95da63d897c0818cbdb833f45e48
[ "Apache-2.0" ]
1
2015-08-13T09:05:26.000Z
2015-08-13T15:49:55.000Z
Wind_API/Wind_strike.cpp
linggen/q_Wind
03317f18128e95da63d897c0818cbdb833f45e48
[ "Apache-2.0" ]
48
2015-03-06T04:10:01.000Z
2022-02-10T10:13:39.000Z
#include "stdafx.h" #include "Wind_strike.h" #include "util.h" #include "kdb+.util/util.h" #include "kdb+.util/type_convert.h" #include <iostream> #include <sstream> Wind::callback::Result::Result() : result_(new Wind::callback::Result::promise_ptr::element_type) {} Wind::callback::Result::promise_ptr* Wind::callback::Result::dup() const { return new promise_ptr(result_); } K Wind::callback::Result::waitFor(::WQID qid, std::chrono::milliseconds const& timeout) { if (qid == 0) { return q::error2q("unknown request ID"); } else if (qid < 0) { std::ostringstream buffer; buffer << "<WQ> strike result error: " << util::error2Text(static_cast<::WQErr>(qid)); return q::error2q(buffer.str()); } assert(result_); std::future<Event*> outcome = result_->get_future(); switch (outcome.wait_for(timeout)) { case std::future_status::ready: try { std::unique_ptr<Event> event(outcome.get()); assert(event); return event->parse(); } catch (std::runtime_error const& error) { return q::error2q(error.what()); } case std::future_status::timeout: return q::error2q((::CancelRequest(qid) == WQERR_OK) ? "request timed out, cancelled" : "request timed out"); default: return q::error2q("TODO request differed or ...?!"); } } int WINAPI Wind::callback::strike(::WQEvent* pEvent, LPVOID lpUserParam) { std::unique_ptr<Result::promise_ptr> pResult(static_cast<Result::promise_ptr*>(lpUserParam)); assert(pResult); Result::promise_ptr& result(*pResult); assert(result); assert(pEvent != NULL); switch (pEvent->EventType) { case eWQResponse: case eWQErrorReport: result->set_value(new Event(*pEvent)); return true; default: { std::ostringstream buffer; buffer << "<WQ> unexpected/unsupported strike response: " << *pEvent; result->set_exception(std::make_exception_ptr(std::runtime_error(buffer.str()))); return false; } } } /* NOTE: Required for WSQ strikes! * * Wind's sample progress sets a global event handler ::SetEventHandler(IEventHandler) * to catch all async query results, while it uses a local event handler for WSQ subscriptions. * That is, WSQ uses whether there is a local event handler to differentiate subscriptions from * strikes. * * For us, however, local event handlers are required for all async queries, therefore depriving * WSQ the information to differentiate both types of the queries. So we need to manually * unsubscribe a WSQ query if it was intended as a strike instead of a subscription. */ int WINAPI Wind::callback::strikeAndUnsub(::WQEvent* pEvent, LPVOID lpUserParam) { if ((pEvent->EventType == eWQOthers) && (pEvent->ErrCode == WQERR_USER_CANCEL)) return false; // Break the reentrance cycle called by calling CancelRequest below! int const result = strike(pEvent, lpUserParam); ::WQErr const error = ::CancelRequest(pEvent->RequestID); if (error != WQERR_OK) { std::cerr << "<WQ> WSQ strike cancellation error: " << Wind::util::error2Text(error) << std::endl; } return result; } WIND_API K K_DECL Wind_wsd(K windCodes, K indicators, K beginDate, K endDate, K params) { std::wstring codes, indis, begin, end, paras; try { codes = Wind::util::qList2WStringJoin(windCodes, L','); indis = Wind::util::qList2WStringJoin(indicators, L','); begin = Wind::util::q2StrOrX(beginDate, &Wind::util::q2DateStr); end = Wind::util::q2StrOrX(endDate, &Wind::util::q2DateStr); paras = Wind::util::qDict2WStringMapJoin(params, L';', L'='); } catch (std::runtime_error const& error) { return q::error2q(error.what()); } Wind::callback::Result result; ::WQID const qid = ::WSD(codes.c_str(), indis.c_str(), begin.c_str(), end.c_str(), paras.c_str(), &Wind::callback::strike, result.dup()); return result.waitFor(qid); } WIND_API K K_DECL Wind_wss(K windCodes, K indicators, K params) { std::wstring codes, indis, paras; try { codes = Wind::util::qList2WStringJoin(windCodes, L','); indis = Wind::util::qList2WStringJoin(indicators, L','); paras = Wind::util::qDict2WStringMapJoin(params, L';', L'='); } catch (std::runtime_error const& error) { return q::error2q(error.what()); } Wind::callback::Result result; ::WQID const qid = ::WSS(codes.c_str(), indis.c_str(), paras.c_str(), &Wind::callback::strike, result.dup()); return result.waitFor(qid); } WIND_API K K_DECL Wind_wsi(K windCode, K indicators, K beginTime, K endTime, K params) { std::wstring code, indis, begin, end, paras; try { code = Wind::util::qList2WStringJoin(windCode, L','); indis = Wind::util::qList2WStringJoin(indicators, L','); begin = Wind::util::q2StrOrX(beginTime, &Wind::util::q2DateTimeStr); end = Wind::util::q2StrOrX(endTime, &Wind::util::q2DateTimeStr); paras = Wind::util::qDict2WStringMapJoin(params, L';', L'='); } catch (std::runtime_error const& error) { return q::error2q(error.what()); } Wind::callback::Result result; ::WQID const qid = ::WSI(code.c_str(), indis.c_str(), begin.c_str(), end.c_str(), paras.c_str(), &Wind::callback::strike, result.dup()); return result.waitFor(qid); } WIND_API K K_DECL Wind_wst(K windCode, K indicators, K beginTime, K endTime, K params) { std::wstring code, indis, begin, end, paras; try { code = q::q2WString(windCode); indis = Wind::util::qList2WStringJoin(indicators, L','); begin = Wind::util::q2StrOrX(beginTime, &Wind::util::q2DateTimeStr); end = Wind::util::q2StrOrX(endTime, &Wind::util::q2DateTimeStr); paras = Wind::util::qDict2WStringMapJoin(params, L';', L'='); } catch (std::runtime_error const& error) { return q::error2q(error.what()); } Wind::callback::Result result; ::WQID const qid = ::WST(code.c_str(), indis.c_str(), begin.c_str(), end.c_str(), paras.c_str(), &Wind::callback::strike, result.dup()); return result.waitFor(qid); } WIND_API K K_DECL Wind_wsq_strike(K windCodes, K indicators, K params) { std::wstring codes, indis, paras; try { codes = Wind::util::qList2WStringJoin(windCodes, L','); indis = Wind::util::qList2WStringJoin(indicators, L','); paras = Wind::util::qDict2WStringMapJoin(params, L';', L'='); } catch (std::runtime_error const& error) { return q::error2q(error.what()); } Wind::callback::Result result; ::WQID const qid = ::WSQ(codes.c_str(), indis.c_str(), paras.c_str(), &Wind::callback::strikeAndUnsub, result.dup()); return result.waitFor(qid); } WIND_API K K_DECL Wind_wset(K reportName, K params) { std::wstring report, paras; try { report = q::q2WString(reportName); paras = Wind::util::qDict2WStringMapJoin(params, L';', L'='); } catch (std::runtime_error const& error) { return q::error2q(error.what()); } Wind::callback::Result result; ::WQID const qid = ::WSET(report.c_str(), paras.c_str(), &Wind::callback::strike, result.dup()); return result.waitFor(qid); } WIND_API K K_DECL Wind_wses(K windCodes, K indicator, K beginDate, K endDate, K params) { std::wstring codes, indi, begin, end, paras; try { codes = Wind::util::qList2WStringJoin(windCodes, L','); indi = q::q2WString(indicator); begin = Wind::util::q2StrOrX(beginDate, &Wind::util::q2DateStr); end = Wind::util::q2StrOrX(endDate, &Wind::util::q2DateStr); paras = Wind::util::qDict2WStringMapJoin(params, L';', L'='); } catch (std::runtime_error const& error) { return q::error2q(error.what()); } Wind::callback::Result result; ::WQID const qid = ::WSES(codes.c_str(), indi.c_str(), begin.c_str(), end.c_str(), paras.c_str(), &Wind::callback::strike, result.dup()); return result.waitFor(qid); } WIND_API K K_DECL Wind_wsee(K windCodes, K indicators, K params) { std::wstring codes, indis, paras; try { codes = Wind::util::qList2WStringJoin(windCodes, L','); indis = Wind::util::qList2WStringJoin(indicators, L','); paras = Wind::util::qDict2WStringMapJoin(params, L';', L'='); } catch (std::runtime_error const& error) { return q::error2q(error.what()); } Wind::callback::Result result; ::WQID const qid = ::WSEE(codes.c_str(), indis.c_str(), paras.c_str(), &Wind::callback::strike, result.dup()); return result.waitFor(qid); } WIND_API K K_DECL Wind_htocode(K codes, K type, K params) { std::wstring codeList, codeType, paras; try { codeList = Wind::util::qList2WStringJoin(codes, L','); codeType = q::q2WString(type); paras = Wind::util::qDict2WStringMapJoin(params, L';', L'='); } catch (std::runtime_error const& error) { return q::error2q(error.what()); } Wind::callback::Result result; ::WQID const qid = ::htocode(codeList.c_str(), codeType.c_str(), paras.c_str(), &Wind::callback::strike, result.dup()); return result.waitFor(qid); } WIND_API K K_DECL Wind_tdays(K beginDate, K endDate, K params) { std::wstring begin, end, paras; try { begin = Wind::util::q2DateStr(beginDate); end = Wind::util::q2DateStr(endDate); paras = Wind::util::qDict2WStringMapJoin(params, L';', L'='); } catch (std::runtime_error const& error) { return q::error2q(error.what()); } Wind::callback::Result result; ::WQID const qid = ::TDays(begin.c_str(), end.c_str(), paras.c_str(), &Wind::callback::strike, result.dup()); return result.waitFor(qid); } WIND_API K K_DECL Wind_tdaysoff(K beginDate, K offset, K params) { std::wstring begin, offs, paras; try { begin = Wind::util::q2DateStr(beginDate); std::wostringstream buffer; buffer << q::q2Dec(offset); offs = buffer.str(); paras = Wind::util::qDict2WStringMapJoin(params, L';', L'='); } catch (std::runtime_error const& error) { return q::error2q(error.what()); } Wind::callback::Result result; ::WQID const qid = ::TDaysOffset(begin.c_str(), offs.c_str(), paras.c_str(), &Wind::callback::strike, result.dup()); return result.waitFor(qid); } WIND_API K K_DECL Wind_tdayscnt(K beginDate, K endDate, K params) { std::wstring begin, end, paras; try { begin = Wind::util::q2DateStr(beginDate); end = Wind::util::q2DateStr(endDate); paras = Wind::util::qDict2WStringMapJoin(params, L';', L'='); } catch (std::runtime_error const& error) { return q::error2q(error.what()); } Wind::callback::Result result; ::WQID const qid = ::TDaysCount(begin.c_str(), end.c_str(), paras.c_str(), &Wind::callback::strike, result.dup()); return result.waitFor(qid); } WIND_API K K_DECL Wind_edb(K windCodes, K beginTime, K endTime, K params) { std::wstring codeList, begin, end, paras; try { codeList = Wind::util::qList2WStringJoin(windCodes, L','); begin = Wind::util::q2DateTimeStr(beginTime); end = Wind::util::q2DateTimeStr(endTime); paras = Wind::util::qDict2WStringMapJoin(params, L';', L'='); } catch (std::runtime_error const& error) { return q::error2q(error.what()); } Wind::callback::Result result; ::WQID const qid = ::EDB(codeList.c_str(), begin.c_str(), end.c_str(), paras.c_str(), &Wind::callback::strike, result.dup()); return result.waitFor(qid); }
33.815625
100
0.687922
FlyingOE
9d46b27baa909430b7fbe29f04e70d801c4b4540
220
cpp
C++
solutions/1342/1342-kir3i.cpp
iknoom/LeetCode-Solutions
85c034dfaf1455bcd69c19a2009197934d83f08e
[ "MIT" ]
4
2021-01-13T11:37:57.000Z
2021-01-17T04:56:46.000Z
solutions/1342/1342-kir3i.cpp
iknoom/LeetCode-Solutions
85c034dfaf1455bcd69c19a2009197934d83f08e
[ "MIT" ]
9
2021-01-21T11:16:29.000Z
2021-02-23T14:27:00.000Z
solutions/1342/1342-kir3i.cpp
iknoom/LeetCode-Solutions
85c034dfaf1455bcd69c19a2009197934d83f08e
[ "MIT" ]
14
2021-01-14T14:36:07.000Z
2021-02-05T09:17:10.000Z
class Solution { public: int numberOfSteps (int num) { if(!num) return 0; else if(num&1) return numberOfSteps(num - 1) + 1; else return numberOfSteps(num / 2) + 1; } };
24.444444
58
0.522727
iknoom
9d46b3015fe4635e409aad8a16c738eebad683ba
1,222
cpp
C++
Effective Debugging: 66 Specific Ways to Debug Software and Systems/src/jenkins/JobButton.cpp
juliagoda/BookProjects
d2c2da993cc9fcbfead696b78d3bf98c66e3373c
[ "Unlicense" ]
null
null
null
Effective Debugging: 66 Specific Ways to Debug Software and Systems/src/jenkins/JobButton.cpp
juliagoda/BookProjects
d2c2da993cc9fcbfead696b78d3bf98c66e3373c
[ "Unlicense" ]
null
null
null
Effective Debugging: 66 Specific Ways to Debug Software and Systems/src/jenkins/JobButton.cpp
juliagoda/BookProjects
d2c2da993cc9fcbfead696b78d3bf98c66e3373c
[ "Unlicense" ]
null
null
null
#include "JobButton.h" #include <JenkinsJobInfo.h> #include <QLabel> #include <QIcon> #include <QHBoxLayout> #include <QMouseEvent> namespace Jenkins { JobButton::JobButton(const JenkinsJobInfo &job, QWidget *parent) : QFrame(parent) , mJob(job) { mJob.name.replace("%2F", "/"); mJob.color.remove("_anime"); if (mJob.color.contains("blue")) mJob.color = "green"; else if (mJob.color.contains("disabled") || mJob.color.contains("grey") || mJob.color.contains("notbuilt")) mJob.color = "grey"; else if (mJob.color.contains("aborted")) mJob.color = "dark_grey"; const auto icon = new QLabel(); icon->setPixmap(QIcon(QString(":/icons/%1").arg(mJob.color)).pixmap(22, 22)); const auto layout = new QHBoxLayout(this); layout->setContentsMargins(QMargins()); layout->setSpacing(20); layout->addWidget(icon); layout->addWidget(new QLabel(mJob.name)); layout->addStretch(); } void JobButton::mousePressEvent(QMouseEvent *e) { mPressed = rect().contains(e->pos()) && e->button() == Qt::LeftButton; } void JobButton::mouseReleaseEvent(QMouseEvent *e) { if (mPressed && rect().contains(e->pos()) && e->button() == Qt::LeftButton) emit clicked(); } }
24.938776
110
0.660393
juliagoda
9d4b7dd693d0a96dad26870ad29b207f96cd4717
8,192
hh
C++
cplusplus/wren_cc/common.hh
ASMlover/study
5878f862573061f94c5776a351e30270dfd9966a
[ "BSD-2-Clause" ]
22
2015-05-18T07:04:36.000Z
2021-08-02T03:01:43.000Z
cplusplus/wren_cc/common.hh
ASMlover/study
5878f862573061f94c5776a351e30270dfd9966a
[ "BSD-2-Clause" ]
1
2017-08-31T22:13:57.000Z
2017-09-05T15:00:25.000Z
cplusplus/wren_cc/common.hh
ASMlover/study
5878f862573061f94c5776a351e30270dfd9966a
[ "BSD-2-Clause" ]
6
2015-06-06T07:16:12.000Z
2021-07-06T13:45:56.000Z
// Copyright (c) 2019 ASMlover. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright // notice, this list ofconditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materialsprovided with the // distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #pragma once #include <cassert> #include <cstdint> #include <cstdlib> #include <iomanip> #include <iostream> #include <sstream> #include <string> #include <string_view> namespace wrencc { using nil_t = std::nullptr_t; using byte_t = std::uint8_t; using i8_t = std::int8_t; using u8_t = std::uint8_t; using i16_t = std::int16_t; using u16_t = std::uint16_t; using i32_t = std::int32_t; using u32_t = std::uint32_t; using i64_t = std::int64_t; using u64_t = std::uint64_t; using ssz_t = std::int32_t; using sz_t = std::size_t; using str_t = std::string; using strv_t = std::string_view; class Copyable { protected: Copyable(void) noexcept = default; ~Copyable(void) noexcept = default; Copyable(const Copyable&) noexcept = default; Copyable(Copyable&&) noexcept = default; Copyable& operator=(const Copyable&) noexcept = default; Copyable& operator=(Copyable&&) noexcept = default; }; class UnCopyable { UnCopyable(const UnCopyable&) noexcept = delete; UnCopyable(UnCopyable&&) noexcept = delete; UnCopyable& operator=(const UnCopyable&) noexcept = delete; UnCopyable& operator=(UnCopyable&&) noexcept = delete; protected: UnCopyable(void) noexcept = default; ~UnCopyable(void) noexcept = default; }; namespace Xt { template <typename T, typename U> inline T as_type(U x) { return static_cast<T>(x); } template <typename T, typename U> inline T* cast(U* x) { return static_cast<T*>(x); } template <typename T, typename U> inline T* down(U* x) { return dynamic_cast<T*>(x); } inline str_t to_string(double d) { std::stringstream ss; ss << std::setprecision(std::numeric_limits<double>::max_digits10) << d; return ss.str(); } inline int power_of_2ceil(int n) { // http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2Float --n; n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; ++n; return n; } } } // if true then Wren will use a NaN tagged double for its core value // representation, otherwise it will use a larger more conventional struct, // the former is significantly faster and more compact, the latter is useful // for debugging and may be more protable // // Defaults to on #ifndef NAN_TAGGING # define NAN_TAGGING (true) #endif // if true the VM's interpreter loop use computed gotos, see this for more: // https://gcc.gnu.org/onlinedocs/gcc-3.1.1/gcc/Labels-as-Values.html, enabling // this speeds up the main dispatch loop a bit, but requires compiler support // // Defaults to on if not MSVC #ifndef COMPUTED_GOTOS # ifndef _MSC_VER # define COMPUTED_GOTOS (true) # else # define COMPUTED_GOTOS (false) # endif #endif // if true loads the `IO` class in the standard library // // Defaults to on #ifndef USE_LIBIO # define USE_LIBIO (true) #endif // the VM includes a number of optional `auxiliary` modules, you can choose to // include these or not, by default, they are all available, to disable one, // set the corresponding `AUX_<name>` define to `false` // // Defaults to on #ifndef AUX_META # define AUX_META (true) #endif #ifndef AUX_RANDOM # define AUX_RANDOM (true) #endif // set this to true to stress test the GC, it will perform a collection before // every allocation, this is useful to ensure that memory is always correctly // pinned #define GC_STRESS (false) // set this to true to log memory operations as they occured #define TRACE_MEMORY (false) // set this to true to log garbage collections as the occured #define TRACE_GC (false) // set this to true to print out the compiled bytecode of each function #define DUMP_COMPILED (false) // set this to trace each instructions as it's executed #define TRACE_INSTRUCTIONS (false) // set this to display object's detail information #define TRACE_OBJECT_DETAIL (false) // the maximum number of module-level variables that may be defined at one // time, this limitation comes from the 16-bits used for the arguments to // `Code::LOAD_MODULE_VAR` and `Code::STORE_MODULE_VAR` #define MAX_MODULE_VARS (65536) // the maximum number of arguments that can be passed to a method, note that // this limitation is hardcoded in order places in the VM, in particular the // `Code::CALL_*` instructions assume a certain maximum number #define MAX_PARAMETERS (16) // the maximum name of a method, not including the signature, this is an // arbitrary but enforced maximum just so we know how long the method name // strings need to be in the parser #define MAX_METHOD_NAME (64) // the maximum length of a method signature, signatures looks like: // // foo // getter // foo() // no argument method // foo(_) // one argument method // foo(_,_) // two arguments method // init foo() // constructor initializer // // the maximum signature length takes into account the longest method name, // the maximum number of parameters with separators between them, "init" and "()" #define MAX_METHOD_SIGNATURE (MAX_METHOD_NAME + (MAX_PARAMETERS * 2) + 6) // the maximum length of an identifier, the only real reason for this limitation // is so that error messages mentioning variables can be stack allocated #define MAX_VARIABLE_NAME (64) // the maximum number of fields a class can have, including inherited fields, // this is explicit in the bytecode since `Code::CLASS` and `Code::SUBCLASS` // take a single byte for the number of fields, note that it's 255 and not // 256 because creating a class takes the *number* of fields, not the *highest // field index* #define MAX_FIELDS (255) #ifndef NDEBUG # define ASSERT(cond, msg) do {\ if (!(cond)) {\ std::cerr << "[" << __FILE__ << ": " << __LINE__ << "] "\ << "Assert failed in " << __func__ << "(): "\ << msg << std::endl;\ std::abort();\ }\ } while (false) // indicates that we know execution should never reach this point in the // program, in debug mode we assert this fact because it's a bug to get here // // in release mode, we use compiler-specific built in functions to tell the // compiler the code can't be reached, this avoids `missing return` warnings // in some cases and also lets it perform some optimizations by assuming the // code in never reached #define UNREACHABLE() do {\ std::cerr << "[" << __FILE__ << ": " << __LINE__ << "] "\ << "This code should not be reached in " << __func__ << "()"\ << std::endl;\ std::abort();\ } while (false) #else # define ASSERT(cond, msg) ((void)0) # if defined(_MSC_VER) # define UNREACHABLE() __assume(0) # elif (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5)) # define UNREACHABLE() __builtin_unreachable() # else # define UNREACHABLE() # endif #endif
33.991701
81
0.700439
ASMlover
9d4d418618a3f1156c0efca5b457aa54f5fcc3b0
556
cpp
C++
tests/unique_ptr_custom.cpp
IvayloTsankov/mempool
f34e7e3d3a51a09f4be6a961ab6fbf1f71d1edf5
[ "MIT" ]
null
null
null
tests/unique_ptr_custom.cpp
IvayloTsankov/mempool
f34e7e3d3a51a09f4be6a961ab6fbf1f71d1edf5
[ "MIT" ]
null
null
null
tests/unique_ptr_custom.cpp
IvayloTsankov/mempool
f34e7e3d3a51a09f4be6a961ab6fbf1f71d1edf5
[ "MIT" ]
null
null
null
#include <memory> #include <utility> #include <functional> struct Vector { float x, y, z; }; struct Del { void del(Vector*) { printf("Call Del::del\n"); } }; int main() { { std::unique_ptr<Vector, std::function<void(Vector*)>> v(new Vector{ 1, 1, 1 }, [](Vector* p) { printf("custom deleter called\n"); }); } { Del d; std::unique_ptr<Vector, std::function<void(Vector*)>> v(new Vector{ 2, 2, 2 }, std::bind(&Del::del, d, std::placeholders::_1)); } return 0; }
17.375
86
0.523381
IvayloTsankov
9d51bd9f0a92d3a9c09c3453c4921aebcac59354
14,958
cpp
C++
src/public/src/ysgebl/src/kernelutil/ysshellext_splitop.cpp
rothberg-cmu/rothberg-run
a42df5ca9fae97de77753864f60d05295d77b59f
[ "MIT" ]
1
2019-08-10T00:24:09.000Z
2019-08-10T00:24:09.000Z
src/public/src/ysgebl/src/kernelutil/ysshellext_splitop.cpp
rothberg-cmu/rothberg-run
a42df5ca9fae97de77753864f60d05295d77b59f
[ "MIT" ]
null
null
null
src/public/src/ysgebl/src/kernelutil/ysshellext_splitop.cpp
rothberg-cmu/rothberg-run
a42df5ca9fae97de77753864f60d05295d77b59f
[ "MIT" ]
2
2019-05-01T03:11:10.000Z
2019-05-01T03:30:35.000Z
/* //////////////////////////////////////////////////////////// File Name: ysshellext_splitop.cpp Copyright (c) 2017 Soji Yamakawa. All rights reserved. http://www.ysflight.com Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //////////////////////////////////////////////////////////// */ #include "ysshellext_splitop.h" #include "ysshellext_trackingutil.h" YsShell_SplitInfo::YsShell_SplitInfo() { CleanUp(); } void YsShell_SplitInfo::CleanUp(void) { edgeSplit.CleanUp(); newPlg.CleanUp(); newConstEdge.CleanUp(); } YSRESULT YsShell_SplitInfo::SetAndSplitPolygon(PolygonSplit &plg,const YsShellExt &shl,const YsShellVertexStore &cutPoint,YsShellPolygonHandle plHd) { YsArray <YsShellVertexHandle,16> plVtHd; YsArray <YsVec3,16> plVtPos; shl.GetVertexListOfPolygon(plVtHd,plHd); shl.GetVertexListOfPolygon(plVtPos,plHd); YsMatrix4x4 prjMat; if(YSOK==YsGetPolygonProjectionMatrix(prjMat,plVtPos.GetN(),plVtPos)) { plg.plHd=plHd; plg.plVtHdArray.CleanUp(); plg.plVtHdArray.Increment(); plg.plVtHdArray[0].Set(plVtHd.GetN(),NULL); plg.prjVtPosArray.CleanUp(); plg.prjVtPosArray.Increment(); plg.prjVtPosArray[0].Set(plVtHd.GetN(),NULL); for(YSSIZE_T vtIdx=0; vtIdx<plVtHd.GetN(); ++vtIdx) { YsVec3 prj; prjMat.Mul(prj,plVtPos[vtIdx],1.0); plg.plVtHdArray[0][vtIdx]=plVtHd[vtIdx]; plg.prjVtPosArray[0][vtIdx].Set(prj.x(),prj.y()); } SplitPolygon(plg,cutPoint); return YSOK; } return YSERR; } void YsShell_SplitInfo::SplitPolygon(PolygonSplit &plg,const YsShellVertexStore &cutPoint) { for(YSSIZE_T todoIdx=0; todoIdx<plg.plVtHdArray.GetN(); ) { YSSIZE_T splitIdx[2]={-1,-1}; for(YSSIZE_T i0=0; i0<plg.plVtHdArray[todoIdx].GetN(); ++i0) { if(YSTRUE==cutPoint.IsIncluded(plg.plVtHdArray[todoIdx][i0])) { for(YSSIZE_T i1=i0+1; i1<plg.plVtHdArray[todoIdx].GetN(); ++i1) { if(YSTRUE==cutPoint.IsIncluded(plg.plVtHdArray[todoIdx][i1])) { if(i0+2<=i1 && YSTRUE==YsCheckSeparatability2((int)plg.prjVtPosArray[todoIdx].GetN(),plg.prjVtPosArray[todoIdx],(int)i0,(int)i1)) { splitIdx[0]=i0; splitIdx[1]=i1; goto BAILOUT; } /* I thought the following else statement was a good idea to save computation, but it was not. See debug/data/20131117-split-polygon.srf In this case, vertices 0,1,2, and 6 of the concave polygon are on the cutting plane (rectangle). Only separatable pair is vertex[2]-vertex[6]. If I add the following else-statement block, this loop will check 0-1, 1-2, and 2-6, but will never check 0-6. else { i0=i1-1; break; } */ } } } } BAILOUT: if(0<=splitIdx[0] && 0<=splitIdx[1]) { plg.plVtHdArray.Increment(); plg.prjVtPosArray.Increment(); if(YSOK!=YsShellExt_SplitLoop(plg.plVtHdArray[todoIdx],plg.plVtHdArray.GetEnd(),splitIdx[0],splitIdx[1]) || YSOK!=YsShellExt_SplitLoop(plg.prjVtPosArray[todoIdx],plg.prjVtPosArray.GetEnd(),splitIdx[0],splitIdx[1])) { plg.plVtHdArray.DeleteLast(); plg.prjVtPosArray.DeleteLast(); ++todoIdx; } } else { ++todoIdx; } } } YSRESULT YsShell_SplitInfo::SetAndSplitConstEdge(ConstEdgeSplit &ce,const YsShellExt &shl,const YsShellVertexStore &cutPoint,YsShellExt::ConstEdgeHandle ceHd) { YSBOOL isLoop; YsArray <YsShellVertexHandle,16> ceVtHd; shl.GetConstEdge(ceVtHd,isLoop,ceHd); ce.ceHd=ceHd; if(YSTRUE==isLoop) { YSSIZE_T vtIdx0=-1; for(YSSIZE_T vtIdx=0; vtIdx<ceVtHd.GetN(); ++vtIdx) { if(YSTRUE==cutPoint.IsIncluded(ceVtHd[vtIdx]) && (YSTRUE!=cutPoint.IsIncluded(ceVtHd.GetCyclic(vtIdx-1)) || YSTRUE!=cutPoint.IsIncluded(ceVtHd.GetCyclic(vtIdx+1)))) { vtIdx0=vtIdx; break; } } if(0<=vtIdx0) { if(0!=vtIdx0 || ceVtHd.GetN()-1==vtIdx0) { const YsArray <YsShellVertexHandle,16> swp(vtIdx0+1,ceVtHd); ceVtHd.Delete(0,vtIdx0); ceVtHd.Append(swp); } } else { return YSERR; } } const YSBOOL wasLoop=isLoop; ce.ceHd=ceHd; ce.ceVtHdArray.CleanUp(); ce.ceVtHdArray.Increment(); ce.ceVtHdArray[0]=ceVtHd; SplitConstEdge(ce,cutPoint); if(YSTRUE==wasLoop || 1<ce.ceVtHdArray.GetN()) { return YSOK; } return YSERR; } void YsShell_SplitInfo::SplitConstEdge(ConstEdgeSplit &ce,const YsShellVertexStore &cutPoint) { YsArray <YSBOOL,16> isCutPointRaw,isCutPoint; isCutPointRaw.Set(ce.ceVtHdArray[0].GetN(),NULL); isCutPoint.Set(ce.ceVtHdArray[0].GetN(),NULL); for(YSSIZE_T vtIdx=0; vtIdx<ce.ceVtHdArray[0].GetN(); ++vtIdx) { isCutPointRaw[vtIdx]=cutPoint.IsIncluded(ce.ceVtHdArray[0][vtIdx]); isCutPoint[vtIdx]=isCutPointRaw[vtIdx]; } for(YSSIZE_T vtIdx=1; vtIdx<ce.ceVtHdArray[0].GetN()-1; ++vtIdx) { if(YSTRUE==isCutPointRaw[vtIdx-1] && YSTRUE==isCutPointRaw[vtIdx] && YSTRUE==isCutPointRaw[vtIdx+1]) { isCutPoint[vtIdx]=YSFALSE; } } for(YSSIZE_T vtIdx=ce.ceVtHdArray[0].GetN()-2; 1<=vtIdx; --vtIdx) { if(YSTRUE==isCutPoint[vtIdx]) { ce.ceVtHdArray.Increment(); YsShellExt_SplitOpenChain(ce.ceVtHdArray[0],ce.ceVtHdArray.GetEnd(),vtIdx); --vtIdx; } } } YSRESULT YsShell_SplitInfo::SplitFaceGroup(FaceGroupSplit &fgSplit,const YsShellExt &shl,YsShellExt::FaceGroupHandle fgHd,const YsShellPolygonStore &newGrouping) { auto fgPlHd=shl.GetFaceGroup(fgHd); YsShellPolygonStore overlapping((const YsShell &)shl),nonOverlapping((const YsShell &)shl); for(auto plHd : fgPlHd) { if(YSTRUE!=overlapping.IsIncluded(plHd) && YSTRUE!=nonOverlapping.IsIncluded(plHd)) { if(YSTRUE==newGrouping.IsIncluded(plHd)) { overlapping.AddPolygon(plHd); } else { nonOverlapping.AddPolygon(plHd); } } } fgSplit.CleanUp(); YsShellPolygonStore visited((const YsShell &)shl); for(auto plHd : fgPlHd) { if(YSTRUE!=visited.IsIncluded(plHd)) { YsShellExt_TrackingUtil::SearchCondition cond; cond.onlyInThisFgHd=fgHd; if(YSTRUE==overlapping.IsIncluded(plHd)) { cond.withinThesePlHd=&overlapping; } else { cond.withinThesePlHd=&nonOverlapping; } auto plgGrp=YsShellExt_TrackingUtil::MakeEdgeConnectedPolygonGroup(shl,plHd,&cond); if(0<plgGrp.GetN()) { fgSplit.fgPlHdArray.Increment(); fgSplit.fgPlHdArray.Last().MoveFrom(plgGrp); visited.AddPolygon(plgGrp); } } } if(1<fgSplit.fgPlHdArray.GetN()) { fgSplit.fgHd=fgHd; return YSOK; } return YSERR; } //////////////////////////////////////////////////////////// void YsShell_CutByPlane::CleanUp(void) { YsShell_SplitInfo::CleanUp(); plg.CleanUp(); prjMat.LoadIdentity(); prjPlg.CleanUp(); plHdToSplit.CleanUp(); ceHdToSplit.CleanUp(); } void YsShell_CutByPlane::SetPlane(const YsPlane &pln) { this->pln=pln; } YSRESULT YsShell_CutByPlane::SetPolygon(YSSIZE_T np,const YsVec3 p[]) { plg.Set(np,p); if(YSOK==YsGetPolygonProjectionMatrix(prjMat,np,p)) { prjPlg.Set(np,NULL); for(YSSIZE_T idx=0; idx<np; ++idx) { YsVec3 prj; prjMat.Mul(prj,p[idx],1.0); prjPlg[idx].Set(prj.x(),prj.y()); } return YSOK; } return YSERR; } void YsShell_CutByPlane::FindPolygonToSplit(const YsShellExt &shl) { plHdToSplit.CleanUp(); YsArray <YsVec3,16> plVtPos; YsShellPolygonHandle plHd=NULL; while(YSOK==shl.MoveToNextPolygon(plHd)) { shl.GetVertexListOfPolygon(plVtPos,plHd); YSBOOL positive=YSFALSE,negative=YSFALSE; for(YSSIZE_T idx=0; idx<plVtPos.GetN() && (YSTRUE!=positive || YSTRUE!=negative); ++idx) { const int sideOfPlane=pln.GetSideOfPlane(plVtPos[idx]); if(0>sideOfPlane) { negative=YSTRUE; } else if(0<sideOfPlane) { positive=YSTRUE; } } if(YSTRUE==positive && YSTRUE==negative) { plHdToSplit.Append(plHd); } } } void YsShell_CutByPlane::FindConstEdgeToSplit(const YsShellExt &shl) { YSBOOL isLoop; YsArray <YsShellVertexHandle,16> ceVtHd; YsShellExt::ConstEdgeHandle ceHd=NULL; while(YSOK==shl.MoveToNextConstEdge(ceHd)) { shl.GetConstEdge(ceVtHd,isLoop,ceHd); YSBOOL positive=YSFALSE,negative=YSFALSE; for(YSSIZE_T idx=0; idx<ceVtHd.GetN() && (YSTRUE!=positive || YSTRUE!=negative); ++idx) { YsVec3 vtPos; shl.GetVertexPosition(vtPos,ceVtHd[idx]); const int sideOfPlane=pln.GetSideOfPlane(vtPos); if(0>sideOfPlane) { negative=YSTRUE; } else if(0<sideOfPlane) { positive=YSTRUE; } } if(YSTRUE==positive && YSTRUE==negative) { ceHdToSplit.Append(ceHd); } } } void YsShell_CutByPlane::MakeEdgeSplitInfo(const YsShellExt &shl) { YsShellEdgeStore visited((const YsShell &)shl); YsArray <YsShellVertexHandle,16> plVtHd; for(YSSIZE_T plIdx=0; plIdx<plHdToSplit.GetN(); ++plIdx) { shl.GetVertexListOfPolygon(plVtHd,plHdToSplit[plIdx]); YsShellVertexHandle vtHd0=plVtHd[0]; plVtHd.Append(vtHd0); for(YSSIZE_T vtIdx=0; vtIdx<plVtHd.GetN()-1; ++vtIdx) { const YsShellVertexHandle edVtHd[2]= { plVtHd[vtIdx], plVtHd[vtIdx+1] }; MakeEdgeSplitInfo_PerEdge(shl,visited,edVtHd); } } YsArray <YsShellVertexHandle,16> ceVtHd; for(YSSIZE_T ceIdx=0; ceIdx<ceHdToSplit.GetN(); ++ceIdx) { YSBOOL isLoop; shl.GetConstEdge(ceVtHd,isLoop,ceHdToSplit[ceIdx]); if(YSTRUE==isLoop) { const YsShellVertexHandle vtHd0=ceVtHd[0]; ceVtHd.Append(vtHd0); } for(YSSIZE_T vtIdx=0; vtIdx<ceVtHd.GetN()-1; ++vtIdx) { const YsShellVertexHandle edVtHd[2]= { ceVtHd[vtIdx], ceVtHd[vtIdx+1] }; MakeEdgeSplitInfo_PerEdge(shl,visited,edVtHd); } } } void YsShell_CutByPlane::MakeEdgeSplitInfo_PerEdge(const YsShellExt &shl,YsShellEdgeStore &visited,const YsShellVertexHandle edVtHd[2]) { if(YSTRUE!=visited.IsIncluded(edVtHd[0],edVtHd[1])) { visited.AddEdge(edVtHd[0],edVtHd[1]); YsVec3 edVtPos[2]; shl.GetVertexPosition(edVtPos[0],edVtHd[0]); shl.GetVertexPosition(edVtPos[1],edVtHd[1]); const int side[2]= { pln.GetSideOfPlane(edVtPos[0]), pln.GetSideOfPlane(edVtPos[1]) }; if(0>side[0]*side[1]) { YsVec3 itsc; if(YSOK==pln.GetPenetrationHighPrecision(itsc,edVtPos[0],edVtPos[1])) { if(3<=prjPlg.GetN()) { YsVec3 prj3d; prjMat.Mul(prj3d,itsc,1.0); const YsVec2 prj2d(prj3d.x(),prj3d.y()); const YSSIDE side=YsCheckInsidePolygon2(prj2d,prjPlg.GetN(),prjPlg); if(YSINSIDE!=side && YSBOUNDARY!=side) { goto BAILOUT; } } edgeSplit.Increment(); edgeSplit.GetEnd().CleanUp(); edgeSplit.GetEnd().edVtHd[0]=edVtHd[0]; edgeSplit.GetEnd().edVtHd[1]=edVtHd[1]; edgeSplit.GetEnd().pos=itsc; edgeSplit.GetEnd().createdVtHd=NULL; BAILOUT: ; } } } } YSRESULT YsShell_CutByPlane::StartByPolygon(const YsShellExt &shl,YSSIZE_T np,const YsShellVertexHandle p[]) { YsArray <YsVec3,16> plVtPos(np,NULL); for(YSSIZE_T idx=0; idx<np; ++idx) { shl.GetVertexPosition(plVtPos[idx],p[idx]); } return StartByPolygon(shl,plVtPos); } YSRESULT YsShell_CutByPlane::StartByPolygon(const YsShellExt &shl,YSSIZE_T np,const YsVec3 p[]) { YsPlane pln; if(YSOK==pln.MakeBestFitPlane(np,p) && YSOK==SetPolygon(np,p)) { SetPlane(pln); FindPolygonToSplit(shl); FindConstEdgeToSplit(shl); MakeEdgeSplitInfo(shl); return YSOK; } return YSERR; } YSRESULT YsShell_CutByPlane::MakeSplitInfoAfterEdgeVertexGeneration(const YsShellExt &shl) { newPlg.CleanUp(); newConstEdge.CleanUp(); YsShellVertexStore cutPoint((const YsShell &)shl); for(YSSIZE_T idx=0; idx<edgeSplit.GetN(); ++idx) { cutPoint.AddVertex(edgeSplit[idx].createdVtHd); } YsArray <YsVec3,16> plVtPos; YsArray <YsShellVertexHandle,16> plVtHd; for(YSSIZE_T plIdx=0; plIdx<plHdToSplit.GetN(); ++plIdx) { shl.GetVertexListOfPolygon(plVtPos,plHdToSplit[plIdx]); shl.GetVertexListOfPolygon(plVtHd,plHdToSplit[plIdx]); for(YSSIZE_T vtIdx=0; vtIdx<plVtHd.GetN(); ++vtIdx) { if(YSTRUE!=cutPoint.IsIncluded(plVtHd[vtIdx]) && YSTRUE==pln.CheckOnPlane(plVtPos[vtIdx])) { if(3<=prjPlg.GetN()) { YsVec3 prj3d; prjMat.Mul(prj3d,plVtPos[vtIdx],1.0); const YsVec2 prj2d(prj3d.x(),prj3d.y()); const YSSIDE side=YsCheckInsidePolygon2(prj2d,prjPlg.GetN(),prjPlg); if(YSINSIDE!=side && YSBOUNDARY!=side) { continue; } } cutPoint.AddVertex(plVtHd[vtIdx]); } } } for(YSSIZE_T ceIdx=0; ceIdx<ceHdToSplit.GetN(); ++ceIdx) { YSBOOL isLoop; shl.GetConstEdge(plVtHd,isLoop,ceHdToSplit[ceIdx]); for(YSSIZE_T vtIdx=0; vtIdx<plVtHd.GetN(); ++vtIdx) { YsVec3 vtPos; shl.GetVertexPosition(vtPos,plVtHd[vtIdx]); if(YSTRUE!=cutPoint.IsIncluded(plVtHd[vtIdx]) && YSTRUE==pln.CheckOnPlane(vtPos)) { if(3<=prjPlg.GetN()) { YsVec3 prj3d; prjMat.Mul(prj3d,vtPos,1.0); const YsVec2 prj2d(prj3d.x(),prj3d.y()); const YSSIDE side=YsCheckInsidePolygon2(prj2d,prjPlg.GetN(),prjPlg); if(YSINSIDE!=side && YSBOUNDARY!=side) { continue; } } cutPoint.AddVertex(plVtHd[vtIdx]); } } } YsArray <YsVec2,16> prjPlVtPos; YsArray <YSBOOL,16> isCutPoint; for(YSSIZE_T plIdx=0; plIdx<plHdToSplit.GetN(); ++plIdx) { shl.GetVertexListOfPolygon(plVtHd,plHdToSplit[plIdx]); int nCutPoint=0; isCutPoint.Set(plVtHd.GetN(),NULL); for(YSSIZE_T vtIdx=0; vtIdx<plVtHd.GetN(); ++vtIdx) { isCutPoint[vtIdx]=cutPoint.IsIncluded(plVtHd[vtIdx]); if(YSTRUE==isCutPoint[vtIdx]) { ++nCutPoint; } } if(2<=nCutPoint) { newPlg.Increment(); if(YSOK!=SetAndSplitPolygon(newPlg.GetEnd(),shl,cutPoint,plHdToSplit[plIdx]) || 1==newPlg.GetEnd().plVtHdArray.GetN()) { newPlg.DeleteLast(); } } } for(YSSIZE_T ceIdx=0; ceIdx<ceHdToSplit.GetN(); ++ceIdx) { newConstEdge.Increment(); if(YSOK!=SetAndSplitConstEdge(newConstEdge.GetEnd(),shl,cutPoint,ceHdToSplit[ceIdx])) { newConstEdge.DeleteLast(); } } return YSOK; }
24.888519
161
0.692138
rothberg-cmu
9d5919eacc1d12a185bd7dfc4419a58895d79047
3,781
hxx
C++
MicroBenchmarks/LCALS/SubsetDataA.hxx
Nuullll/llvm-test-suite
afbdd0a9ee7770e074708b68b34a6a5312bb0b36
[ "Apache-2.0" ]
70
2019-01-15T03:03:55.000Z
2022-03-28T02:16:13.000Z
MicroBenchmarks/LCALS/SubsetDataA.hxx
Nuullll/llvm-test-suite
afbdd0a9ee7770e074708b68b34a6a5312bb0b36
[ "Apache-2.0" ]
519
2020-09-15T07:40:51.000Z
2022-03-31T20:51:15.000Z
MicroBenchmarks/LCALS/SubsetDataA.hxx
Nuullll/llvm-test-suite
afbdd0a9ee7770e074708b68b34a6a5312bb0b36
[ "Apache-2.0" ]
117
2020-06-24T13:11:04.000Z
2022-03-23T15:44:23.000Z
// // See README-LCALS_license.txt for access and distribution restrictions // // // Header file defining macros, routines, structures used in Loop Subset A. // #ifndef SubsetDataA_HXX #define SubsetDataA_HXX // // Some macros used in kernels to mimic real code usage. // #define NDPTRSET(v,v0,v1,v2,v3,v4,v5,v6,v7) \ v0 = v ; \ v1 = v0 + 1 ; \ v2 = v0 + domain.jp ; \ v3 = v1 + domain.jp ; \ v4 = v0 + domain.kp ; \ v5 = v1 + domain.kp ; \ v6 = v2 + domain.kp ; \ v7 = v3 + domain.kp ; #define NDSET2D(v,v1,v2,v3,v4) \ v4 = v ; \ v1 = v4 + 1 ; \ v2 = v1 + domain.jp ; \ v3 = v4 + domain.jp ; #define zabs2(z) ( real(z)*real(z)+imag(z)*imag(z) ) // // Domain structure to mimic structured mesh loops in real codes. // struct ADomain { ADomain( int ilen, Index_type ndims ) : ndims(ndims), NPNL(2), NPNR(1) { Index_type rzmax; switch ( ilen ) { case LONG : { if ( ndims == 2 ) { rzmax = 156 * loop_length_factor; } else if ( ndims == 3 ) { rzmax = 28 * loop_length_factor; } break; } case MEDIUM : { if ( ndims == 2 ) { rzmax = 64 * loop_length_factor; } else if ( ndims == 3 ) { rzmax = 16 * loop_length_factor; } break; } case SHORT : { if ( ndims == 2 ) { rzmax = 8 * loop_length_factor; } else if ( ndims == 3 ) { rzmax = 4 * loop_length_factor; } break; } default : { } } imin = NPNL; jmin = NPNL; imax = rzmax + NPNR; jmax = rzmax + NPNR; jp = imax - imin + 1 + NPNL + NPNR; if ( ndims == 2 ) { kmin = 0; kmax = 0; kp = 0; nnalls = jp * (jmax - jmin + 1 + NPNL + NPNR) ; } else if ( ndims == 3 ) { kmin = NPNL; kmax = rzmax + NPNR; kp = jp * (jmax - jmin + 1 + NPNL + NPNR); nnalls = kp * (kmax - kmin + 1 + NPNL + NPNR) ; } fpn = 0; lpn = nnalls - 1; frn = fpn + NPNL * (kp + jp) + NPNL; lrn = lpn - NPNR * (kp + jp) - NPNR; fpz = frn - jp - kp - 1; lpz = lrn; real_zones = new Index_type[nnalls]; for (Index_type i = 0; i < nnalls; ++i) real_zones[i] = -1; n_real_zones = 0; if ( ndims == 2 ) { for (Index_type j = jmin; j < jmax; j++) { for (Index_type i = imin; i < imax; i++) { Index_type ip = i + j*jp ; Index_type id = n_real_zones; real_zones[id] = ip; n_real_zones++; } } } else if ( ndims == 3 ) { for (Index_type k = kmin; k < kmax; k++) { for (Index_type j = jmin; j < jmax; j++) { for (Index_type i = imin; i < imax; i++) { Index_type ip = i + j*jp + kp*k ; Index_type id = n_real_zones; real_zones[id] = ip; n_real_zones++; } } } } } ~ADomain() { if (real_zones) delete [] real_zones; } static double loop_length_factor; Index_type ndims; Index_type NPNL; Index_type NPNR; Index_type imin; Index_type jmin; Index_type kmin; Index_type imax; Index_type jmax; Index_type kmax; Index_type jp; Index_type kp; Index_type nnalls; Index_type fpn; Index_type lpn; Index_type frn; Index_type lrn; Index_type fpz; Index_type lpz; Index_type* real_zones; Index_type n_real_zones; }; #endif // closing endif for header file include guard
22.372781
75
0.475536
Nuullll
9d5ae33db573d721c35a7d25dc478a6be1d4f306
207
hpp
C++
yac/lib/yac.hpp
chutsu/yac
789c8b4116197e3a4b0232568414eec5489836da
[ "MIT" ]
18
2020-04-29T17:25:44.000Z
2022-03-10T05:57:27.000Z
yac/lib/yac.hpp
chutsu/yac
789c8b4116197e3a4b0232568414eec5489836da
[ "MIT" ]
1
2021-06-26T04:44:13.000Z
2021-07-04T17:56:35.000Z
yac/lib/yac.hpp
chutsu/yac
789c8b4116197e3a4b0232568414eec5489836da
[ "MIT" ]
3
2020-07-15T18:04:26.000Z
2021-04-13T13:19:58.000Z
#include "core.hpp" #include "aprilgrid.hpp" #include "ceres_utils.hpp" #include "calib_data.hpp" #include "calib_params.hpp" #include "calib_mono.hpp" #include "calib_stereo.hpp" #include "calib_mocap.hpp"
23
27
0.768116
chutsu
9d5cbaa7701c94ef7fc554b9526d20b8543f16f6
1,113
cpp
C++
ExodusImport/Source/ExodusImport/Private/JsonObjects/JsonRigidbody.cpp
AldeRoberge/ProjectExodus
74ecd6c8719e6365b51458c65954bff2910bc36e
[ "BSD-3-Clause" ]
288
2019-04-02T08:02:59.000Z
2022-03-28T23:53:28.000Z
ExodusImport/Source/ExodusImport/Private/JsonObjects/JsonRigidbody.cpp
adamgoodrich/ProjectExodus
29a9fa87f981ad41e3b323702dc2b0d4523889d8
[ "BSD-3-Clause" ]
54
2019-04-19T08:24:05.000Z
2022-03-28T19:44:42.000Z
ExodusImport/Source/ExodusImport/Private/JsonObjects/JsonRigidbody.cpp
adamgoodrich/ProjectExodus
29a9fa87f981ad41e3b323702dc2b0d4523889d8
[ "BSD-3-Clause" ]
56
2019-04-07T03:55:39.000Z
2022-03-20T04:54:57.000Z
#include "JsonImportPrivatePCH.h" #include "JsonRigidbody.h" #include "macros.h" using namespace JsonObjects; JsonRigidbody::JsonRigidbody(JsonObjPtr data){ load(data); } void JsonRigidbody::load(JsonObjPtr data){ /*I should probably get rid of those helper macros due to reduced error checking...*/ JSON_GET_VAR(data, angularDrag); JSON_GET_VAR(data, angularVelocity); JSON_GET_VAR(data, centerOfMass); JSON_GET_VAR(data, collisionDetectionMode); JSON_GET_VAR(data, constraints); JSON_GET_VAR(data, detectCollisions); JSON_GET_VAR(data, drag); JSON_GET_VAR(data, freezeRotation); JSON_GET_VAR(data, inertiaTensor); JSON_GET_VAR(data, interpolation); JSON_GET_VAR(data, isKinematic); JSON_GET_VAR(data, mass); JSON_GET_VAR(data, maxAngularVelocity); JSON_GET_VAR(data, maxDepenetrationVelocity); JSON_GET_VAR(data, position); JSON_GET_VAR(data, rotation); JSON_GET_VAR(data, sleepThreshold); JSON_GET_VAR(data, solverIterations); JSON_GET_VAR(data, solverVelocityIterations); JSON_GET_VAR(data, useGravity); JSON_GET_VAR(data, velocity); JSON_GET_VAR(data, worldCenterOfMass); }
25.883721
86
0.791554
AldeRoberge
9d5d291026ebc17df3c4dc9b3c522477f4e2933f
4,703
cpp
C++
app/src/main/cpp/src/MeshLoader.cpp
MickaelSERENO/SciVis_Android
8a8f49d1ac05f7fe559c562942d4eb4ca0e72f16
[ "MIT" ]
null
null
null
app/src/main/cpp/src/MeshLoader.cpp
MickaelSERENO/SciVis_Android
8a8f49d1ac05f7fe559c562942d4eb4ca0e72f16
[ "MIT" ]
null
null
null
app/src/main/cpp/src/MeshLoader.cpp
MickaelSERENO/SciVis_Android
8a8f49d1ac05f7fe559c562942d4eb4ca0e72f16
[ "MIT" ]
null
null
null
#include "MeshLoader.h" namespace sereno { MeshLoader* MeshLoader::loadFrom3DS(const std::string& path) { Lib3dsFile* file3ds = lib3ds_file_open(path.c_str()); if(!file3ds || !file3ds->meshes) { LOG_ERROR("Could not load properly the file %s\n", path.c_str()); if(file3ds) lib3ds_file_free(file3ds); return NULL; } Lib3dsMesh** mesh3ds = file3ds->meshes; Lib3dsMaterial** mtl3ds = file3ds->materials; uint32_t nbPoints = 0; //Go through all the meshes for knowing the number of points and elements for(uint32_t i = 0; i < file3ds->nmeshes; i++) { Lib3dsMesh* subMesh = file3ds->meshes[i]; nbPoints += subMesh->nfaces*3; } //The extracted value : texels, points and elems float* texels = (float*)malloc(sizeof(float)*2*nbPoints); float* points = (float*)malloc(sizeof(float)*3*nbPoints); float* norms = (float*)malloc(sizeof(float)*3*nbPoints); SubMeshData* currentData = NULL; MeshLoader* loader = new MeshLoader(); uint32_t nbCurrentPoints = 0; for(uint32_t it = 0; it < file3ds->nmeshes; it++) { Lib3dsMesh* subMesh = mesh3ds[it]; const char* oldMaterial = NULL; float (*faceNormals)[3] = (float (*)[3])malloc(sizeof(float)*3*3*subMesh->nfaces); //The normals of all the faces lib3ds_mesh_calculate_vertex_normals(subMesh, faceNormals); //Fill the elements array and determine when the material changed for(uint32_t i = 0; i < subMesh->nfaces; i++) { //If the material has changed, recreate a sub data if(oldMaterial == NULL || std::string(oldMaterial) != mtl3ds[subMesh->faces[i].material]->name) { //Create and fill the new 3DS internal data SubMeshData* data = (SubMeshData*)malloc(sizeof(SubMeshData)); currentData = data; data->nbVertices = 0; //Work with the material Lib3dsMaterial* mtl = mtl3ds[subMesh->faces[i].material]; //Copy only the diffuse color. If we want a more complicate draw model, we shall update our internal data for(uint8_t j = 0; j < 3; j++) data->color[j] = mtl->diffuse[j]; data->color[3] = 1.0; //Look for the texture if(mtl->texture1_map.name[0]) data->textureName = mtl->texture1_map.name[0]; //Remember this material. oldMaterial = mtl->name; //Prepend to our internal data list loader->subMeshData.push_back(data); } currentData->nbVertices += 3; //COpy points & normals for(uint32_t j = 0; j < 3; j++) { for(uint32_t k = 0; k < 3; k++) { uint32_t indice = 9*i + 3*j + k + 3*nbCurrentPoints; norms[indice] = faceNormals[3*i+j][k]; points[indice] = subMesh->vertices[subMesh->faces[i].index[j]][k]; } } //Copy Texels if(subMesh->texcos) { for(uint32_t j = 0; j < 2; j++) for(uint32_t k = 0; k < 2; k++) { uint32_t indice = 6*i + 2*j + k + 2*nbCurrentPoints; texels[indice] = subMesh->texcos[subMesh->faces[i].index[j]][k]; } } else for(uint32_t j = 0; j < 2; j++) for(uint32_t k = 0; k < 2; k++) { uint32_t indice = 6*i + 2*j + k + 2*nbCurrentPoints; texels[indice] = -1; } } free(faceNormals); nbCurrentPoints += subMesh->nfaces*3; } loader->nbVertices = nbPoints; loader->normals = norms; loader->vertices = points; loader->texels = texels; lib3ds_file_free(file3ds); return loader; } MeshLoader::~MeshLoader() { for(SubMeshData* data : subMeshData) free(data); free(normals); free(vertices); free(texels); } }
36.176923
125
0.473953
MickaelSERENO
9d5d30f769acc3c23f87e5c9875d59f3b69ce15f
17,404
cpp
C++
nau/src/nau/material/material.cpp
Khirion/nau
47a2ad8e0355a264cd507da5e7bba1bf7abbff95
[ "MIT" ]
29
2015-09-16T22:28:30.000Z
2022-03-11T02:57:36.000Z
nau/src/nau/material/material.cpp
Khirion/nau
47a2ad8e0355a264cd507da5e7bba1bf7abbff95
[ "MIT" ]
1
2017-03-29T13:32:58.000Z
2017-03-31T13:56:03.000Z
nau/src/nau/material/material.cpp
Khirion/nau
47a2ad8e0355a264cd507da5e7bba1bf7abbff95
[ "MIT" ]
10
2015-10-15T14:20:15.000Z
2022-02-17T10:37:29.000Z
#include "nau/material/material.h" #include "nau.h" #include "nau/slogger.h" #include "nau/debug/profile.h" #include "nau/material/uniformBlockManager.h" using namespace nau::material; using namespace nau::render; using namespace nau::resource; Material::Material() : m_Color (), //m_Texmat (0), m_Shader (NULL), m_ProgramValues(), m_UniformValues(), m_Enabled (true), m_Name ("__Default"), m_State(NULL) { } Material::~Material() { while (!m_ImageTextures.empty()) { delete((*m_ImageTextures.begin()).second); m_ImageTextures.erase(m_ImageTextures.begin()); } while (!m_Textures.empty()) { delete((*m_Textures.begin()).second); m_Textures.erase(m_Textures.begin()); } while (!m_Buffers.empty()) { delete((*m_Buffers.begin()).second); m_Buffers.erase(m_Buffers.begin()); } } std::shared_ptr<Material> Material::clone() { // check clone Program Values Material *mat; mat = new Material(); mat->setName(m_Name); mat->m_Enabled = m_Enabled; mat->m_Shader = m_Shader; mat->m_ProgramValues = m_ProgramValues; mat->m_ProgramBlockValues = m_ProgramBlockValues; mat->m_Color = m_Color; mat->m_Buffers = m_Buffers; mat->m_Textures = m_Textures; for (auto &it : m_ImageTextures) { mat->attachImageTexture(it.second->getLabel(), it.second->getPropi(IImageTexture::UNIT), it.second->getPropui(IImageTexture::TEX_ID)); } for (auto &it : m_Textures) { mat->attachTexture(it.first, it.second->getTexture()); } mat->m_State = m_State; mat->m_ArrayOfTextures = m_ArrayOfTextures; //mat->m_ArrayOfImageTextures = new MaterialArrayOfTextures(m_ArrayOfImageTextures); return std::shared_ptr<Material>(mat); } bool Material::isShaderLinked() { return(m_Shader->isLinked()); } std::map<std::string, nau::material::ProgramValue>& Material::getProgramValues() { return m_ProgramValues; } std::map<std::string, nau::material::ProgramValue>& Material::getUniformValues() { return m_UniformValues; } std::map<std::pair<std::string, std::string>, nau::material::ProgramBlockValue>& Material::getProgramBlockValues() { return m_ProgramBlockValues; } void Material::setName (std::string name) { m_Name = name; } std::string& Material::getName () { return m_Name; } void Material::getValidProgramValueNames(std::vector<std::string> *names) { // valid program value names are program values that are not part of the uniforms map // this is because there may be a program value specified in the project file whose type // does not match the shader variable type std::map<std::string,ProgramValue>::iterator progValIter; progValIter = m_ProgramValues.begin(); for (; progValIter != m_ProgramValues.end(); progValIter++) { if (m_UniformValues.count(progValIter->first) == 0) names->push_back(progValIter->first); } } void Material::getUniformNames(std::vector<std::string> *names) { std::map<std::string,ProgramValue>::iterator progValIter; progValIter = m_UniformValues.begin(); for (; progValIter != m_UniformValues.end(); progValIter++) { names->push_back(progValIter->first); } } ProgramValue * Material::getProgramValue(std::string name) { if (m_ProgramValues.count(name) > 0) return &m_ProgramValues[name]; else return NULL; } void Material::getTextureNames(std::vector<std::string> *vs) { for (auto t : m_Textures) { vs->push_back(t.second->getTexture()->getLabel()); } } void Material::getTextureUnits(std::vector<unsigned int> *vi) { for (auto t : m_Textures) { vi->push_back(t.second->getPropi(MaterialTexture::UNIT)); } } void Material::setUniformValues() { { // explicit block for profiler PROFILE_GL("Set Uniforms"); std::map<std::string, ProgramValue>::iterator progValIter; progValIter = m_ProgramValues.begin(); for (; progValIter != m_ProgramValues.end(); ++progValIter) { void *v = progValIter->second.getValues(); m_Shader->setValueOfUniform(progValIter->first, v); } } int x = 3; } void Material::setUniformBlockValues() { { // explicit block for profiler PROFILE_GL("Set Blocks"); std::set<std::string> blocks; for (auto pbv : m_ProgramBlockValues) { void *v = pbv.second.getValues(); const std::string &block = pbv.first.first; std::string uniform = pbv.first.second; IUniformBlock *b = UNIFORMBLOCKMANAGER->getBlock(block); if (b) { b->setUniform(uniform, v); blocks.insert(block); } } m_Shader->prepareBlocks(); } } #include <algorithm> void Material::checkProgramValuesAndUniforms(std::string &result) { int loc; IUniform iu; std::string s,aux; std::vector<std::string> names, otherNames; m_Shader->getAttributeNames(&names); for (auto n : names) { if (VertexData::GetAttribIndex(n) == VertexData::MaxAttribs) { aux = "Material " + m_Name + ": attribute " + n + " - not valid"; result += aux + "\n"; SLOG("Material %s: attribute %s - not valid", m_Name.c_str(), n.c_str()); } } names.clear(); m_Shader->getUniformBlockNames(&names); // check if uniforms defined in the project are active in the shader std::string aName; for (auto bi : m_ProgramBlockValues) { aName = bi.first.first; if (std::any_of(names.begin(), names.end(), [aName](std::string i) {return i == aName; })) { IUniformBlock *b = UNIFORMBLOCKMANAGER->getBlock(aName); otherNames.clear(); b->getUniformNames(&otherNames); std::string uniName = bi.first.second; if (!std::any_of(otherNames.begin(), otherNames.end(), [uniName](std::string i) {return i == uniName; })) { aux = "Material " + m_Name + ": block: " + bi.first.first + " uniform: " + uniName + " - not active in shader"; result += aux + "\n"; SLOG("Material %s: block %s: uniform %s not active in shader", m_Name.c_str(), bi.first.first.c_str(), uniName.c_str()); } } else { SLOG("Material %s: block %s is not active in shader", m_Name.c_str(), bi.first.first.c_str()); aux = "Material " + m_Name + ": block: " + bi.first.first + " - not active in shader"; result += aux + "\n"; } } // check if uniforms used in the shader are defined in the project // for each block for (auto name : names) { IUniformBlock *b = UNIFORMBLOCKMANAGER->getBlock(name); otherNames.clear(); b->getUniformNames(&otherNames); // for each uniform in the block for (auto uni : otherNames) { if (uni.find(".") == std::string::npos && !std::any_of(m_ProgramBlockValues.begin(), m_ProgramBlockValues.end(), [&](std::pair<std::pair<std::string , std::string >, ProgramBlockValue> k) {return k.first == std::pair<std::string, std::string>(name, uni); })) { SLOG("Material %s: block %s: uniform %s is not defined in the material", m_Name.c_str(), name.c_str(), uni.c_str()); aux = "Material " + m_Name + ": shader block: " + name + " uniform: " + uni + " - not defined in the material"; result += aux + "\n"; } } } // get the location of the ProgramValue in the shader // loc == -1 means that ProgramValue is not an active uniform std::map<std::string, ProgramValue>::iterator progValIter; progValIter = m_ProgramValues.begin(); for (; progValIter != m_ProgramValues.end(); ++progValIter) { loc = m_Shader->getUniformLocation(progValIter->first); progValIter->second.setLoc(loc); if (loc == -1) { SLOG("Material %s: material uniform %s is not active in shader %s", m_Name.c_str(), progValIter->first.c_str(), m_Shader->getName().c_str()); aux = "Material: " + m_Name + " uniform: " + progValIter->first + " - not active in shader " + m_Shader->getName(); result += aux + "\n"; } } int k = m_Shader->getNumberOfUniforms(); for (int i = 0; i < k; ++i) { iu = m_Shader->getIUniform(i); s = iu.getName(); if (m_ProgramValues.count(s) == 0) { SLOG("Material %s: shader uniform %s from shader %s is not defined", m_Name.c_str(), s.c_str(), m_Shader->getName().c_str()); aux = "Material: " + m_Name + " shader : " + m_Shader->getName() + " + shader uniform: " + s + " - not defined in material"; result += aux + "\n"; } else if (! Enums::isCompatible(m_ProgramValues[s].getValueType(), iu.getSimpleType())) { aux = "Material: " + m_Name + " uniform: " + s + " - types are not compatible(" + iu.getStringSimpleType() + "," + Enums::DataTypeToString[m_ProgramValues[s].getValueType()] + ")"; result += aux + "\n"; SLOG("Material %s: uniform %s types are not compatiple (%s, %s)", m_Name.c_str(), s.c_str(), iu.getStringSimpleType().c_str(), Enums::DataTypeToString[m_ProgramValues[s].getValueType()].c_str()); } } } void Material::prepareNoShaders () { RENDERER->setState (getState()); m_Color.prepare(); for (auto t : m_Textures) t.second->bind(); if (APISupport->apiSupport(IAPISupport::APIFeatureSupport::IMAGE_TEXTURE)) { for (auto it : m_ImageTextures) it.second->prepare(); } for (auto b : m_Buffers) { b.second->bind(); } } void Material::prepare () { { PROFILE("Buffers"); for (auto &b : m_Buffers) { b.second->bind(); } } { PROFILE("State"); RENDERER->setState (getState()); } { PROFILE("Color"); m_Color.prepare(); } { PROFILE("Texture"); for (auto &t : m_Textures) { t.second->bind(); } } { PROFILE("Image Textures"); if (APISupport->apiSupport(IAPISupport::APIFeatureSupport::IMAGE_TEXTURE)) { for (auto &it : m_ImageTextures) it.second->prepare(); } } if (m_ArrayOfTextures.size()) { PROFILE("Array Of Textures"); for (auto &at : m_ArrayOfTextures) at.bind(); } if (m_ArrayOfImageTextures.size()) { PROFILE("Array Of Image Textures"); for (auto at : m_ArrayOfImageTextures) at->bind(); } { PROFILE("Shaders"); if (NULL != m_Shader) { bool prepared = m_Shader->prepare(); RENDERER->setShader(m_Shader); if (prepared) { setUniformValues(); setUniformBlockValues(); } } else RENDERER->setShader(NULL); } } void Material::restore() { //m_Color.restore(); //if (NULL != m_Shader && m_useShader) { // m_Shader->restore(); //} if (m_Shader) m_Shader->restore(); RENDERER->resetTextures(m_Textures); //for (auto t : m_Textures) // t.second->unbind(); for (auto b : m_Buffers) b.second->unbind(); if (APISupport->apiSupport(IAPISupport::APIFeatureSupport::IMAGE_TEXTURE)) { for (auto &b : m_ImageTextures) b.second->restore(); } for (auto &b: m_ArrayOfTextures) b.unbind(); } void Material::restoreNoShaders() { m_Color.restore(); for (auto t : m_Textures) t.second->unbind(); for (auto b : m_Buffers) b.second->unbind(); if (APISupport->apiSupport(IAPISupport::APIFeatureSupport::IMAGE_TEXTURE)) { for (auto b : m_ImageTextures) b.second->restore(); } } void Material::addArrayOfTextures(IArrayOfTextures *at, int unit) { size_t k = m_ArrayOfTextures.size(); m_ArrayOfTextures.resize(k+1); m_ArrayOfTextures[k].setArrayOfTextures(at); m_ArrayOfTextures[k].setPropi(MaterialArrayOfTextures::FIRST_UNIT, unit); // m_ArrayOfTextures.setArrayOfTextures(at); // m_ArrayOfTextures.setPropi(MaterialArrayOfTextures::FIRST_UNIT, unit); } MaterialArrayOfTextures * Material::getMaterialArrayOfTextures(int k) { if (k < m_ArrayOfTextures.size()) return &m_ArrayOfTextures[k]; else return NULL; }; void Material::addArrayOfImageTextures(MaterialArrayOfImageTextures *m) { m_ArrayOfImageTextures.push_back(m); } MaterialArrayOfImageTextures * Material::getArrayOfImageTextures(int id) { if (id < m_ArrayOfImageTextures.size()) return m_ArrayOfImageTextures[id]; else return NULL; } void Material::setState(IState *s) { m_State = s; } void Material::attachImageTexture(std::string label, unsigned int unit, unsigned int texID) { assert(APISupport->apiSupport(IAPISupport::APIFeatureSupport::IMAGE_TEXTURE) && "No image texture support"); IImageTexture *it = IImageTexture::Create(label, unit, texID); m_ImageTextures[unit] = it; } IImageTexture * Material::getImageTexture(unsigned int unit) { if (m_ImageTextures.count(unit)) return m_ImageTextures[unit]; else return NULL; } void Material::getImageTextureUnits(std::vector<unsigned int> *v) { for (auto i : m_ImageTextures) { v->push_back(i.first); } } void Material::getTextureIDs(std::vector<unsigned int>* v) { for (auto i : m_Textures) { v->push_back(i.second->getTexture()->getPropi(ITexture::ID)); } } void Material::attachBuffer(IMaterialBuffer *b) { int bp = b->getPropi(IMaterialBuffer::BINDING_POINT); m_Buffers[bp] = b; } IMaterialBuffer * Material::getMaterialBuffer(int id) { if (m_Buffers.count(id)) return m_Buffers[id]; else return NULL; } IBuffer * Material::getBuffer(int id) { if (m_Buffers.count(id)) return m_Buffers[id]->getBuffer(); else return NULL; } bool Material::hasBuffer(int id) { return 0 != m_Buffers.count(id); } void Material::getBufferBindings(std::vector<unsigned int> *vi) { for (auto t : m_Buffers) { vi->push_back(t.second->getPropi(IMaterialBuffer::BINDING_POINT)); } } bool Material::createTexture (int unit, std::string fn) { ITexture *tex = RESOURCEMANAGER->addTexture (fn); if (tex) { MaterialTexture *t = new MaterialTexture(unit); t->setTexture(tex); // t->setSampler(ITextureSampler::create(tex)); m_Textures[unit] = t; return(true); } else { SLOG("Texture not found: %s", fn.c_str()); return(false); } } void Material::unsetTexture(int unit) { m_Textures.erase(unit); } void Material::attachTexture (int unit, ITexture *tex) { MaterialTexture *t = new MaterialTexture(unit); t->setTexture(tex); // t->setSampler(ITextureSampler::create(tex)); m_Textures[unit] = t; } void Material::attachTexture (int unit, std::string label) { ITexture *tex = RESOURCEMANAGER->getTexture (label); assert(tex != NULL); MaterialTexture *t = new MaterialTexture(unit); t->setTexture(tex); // t->setSampler(ITextureSampler::create(tex)); m_Textures[unit] = t; } ITexture* Material::getTexture(int unit) { if (m_Textures.count(unit)) return m_Textures[unit]->getTexture() ; else return(NULL); } ITextureSampler* Material::getTextureSampler(unsigned int unit) { if (m_Textures.count(unit)) return m_Textures[unit]->getSampler(); else return(NULL); } MaterialTexture * Material::getMaterialTexture(int unit) { if (m_Textures.count(unit)) return m_Textures[unit]; else return(NULL); } void Material::attachProgram (std::string shaderName) { m_Shader = RESOURCEMANAGER->getProgram(shaderName); //m_ProgramValues.clear(); } void Material::cloneProgramFromMaterial(std::shared_ptr<Material> &mat) { m_Shader = mat->getProgram(); m_ProgramValues.clear(); m_ProgramBlockValues.clear(); m_UniformValues.clear(); std::map<std::string, nau::material::ProgramValue>::iterator iter; iter = mat->m_ProgramValues.begin(); for( ; iter != mat->m_ProgramValues.end(); ++iter) { m_ProgramValues[(*iter).first] = (*iter).second; } for (auto pbv : mat->m_ProgramBlockValues) { m_ProgramBlockValues[pbv.first] = pbv.second; } iter = mat->m_UniformValues.begin(); for( ; iter != mat->m_UniformValues.end(); ++iter) { m_UniformValues[(*iter).first] = (*iter).second; } } std::string Material::getProgramName() { if (m_Shader) return m_Shader->getName(); else return ""; } IProgram * Material::getProgram() { return m_Shader; } void Material::setValueOfUniform(std::string name, void *values) { if (m_ProgramValues.count(name)) m_ProgramValues[name].setValueOfUniform(values); } void Material::clearProgramValues() { m_ProgramValues.clear(); } void Material::addProgramValue (std::string name, nau::material::ProgramValue progVal) { // if specified in the material lib, add it to the program values if (progVal.isInSpecML()) m_ProgramValues[name] = progVal; else { // if the name is not part of m_ProgramValues or if it is but the type does not match if (m_ProgramValues.count(name) == 0 || !Enums::isCompatible(m_ProgramValues[name].getValueType(),progVal.getValueType())) { // if there is already a uniform with the same name, and a different type remove it if (m_UniformValues.count(name) || m_UniformValues[name].getValueType() != progVal.getValueType()) { m_UniformValues.erase(name); } // add it to the uniform values m_UniformValues[name] = progVal; } } } void Material::addProgramBlockValue (std::string block, std::string name, nau::material::ProgramBlockValue progVal) { m_ProgramBlockValues[std::pair<std::string, std::string>(block,name)] = progVal; } IState* Material::getState (void) { if (m_State == NULL) { m_State = RESOURCEMANAGER->createState(m_Name); } return m_State; } ColorMaterial& Material::getColor (void) { return m_Color; } //nau::material::TextureMat* //Material::getTextures (void) { // // return m_Texmat; //} //void //Material::clear() { // // m_Color.clear(); // m_Buffers.clear(); // m_Textures.clear(); // // m_ImageTextures.clear(); // // m_Shader = NULL; // m_ProgramValues.clear(); // m_Enabled = true; // //m_State->clear(); // m_State->setDefault(); // m_Name = "Default"; //} void Material::enable (void) { m_Enabled = true; } void Material::disable (void) { m_Enabled = false; } bool Material::isEnabled (void) { return m_Enabled; }
20.843114
127
0.675822
Khirion
9d5d32b2050f8f812e161fc6bbf624c6ea44dd9d
1,969
cpp
C++
src/core/correlationmatrix.cpp
mfayk/KINC
0f6565ce8e1102392382e4c716c128115b611f0c
[ "MIT" ]
10
2018-08-15T13:27:35.000Z
2020-12-10T17:20:40.000Z
src/core/correlationmatrix.cpp
mfayk/KINC
0f6565ce8e1102392382e4c716c128115b611f0c
[ "MIT" ]
182
2016-07-31T07:15:15.000Z
2022-01-30T01:25:41.000Z
src/core/correlationmatrix.cpp
mfayk/KINC
0f6565ce8e1102392382e4c716c128115b611f0c
[ "MIT" ]
7
2017-10-12T22:03:42.000Z
2020-02-26T00:01:18.000Z
#include "correlationmatrix.h" #include "correlationmatrix_model.h" #include "correlationmatrix_pair.h" /*! * Return a qt table model that represents this data object as a table. */ QAbstractTableModel* CorrelationMatrix::model() { EDEBUG_FUNC(this); if ( !_model ) { _model = new Model(this); } return _model; } /*! * Initialize this correlation matrix with a list of gene names, the max cluster * size, and a correlation name. * * @param geneNames * @param maxClusterSize * @param correlationName */ void CorrelationMatrix::initialize(const EMetaArray& geneNames, int maxClusterSize, const QString& correlationName) { EDEBUG_FUNC(this,&geneNames,maxClusterSize,&correlationName); // save correlation names to metadata EMetaObject metaObject {meta().toObject()}; metaObject.insert("correlation", correlationName); setMeta(metaObject); // initialize base class Matrix::initialize(geneNames, maxClusterSize, sizeof(float), SUBHEADER_SIZE); } /*! * Return the correlation name for this correlation matrix. */ QString CorrelationMatrix::correlationName() const { EDEBUG_FUNC(this); return meta().toObject().at("correlation").toString(); } /*! * Return a list of correlation pairs in raw form. */ std::vector<CorrelationMatrix::RawPair> CorrelationMatrix::dumpRawData() const { EDEBUG_FUNC(this); // create list of raw pairs std::vector<RawPair> pairs; pairs.reserve(size()); // iterate through all pairs Pair pair(this); while ( pair.hasNext() ) { // read in next pair pair.readNext(); // copy pair to raw list RawPair rawPair; rawPair.index = pair.index(); rawPair.correlations.resize(pair.clusterSize()); for ( int k = 0; k < pair.clusterSize(); ++k ) { rawPair.correlations[k] = pair.at(k); } pairs.push_back(rawPair); } return pairs; }
21.402174
115
0.663281
mfayk
9d5d48871ba785a309b1d82c63ed1dba6eda71a1
698
hpp
C++
src/camera.hpp
VeganPower/potato3d
4f0bacbd883f42be7c1acdf1f700045325512da2
[ "MIT" ]
null
null
null
src/camera.hpp
VeganPower/potato3d
4f0bacbd883f42be7c1acdf1f700045325512da2
[ "MIT" ]
1
2018-03-29T10:56:25.000Z
2018-03-29T11:00:57.000Z
src/camera.hpp
VeganPower/potato3d
4f0bacbd883f42be7c1acdf1f700045325512da2
[ "MIT" ]
null
null
null
#pragma once #include <memory> #include "transformation.hpp" namespace potato { class Camera { public: typedef std::shared_ptr<Camera> ptr; Camera(); void transformation(Transformation const& p); Transformation const& transformation() const; f32 tan_half_fov() const; private: Transformation t_; f32 fov_; f32 tan_half_fov_; }; inline Camera::Camera() : t_(Transformation::identity) , fov_(90.f) , tan_half_fov_(tan(fov_/2.f)) { } inline Transformation const& Camera::transformation() const { return t_; } inline void Camera::transformation(Transformation const& p) { t_ = p; } inline f32 Camera::tan_half_fov() const { return tan_half_fov_; } }
14.541667
59
0.700573
VeganPower
9d60486947ed7f7d700729fa869d1fb3753bc7aa
2,987
hpp
C++
src/spline2/MultiBsplineValue_BGQ.hpp
prckent/qmcpack
127caf219ee99c2449b803821fcc8b1304b66ee1
[ "NCSA" ]
null
null
null
src/spline2/MultiBsplineValue_BGQ.hpp
prckent/qmcpack
127caf219ee99c2449b803821fcc8b1304b66ee1
[ "NCSA" ]
null
null
null
src/spline2/MultiBsplineValue_BGQ.hpp
prckent/qmcpack
127caf219ee99c2449b803821fcc8b1304b66ee1
[ "NCSA" ]
null
null
null
////////////////////////////////////////////////////////////////////////////////////// // This file is distributed under the University of Illinois/NCSA Open Source License. // See LICENSE file in top directory for details. // // Copyright (c) 2016 Jeongnim Kim and QMCPACK developers. // // File developed by: Jeongnim Kim, jeongnim.kim@intel.com, Intel Corp. // Amrita Mathuriya, amrita.mathuriya@intel.com, Intel Corp. // Ye Luo, yeluo@anl.gov, Argonne National Laboratory // // File created by: Jeongnim Kim, jeongnim.kim@intel.com, Intel Corp. ////////////////////////////////////////////////////////////////////////////////////// // -*- C++ -*- #ifndef SPLINE2_MULTIEINSPLINE_VALUE_BGQ_HPP #define SPLINE2_MULTIEINSPLINE_VALUE_BGQ_HPP #if defined(__xlC__) #include <builtins.h> #endif namespace spline2 { template<typename T> inline void evaluate_v_impl(const typename qmcplusplus::bspline_traits<T, 3>::SplineType* restrict spline_m, T x, T y, T z, T* restrict vals, int first, int last) { int ix, iy, iz; T a[4], b[4], c[4]; computeLocationAndFractional(spline_m, x, y, z, ix, iy, iz, a, b, c); vector4double vec_c0 = vec_splats(c[0]); vector4double vec_c1 = vec_splats(c[1]); vector4double vec_c2 = vec_splats(c[2]); vector4double vec_c3 = vec_splats(c[3]); const intptr_t xs = spline_m->x_stride; const intptr_t ys = spline_m->y_stride; const intptr_t zs = spline_m->z_stride; constexpr T zero(0); const int num_splines = last - first; std::fill(vals, vals + num_splines, zero); for (int i = 0; i < 4; i++) for (int j = 0; j < 4; j++) { const T pre00 = a[i] * b[j]; vector4double vec_pre00 = vec_splats(pre00); T* restrict coefs0 = spline_m->coefs + ((ix + i) * xs + (iy + j) * ys + iz * zs) + first; T* restrict coefs1 = coefs0 + zs; T* restrict coefs2 = coefs0 + 2 * zs; T* restrict coefs3 = coefs0 + 3 * zs; for (int n = 0, p = 0; n < num_splines; n += 4, p += 4 * sizeof(T)) { vector4double vec_coef0, vec_coef1, vec_coef2, vec_coef3, vec_val; __dcbt(&coefs0[n + 8]); __dcbt(&coefs1[n + 8]); __dcbt(&coefs2[n + 8]); __dcbt(&coefs3[n + 8]); vec_coef0 = vec_ld(p, coefs0); vec_coef1 = vec_ld(p, coefs1); vec_coef2 = vec_ld(p, coefs2); vec_coef3 = vec_ld(p, coefs3); vec_val = vec_ld(p, vals); vec_coef0 = vec_mul(vec_c0, vec_coef0); vec_coef0 = vec_madd(vec_c1, vec_coef1, vec_coef0); vec_coef0 = vec_madd(vec_c2, vec_coef2, vec_coef0); vec_coef0 = vec_madd(vec_c3, vec_coef3, vec_coef0); vec_val = vec_madd(vec_pre00, vec_coef0, vec_val); vec_st(vec_val, p, vals); } } } } // namespace spline2 #endif
34.732558
108
0.554737
prckent
9d60de0c2359963f88991fa95853b16d75bb02dc
2,022
cc
C++
blades/mediatomb/src/zmm/object.cc
krattai/AEBL
a7b12c97479e1236d5370166b15ca9f29d7d4265
[ "BSD-2-Clause" ]
4
2016-04-26T03:43:54.000Z
2016-11-17T08:09:04.000Z
blades/mediatomb/src/zmm/object.cc
krattai/AEBL
a7b12c97479e1236d5370166b15ca9f29d7d4265
[ "BSD-2-Clause" ]
17
2015-01-05T21:06:22.000Z
2015-12-07T20:45:44.000Z
blades/mediatomb/src/zmm/object.cc
krattai/AEBL
a7b12c97479e1236d5370166b15ca9f29d7d4265
[ "BSD-2-Clause" ]
3
2016-04-26T03:43:55.000Z
2020-11-06T11:02:08.000Z
/*MT* MediaTomb - http://www.mediatomb.cc/ object.cc - this file is part of MediaTomb. Copyright (C) 2005 Gena Batyan <bgeradz@mediatomb.cc>, Sergey 'Jin' Bostandzhyan <jin@mediatomb.cc> Copyright (C) 2006-2010 Gena Batyan <bgeradz@mediatomb.cc>, Sergey 'Jin' Bostandzhyan <jin@mediatomb.cc>, Leonhard Wimmer <leo@mediatomb.cc> MediaTomb is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. MediaTomb 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 version 2 along with MediaTomb; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. $Id$ */ /// \file object.cc #ifdef HAVE_CONFIG_H #include "autoconfig.h" #endif #include <stdio.h> #include <stdlib.h> #include "object.h" #include "memory.h" using namespace zmm; Object::Object() { atomic_set(&_ref_count, 0); #ifdef ATOMIC_NEED_MUTEX pthread_mutex_init(&mutex, NULL); #endif } Object::~Object() { #ifdef ATOMIC_NEED_MUTEX pthread_mutex_destroy(&mutex); #endif } void Object::retain() { #ifdef ATOMIC_NEED_MUTEX atomic_inc(&_ref_count, &mutex); #else atomic_inc(&_ref_count); #endif } void Object::release() { #ifdef ATOMIC_NEED_MUTEX if(atomic_dec(&_ref_count, &mutex)) #else if(atomic_dec(&_ref_count)) #endif { delete this; } } int Object::getRefCount() { return atomic_get(&_ref_count); } void* Object::operator new (size_t size) { return MALLOC(size); } void Object::operator delete (void *ptr) { FREE(ptr); }
22.21978
78
0.66815
krattai
9d667cb4707efcd4045cf34eac597f7cd8a03877
1,439
cpp
C++
src/chart/speclayout/treemap.cpp
dyuri/vizzu-lib
e5eb4bee98445a85c0a6a61b820ad355851f38c8
[ "Apache-2.0" ]
1,159
2021-09-23T14:53:16.000Z
2022-03-30T21:23:41.000Z
src/chart/speclayout/treemap.cpp
dyuri/vizzu-lib
e5eb4bee98445a85c0a6a61b820ad355851f38c8
[ "Apache-2.0" ]
29
2021-10-05T13:28:01.000Z
2022-03-29T16:16:20.000Z
src/chart/speclayout/treemap.cpp
dyuri/vizzu-lib
e5eb4bee98445a85c0a6a61b820ad355851f38c8
[ "Apache-2.0" ]
47
2021-09-30T14:04:25.000Z
2022-02-21T16:01:58.000Z
#include "treemap.h" #include <algorithm> #include "base/math/interpolation.h" using namespace Vizzu; using namespace Vizzu::Charts; using namespace Geom; TreeMap::TreeMap(const std::vector<double> &sizes, const Point &p0, const Point &p1) { for (auto j = 0u; j < sizes.size(); j++) sums.push_back({ j, sizes[j] }); std::sort(sums.begin(), sums.end(), [](const SizeRecord &a, const SizeRecord &b) { return b.value < a.value; }); divide(sums.begin(), sums.end(), p0, p1); std::sort(data.begin(), data.end(), [](const DataRecord &a, const DataRecord &b) { return a.index < b.index; }); } void TreeMap::divide(It begin, It end, const Point &p0, const Point &p1, bool horizontal) { if (begin + 1 == end) { data.push_back({ begin->index, p0, p1 }); return; } auto sum = 0.0; for (auto it = begin; it != end; ++it) sum += it->value; if (sum == 0) { for (auto it = begin; it != end; ++it) data.push_back({ it->index, p0, p1 }); return; } auto factor = 0.0; auto it = begin; for (;it != end; ++it) { if (sum > 0) factor += it->value/sum; if (factor > 0.4) { ++it; break; } } auto p = Math::interpolate(p0, p1, factor); if (horizontal) divide(begin, it, p0, Point(p1.x,p.y), !horizontal); else divide(begin, it, p0, Point(p.x,p1.y), !horizontal); if (horizontal) divide(it, end, Point(p0.x ,p.y), p1, !horizontal); else divide(it, end, Point(p.x,p0.y), p1, !horizontal); }
21.477612
89
0.608756
dyuri
9d66aba8e3c327d02da94421a58bb54b6bcaced1
285
cpp
C++
src/13000/13241.cpp
upple/BOJ
e6dbf9fd17fa2b458c6a781d803123b14c18e6f1
[ "MIT" ]
8
2018-04-12T15:54:09.000Z
2020-06-05T07:41:15.000Z
src/13000/13241.cpp
upple/BOJ
e6dbf9fd17fa2b458c6a781d803123b14c18e6f1
[ "MIT" ]
null
null
null
src/13000/13241.cpp
upple/BOJ
e6dbf9fd17fa2b458c6a781d803123b14c18e6f1
[ "MIT" ]
null
null
null
#include <cstdio> #include <algorithm> typedef long long ll; ll gcd(ll a, ll b) { if (a < b) std::swap(a, b); while (a) { ll tmp = b % a; b = a; a = tmp; } return b; } int main() { ll a, b, m; scanf("%lld %lld", &a, &b); m = gcd(a, b); printf("%lld", (a / m)*b); }
10.961538
28
0.487719
upple
9d6a0d980860b3cc519658461272b44e3ee633a5
814
hpp
C++
Gpx/Gpx/Window/GlfwWindow.hpp
DexterDreeeam/DxtSdk2021
2dd8807b4ebe1d65221095191eaa7938bc5e9e78
[ "MIT" ]
1
2021-11-18T03:57:54.000Z
2021-11-18T03:57:54.000Z
Gpx/Gpx/Window/GlfwWindow.hpp
DexterDreeeam/P9
2dd8807b4ebe1d65221095191eaa7938bc5e9e78
[ "MIT" ]
null
null
null
Gpx/Gpx/Window/GlfwWindow.hpp
DexterDreeeam/P9
2dd8807b4ebe1d65221095191eaa7938bc5e9e78
[ "MIT" ]
null
null
null
#pragma once #define GLFW_INCLUDE_VULKAN #include "../../External/Vulkan/Windows/Header/glfw3.h" #include "../Runtime/Interface.hpp" namespace gpx { class runtime; class glfw_window : public window { friend class vulkan_runtime; public: glfw_window(const window_desc& desc, obs<runtime> rt); virtual ~glfw_window() override; public: virtual string name() override; virtual boole start() override; virtual boole stop() override; // virtual boole present(s64 my_image) override; virtual boole poll_event() override; virtual boole is_running() override; private: static mutex _glfw_op_lock; static s64 _window_number; window_desc _desc; obs<runtime> _rt; GLFWwindow* _ctx; VkSurfaceKHR _surface; }; }
17.695652
58
0.673219
DexterDreeeam
9d6bf36c06605275a53bcb2ec3eeece2c6caa2f1
2,674
hpp
C++
core/plan/abstract_function_store.hpp
Yuzhen11/tangram
67b06a0d2b23c3e263044b6e4d293e263dae7a94
[ "Apache-2.0" ]
14
2019-05-14T05:26:45.000Z
2021-08-06T00:10:13.000Z
core/plan/abstract_function_store.hpp
animeshtrivedi/tangram
67b06a0d2b23c3e263044b6e4d293e263dae7a94
[ "Apache-2.0" ]
1
2021-11-10T13:24:29.000Z
2021-11-10T13:24:29.000Z
core/plan/abstract_function_store.hpp
animeshtrivedi/tangram
67b06a0d2b23c3e263044b6e4d293e263dae7a94
[ "Apache-2.0" ]
2
2019-05-10T03:02:06.000Z
2019-06-28T12:32:26.000Z
#pragma once #include <functional> #include <memory> #include "core/intermediate/abstract_intermediate_store.hpp" #include "core/map_output/abstract_map_output.hpp" #include "core/map_output/map_output_stream.hpp" #include "core/partition/abstract_partition.hpp" #include "core/cache/abstract_fetcher.hpp" #include "io/abstract_block_reader.hpp" #include "io/abstract_writer.hpp" namespace xyz { class AbstractFunctionStore { public: using MapFuncT = std::function<std::shared_ptr<AbstractMapOutput>( std::shared_ptr<AbstractPartition>)>; using MergeCombineFuncT = std::function<SArrayBinStream(const std::vector<std::shared_ptr<AbstractMapOutput>>& map_outputs, int part_id)>; using JoinFuncT = std::function<void (std::shared_ptr<AbstractPartition>, SArrayBinStream)>; using JoinFunc2T = std::function<void(std::shared_ptr<AbstractPartition>, std::shared_ptr<AbstractMapOutputStream>)>; using MapWith = std::function<std::shared_ptr<AbstractMapOutput>(int, int, std::shared_ptr<AbstractPartition>, std::shared_ptr<AbstractFetcher>)>; using CreatePartFromBinFuncT = std::function<std::shared_ptr<AbstractPartition>( SArrayBinStream bin, int part_id, int num_part)>; using CreatePartFromBlockReaderFuncT = std::function<std::shared_ptr<AbstractPartition>( std::shared_ptr<AbstractBlockReader>)>; using WritePartFuncT = std::function<void(std::shared_ptr<AbstractPartition>, std::shared_ptr<AbstractWriter>, std::string)>; using GetterFuncT = std::function< SArrayBinStream(SArrayBinStream bin, std::shared_ptr<AbstractPartition>)>; using CreatePartFuncT = std::function<std::shared_ptr<AbstractPartition>()>; using CreatePartFromStringFuncT = std::function<std::shared_ptr<AbstractPartition>(std::string)>; ~AbstractFunctionStore(){} virtual void AddMap(int id, MapFuncT func) = 0; virtual void AddMergeCombine(int id, MergeCombineFuncT func) = 0; virtual void AddJoin(int id, JoinFuncT func) = 0; virtual void AddJoin2(int id, JoinFunc2T func) = 0; virtual void AddMapWith(int id, MapWith func) = 0; virtual void AddCreatePartFromBinFunc(int id, CreatePartFromBinFuncT func) = 0; virtual void AddCreatePartFromBlockReaderFunc(int id, CreatePartFromBlockReaderFuncT func) = 0; virtual void AddWritePart(int id, WritePartFuncT func) = 0; virtual void AddGetter(int id, GetterFuncT func) = 0; virtual void AddCreatePartFunc(int id, CreatePartFuncT func) = 0; virtual void AddCreatePartFromStringFunc(int id, CreatePartFromStringFuncT func) = 0; }; } // namespaca xyz
50.45283
140
0.742708
Yuzhen11
9d6d802cee9fc387ad1a03df17cbb4fddc34eda4
5,713
hpp
C++
include/polynomial/polynomial.hpp
adityakadoo/CPPMatrixLib
de577017fcbbd3d7e960c71853b1fde65ec53dbb
[ "MIT" ]
null
null
null
include/polynomial/polynomial.hpp
adityakadoo/CPPMatrixLib
de577017fcbbd3d7e960c71853b1fde65ec53dbb
[ "MIT" ]
null
null
null
include/polynomial/polynomial.hpp
adityakadoo/CPPMatrixLib
de577017fcbbd3d7e960c71853b1fde65ec53dbb
[ "MIT" ]
null
null
null
#ifndef _POLYNOMIAL_H_ #define _POLYNOMIAL_H_ #include "../matrix/matrix.hpp" #include "../matrix/matrix_utility.hpp" template<typename T> class polynomial { public: // constructor with memory allocation polynomial(size_t d,T x=0) : D(d) { P.resize(d+1, 1, x); } // default constructor polynomial() : D(-1) {} // constructor from initializer list polynomial(const std::initializer_list<T> p) { D = p.size()-1; P.resize(D+1, 1); auto k = p.begin(); for(size_t i=0;i<D+1;i++) { P(i,0)+= *k; k++; } } // check if empty bool empty() const { return D == -1; } // access degree size_t degree() const { return D; } // resize polynomial void resize(size_t d,T x=0) { D = d; P.resize(d+1, 1, x); } // Algebraic Operations: // 1 polynomial(p), 1 scalar(a): -p, p*a, a*p // 2 polynomial(p, q): p+q, p-q, p*q, p==q, p!=q polynomial operator-() const { return polynomial(D) - *this; } polynomial operator*=(const T &rhs) { P *= rhs; return *this; } polynomial operator*(const T &rhs) const { return polynomial(*this) *= rhs; } friend polynomial<T> operator*(const T &lhs,const polynomial<T> &rhs) { return rhs * lhs; } polynomial operator+=(const polynomial &rhs) { if(D<rhs.D) { matrix<T> temp(rhs.D+1,1); for(size_t i=0;i<D+1;i++) { temp(i,0)+= P(i,0); } D=rhs.D; P.resize(D+1,1); P+=temp; } for(size_t i=0;i<rhs.D+1;i++) { P(i,0)+= rhs[i]; } return *this; } polynomial operator+(const polynomial &rhs) const { return polynomial(*this) += rhs; } polynomial operator-=(const polynomial &rhs) { if(D<rhs.D) { matrix<T> temp(rhs.D+1,1); for(size_t i=0;i<D+1;i++) { temp(i,0)+= P(i,0); } D=rhs.D; P.resize(D+1,1); P+=temp; } for(size_t i=0;i<rhs.D+1;i++) { P(i,0)-= rhs[i]; } return *this; } polynomial operator-(const polynomial &rhs) const { return polynomial(*this) -= rhs; } polynomial operator*(const polynomial &rhs) const { polynomial res(D+rhs.D); for(size_t i=0;i<D+1;i++) { for(size_t j=0;j<rhs.D+1;j++) { res[i+j] += P(i,0)*rhs[j]; } } return res; } polynomial operator*=(const polynomial &rhs) { (*this) = (*this)*rhs; return *this; } bool equality_floating_point(const polynomial &rhs) const { if( D<rhs.D ) { for(size_t i=D+1;i<=rhs.D;i++) { if( rhs[i]!=0 ) { return false; } } } else if( rhs.D<D ) { for(size_t i=rhs.D+1;i<=D;i++) { if( P(i,0)!=0 ) { return false; } } } double sum = 0; size_t min_deg = D<rhs.D ? D : rhs.D; for(size_t i=0;i<=min_deg;i++) { sum += (P(i,0) - rhs[i]) * (P(i,0) - rhs[i]); } sum /= min_deg+1; return sum < _MN_ERR; } bool equality_integral(const polynomial &rhs) const { if( D<rhs.D ) { for(size_t i=D+1;i<=rhs.D;i++) { if( rhs[i]!=0 ) { return false; } } } else if( rhs.D<D ) { for(size_t i=rhs.D+1;i<=D;i++) { if( P(i,0)!=0 ) { return false; } } } size_t min_deg = D<rhs.D ? D : rhs.D; for(size_t i=0;i<=min_deg;i++) { if( P(i,0)!=rhs[i] ) { return false; } } return true; } bool operator==(const polynomial &rhs) const { if (empty() || rhs.empty()) { return false; } if(std::is_floating_point<T>::value) { return this->equality_floating_point(rhs); } return this->equality_integral(rhs); } bool operator!=(const polynomial &rhs) const { return !((*this)==rhs); } // Element Numbering is based on power T& operator[](size_t i) { assert(0 <= i && i <= D); return P(i,0); } T operator[](size_t i) const { assert(0 <= i && i <= D); return P(i,0); } //Calculating value for given parameter T calculate(const T x) { assert(!empty()); T res=0; T fac=1; for(size_t i=0;i<=D;i++) { res += fac * P(i,0); fac *= x; } return res; } //First order derivative polynomial derivative() { assert(!empty()); if(D==0) { return polynomial(0); } matrix<T> derv_op(D,D+1); for(size_t i=0;i<D;i++) { derv_op(i,i+1)= i+1; } matrix<T> prod(derv_op*P); polynomial<T> res(D-1); for(size_t i=0;i<D;i++) { res[i]=prod[i]; } return res; } // Display polynomial friend std::ostream& operator<<(std::ostream &cout, polynomial<T> p) { size_t d = p.degree(); for(size_t i=0;i<d;i++) { cout<<"("<<p[i]<<")x^"<<i<<"+"; } if( !p.empty() ) { cout<<"("<<p[d]<<")x^"<<d; } return cout; } private: size_t D; matrix<T> P; }; #endif
25.057018
75
0.437598
adityakadoo
9d6dc6ab2d7223a691e31895c2ed17549977a850
864
cpp
C++
Chapter 05: Complete Search/Part1 : Generating Subsets/generatingsubsets_method2.cpp
pulkit1joshi/handbook_codes
4ddbd5eb53807cf93f8bae910e732e58af46d842
[ "MIT" ]
18
2020-11-26T02:26:33.000Z
2022-03-24T02:36:22.000Z
Chapter 05: Complete Search/Part1 : Generating Subsets/generatingsubsets_method2.cpp
abdullah-azab/handbook_codes
4ddbd5eb53807cf93f8bae910e732e58af46d842
[ "MIT" ]
1
2021-03-02T07:52:48.000Z
2021-03-02T07:52:48.000Z
Chapter 05: Complete Search/Part1 : Generating Subsets/generatingsubsets_method2.cpp
abdullah-azab/handbook_codes
4ddbd5eb53807cf93f8bae910e732e58af46d842
[ "MIT" ]
2
2020-11-26T02:26:35.000Z
2021-11-26T11:19:09.000Z
#include <bits/stdc++.h> using namespace std; /* Generating Subsets : Method 2 You are given a set of numbers : {0 , 1 , 2 , 3 , 4} You have to find all the subsets of this set. */ int n; int A[100]; void search() { // 1 << n means 2^n i.e this number of combinations are possible // Now 2^n will take n bits 101001... n // Each xth bit represets the presence of xth number in A[i] for(int i=0;i< (1<<n);i++) { for(int j=0;j<n;j++) { // 1<<j means setting jth bit as 1 and checking if it is set in i using && if((1<<j)&i) { cout << A[j] << " "; } } cout << endl; } } int main() { // The number of elements cin >> n; // Input the elements for(int i=0;i<n;i++) { cin >> A[i]; } search(); return 0; }
19.636364
86
0.493056
pulkit1joshi
9d6de54959618449bbb8c995ef787f1cbe1daa81
681
cpp
C++
owGameMap/Sky_Material.cpp
fan3750060/OpenWow
28925ebed1b3503d88014f6a3a7bd8adc777fdcc
[ "Apache-2.0" ]
null
null
null
owGameMap/Sky_Material.cpp
fan3750060/OpenWow
28925ebed1b3503d88014f6a3a7bd8adc777fdcc
[ "Apache-2.0" ]
null
null
null
owGameMap/Sky_Material.cpp
fan3750060/OpenWow
28925ebed1b3503d88014f6a3a7bd8adc777fdcc
[ "Apache-2.0" ]
1
2020-03-30T03:22:38.000Z
2020-03-30T03:22:38.000Z
#include "stdafx.h" // General #include "Sky_Material.h" Sky_Material::Sky_Material() : MaterialWrapper(_RenderDevice->CreateMaterial()) { std::shared_ptr<Shader> g_pVertexShader = _RenderDevice->CreateShader( Shader::VertexShader, "shaders_D3D/Sky.hlsl", Shader::ShaderMacros(), "VS_main", "latest" ); g_pVertexShader->LoadInputLayoutFromReflector(); std::shared_ptr<Shader> g_pPixelShader = _RenderDevice->CreateShader( Shader::PixelShader, "shaders_D3D/Sky.hlsl", Shader::ShaderMacros(), "PS_main", "latest" ); // Material SetShader(Shader::VertexShader, g_pVertexShader); SetShader(Shader::PixelShader, g_pPixelShader); } Sky_Material::~Sky_Material() { }
26.192308
91
0.754772
fan3750060
9d6e36e5cde619703fdf2cae129b1274e13a2192
460
cpp
C++
meshler/source/Interactors/CommandInteractor.cpp
timow-gh/FilApp
02ec78bf617fb78d872b2adceeb8a8351aa8f408
[ "Apache-2.0" ]
null
null
null
meshler/source/Interactors/CommandInteractor.cpp
timow-gh/FilApp
02ec78bf617fb78d872b2adceeb8a8351aa8f408
[ "Apache-2.0" ]
null
null
null
meshler/source/Interactors/CommandInteractor.cpp
timow-gh/FilApp
02ec78bf617fb78d872b2adceeb8a8351aa8f408
[ "Apache-2.0" ]
null
null
null
#include <Meshler/Interactors/CommandInteractor.hpp> #include <Meshler/MController.hpp> namespace Meshler { CommandInteractor::CommandInteractor(MController& controller) : m_controller(&controller) { } void CommandInteractor::onEvent(const Graphics::KeyEvent& keyEvent) { if (auto nextInteractorCommand = m_interactorKeyMap.nextInteractor(keyEvent.keyScancode)) m_controller->setNextInteractor(*nextInteractorCommand); } } // namespace Meshler
25.555556
93
0.797826
timow-gh
9d6fb6435f315a375d36ab412baf2425ae35db29
7,436
cpp
C++
LevelHEngine/Components/ModelComponent.cpp
JSlowgrove/LevelHEngine-GEP-Assignment-2
dedbd8e3a3314b27841fee36cc3c251a90c80e5d
[ "MIT" ]
null
null
null
LevelHEngine/Components/ModelComponent.cpp
JSlowgrove/LevelHEngine-GEP-Assignment-2
dedbd8e3a3314b27841fee36cc3c251a90c80e5d
[ "MIT" ]
null
null
null
LevelHEngine/Components/ModelComponent.cpp
JSlowgrove/LevelHEngine-GEP-Assignment-2
dedbd8e3a3314b27841fee36cc3c251a90c80e5d
[ "MIT" ]
null
null
null
#include "ModelComponent.h" #include "TransformComponent.h" #include "CameraComponent.h" #include "GL/glew.h" #include "../ResourceManagement/ResourceManager.h" #include "../Maths/Mat4.h" #include "../Core/Logging.h" #include "../Rendering/OpenGLRendering.h" ModelComponent::~ModelComponent() { } void ModelComponent::onAwake() { id = "model"; } void ModelComponent::onDestroy() { } void ModelComponent::setColour() { colour = true; } void ModelComponent::onRender() { auto camera = Application::camera; Mat4 view = camera->getComponent<TransformComponent>().lock()->getTransformMat4(); Mat4 projection = camera->getComponent<CameraComponent>().lock()->getProjection(); Mat4 model = getGameObject().lock()->getComponent<TransformComponent>().lock()->getTransformMat4(); //Activate the shader program OpenGLRendering::activateShaderProgram(shaderID); //Activate the vertex array object OpenGLRendering::activateMeshVAO(meshID); //Send the matrices to the shader as uniforms locations OpenGLRendering::activateMat4Uniform(shaderID, "modelMat", model.getMatrixArray()); OpenGLRendering::activateMat4Uniform(shaderID, "viewMat", view.getMatrixArray()); OpenGLRendering::activateMat4Uniform(shaderID, "projMat", projection.getMatrixArray()); //loop through the mat4 uniforms for (auto i = mat4Uniforms.begin(); i != mat4Uniforms.end(); ++i) { OpenGLRendering::activateMat4Uniform(shaderID, i->first, i->second); } //loop through the vec3 uniforms for (auto i = vec3Uniforms.begin(); i != vec3Uniforms.end(); ++i) { OpenGLRendering::activateVec3Uniform(shaderID, i->first, i->second); } //if the model uses a texture if (textured) { OpenGLRendering::bindTextures(meshID, shaderID); } if (colour) { OpenGLRendering::activateVec3Uniform(shaderID, "diffuseColour", diffuse); OpenGLRendering::activateVec3Uniform(shaderID, "ambientColour", ambient); } if (ResourceManager::getMesh(meshID)->checkHeightmap()) { OpenGLRendering::drawWithIndices(meshID); } else if (ResourceManager::getMesh(meshID)->checkPrimitive()) { OpenGLRendering::drawWithPoints(meshID); } else { OpenGLRendering::drawWithVerticies(meshID); } //Unbind the vertex array object OpenGLRendering::unbindVAO(); //disable the shader program OpenGLRendering::disableShaderProgram(); } void ModelComponent::initaliseHeightmap(std::string fileName) { meshID = ResourceManager::initialiseHeightmap(fileName); colour = textured = false; diffuse = ambient = Vec3(0.0f, 0.0f, 0.0f); } void ModelComponent::initalisePrimitive(Primitives::PrimativeType primType) { meshID = ResourceManager::initialisePrimitive(primType); colour = textured = false; diffuse = ambient = Vec3(0.0f, 0.0f, 0.0f); } void ModelComponent::initaliseHeightmap(std::string fileName, std::string textureFileName) { meshID = ResourceManager::initialiseHeightmap(fileName, textureFileName); textured = true; colour = false; diffuse = ambient = Vec3(0.0f, 0.0f, 0.0f); } void ModelComponent::initaliseMesh(std::string objFileName) { meshID = ResourceManager::initialiseMesh(objFileName); colour = textured = false; diffuse = ambient = Vec3(0.0f, 0.0f, 0.0f); } void ModelComponent::initaliseMesh(std::string objFileName, std::string textureFileName) { meshID = ResourceManager::initialiseMesh(objFileName, textureFileName); textured = true; colour = false; diffuse = ambient = Vec3(0.0f, 0.0f, 0.0f); } void ModelComponent::initaliseShaders(std::string vertexShaderFileName, std::string fragmentShaderFileName) { shaderID = ResourceManager::initialiseShader(vertexShaderFileName, fragmentShaderFileName); if (meshID == "") { Logging::logE("Model Mesh MUST be initalised BEFORE the Shaders!!!"); } //initalise uniforms initaliseUniforms(); } void ModelComponent::initaliseShaders(std::string vertexShaderFileName, float inR, float inG, float inB) { colour = true; shaderID = ResourceManager::initialiseShader(vertexShaderFileName, "colour"); if (meshID == "") { Logging::logE("Model Mesh MUST be initalised BEFORE the Shaders!!!"); } diffuse.x = inR; diffuse.y = inG; diffuse.z = inB; ambient = Vec3(0.0f, 0.0f, 0.0f); //initalise uniforms initaliseUniforms(); } void ModelComponent::initaliseShaders(std::string vertexShaderFileName, Vec3 inDiffuse, Vec3 inAmbient) { colour = true; shaderID = ResourceManager::initialiseShader(vertexShaderFileName, "colour"); if (meshID == "") { Logging::logE("Model Mesh MUST be initalised BEFORE the Shaders!!!"); } diffuse = inDiffuse; ambient = inAmbient; //initalise uniforms initaliseUniforms(); } void ModelComponent::initaliseDefaultColourShaders(std::string vertexShaderFileName, std::string inColour) { colour = true; shaderID = ResourceManager::initialiseShader(vertexShaderFileName, "colour"); if (meshID == "") { Logging::logE("Model Mesh MUST be initalised BEFORE the Shaders!!!"); } if (inColour == "default") { ambient = Vec3(0.1f, 0.1f, 0.2f); diffuse = Vec3(0.8f, 0.1f, 0.1f); } if (inColour == "black") { ambient = Vec3(0.0f, 0.0f, 0.0f); diffuse = Vec3(1.0f, 1.0f, 1.0f); } if (inColour == "blue") { ambient = Vec3(0.1f, 0.1f, 0.2f); diffuse = Vec3(0.0f, 0.1f, 0.8f); } if (inColour == "cyan") { ambient = Vec3(0.1f, 0.2f, 0.2f); diffuse = Vec3(0.0f, 0.8f, 0.8f); } if (inColour == "green") { ambient = Vec3(0.1f, 0.1f, 0.1f); diffuse = Vec3(0.0f, 0.8f, 0.1f); } if (inColour == "lightgrey") { ambient = Vec3(0.2f, 0.2f, 0.2f); diffuse = Vec3(0.7f, 0.7f, 0.7f); } if (inColour == "magenta") { ambient = Vec3(0.2f, 0.1f, 0.2f); diffuse = Vec3(0.8f, 0.1f, 0.8f); } if (inColour == "red") { ambient = Vec3(1.0f, 0.0f, 0.0f); diffuse = Vec3(1.0f, 0.0f, 0.0f); } if (inColour == "white") { ambient = Vec3(0.2f, 0.2f, 0.2f); diffuse = Vec3(1.0f, 1.0f, 1.0f); } if (inColour == "yellow") { ambient = Vec3(0.2f, 0.2f, 0.0f); diffuse = Vec3(0.8f, 0.8f, 0.0f); } //initalise uniforms initaliseUniforms(); } void ModelComponent::addMat4Uniform(std::string uniformID, float* matPointer) { ResourceManager::getShaders(shaderID)->initaliseUniform(uniformID); //test if the uniform has not already been added if (mat4Uniforms.count(uniformID) == 0) { mat4Uniforms[uniformID] = matPointer; } else { //print out that it is already initalise Logging::logI(uniformID + " uniform already added."); } } void ModelComponent::addVec3Uniform(std::string uniformID, Vec3 vec) { ResourceManager::getShaders(shaderID)->initaliseUniform(uniformID); //test if the uniform has not already been added if (vec3Uniforms.count(uniformID) == 0) { vec3Uniforms[uniformID] = vec; } else { //print out that it is already initalise Logging::logI(uniformID + " uniform already added."); } } void ModelComponent::initaliseUniforms() { ResourceManager::getShaders(shaderID)->initaliseUniform("modelMat"); ResourceManager::getShaders(shaderID)->initaliseUniform("viewMat"); ResourceManager::getShaders(shaderID)->initaliseUniform("projMat"); if (textured) { ResourceManager::getShaders(shaderID)->initaliseUniform("textureSampler"); } if (colour) { ResourceManager::getShaders(shaderID)->initaliseUniform("diffuseColour"); ResourceManager::getShaders(shaderID)->initaliseUniform("ambientColour"); } } void ModelComponent::setDiffuse(Vec3 inDif) { diffuse = inDif; } void ModelComponent::setAmbient(Vec3 inAmb) { ambient = inAmb; }
24.704319
107
0.715573
JSlowgrove
9d71cb630c4a2b418c9850d9b403295f5a74d91a
574
cpp
C++
c++/excel_sheet_column_title.cpp
SongZhao/leetcode
4a2b4f554e91f6a2167b336f8a69b80fa9f3f920
[ "Apache-2.0" ]
null
null
null
c++/excel_sheet_column_title.cpp
SongZhao/leetcode
4a2b4f554e91f6a2167b336f8a69b80fa9f3f920
[ "Apache-2.0" ]
null
null
null
c++/excel_sheet_column_title.cpp
SongZhao/leetcode
4a2b4f554e91f6a2167b336f8a69b80fa9f3f920
[ "Apache-2.0" ]
null
null
null
/* Given a positive integer, return its corresponding column title as appear in an Excel sheet. For example: 1 -> A 2 -> B 3 -> C ... 26 -> Z 27 -> AA 28 -> AB */ /* * */ #include "helper.h" class Solution { public: string convertToTitle(int n) { string res; while (n > 0) { n--; res += char('A' + n % 26); n /= 26; } reverse(res.begin(), res.end()); return res; } }; int main() { Solution s; cout << s.convertToTitle(28) << endl; return 0; }
14.35
92
0.468641
SongZhao
9d72e5973e0c77ec6d36e7a4797c223f5d28ed49
1,437
hpp
C++
pythran/pythonic/numpy/copy.hpp
Pikalchemist/Pythran
17d4108b56b3b365e089a4e1b01a09eb7e12942b
[ "BSD-3-Clause" ]
null
null
null
pythran/pythonic/numpy/copy.hpp
Pikalchemist/Pythran
17d4108b56b3b365e089a4e1b01a09eb7e12942b
[ "BSD-3-Clause" ]
null
null
null
pythran/pythonic/numpy/copy.hpp
Pikalchemist/Pythran
17d4108b56b3b365e089a4e1b01a09eb7e12942b
[ "BSD-3-Clause" ]
1
2017-03-12T20:32:36.000Z
2017-03-12T20:32:36.000Z
#ifndef PYTHONIC_NUMPY_COPY_HPP #define PYTHONIC_NUMPY_COPY_HPP #include "pythonic/utils/proxy.hpp" #include "pythonic/utils/numpy_conversion.hpp" #include "pythonic/types/ndarray.hpp" #include "pythonic/types/ndarray.hpp" namespace pythonic { namespace numpy { // list case template<class E> typename std::enable_if<!types::is_array<E>::value and !std::is_scalar<E>::value and !types::is_complex<E>::value, typename types::numpy_expr_to_ndarray<E>::type >::type copy(E const& v) { return typename types::numpy_expr_to_ndarray<E>::type{v}; } // scalar / complex case template<class E> auto copy(E const &v) -> typename std::enable_if<std::is_scalar<E>::value or types::is_complex<E>::value, E>::type { return v; } // No copy is required for numpy_expr template<class E> auto copy(E && v) -> typename std::enable_if<types::is_array<E>::value, decltype(std::forward<E>(v))>::type { return std::forward<E>(v); } // ndarray case template<class T, size_t N> types::ndarray<T,N> copy(types::ndarray<T,N> const& a) { return a.copy(); } PROXY(pythonic::numpy, copy); } } #endif
29.9375
126
0.544885
Pikalchemist
9d761c433f1ba80f04b598ab74fd262121d9c126
929
cpp
C++
src/utils/splitStrByDelimTest.cpp
lunalabsltd/fontbm
6db91d9d898ae8273d8676a5d2d71b2362466f23
[ "MIT" ]
148
2018-01-22T08:59:11.000Z
2022-03-29T05:12:49.000Z
src/utils/splitStrByDelimTest.cpp
lunalabsltd/fontbm
6db91d9d898ae8273d8676a5d2d71b2362466f23
[ "MIT" ]
18
2017-09-21T15:41:26.000Z
2022-03-10T12:08:39.000Z
src/utils/splitStrByDelimTest.cpp
lunalabsltd/fontbm
6db91d9d898ae8273d8676a5d2d71b2362466f23
[ "MIT" ]
21
2017-12-12T20:01:08.000Z
2022-02-17T20:56:51.000Z
#include "../external/catch.hpp" #include "splitStrByDelim.h" TEST_CASE("splitStrByDelim") { { std::vector<std::string> r = splitStrByDelim("1-2", '-'); REQUIRE(r.size() == 2); REQUIRE(r[0] == "1"); REQUIRE(r[1] == "2"); } { std::vector<std::string> r = splitStrByDelim("1", '-'); REQUIRE(r.size() == 1); REQUIRE(r[0] == "1"); } { std::vector<std::string> r = splitStrByDelim("a/b/z", '/'); REQUIRE(r.size() == 3); REQUIRE(r[0] == "a"); REQUIRE(r[1] == "b"); REQUIRE(r[2] == "z"); } { std::vector<std::string> r = splitStrByDelim("--1---2-", '-'); REQUIRE(r.size() == 7); REQUIRE(r[0] == ""); REQUIRE(r[1] == ""); REQUIRE(r[2] == "1"); REQUIRE(r[3] == ""); REQUIRE(r[4] == ""); REQUIRE(r[5] == "2"); REQUIRE(r[6] == ""); } }
23.820513
70
0.420883
lunalabsltd
9d7e1da53bb71b08d84ee8d85e55df5c9171a970
2,586
cpp
C++
src/wamr/pthread.cpp
n-krueger/faasm
093cb032a3d938d3a41d8aa9644bb5efbc632a95
[ "Apache-2.0" ]
null
null
null
src/wamr/pthread.cpp
n-krueger/faasm
093cb032a3d938d3a41d8aa9644bb5efbc632a95
[ "Apache-2.0" ]
null
null
null
src/wamr/pthread.cpp
n-krueger/faasm
093cb032a3d938d3a41d8aa9644bb5efbc632a95
[ "Apache-2.0" ]
null
null
null
#include <wamr/native.h> #include <wasm_export.h> #include <faabric/util/logging.h> namespace wasm { // ------------------------------------------- // 14/04/21 - WAMR threading not implemented // All of these functions are stubbed as threading with WAMR isn't yet // implemented. Once it is, we will need to implement the function here, // exepctially the locking which is used to manage thread-safe memory // provisioning. // ------------------------------------------- static int32_t pthread_mutex_init_wrapper(wasm_exec_env_t exec_env, int32_t a, int32_t b) { faabric::util::getLogger()->debug("S - pthread_mutex_init {} {}", a, b); return 0; } static int32_t pthread_mutex_lock_wrapper(wasm_exec_env_t exec_env, int32_t a) { faabric::util::getLogger()->debug("S - pthread_mutex_lock {}", a); return 0; } static int32_t pthread_mutex_unlock_wrapper(wasm_exec_env_t exec_env, int32_t a) { faabric::util::getLogger()->debug("S - pthread_mutex_unlock {}", a); return 0; } static int32_t pthread_cond_broadcast_wrapper(wasm_exec_env_t exec_env, int32_t a) { faabric::util::getLogger()->debug("S - pthread_cond_broadcast_wrapper {}", a); return 0; } static int32_t pthread_mutexattr_init_wrapper(wasm_exec_env_t exec_env, int32_t a) { faabric::util::getLogger()->debug("S - pthread_mutexattr_init {}", a); return 0; } static int32_t pthread_mutexattr_destroy_wrapper(wasm_exec_env_t exec_env, int32_t a) { faabric::util::getLogger()->debug("S - pthread_mutexattr_destroy {}", a); return 0; } static int32_t pthread_equal_wrapper(wasm_exec_env_t exec_env, int32_t a, int32_t b) { faabric::util::getLogger()->debug("S - pthread_equal {} {}", a, b); return 0; } static NativeSymbol ns[] = { REG_NATIVE_FUNC(pthread_mutex_init, "(ii)i"), REG_NATIVE_FUNC(pthread_mutex_lock, "(i)i"), REG_NATIVE_FUNC(pthread_mutex_unlock, "(i)i"), REG_NATIVE_FUNC(pthread_cond_broadcast, "(i)i"), REG_NATIVE_FUNC(pthread_mutexattr_init, "(i)i"), REG_NATIVE_FUNC(pthread_mutexattr_destroy, "(i)i"), REG_NATIVE_FUNC(pthread_equal, "(ii)i"), }; uint32_t getFaasmPthreadApi(NativeSymbol** nativeSymbols) { *nativeSymbols = ns; return sizeof(ns) / sizeof(NativeSymbol); } }
31.536585
80
0.606342
n-krueger
9d8042c726501c50802a7e332e5bba6356af9ff4
5,523
cpp
C++
thirdparty/instant-meshes/instant-meshes-dust3d/src/subdivide.cpp
MelvinG24/dust3d
c4936fd900a9a48220ebb811dfeaea0effbae3ee
[ "MIT" ]
2,392
2016-12-17T14:14:12.000Z
2022-03-30T19:40:40.000Z
thirdparty/instant-meshes/instant-meshes-dust3d/src/subdivide.cpp
MelvinG24/dust3d
c4936fd900a9a48220ebb811dfeaea0effbae3ee
[ "MIT" ]
106
2018-04-19T17:47:31.000Z
2022-03-01T19:44:11.000Z
thirdparty/instant-meshes/instant-meshes-dust3d/src/subdivide.cpp
MelvinG24/dust3d
c4936fd900a9a48220ebb811dfeaea0effbae3ee
[ "MIT" ]
184
2017-11-15T09:55:37.000Z
2022-02-21T16:30:46.000Z
/* subdivide.cpp: Subdivides edges in a triangle mesh until all edges are below a specified maximum length This file is part of the implementation of Instant Field-Aligned Meshes Wenzel Jakob, Daniele Panozzo, Marco Tarini, and Olga Sorkine-Hornung In ACM Transactions on Graphics (Proc. SIGGRAPH Asia 2015) All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE.txt file. */ #include "subdivide.h" #include "dedge.h" void subdivide(MatrixXu &F, MatrixXf &V, VectorXu &V2E, VectorXu &E2E, VectorXb &boundary, VectorXb &nonmanifold, Float maxLength, bool deterministic, const ProgressCallback &progress) { typedef std::pair<uint32_t, Float> Edge; struct EdgeComp { bool operator()(const Edge& u, const Edge& v) const { return u.second < v.second; } }; tbb::concurrent_priority_queue<Edge, EdgeComp> queue; maxLength *= maxLength; cout << "Subdividing mesh .. "; cout.flush(); Timer<> timer; if (progress) progress("Subdividing mesh", 0.0f); tbb::blocked_range<uint32_t> range(0u, (uint32_t) E2E.size(), GRAIN_SIZE); auto subdiv = [&](const tbb::blocked_range<uint32_t> &range) { for (uint32_t i = range.begin(); i<range.end(); ++i) { uint32_t v0 = F(i%3, i/3), v1 = F((i+1)%3, i/3); if (nonmanifold[v0] || nonmanifold[v1]) continue; Float length = (V.col(v0) - V.col(v1)).squaredNorm(); if (length > maxLength) { uint32_t other = E2E[i]; if (other == INVALID || other > i) queue.push(Edge(i, length)); } } SHOW_PROGRESS_RANGE(range, E2E.size(), "Subdividing mesh (1/2)"); }; if (!deterministic) tbb::parallel_for(range, subdiv); else subdiv(range); uint32_t nV = V.cols(), nF = F.cols(), nSplit = 0; /* / v0 \ v1p 1 | 0 v0p \ v1 / / v0 \ / 1 | 0 \ v1p - vn - v0p \ 2 | 3 / \ v1 / f0: vn, v0p, v0 f1: vn, v0, v1p f2: vn, v1p, v1 f3: vn, v1, v0p */ while (!queue.empty()) { Edge edge; if (!queue.try_pop(edge)) return; uint32_t e0 = edge.first, e1 = E2E[e0]; bool is_boundary = e1 == INVALID; uint32_t f0 = e0/3, f1 = is_boundary ? INVALID : (e1 / 3); uint32_t v0 = F(e0%3, f0), v0p = F((e0+2)%3, f0), v1 = F((e0+1)%3, f0); if ((V.col(v0) - V.col(v1)).squaredNorm() != edge.second) continue; uint32_t v1p = is_boundary ? INVALID : F((e1+2)%3, f1); uint32_t vn = nV++; nSplit++; /* Update V */ if (nV > V.cols()) { V.conservativeResize(V.rows(), V.cols() * 2); V2E.conservativeResize(V.cols()); boundary.conservativeResize(V.cols()); nonmanifold.conservativeResize(V.cols()); } /* Update V */ V.col(vn) = (V.col(v0) + V.col(v1)) * 0.5f; nonmanifold[vn] = false; boundary[vn] = is_boundary; /* Update F and E2E */ uint32_t f2 = is_boundary ? INVALID : (nF++); uint32_t f3 = nF++; if (nF > F.cols()) { F.conservativeResize(F.rows(), std::max(nF, (uint32_t) F.cols() * 2)); E2E.conservativeResize(F.cols()*3); } /* Update F */ F.col(f0) << vn, v0p, v0; if (!is_boundary) { F.col(f1) << vn, v0, v1p; F.col(f2) << vn, v1p, v1; } F.col(f3) << vn, v1, v0p; /* Update E2E */ const uint32_t e0p = E2E[dedge_prev_3(e0)], e0n = E2E[dedge_next_3(e0)]; #define sE2E(a, b) E2E[a] = b; if (b != INVALID) E2E[b] = a; sE2E(3*f0+0, 3*f3+2); sE2E(3*f0+1, e0p); sE2E(3*f3+1, e0n); if (is_boundary) { sE2E(3*f0+2, INVALID); sE2E(3*f3+0, INVALID); } else { const uint32_t e1p = E2E[dedge_prev_3(e1)], e1n = E2E[dedge_next_3(e1)]; sE2E(3*f0+2, 3*f1+0); sE2E(3*f1+1, e1n); sE2E(3*f1+2, 3*f2+0); sE2E(3*f2+1, e1p); sE2E(3*f2+2, 3*f3+0); } #undef sE2E /* Update V2E */ V2E[v0] = 3*f0 + 2; V2E[vn] = 3*f0 + 0; V2E[v1] = 3*f3 + 1; V2E[v0p] = 3*f0 + 1; if (!is_boundary) V2E[v1p] = 3*f1 + 2; auto schedule = [&](uint32_t f) { for (int i=0; i<3; ++i) { Float length = (V.col(F(i, f))-V.col(F((i+1)%3, f))).squaredNorm(); if (length > maxLength) queue.push(Edge(f*3+i, length)); } }; schedule(f0); if (!is_boundary) { schedule(f2); schedule(f1); }; schedule(f3); } F.conservativeResize(F.rows(), nF); V.conservativeResize(V.rows(), nV); V2E.conservativeResize(nV); boundary.conservativeResize(nV); nonmanifold.conservativeResize(nV); E2E.conservativeResize(nF*3); cout << "done. (split " << nSplit << " edges, took " << timeString(timer.value()) << ", new V=" << V.cols() << ", F=" << F.cols() << ", took " << timeString(timer.value()) << ")" << endl; }
30.346154
88
0.491219
MelvinG24
9d80a5e5c7e44411061b2953089b1005145388b0
1,822
cpp
C++
Source/web/tests/WebDocumentTest.cpp
quanganh2627/bytm-x64-L-w05-2015_external_chromium_org_third_party_WebKit
20e637e67a0c272870ae4d78466a68bcb77af041
[ "BSD-3-Clause" ]
null
null
null
Source/web/tests/WebDocumentTest.cpp
quanganh2627/bytm-x64-L-w05-2015_external_chromium_org_third_party_WebKit
20e637e67a0c272870ae4d78466a68bcb77af041
[ "BSD-3-Clause" ]
null
null
null
Source/web/tests/WebDocumentTest.cpp
quanganh2627/bytm-x64-L-w05-2015_external_chromium_org_third_party_WebKit
20e637e67a0c272870ae4d78466a68bcb77af041
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "config.h" #include "public/web/WebDocument.h" #include "core/CSSPropertyNames.h" #include "core/dom/Document.h" #include "core/dom/NodeRenderStyle.h" #include "core/frame/LocalFrame.h" #include "core/html/HTMLElement.h" #include "core/rendering/style/RenderStyle.h" #include "platform/graphics/Color.h" #include "web/tests/FrameTestHelpers.h" #include <gtest/gtest.h> using WebCore::Color; using WebCore::Document; using WebCore::HTMLElement; using WebCore::RenderStyle; using blink::FrameTestHelpers::WebViewHelper; using blink::WebDocument; namespace { TEST(WebDocumentTest, InsertStyleSheet) { WebViewHelper webViewHelper; webViewHelper.initializeAndLoad("about:blank"); WebDocument webDoc = webViewHelper.webView()->mainFrame()->document(); Document* coreDoc = toLocalFrame(webViewHelper.webViewImpl()->page()->mainFrame())->document(); webDoc.insertStyleSheet("body { color: green }"); // Check insertStyleSheet did not cause a synchronous style recalc. unsigned accessCount = coreDoc->styleEngine()->resolverAccessCount(); ASSERT_EQ(0U, accessCount); HTMLElement* bodyElement = coreDoc->body(); ASSERT(bodyElement); RenderStyle* style = bodyElement->renderStyle(); ASSERT(style); // Inserted stylesheet not yet applied. ASSERT_EQ(Color(0, 0, 0), style->visitedDependentColor(WebCore::CSSPropertyColor)); // Apply inserted stylesheet. coreDoc->updateRenderTreeIfNeeded(); style = bodyElement->renderStyle(); ASSERT(style); // Inserted stylesheet applied. ASSERT_EQ(Color(0, 128, 0), style->visitedDependentColor(WebCore::CSSPropertyColor)); } }
28.920635
99
0.739297
quanganh2627
9d82ca5776e0c538827b2aba32931e1663e7c167
1,278
cc
C++
FiniteElementSpace/Methods/FiniteVolume/fv_mapping_00_general.cc
Naktakala/FESpace
5d0e7aebdf17f5da233d97983a2535737207c7df
[ "MIT" ]
null
null
null
FiniteElementSpace/Methods/FiniteVolume/fv_mapping_00_general.cc
Naktakala/FESpace
5d0e7aebdf17f5da233d97983a2535737207c7df
[ "MIT" ]
null
null
null
FiniteElementSpace/Methods/FiniteVolume/fv_mapping_00_general.cc
Naktakala/FESpace
5d0e7aebdf17f5da233d97983a2535737207c7df
[ "MIT" ]
null
null
null
#include "fv_mapping.h" #include "ChiMesh/MeshContinuum/chi_meshcontinuum.h" #include "ChiMesh/chi_mesh_utils.h" using namespace chi_math::finite_element; //################################################################### /**Constructs a Finite Volume mapping of a cell.*/ FiniteVolume:: FiniteVolume(const chi_mesh::Cell& cell, const chi_mesh::MeshContinuum& grid, std::vector<NodeInfo>& node_list) : FiniteElementMapping(cell, grid) { const size_t num_nodes = 1; SetNumNodesAndLocalRegister(num_nodes, node_list.size()); //======================================== Add the nodes to node_list node_list.emplace_back(NodeType::INTERNAL, IdentifyingInfo({{},{m_cell.global_id}}), m_cell.centroid); //======================================== Compute mandatories auto cell_info = chi_mesh::ComputeCellVolumeAndFaceAreas(cell, grid); m_volume = cell_info.volume; m_face_areas = std::move(cell_info.face_areas); } size_t FiniteVolume::FaceNumNodes(const size_t face_index) const { return 0; } size_t FiniteVolume::MapFaceNodeToCellNode(const size_t face_index, const size_t face_node_index) const { return 0; }
29.72093
78
0.598592
Naktakala
9d82d37ffe0d65cbc32e5e293b0645f032a51a86
1,320
hpp
C++
scipy/optimize/_highs/external/filereaderlp/model.hpp
Ennosigaeon/scipy
2d872f7cf2098031b9be863ec25e366a550b229c
[ "BSD-3-Clause" ]
3
2021-12-15T10:06:16.000Z
2022-02-08T19:55:58.000Z
scipy/optimize/_highs/external/filereaderlp/model.hpp
Ennosigaeon/scipy
2d872f7cf2098031b9be863ec25e366a550b229c
[ "BSD-3-Clause" ]
44
2019-06-27T15:56:14.000Z
2022-03-15T22:21:10.000Z
scipy/optimize/_highs/external/filereaderlp/model.hpp
Ennosigaeon/scipy
2d872f7cf2098031b9be863ec25e366a550b229c
[ "BSD-3-Clause" ]
4
2019-07-25T01:57:45.000Z
2021-04-29T06:54:23.000Z
#ifndef __READERLP_MODEL_HPP__ #define __READERLP_MODEL_HPP__ #include <limits> #include <memory> #include <string> #include <vector> enum class VariableType { CONTINUOUS, BINARY, GENERAL, SEMICONTINUOUS }; enum class ObjectiveSense { MIN, MAX }; struct Variable { VariableType type = VariableType::CONTINUOUS; double lowerbound = 0.0; double upperbound = std::numeric_limits<double>::infinity(); std::string name; Variable(std::string n="") : name(n) {}; }; struct LinTerm { std::shared_ptr<Variable> var; double coef; }; struct QuadTerm { std::shared_ptr<Variable> var1; std::shared_ptr<Variable> var2; double coef; }; struct Expression { std::vector<std::shared_ptr<LinTerm>> linterms; std::vector<std::shared_ptr<QuadTerm>> quadterms; double offset = 0; std::string name = ""; }; struct Constraint { double lowerbound = -std::numeric_limits<double>::infinity(); double upperbound = std::numeric_limits<double>::infinity(); std::shared_ptr<Expression> expr; Constraint() : expr(std::shared_ptr<Expression>(new Expression)) {}; }; struct Model { std::shared_ptr<Expression> objective; ObjectiveSense sense; std::vector<std::shared_ptr<Constraint>> constraints; std::vector<std::shared_ptr<Variable>> variables; }; #endif
20.625
71
0.699242
Ennosigaeon
9d8343e1fc243ad7e8bd42b8ccc33a1d8ef097a0
531
cpp
C++
CC/CF/Good Subarrays.cpp
MrRobo24/Codes
9513f42b61e898577123d5b996e43ba7a067a019
[ "MIT" ]
1
2020-10-12T08:03:20.000Z
2020-10-12T08:03:20.000Z
CC/CF/Good Subarrays.cpp
MrRobo24/Codes
9513f42b61e898577123d5b996e43ba7a067a019
[ "MIT" ]
null
null
null
CC/CF/Good Subarrays.cpp
MrRobo24/Codes
9513f42b61e898577123d5b996e43ba7a067a019
[ "MIT" ]
null
null
null
//TLE #include <bits/stdc++.h> #define LLI long long using namespace std; int main() { LLI t; cin >> t; while (t--) { LLI n; cin >> n; string s; cin >> s; vector<LLI> arr; for (LLI i=0;i<n;i++) { arr.push_back(s[i] - '0'); } LLI counter = 0; vector<LLI> pfx; LLI sum = 0; for (LLI i=0;i<n;i++) { sum += arr[i]; pfx.push_back(sum); } for (LLI i=0;i) } return 0; }
14.75
38
0.39548
MrRobo24
9d8cbaff66c5937dcdfd2cda82681aa6d51fe300
383
cc
C++
test/stl/forward_list.cc
Alexhuszagh/funxx
9f6c1fae92d96a84282fc62be272f4dc1e1dba9b
[ "MIT", "BSD-3-Clause" ]
1
2017-07-21T22:58:38.000Z
2017-07-21T22:58:38.000Z
test/stl/forward_list.cc
Alexhuszagh/funxx
9f6c1fae92d96a84282fc62be272f4dc1e1dba9b
[ "MIT", "BSD-3-Clause" ]
null
null
null
test/stl/forward_list.cc
Alexhuszagh/funxx
9f6c1fae92d96a84282fc62be272f4dc1e1dba9b
[ "MIT", "BSD-3-Clause" ]
null
null
null
// :copyright: (c) 2017 Alex Huszagh. // :license: MIT, see LICENSE.md for more details. /* * \addtogroup Tests * \brief STL forward_list alias unittests. */ #include <pycpp/stl/forward_list.h> #include <gtest/gtest.h> PYCPP_USING_NAMESPACE // TESTS // ----- TEST(forward_list, forward_list) { using forward_list_type = forward_list<int>; forward_list_type fwd; }
18.238095
51
0.697128
Alexhuszagh
9d8cdcdc3f0c7bfb50b08797b36e7e3800833873
1,301
cpp
C++
2015/25/main.cpp
adrian-stanciu/adventofcode
47b3d12226b0c71fff485ef140cd7731c9a5d72f
[ "MIT" ]
null
null
null
2015/25/main.cpp
adrian-stanciu/adventofcode
47b3d12226b0c71fff485ef140cd7731c9a5d72f
[ "MIT" ]
null
null
null
2015/25/main.cpp
adrian-stanciu/adventofcode
47b3d12226b0c71fff485ef140cd7731c9a5d72f
[ "MIT" ]
null
null
null
#include <iostream> #include <regex> #include <string> auto read_position() { static const std::regex re{R"(\s+Enter the code at row ([1-9][0-9]*), column ([1-9][0-9]*).)"}; static const auto to_number = [] (const auto& s) { return strtol(s.data(), nullptr, 10); }; std::string line; getline(std::cin, line); auto msg = line.substr(line.find_first_of('.') + 1); std::smatch matched; regex_match(msg, matched, re); return std::make_pair(to_number(matched[1].str()), to_number(matched[2].str())); } auto next(long n) { return n * 252533 % 33554393; } auto next_after(long n, long iters) { while (iters--) n = next(n); return n; } auto sum_1_to_n(long n) { return n * (n + 1) / 2; } auto index_of_position(long row, long col) { // find on which row the diagonal containing this position begins auto diag_row = row + col - 1; // count how many numbers are above that diagonal // (use the fact that the i-th diagonal contains i numbers) auto numbers_above_diag = sum_1_to_n(diag_row - 1); return numbers_above_diag + col; } int main() { auto [row, col] = read_position(); auto index = index_of_position(row, col); std::cout << next_after(20151125, index - 1) << "\n"; return 0; }
20.015385
99
0.619523
adrian-stanciu
9d8df8659c3330ef6451388045664d67ba3ab292
842
cpp
C++
engine/Engine/src/graphics/shader/ShaderType.cpp
ZieIony/Ghurund
be84166ef0aba5556910685b7a3b754b823da556
[ "MIT" ]
66
2018-12-16T21:03:36.000Z
2022-03-26T12:23:57.000Z
engine/Engine/src/graphics/shader/ShaderType.cpp
ZieIony/Ghurund
be84166ef0aba5556910685b7a3b754b823da556
[ "MIT" ]
57
2018-04-24T20:53:01.000Z
2021-02-21T12:14:20.000Z
engine/Engine/src/graphics/shader/ShaderType.cpp
ZieIony/Ghurund
be84166ef0aba5556910685b7a3b754b823da556
[ "MIT" ]
7
2019-07-16T08:25:25.000Z
2022-03-21T08:29:46.000Z
#include "ghpch.h" #include "ShaderType.h" namespace Ghurund { const ShaderType &ShaderType::VS = ShaderType(1, "vs", "vertexMain", D3D12_SHADER_VISIBILITY_VERTEX); const ShaderType &ShaderType::PS = ShaderType(2, "ps", "pixelMain", D3D12_SHADER_VISIBILITY_PIXEL); const ShaderType &ShaderType::GS = ShaderType(4, "gs", "geometryMain", D3D12_SHADER_VISIBILITY_GEOMETRY); const ShaderType &ShaderType::HS = ShaderType(8, "hs", "hullMain", D3D12_SHADER_VISIBILITY_HULL); const ShaderType &ShaderType::DS = ShaderType(16, "ds", "domainMain", D3D12_SHADER_VISIBILITY_DOMAIN); const ShaderType &ShaderType::CS = ShaderType(32, "cs", "computeMain", D3D12_SHADER_VISIBILITY_ALL); const ShaderType ShaderType::values[] = {ShaderType::VS, ShaderType::PS, ShaderType::GS, ShaderType::HS, ShaderType::DS, ShaderType::CS}; }
64.769231
141
0.745843
ZieIony
9d8f43f62d0556a2e29d947d6dc708a8009b3931
1,630
cpp
C++
parse/tests/parser_unittest.cpp
jpatton-USGS/neic-glass3
52ab2eabd5d5d97c9d74f44c462aec7e88e51899
[ "CC0-1.0" ]
9
2019-02-18T09:08:43.000Z
2021-08-25T13:59:15.000Z
parse/tests/parser_unittest.cpp
jpatton-USGS/neic-glass3
52ab2eabd5d5d97c9d74f44c462aec7e88e51899
[ "CC0-1.0" ]
65
2017-12-06T16:01:11.000Z
2021-06-10T15:24:23.000Z
parse/tests/parser_unittest.cpp
jpatton-USGS/neic-glass3
52ab2eabd5d5d97c9d74f44c462aec7e88e51899
[ "CC0-1.0" ]
7
2017-12-04T20:21:28.000Z
2021-12-01T15:59:40.000Z
#include <parser.h> #include <gtest/gtest.h> #include <string> #include <memory> #define TESTAGENCYID "US" #define TESTAUTHOR "glasstest" // glass3::parse::Parser is an abstract class and // must be derived into a concrete class before use. class parserstub : public glass3::parse::Parser { public: parserstub() : glass3::parse::Parser() { } parserstub(const std::string &defaultAgencyId, const std::string &defaultAuthor) : glass3::parse::Parser(defaultAgencyId, defaultAuthor) { } ~parserstub() { } std::shared_ptr<json::Object> parse(const std::string &input) override { return (NULL); } }; // tests to see if parser constructs correctly TEST(ParserTest, Construction) { // default constructor parserstub * Parser = new parserstub(); std::string emptyString = ""; // assert that agencyid is ok ASSERT_STREQ(Parser->getDefaultAgencyId().c_str(), emptyString.c_str())<< "AgencyID check"; // assert that author is ok ASSERT_STREQ(Parser->getDefaultAuthor().c_str(), emptyString.c_str())<< "Author check"; ASSERT_TRUE(Parser->parse(emptyString) == NULL)<< "parse returns null"; std::string agencyid = std::string(TESTAGENCYID); std::string author = std::string(TESTAUTHOR); // advanced constructor (tests setting agency id and author) parserstub * Parser2 = new parserstub(agencyid, author); // assert that agencyid is ok ASSERT_STREQ(Parser2->getDefaultAgencyId().c_str(), agencyid.c_str())<< "AgencyID check"; // assert that author is ok ASSERT_STREQ(Parser2->getDefaultAuthor().c_str(), author.c_str())<< "Author check"; // cleanup delete (Parser); delete (Parser2); }
25.076923
74
0.715337
jpatton-USGS
9d982be45559d04533ede9e5ea40e5e0b2806964
39,011
hh
C++
TswDps/Skills.hh
Philip-Trettner/tsw-optimal-dps
512ba96066b850d4a1bcdbaaac4718f95bbe7bd7
[ "MIT" ]
null
null
null
TswDps/Skills.hh
Philip-Trettner/tsw-optimal-dps
512ba96066b850d4a1bcdbaaac4718f95bbe7bd7
[ "MIT" ]
null
null
null
TswDps/Skills.hh
Philip-Trettner/tsw-optimal-dps
512ba96066b850d4a1bcdbaaac4718f95bbe7bd7
[ "MIT" ]
1
2021-12-16T20:53:51.000Z
2021-12-16T20:53:51.000Z
#pragma once #include "Skill.hh" /** * @brief Skill library * * For scalings see https://docs.google.com/spreadsheets/d/1z9b23xHPNQuqmZ5t51SeIMq2rlI6d8mPyWp9BmGNxjc/ */ struct Skills { public: private: template <Weapon weapon, DmgType dmgtype> struct Base { protected: Base() = delete; static Skill skill(std::string const& name, SkillType skilltype) { Skill s; s.name = name; s.weapon = weapon; s.dmgtype = dmgtype; s.skilltype = skilltype; return s; } }; static float scaling(std::string const& name); public: struct Pistol : private Base<Weapon::Pistol, DmgType::Ranged> { static Skill TheBusiness() { auto s = skill("The Business", SkillType::Builder); s.timeIn60th = 60; s.hits = 3; s.dmgScaling = scaling(s.name); return s; } static Skill GunFu() { auto s = skill("Gun-Fu", SkillType::None); s.timeIn60th = 60; s.passive.trigger = Trigger::FinishActivation; s.passive.effect = EffectSlot::GunFu; s.cooldownIn60th = 30 * 60; s.reduceWeaponConsumerCD = 4 * 60; s.slotForDmgAug = false; s.slotForSupportAug = true; return s; } static Skill Collaboration() { auto s = skill("Collaboration", SkillType::Builder); s.timeIn60th = 60; s.casttimeIn60th = 60; s.hits = 1; s.dmgScaling = scaling(s.name); return s; } static Skill HairTrigger() { auto s = skill("Hair Trigger", SkillType::Builder); s.timeIn60th = 60; s.hits = 4; s.subtype = SubType::Focus; s.dmgScaling = scaling(s.name); s.channeling = true; return s; } static Skill Shootout() { auto s = skill("Shootout", SkillType::Consumer); s.timeIn60th = 150; s.cooldownIn60th = 60 * 4; s.hits = 5; s.dmgScaling = scaling(s.name + " @1"); s.dmgScaling5 = scaling(s.name + " @5"); s.channeling = true; s.subtype = SubType::Focus; return s; } static Skill Marked() { auto s = skill("Marked", SkillType::None); s.timeIn60th = 90; s.casttimeIn60th = 90; s.cooldownIn60th = 60 * 30; s.hits = 1; s.dmgScaling = scaling(s.name); s.slotForSupportAug = true; return s; } static Skill StartAndFinish() { auto s = skill("Start & Finish", SkillType::Consumer); s.timeIn60th = 60; s.cooldownIn60th = 60 * 4; s.hits = 2; s.dmgScalingA = scaling(s.name + " 1st"); s.specialHitsA = 1; s.dmgScaling = scaling(s.name + " @1"); s.dmgScaling5 = scaling(s.name + " @5"); s.channeling = true; return s; } static Skill BondStrongBond() { auto s = skill("Bond, Strong Bond", SkillType::Consumer); s.timeIn60th = 3 * 60; s.hits = 10; s.dmgScaling = scaling(s.name + " @1"); s.dmgScaling5 = scaling(s.name + " @5"); s.cooldownIn60th = 60 * 4; s.channeling = true; return s; } static Skill Big45() { auto s = skill("Big Forty Five", SkillType::Consumer); s.casttimeIn60th = 90; // TODO: CD passive s.timeIn60th = 90; // TODO: CD passive s.cooldownIn60th = 60 * 4; s.hits = 1; s.dmgScaling = scaling(s.name + " @1"); s.dmgScaling5 = scaling(s.name + " @5"); return s; } static Skill DirtyTricks() { auto s = skill("Dirty Tricks", SkillType::Elite); s.cooldownIn60th = 25 * 60; s.timeIn60th = 60; s.hits = 1; s.dmgScaling = scaling(s.name); s.animaDeviation = true; s.slotForSupportAug = true; return s; } static Skill GunCrazy() { auto s = skill("Gun Crazy", SkillType::Elite); s.cooldownIn60th = 20 * 60; s.timeIn60th = 3 * 60; s.hits = 10; s.channeling = true; s.dmgScalingA = scaling(s.name + " 3xA"); s.dmgScalingB = scaling(s.name + " 3xB"); s.dmgScalingC = scaling(s.name + " 3xC"); s.dmgScaling = scaling(s.name + " Final"); s.specialHitsA = 3; s.specialHitsB = 3; s.specialHitsC = 3; s.appliesVulnerability = DmgType::Magic; s.slotForSupportAug = true; return s; } static Skill BulletBallet() { auto s = skill("Bullet Ballet", SkillType::Elite); s.consumesAnyways = true; s.cooldownIn60th = 20 * 60; s.timeIn60th = 2 * 60; s.hits = 10; s.channeling = true; s.specialHitsA = 9; s.dmgScalingA = scaling(s.name); s.dmgScaling = scaling(s.name + " @1"); s.dmgScaling5 = scaling(s.name + " @5"); s.appliesVulnerability = DmgType::Melee; s.passive.trigger = Trigger::Hit; s.passive.effect = EffectSlot::CritRating; s.slotForSupportAug = true; return s; } }; struct Shotgun : private Base<Weapon::Shotgun, DmgType::Ranged> { static Skill Striker() { auto s = skill("Striker", SkillType::Builder); s.timeIn60th = 60; s.hits = 1; s.subtype = SubType::Strike; s.dmgScaling = scaling(s.name); return s; } static Skill SingleBarrel() { auto s = skill("Single Barrel", SkillType::Builder); s.timeIn60th = 60; s.casttimeIn60th = 30; s.hits = 1; s.dmgScaling = scaling(s.name); return s; } static Skill OutForAKill() { auto s = skill("Out for a Kill", SkillType::Consumer); s.timeIn60th = 60; s.hits = 1; s.dmgScaling = scaling(s.name + " @1"); s.dmgScaling5 = scaling(s.name + " @5"); s.cooldownIn60th = 60 * 4; return s; } static Skill SureShot() { auto s = skill("Sure Shot", SkillType::Consumer); s.timeIn60th = 60; s.hits = 1; s.dmgScaling = scaling(s.name + " @1"); s.dmgScaling5 = scaling(s.name + " @5"); s.cooldownIn60th = 60 * 4; return s; } static Skill Takedown() { auto s = skill("Takedown", SkillType::None); s.timeIn60th = 60; s.hits = 1; s.dmgScaling = scaling(s.name); s.cooldownIn60th = 60 * 25; s.slotForSupportAug = true; return s; } /// Assumes close range static Skill RagingBullet() { auto s = skill("Raging Bullet", SkillType::Consumer); s.timeIn60th = 60; s.hits = 1; s.subtype = SubType::Strike; s.dmgScaling = scaling(s.name + " A @1"); s.dmgScaling5 = scaling(s.name + " A @5"); s.cooldownIn60th = 60 * 4; return s; } static Skill PointBlank() { auto s = skill("Point Blank", SkillType::Elite); s.timeIn60th = 60; s.hits = 1; s.dmgScaling = scaling(s.name); s.cooldownIn60th = 60 * 25; s.animaDeviation = true; s.appliesVulnerability = DmgType::Melee; s.slotForSupportAug = true; return s; } static Skill Kneecapper() { auto s = skill("Kneecapper", SkillType::Elite); s.timeIn60th = 60; s.hits = 1; s.dmgScaling = scaling(s.name); s.cooldownIn60th = 60 * 25; s.animaDeviation = true; s.slotForSupportAug = true; return s; } static Skill Bombardment() { auto s = skill("Bombardment", SkillType::Elite); s.timeIn60th = 60; s.cooldownIn60th = 60 * 30; s.passive.trigger = Trigger::StartActivation; s.passive.effect = EffectSlot::Bombardment; s.passive.effectStacks = 8; s.slotForSupportAug = true; return s; } static Skill LockStockBarrel() { auto s = skill("Lock, Stock & Barrel", SkillType::None); s.cooldownIn60th = 30 * 60; s.passive.effect = EffectSlot::LockStockBarrel; s.passive.trigger = Trigger::FinishActivation; s.slotForDmgAug = false; s.slotForSupportAug = true; return s; } static Skill ShotgunWedding() { auto s = skill("Shotgun Wedding", SkillType::Elite); s.timeIn60th = 2 * 60 + 30; s.hits = 5; s.dmgScaling = scaling(s.name); s.cooldownIn60th = 20 * 60; s.channeling = true; s.baseDmgIncPerHit = 0.25f; // 25% more dmg per hit s.appliesVulnerability = DmgType::Magic; s.slotForSupportAug = true; return s; } }; struct Rifle : private Base<Weapon::Rifle, DmgType::Ranged> { static Skill SafetyOff() { auto s = skill("Safety Off", SkillType::Builder); s.timeIn60th = 60; s.casttimeIn60th = 60; s.hits = 3; s.subtype = SubType::Burst; s.dmgScaling = scaling(s.name); return s; } static Skill LockAndLoad() { auto s = skill("Lock & Load", SkillType::None); s.passive.trigger = Trigger::FinishActivation; s.passive.effect = EffectSlot::LockAndLoad; s.cooldownIn60th = 25 * 60; s.reduceWeaponConsumerCD = 4 * 60; s.slotForDmgAug = false; s.slotForSupportAug = true; return s; } static Skill TriggerHappy() { auto s = skill("Trigger Happy", SkillType::Builder); s.timeIn60th = 60; s.casttimeIn60th = 60; s.hits = 1; s.dmgScaling = scaling(s.name); return s; } static Skill Shellshocker() { auto s = skill("Shellshocker", SkillType::Elite); s.timeIn60th = 2 * 60; s.hits = 8; s.dmgScaling = scaling(s.name); s.cooldownIn60th = 25 * 60; s.channeling = true; s.animaDeviation = true; s.appliesVulnerability = DmgType::Melee; s.slotForSupportAug = true; return s; } static Skill RedMist() { auto s = skill("Red Mist", SkillType::Elite); s.timeIn60th = 2 * 60; s.casttimeIn60th = s.timeIn60th; s.hits = 1; s.dmgScaling = scaling(s.name); s.cooldownIn60th = 20 * 60; s.appliesVulnerability = DmgType::Magic; s.slotForSupportAug = true; return s; } static Skill ThreeRoundBurst() { auto s = skill("Three Round Burst", SkillType::Consumer); s.timeIn60th = 60; s.hits = 3; s.cooldownIn60th = 4 * 60; s.subtype = SubType::Burst; s.dmgScaling = scaling(s.name + " @1"); s.dmgScaling5 = scaling(s.name + " @5"); return s; } static Skill FireInTheHole() { auto s = skill("Fire in the Hole", SkillType::Consumer); s.timeIn60th = 60; s.hits = 1; s.cooldownIn60th = 4 * 60; s.dmgScaling = scaling(s.name + " @1"); s.dmgScaling5 = scaling(s.name + " @5"); s.passive.trigger = Trigger::Hit; s.passive.effect = EffectSlot::FireInTheHole; return s; } }; struct Chaos : private Base<Weapon::Chaos, DmgType::Magic> { static Skill RunRampant() { auto s = skill("Run Rampant", SkillType::Builder); s.timeIn60th = 60; s.hits = 3; s.subtype = SubType::Burst; s.dmgScaling = scaling(s.name); return s; } static Skill HandOfChange() { auto s = skill("Hand of Change", SkillType::Builder); s.timeIn60th = 60; s.hits = 1; s.dmgScaling = scaling(s.name); return s; } static Skill FourHorsemen() { auto s = skill("Four Horsemen", SkillType::Consumer); s.timeIn60th = 60; s.hits = 4; s.subtype = SubType::Burst; s.dmgScaling = scaling(s.name + " @1"); s.dmgScaling5 = scaling(s.name + " @5"); /** Tooltip: 262 * * Hit 1: 263.12996941896 = 100% * Hit 2: 289.979719188768 = 110.20398772101% * Hit 3: 317.655963302752 = 120.722076624033% * Hit 4: 367.837606837607 = 139.793124914604% * * Tooltip: 365 (+39.5%) * Hit 1: 365.997957099081 = 100% * Hit 2: 393.580384226491 = 107.536224340166% * Hit 3: 420.548979591837 = 114.904734148007% * Hit 4: 472.626116071429 = 129.133539382976% */ // additive +10%, +20%, +30% s.baseDmgIncPerHit = 10 / 100.f; return s; } static Skill PullingTheStrings() { auto s = skill("Pulling the Strings", SkillType::Consumer); s.timeIn60th = 60; s.hits = 1; s.dmgScaling = scaling(s.name + " @1"); s.dmgScaling5 = scaling(s.name + " @5"); // TODO: minor hit chance return s; } static Skill SufferingAndSolace() { auto s = skill("Suffering and Solace", SkillType::Consumer); s.timeIn60th = 60; s.hits = 1; s.dmgScaling = scaling(s.name + " @1"); s.dmgScaling5 = scaling(s.name + " @5"); return s; } static Skill ChaoticPull() { auto s = skill("Chaotic Pull", SkillType::None); s.timeIn60th = 60; s.cooldownIn60th = 35 * 60; s.hits = 1; s.dmgScaling = scaling(s.name); s.slotForSupportAug = true; return s; } static Skill Schism() { auto s = skill("Schism", SkillType::Consumer); s.timeIn60th = 60; s.hits = 1; s.dmgScaling = scaling(s.name + " @1"); s.dmgScaling5 = scaling(s.name + " @5"); s.dmgScalingLow = scaling(s.name + " @1 low"); s.dmgScaling5Low = scaling(s.name + " @5 low"); return s; } static Skill CallForEris() { auto s = skill("Call for Eris", SkillType::Consumer); s.timeIn60th = 60; s.hits = 1; s.extraHitPerResource = 1; s.fixedMultiHitPenalty = 0.70; // ?????? no fucking idea s.subtype = SubType::Burst; s.specialHitsA = 1; s.dmgScalingA = scaling(s.name + " 1st"); s.dmgScaling = scaling(s.name + " @1"); s.dmgScaling5 = scaling(s.name + " @5"); return s; } static Skill AmorFati() { auto s = skill("Amor Fati", SkillType::None); s.cooldownIn60th = 60 * 60; s.passive.trigger = Trigger::FinishActivation; s.passive.effect = EffectSlot::AmorFati; s.slotForDmgAug = false; s.slotForSupportAug = true; return s; } static Skill DominoEffect() { auto s = skill("Domino Effect", SkillType::Elite); s.timeIn60th = 60; s.hits = 1; s.dmgScaling = scaling(s.name); s.cooldownIn60th = 25 * 60; s.slotForSupportAug = true; return s; } static Skill PrisonerOfFate() { auto s = skill("Prisoner of Fate", SkillType::Elite); s.timeIn60th = 5 * 60; s.hits = 5; s.dmgScaling = scaling(s.name); s.dmgScalingLow = scaling(s.name + " low"); s.cooldownIn60th = 20 * 60; s.channeling = true; s.animaDeviation = true; s.appliesVulnerability = DmgType::Melee; s.slotForSupportAug = true; return s; } static Skill EyeOfPandemonium() { auto s = skill("Eye of Pandemonium", SkillType::Elite); s.timeIn60th = 60; s.cooldownIn60th = 25 * 60; s.hits = 1; s.dmgScaling = scaling(s.name); s.passive.trigger = Trigger::FinishActivation; s.passive.effect = EffectSlot::EyeOfPandemonium; s.passive.effectStacks = 10; s.animaDeviation = true; s.slotForSupportAug = true; s.appliesVulnerability = DmgType::Ranged; return s; } static Skill GravitationalAnomaly() { auto s = skill("Gravitational Anomaly", SkillType::Elite); s.timeIn60th = 3 * 60; s.hits = 3; s.dmgScaling = scaling(s.name); s.cooldownIn60th = 25 * 60; s.channeling = true; s.slotForSupportAug = true; return s; } static Skill Paradox() { auto s = skill("Paradox", SkillType::None); s.timeIn60th = 60; s.hits = 1; s.dmgScaling = scaling(s.name); s.cooldownIn60th = 10 * 60; return s; } }; struct Blood : private Base<Weapon::Blood, DmgType::Magic> { static Skill BoilingBlood() { auto s = skill("Boiling Blood", SkillType::Builder); s.timeIn60th = 60; s.casttimeIn60th = s.timeIn60th; s.hits = 1; s.dmgScaling = scaling(s.name); return s; } static Skill CardiacArrest() { auto s = skill("Cardiac Arrest", SkillType::Elite); s.timeIn60th = 60; s.casttimeIn60th = s.timeIn60th; s.cooldownIn60th = 25 * 60; s.hits = 1; s.dmgScaling = scaling(s.name); s.animaDeviation = true; s.appliesVulnerability = DmgType::Melee; s.slotForSupportAug = true; return s; } static Skill Exsanguinate() { auto s = skill("Exsanguinate", SkillType::Consumer); s.timeIn60th = 150; s.hits = 5; s.fixedConsumerResources = 5; s.dmgScaling = scaling(s.name); s.channeling = true; s.subtype = SubType::Focus; return s; } static Skill Bloodline() { auto s = skill("Bloodline", SkillType::Builder); s.timeIn60th = 60; s.hits = 4; s.subtype = SubType::Focus; s.dmgScaling = scaling(s.name); s.channeling = true; return s; } static Skill Bloodshot() { auto s = skill("Bloodshot", SkillType::Consumer); s.timeIn60th = 60; s.hits = 1; s.fixedConsumerResources = 2; s.dmgScaling = scaling(s.name); return s; } static Skill Cannibalise() { auto s = skill("Cannibalise", SkillType::None); s.passive.trigger = Trigger::FinishActivation; s.passive.effect = EffectSlot::Cannibalise; s.cooldownIn60th = 25 * 60; s.slotForDmgAug = false; s.slotForSupportAug = true; return s; } static Skill Plague() { auto s = skill("Plague", SkillType::Elite); s.timeIn60th = 60 + 30; s.casttimeIn60th = s.timeIn60th; s.cooldownIn60th = 20 * 60; s.passive.trigger = Trigger::FinishActivation; s.passive.effect = EffectSlot::Plague; s.passive.effectStacks = 6; s.appliesVulnerability = DmgType::Ranged; return s; } static Skill LeftHandOfDarkness() { auto s = skill("Left Hand of Darkness", SkillType::Consumer); s.timeIn60th = 60; s.cooldownIn60th = 4 * 60; s.fixedConsumerResources = 3; s.passive.trigger = Trigger::StartActivation; s.passive.effect = EffectSlot::LeftHandOfDarkness; s.passive.effectStacks = 4; return s; } static Skill Contaminate() { auto s = skill("Contaminate", SkillType::None); s.timeIn60th = 60; s.casttimeIn60th = s.timeIn60th; s.cooldownIn60th = 40 * 60; s.fixedConsumerResources = 3; s.passive.trigger = Trigger::FinishActivation; s.passive.effect = EffectSlot::Contaminate; s.passive.effectStacks = 6; s.slotForSupportAug = true; return s; } }; struct Elemental : private Base<Weapon::Elemental, DmgType::Magic> { static Skill Shock() { auto s = skill("Shock", SkillType::Builder); s.timeIn60th = 60; s.casttimeIn60th = s.timeIn60th; s.hits = 1; s.dmgScaling = scaling(s.name); return s; } static Skill ElectricalBolt() { auto s = skill("Electrical Bolt", SkillType::Builder); s.timeIn60th = 60; s.casttimeIn60th = s.timeIn60th; s.hits = 1; s.dmgScaling = scaling(s.name); // TODO: 2 res if hindered return s; } static Skill Ignition() { auto s = skill("Ignition", SkillType::Builder); s.timeIn60th = 60; s.casttimeIn60th = 30; s.hits = 1; s.dmgScaling = scaling(s.name); s.subtype = SubType::Strike; return s; } static Skill Ignite() { auto s = skill("Ignite", SkillType::Builder); s.timeIn60th = 60; s.hits = 1; s.dmgScaling = scaling(s.name); s.dmgScaling = scaling(s.name + " First"); return s; } static Skill Combust() { auto s = skill("Combust", SkillType::Consumer); s.timeIn60th = 60 + 30; // TODO: passive s.casttimeIn60th = s.timeIn60th; s.hits = 1; s.fixedConsumerResources = 2; // TODO: 1 if hindered s.dmgScaling = scaling(s.name); return s; } static Skill FlameStrike() { auto s = skill("Flame Strike", SkillType::Consumer); s.timeIn60th = 60; s.casttimeIn60th = s.timeIn60th; s.hits = 1; s.fixedConsumerResources = 2; s.dmgScaling = scaling(s.name); s.subtype = SubType::Strike; return s; } static Skill Blaze() { auto s = skill("Blaze", SkillType::Consumer); s.timeIn60th = 60 + 30; s.casttimeIn60th = s.timeIn60th; s.hits = 1; s.fixedConsumerResources = 3; s.dmgScaling = scaling(s.name); // TODO: Aidolon Passive return s; } static Skill MoltenEarth() { auto s = skill("Molten Earth", SkillType::Elite); s.timeIn60th = 60; s.cooldownIn60th = 25 * 60; s.hits = 1; s.dmgScaling = scaling(s.name); s.animaDeviation = true; s.slotForSupportAug = true; return s; } static Skill ThorsHammer() { auto s = skill("Thor's Hammer", SkillType::Consumer); s.timeIn60th = 2 * 60; s.hits = 1; s.dmgScaling = scaling(s.name); s.fixedConsumerResources = 5; s.subtype = SubType::Strike; return s; } static Skill HardReset() { auto s = skill("Hard Reset", SkillType::Elite); s.timeIn60th = 2 * 60; s.cooldownIn60th = 35 * 60; s.hits = 1; s.dmgScaling = scaling(s.name); s.passive.bonusStats.addedCritChance = 1; // guaranteed crit s.animaDeviation = true; s.slotForSupportAug = true; return s; } static Skill Overload() { auto s = skill("Overload", SkillType::Elite); s.timeIn60th = 3 * 60; s.cooldownIn60th = 20 * 60; s.hits = 3; s.channeling = true; s.dmgScalingA = scaling(s.name); s.specialHitsA = 2; s.dmgScaling = scaling(s.name + " final"); s.appliesVulnerability = DmgType::Melee; s.slotForSupportAug = true; return s; } static Skill Whiteout() { auto s = skill("Whiteout", SkillType::Elite); s.timeIn60th = 60; s.casttimeIn60th = s.timeIn60th; s.cooldownIn60th = 25 * 60; s.passive.trigger = Trigger::FinishActivation; s.passive.effect = EffectSlot::Whiteout; s.passive.effectStacks = 16; s.animaDeviation = true; s.slotForSupportAug = true; return s; } static Skill PowerLine() { auto s = skill("Power Line", SkillType::Elite); s.timeIn60th = 60; s.cooldownIn60th = 20 * 60; s.passive.trigger = Trigger::StartActivation; s.passive.effect = EffectSlot::PowerLine; s.passive.effectStacks = 10; s.appliesVulnerability = DmgType::Ranged; s.slotForSupportAug = true; return s; } static Skill FireManifestation() { auto s = skill("Fire Manifestation", SkillType::Consumer); s.timeIn60th = 60; s.cooldownIn60th = 10 * 60; s.fixedConsumerResources = 2; s.passive.trigger = Trigger::StartActivation; s.passive.effect = EffectSlot::FireManifestation; s.passive.effectStacks = 4; s.slotForSupportAug = true; return s; } static Skill LightningManifestation() { auto s = skill("Lightning Manifestation", SkillType::Consumer); s.timeIn60th = 60; s.casttimeIn60th = s.timeIn60th; s.cooldownIn60th = 15 * 60; s.fixedConsumerResources = 2; s.passive.trigger = Trigger::StartActivation; s.passive.effect = EffectSlot::LightningManifestation; s.passive.effectStacks = 10; s.slotForSupportAug = true; return s; } static Skill AnimaCharge() { auto s = skill("Anima Charge", SkillType::None); s.passive.trigger = Trigger::FinishActivation; s.passive.effect = EffectSlot::AnimaCharge; s.cooldownIn60th = 30 * 60; s.slotForDmgAug = false; s.slotForSupportAug = true; // Casttime can be mitigated! return s; } }; struct Blade : private Base<Weapon::Blade, DmgType::Melee> { static Skill DelicateStrike() { auto s = skill("Delicate Strike", SkillType::Builder); s.timeIn60th = 60; s.hits = 1; s.dmgScaling = scaling(s.name); return s; } static Skill GrassCutter() { auto s = skill("Grass Cutter", SkillType::Builder); s.timeIn60th = 60; s.hits = 1; s.dmgScaling = scaling(s.name); return s; } static Skill SteelEcho() { auto s = skill("Steel Echo", SkillType::None); s.cooldownIn60th = 60 * 60; s.passive.trigger = Trigger::StartActivation; s.passive.effect = EffectSlot::SteelEcho; s.slotForSupportAug = true; s.slotForDmgAug = true; // TODO: Affects steel echo proc! // TODO: Can this proc more than once per sec? return s; } static Skill SlingBlade() { auto s = skill("Sling Blade", SkillType::None); s.timeIn60th = 60; s.hits = 1; s.dmgScaling = scaling(s.name); s.cooldownIn60th = 35 * 60; s.slotForSupportAug = true; // TODO: afflict return s; } static Skill BalancedBlade() { auto s = skill("Balanced Blade", SkillType::Consumer); s.timeIn60th = 60; s.hits = 1; s.dmgScaling = scaling(s.name + " @1"); s.dmgScaling5 = scaling(s.name + " @5"); return s; } static Skill BindingWounds() { auto s = skill("Binding Wounds", SkillType::Consumer); s.timeIn60th = 60; s.hits = 1; s.dmgScaling = scaling(s.name + " @1"); s.dmgScaling5 = scaling(s.name + " @5"); return s; } static Skill DancingBlade() { auto s = skill("Dancing Blade", SkillType::Consumer); s.timeIn60th = 150; s.hits = 5; s.dmgScaling = scaling(s.name + " @1"); s.dmgScaling5 = scaling(s.name + " @5"); s.channeling = true; s.subtype = SubType::Focus; return s; } static Skill StunningSwirl() { auto s = skill("Stunning Swirl", SkillType::Elite); s.timeIn60th = 60; s.cooldownIn60th = 20 * 60; s.hits = 1; s.dmgScaling = scaling(s.name); s.appliesVulnerability = DmgType::Ranged; s.slotForSupportAug = true; return s; } static Skill FourSeasons() { auto s = skill("Four Seasons", SkillType::Elite); s.timeIn60th = 150; s.hits = 5; s.cooldownIn60th = 20 * 60; s.passive.bonusStats.addedPenChance = 2.0; // guaranteed pen, even after penalty s.dmgScalingA = scaling(s.name); s.specialHitsA = 4; s.dmgScaling = scaling(s.name + " Final"); s.channeling = true; s.appliesVulnerability = DmgType::Magic; s.slotForSupportAug = true; return s; } }; struct Hammer : private Base<Weapon::Hammer, DmgType::Melee> { static Skill Smash() { auto s = skill("Smash", SkillType::Builder); s.timeIn60th = 60; s.hits = 1; s.dmgScaling = scaling(s.name); return s; } static Skill FirstBlood() { auto s = skill("First Blood", SkillType::Builder); s.timeIn60th = 60; s.subtype = SubType::Strike; s.hits = 1; s.dmgScaling = scaling(s.name); s.dmgScaling0 = scaling(s.name + " First"); return s; } static Skill GrandSlam() { auto s = skill("Grand Slam", SkillType::Builder); s.timeIn60th = 60; s.hits = 1; s.dmgScaling = scaling(s.name); s.passive.trigger = Trigger::Hit; s.passive.effect = EffectSlot::GrandSlam; return s; } static Skill Haymaker() { auto s = skill("Haymaker", SkillType::Consumer); s.timeIn60th = 60; s.hits = 1; s.dmgScaling = scaling(s.name + " @1"); s.dmgScaling5 = scaling(s.name + " @5"); s.subtype = SubType::Strike; return s; } static Skill StonesThrow() { auto s = skill("Stone's Throw", SkillType::None); s.timeIn60th = 60; s.hits = 1; s.cooldownIn60th = 15 * 60; s.dmgScaling = scaling(s.name); s.slotForSupportAug = true; return s; } static Skill Shockwave() { auto s = skill("Shockwave", SkillType::Elite); s.timeIn60th = 60; s.cooldownIn60th = 25 * 60; s.hits = 1; s.dmgScaling = scaling(s.name); s.appliesVulnerability = DmgType::Magic; s.slotForSupportAug = true; return s; } static Skill Eruption() { auto s = skill("Eruption", SkillType::Elite); s.timeIn60th = 60; s.cooldownIn60th = 25 * 60; s.hits = 1; s.dmgScaling = scaling(s.name); s.appliesVulnerability = DmgType::Ranged; s.slotForSupportAug = true; return s; } static Skill MoltenSteel() { auto s = skill("Molten Steel", SkillType::Consumer); s.timeIn60th = 60; s.hits = 1; s.dmgScaling = scaling(s.name + " @1"); s.dmgScaling5 = scaling(s.name + " @5"); s.passive.bonusStats.addedCritChance = 30 / 100.f; s.passive.bonusStats.addedCritPower = 15 / 100.f; return s; } static Skill BoneBreaker() { auto s = skill("Bone Breaker", SkillType::Consumer); s.timeIn60th = 60; s.hits = 1; s.dmgScaling = scaling(s.name + " @1"); s.dmgScaling5 = scaling(s.name + " @5"); return s; } static Skill FullMomentum() { auto s = skill("Full Momentum", SkillType::None); s.cooldownIn60th = 30 * 60; s.passive.effect = EffectSlot::FullMomentum; s.passive.trigger = Trigger::FinishActivation; s.slotForDmgAug = false; s.slotForSupportAug = true; return s; } }; struct Fist : private Base<Weapon::Fist, DmgType::Melee> { static Skill SeeRed() { auto s = skill("See Red", SkillType::Elite); s.timeIn60th = 4 * 60; s.hits = 20; s.dmgScaling = scaling(s.name); s.cooldownIn60th = 25 * 60; s.channeling = true; s.animaDeviation = true; s.appliesVulnerability = DmgType::Magic; s.slotForSupportAug = true; return s; } static Skill Reckless() { auto s = skill("Reckless", SkillType::None); s.cooldownIn60th = 40 * 60; s.passive.trigger = Trigger::FinishActivation; s.passive.effect = EffectSlot::Reckless; s.slotForDmgAug = false; s.slotForSupportAug = true; return s; } static Skill Claw() { auto s = skill("Claw", SkillType::Builder); s.timeIn60th = 60; s.hits = 1; s.dmgScaling = scaling(s.name); return s; } static Skill PreyOnTheWeak() { auto s = skill("Prey on the Weak", SkillType::Builder); s.timeIn60th = 60; s.hits = 3; s.dmgScaling = scaling(s.name); s.subtype = SubType::Burst; return s; } static Skill WildAtHeart() { auto s = skill("Wild at Heart", SkillType::Consumer); s.timeIn60th = 60; s.hits = 1; s.dmgScaling = scaling(s.name + " @1"); s.dmgScaling5 = scaling(s.name + " @5"); return s; } static Skill TearEmUp() { auto s = skill("Tear Em Up", SkillType::Consumer); s.timeIn60th = 60; s.hits = 1; s.dmgScaling = scaling(s.name + " @1"); s.dmgScaling5 = scaling(s.name + " @5"); s.passive.trigger = Trigger::Hit; s.passive.effect = EffectSlot::TearEmUp; return s; } static Skill GoForTheThroat() { auto s = skill("Go for the Throat", SkillType::Elite); s.timeIn60th = 60; s.cooldownIn60th = 25 * 60; s.hits = 1; s.dmgScaling = scaling(s.name); s.passive.trigger = Trigger::FinishActivation; s.passive.effect = EffectSlot::GoForTheThroat; s.passive.effectStacks = 10; s.animaDeviation = true; s.slotForSupportAug = true; return s; } static Skill OneTwo() { auto s = skill("One-Two", SkillType::Consumer); s.timeIn60th = 60; s.hits = 2; s.dmgScalingA = scaling(s.name + " 1st"); s.specialHitsA = 1; s.dmgScaling = scaling(s.name + " @1"); s.dmgScaling5 = scaling(s.name + " @5"); s.subtype = SubType::Burst; return s; } }; struct Chainsaw : private Base<Weapon::Aux, DmgType::None> { static Skill Timber() { auto s = skill("Timber", SkillType::None); s.timeIn60th = 60; s.hits = 1; s.cooldownIn60th = 15 * 60; s.dmgScaling = scaling(s.name); s.chanceForScaleInc = 0.33f; s.scaleIncPerc = .45f; s.slotForDmgAug = false; return s; } }; struct Flamethrower : private Base<Weapon::Aux, DmgType::None> { static Skill ScorchedEarth() { auto s = skill("Scorched Earth", SkillType::None); s.timeIn60th = 60; s.casttimeIn60th = 30; s.cooldownIn60th = 20 * 60; // TODO: get real number with passive // TODO: continue assert(0 && "not impl"); s.slotForDmgAug = false; return s; } }; static Skill empty() { return Skill(); } static std::vector<Skill> all(); private: Skills() = delete; };
31.384553
104
0.488529
Philip-Trettner
9d9d5b7473894407a4608b205be216e53d7cc87b
839
hpp
C++
Core/src/Core/Texture/TextureGL.hpp
Zephilinox/Ricochet
9ace649ecb1ccc0fa6e8b8d35b449676452d0616
[ "Unlicense" ]
null
null
null
Core/src/Core/Texture/TextureGL.hpp
Zephilinox/Ricochet
9ace649ecb1ccc0fa6e8b8d35b449676452d0616
[ "Unlicense" ]
null
null
null
Core/src/Core/Texture/TextureGL.hpp
Zephilinox/Ricochet
9ace649ecb1ccc0fa6e8b8d35b449676452d0616
[ "Unlicense" ]
null
null
null
#pragma once //SELF //LIBS //STD #include <array> #include <vector> #include <functional> namespace core { struct Pixel { std::uint8_t r = 0; std::uint8_t g = 0; std::uint8_t b = 0; std::uint8_t a = 0; }; class TextureGL { public: TextureGL(); void load(std::vector<Pixel> pixels, unsigned int width, unsigned int height); const std::vector<Pixel>& getPixels() const; const Pixel& operator[](unsigned int index) const; void update(std::function<void(std::vector<Pixel>& pixels)> updater); unsigned int getOpenglTextureID() const; [[nodiscard]] unsigned int getWidth() const; [[nodiscard]] unsigned int getHeight() const; private: unsigned int width = 0; unsigned int height = 0; std::vector<Pixel> pixels; unsigned int opengl_texture_id = 0; }; } // namespace core
18.644444
82
0.66031
Zephilinox
9d9e74482cc40aa003ecdb937db3342304fe3021
275
cpp
C++
3rdparty/ImagingEngineLib/data/light.cpp
jia1000/DW_Client_CTA_Multi_Tab
3f69c8354dd37f3c8bbeaefc28a2e643bcdb1ee1
[ "MIT" ]
4
2021-05-17T19:33:22.000Z
2022-03-09T12:48:58.000Z
3rdparty/ImagingEngineLib/data/light.cpp
jia1000/DW_Client_CTA_Multi_Tab
3f69c8354dd37f3c8bbeaefc28a2e643bcdb1ee1
[ "MIT" ]
null
null
null
3rdparty/ImagingEngineLib/data/light.cpp
jia1000/DW_Client_CTA_Multi_Tab
3f69c8354dd37f3c8bbeaefc28a2e643bcdb1ee1
[ "MIT" ]
null
null
null
#pragma once #include "light.h" using namespace DW::IMAGE; using namespace std; Light::Light() { } Light::~Light() { } void Light::SetLight(vtkSmartPointer<vtkLight> light) { vtk_light_ = light; } vtkSmartPointer<vtkLight> Light::GetLight() { return vtk_light_; }
10.576923
54
0.701818
jia1000
9d9f4774146b0346c153bb9a314f94f24e4b1ffb
343
hpp
C++
src/include/translate.hpp
VedantParanjape/hack-assembler
59e4bc8ec7933df42da108d3313d8a303e513253
[ "MIT" ]
1
2020-04-06T14:59:30.000Z
2020-04-06T14:59:30.000Z
src/include/translate.hpp
VedantParanjape/hack-assembler
59e4bc8ec7933df42da108d3313d8a303e513253
[ "MIT" ]
null
null
null
src/include/translate.hpp
VedantParanjape/hack-assembler
59e4bc8ec7933df42da108d3313d8a303e513253
[ "MIT" ]
null
null
null
#ifndef TRANSLATE_HPP #define TRANSLATE_HPP #include <vector> #include <string> #include <bitset> #include <map> #include "util.hpp" std::string translate_a_instructions(std::string instruction); std::string translate_c_instructions(std::string instruction); std::vector<std::string> translate(std::vector<std::string> instructions); #endif
24.5
74
0.784257
VedantParanjape
9d9fe9e904353666f2eff93c607d1edb72acfe0b
43,319
cpp
C++
src/OBJECTS/Obj.cpp
Seideman-Group/chiML
9ace5dccdbc6c173e8383f6a31ff421b4fefffdf
[ "MIT" ]
1
2019-04-27T05:25:27.000Z
2019-04-27T05:25:27.000Z
src/OBJECTS/Obj.cpp
Seideman-Group/chiML
9ace5dccdbc6c173e8383f6a31ff421b4fefffdf
[ "MIT" ]
null
null
null
src/OBJECTS/Obj.cpp
Seideman-Group/chiML
9ace5dccdbc6c173e8383f6a31ff421b4fefffdf
[ "MIT" ]
2
2019-04-03T10:08:21.000Z
2019-09-30T22:40:28.000Z
/** @file OBJECTS/Obj.cpp * @brief Class that stores all object/material information * * A class that determines if a grid point is inside the object, stores the material parameters, and * finds the gradient to determine the surface normal vector. * * @author Thomas A. Purcell (tpurcell90) * @bug No known bugs. */ #include "Obj.hpp" std::array<double, 3> Obj::RealSpace2ObjectSpace(const std::array<double,3>& pt) { std::array<double,3> v_trans; std::array<double,3> v_cen; // Move origin to object's center std::transform(pt.begin(), pt.end(), location_.begin(), v_cen.begin(), std::minus<double>() ); // Convert x, y, z coordinates to coordinates along the object's unit axis dgemv_('T', v_cen.size(), v_cen.size(), 1.0, coordTransform_.data(), v_cen.size(), v_cen.data(), 1, 0.0, v_trans.data(), 1 ); return v_trans; } std::array<double, 3> Obj::ObjectSpace2RealSpace(const std::array<double,3>& pt) { std::array<double,3> realSpacePt; dgemv_('T', pt.size(), pt.size(), 1.0, invCoordTransform_.data(), pt.size(), pt.data(), 1, 0.0, realSpacePt.data(), 1 ); // Normalize the gradient vector if(std::accumulate(realSpacePt.begin(), realSpacePt.end(), 0.0, vecMagAdd<double>() ) < 1e-20) realSpacePt = {{ 0.0, 0.0, 0.0 }}; else normalize(realSpacePt); return realSpacePt; } Obj::Obj(const Obj &o) : ML_(o.ML_), useOrientedDipols_(o.useOrientedDipols_), eps_infty_(o.eps_infty_), mu_infty_(o.mu_infty_), tellegen_(o.tellegen_), unitVec_(o.unitVec_), dipOr_(o.dipOr_), magDipOr_(o.magDipOr_), geoParam_(o.geoParam_), geoParamML_(o.geoParamML_), location_(o.location_), alpha_(o.alpha_), xi_(o.xi_), gamma_(o.gamma_), magAlpha_(o.magAlpha_), magXi_(o.magXi_), magGamma_(o.magGamma_), chiAlpha_(o.chiAlpha_), chiXi_(o.chiXi_), chiGamma_(o.chiGamma_), chiGammaPrev_(o.chiGammaPrev_), dipE_(o.dipE_), dipM_(o.dipM_), pols_(o.pols_) {} Obj::Obj(double eps_infty, double mu_infty, double tellegen, std::vector<LorenzDipoleOscillator> pols, bool ML, std::vector<double> geo, std::array<double,3> loc, std::array<std::array<double,3>,3> unitVec) : ML_(ML), useOrientedDipols_(false), eps_infty_(eps_infty), mu_infty_(mu_infty), tellegen_(tellegen), unitVec_(unitVec), geoParam_(geo), geoParamML_(geo), location_(loc), pols_(pols) { for(int ii = 0; ii < 3; ++ii) { for(int jj = 0; jj < 3; ++jj) { std::array<double,3>cartCoord = {{ 0, 0, 0 }}; cartCoord[jj] = 1.0; coordTransform_[(ii)*3+jj] = ddot_(unitVec[ii].size(), unitVec[ii].data(), 1, cartCoord.data(), 1) / ( std::sqrt( std::accumulate(unitVec[ii].begin(),unitVec[ii].end(),0.0, vecMagAdd<double>() ) ) ); } } std::copy_n(coordTransform_.begin(), coordTransform_.size(), invCoordTransform_.begin()); std::vector<int>invIpiv(invCoordTransform_.size(), 0.0); std::vector<double>work(invCoordTransform_.size(), -1) ; int info; dgetrf_(3, 3, invCoordTransform_.data(), 3, invIpiv.data(), &info); if(info < 0) throw std::logic_error("The " + std::to_string(-1.0*info) + "th value of the coordTransform_ matrix is an illegal value."); else if(info > 0) throw std::logic_error("WARNING: The " + std::to_string(info) + "th diagonal element of u is 0. The invCoordTransform_ can't be calculated!"); dgetri_(3, invCoordTransform_.data(), 3, invIpiv.data(), work.data(), work.size(), &info); if(info < 0) throw std::logic_error("The " + std::to_string(-1.0*info) + "th value of the coordTransform_ matrix is an illegal value."); else if(info > 0) throw std::logic_error("WARNING: The " + std::to_string(info) + "th diagonal element of u is 0. The invCoordTransform_ can't be calculated!"); // for(int ii = 0; ii < 3; ++ii) // for(int jj = 0; jj < 3; ++jj) // invCoordTransform_[(jj)*3+ii] = coordTransform_[ ( (ii+1)%3 )*3 + ( (jj+1)%3 ) ]*coordTransform_[ ( (ii+2)%3 )*3 + ( (jj+2)%3 ) ] - coordTransform_[ ( (ii+2)%3 )*3 + ( (jj+1)%3 ) ]*coordTransform_[ ( (ii+1)%3 )*3 + ( (jj+2)%3 ) ]; // double detCoord = coordTransform_[0]*invCoordTransform_[0] + coordTransform_[3]*invCoordTransform_[1] + coordTransform_[6]*invCoordTransform_[2]; // if(std::abs(detCoord) < 1e-15) // throw std::logic_error("Determinant of the coordTransform_ matrix is 0, inverse is undefined."); // dscal_(invCoordTransform_.size(), 1.0/detCoord, invCoordTransform_.data(), 1); } sphere::sphere(double eps_infty, double mu_infty, double tellegen, std::vector<LorenzDipoleOscillator> pols, bool ML, std::vector<double> geo, std::array<double,3> loc, std::array<std::array<double,3>,3> unitVec) : Obj(eps_infty, mu_infty, tellegen, pols, ML, geo, loc, unitVec) {} hemisphere::hemisphere(double eps_infty, double mu_infty, double tellegen, std::vector<LorenzDipoleOscillator> pols, bool ML, std::vector<double> geo, std::array<double,3> loc, std::array<std::array<double,3>,3> unitVec) : Obj(eps_infty, mu_infty, tellegen, pols, ML, geo, loc, unitVec) {} cylinder::cylinder(double eps_infty, double mu_infty, double tellegen, std::vector<LorenzDipoleOscillator> pols, bool ML, std::vector<double> geo, std::array<double,3> loc, std::array<std::array<double,3>,3> unitVec) : Obj(eps_infty, mu_infty, tellegen, pols, ML, geo, loc, unitVec) {} cone::cone(double eps_infty, double mu_infty, double tellegen, std::vector<LorenzDipoleOscillator> pols, bool ML, std::vector<double> geo, std::array<double,3> loc, std::array<std::array<double,3>,3> unitVec) : Obj(eps_infty, mu_infty, tellegen, pols, ML, geo, loc, unitVec) {} ellipsoid::ellipsoid(double eps_infty, double mu_infty, double tellegen, std::vector<LorenzDipoleOscillator> pols, bool ML, std::vector<double> geo, std::array<double,3> axisCutNeg, std::array<double,3> axisCutPos, std::array<double,3> axisCutGlobal, std::array<double,3> loc, std::array<std::array<double,3>,3> unitVec) : Obj(eps_infty, mu_infty, tellegen, pols, ML, geo, loc, unitVec), axisCutNeg_(axisCutNeg), axisCutPos_(axisCutPos), axisCutGlobal_(axisCutGlobal) {} hemiellipsoid::hemiellipsoid(double eps_infty, double mu_infty, double tellegen, std::vector<LorenzDipoleOscillator> pols, bool ML, std::vector<double> geo, std::array<double,3> loc, std::array<std::array<double,3>,3> unitVec) : Obj(eps_infty, mu_infty, tellegen, pols, ML, geo, loc, unitVec) {} block::block(double eps_infty, double mu_infty, double tellegen, std::vector<LorenzDipoleOscillator> pols, bool ML, std::vector<double> geo, std::array<double,3> loc, std::array<std::array<double,3>,3> unitVec) : Obj(eps_infty, mu_infty, tellegen, pols, ML, geo, loc, unitVec) {} rounded_block::rounded_block(double eps_infty, double mu_infty, double tellegen, std::vector<LorenzDipoleOscillator> pols, bool ML, std::vector<double> geo, std::array<double,3> loc, std::array<std::array<double,3>,3> unitVec) : Obj(eps_infty, mu_infty, tellegen, pols, ML, geo, loc, unitVec) { double radCurv = geoParam_[geoParam_.size()-1]; curveCens_[0] = { geoParam_[0]/2.0 - radCurv, geoParam_[1]/2.0 - radCurv, geoParam_[2]/2.0 - radCurv}; curveCens_[1] = {-1.0*geoParam_[0]/2.0 + radCurv, geoParam_[1]/2.0 - radCurv, geoParam_[2]/2.0 - radCurv}; curveCens_[2] = { geoParam_[0]/2.0 - radCurv, -1.0*geoParam_[1]/2.0 + radCurv, geoParam_[2]/2.0 - radCurv}; curveCens_[3] = {-1.0*geoParam_[0]/2.0 + radCurv, -1.0*geoParam_[1]/2.0 + radCurv, geoParam_[2]/2.0 - radCurv}; curveCens_[4] = { geoParam_[0]/2.0 - radCurv, geoParam_[1]/2.0 - radCurv, -1.0*geoParam_[2]/2.0 + radCurv}; curveCens_[5] = {-1.0*geoParam_[0]/2.0 + radCurv, geoParam_[1]/2.0 - radCurv, -1.0*geoParam_[2]/2.0 + radCurv}; curveCens_[6] = { geoParam_[0]/2.0 - radCurv, -1.0*geoParam_[1]/2.0 + radCurv, -1.0*geoParam_[2]/2.0 + radCurv}; curveCens_[7] = {-1.0*geoParam_[0]/2.0 + radCurv, -1.0*geoParam_[1]/2.0 + radCurv, -1.0*geoParam_[2]/2.0 + radCurv}; } tri_prism::tri_prism(double eps_infty, double mu_infty, double tellegen, std::vector<LorenzDipoleOscillator> pols, bool ML, std::vector<double> geo, std::array<double,3> loc, std::array<std::array<double,3>,3> unitVec) : Obj(eps_infty, mu_infty, tellegen, pols, ML, geo, loc, unitVec), invVertIpiv_(3, 0), invVertMat_(9,1.0) { vertLocs_[0] = {{ 0.5*geoParam_[0], -0.5*geoParam_[1] }}; vertLocs_[1] = {{ -0.5*geoParam_[0], -0.5*geoParam_[1] }}; vertLocs_[2] = {{ 0 , 0.5*geoParam_[1] }}; // For scaling recenter the object space geometry to the centroid std::array<double, 3> centroidLoc = {0.0,0.0,0.0}; for(int ii = 0; ii < 3; ++ii) std::transform(vertLocs_[ii].begin(), vertLocs_[ii].end(), centroidLoc.begin(), centroidLoc.begin(), [](double vert, double cent){return cent + vert/3.0;}); std::transform(location_.begin(), location_.end(), centroidLoc.begin(), location_.begin(), std::plus<double>() ); for(int ii = 0; ii < 3; ++ii) { std::transform(vertLocs_[ii].begin(), vertLocs_[ii].end(), centroidLoc.begin(), vertLocs_[ii].begin(), std::minus<double>() ); dcopy_(2, vertLocs_[ii].begin(), 1, &invVertMat_[ii], 3); } int info; dgetrf_(3, 3, invVertMat_.data(), 3, invVertIpiv_.data(), &info); d0_ = getLUFactMatDet(invVertMat_, invVertIpiv_, 3); if(d0_ == 0) throw std::logic_error("The triangular base is a line."); std::vector<double>work(9,0.0); dgetri_(3, invVertMat_.data(), 3, invVertIpiv_.data(), work.data(), work.size(), &info); geoParam_ = {{ 1.0, 1.0, 1.0, geoParam_[3] }}; } tri_prism::tri_prism(double eps_infty, double mu_infty, double tellegen, std::vector<LorenzDipoleOscillator> pols, bool ML, std::vector<double> geo, std::array<std::array<double, 2>, 3> vertLocs, std::array<double,3> loc, std::array<std::array<double,3>,3> unitVec) : Obj(eps_infty, mu_infty, tellegen, pols, ML, geo, loc, unitVec), invVertIpiv_(3, 0), invVertMat_(9,1.0), vertLocs_(vertLocs) { // For scaling recenter the object space geometry to the centroid std::array<double, 3> centroidLoc = {0.0,0.0,0.0}; for(int ii = 0; ii < 3; ++ii) std::transform(vertLocs_[ii].begin(), vertLocs_[ii].end(), centroidLoc.begin(), centroidLoc.begin(), [](double vert, double cent){return cent + vert/3.0;}); std::transform(location_.begin(), location_.end(), centroidLoc.begin(), location_.begin(), std::plus<double>() ); for(int ii = 0; ii < 3; ++ii) { std::transform(vertLocs_[ii].begin(), vertLocs_[ii].end(), centroidLoc.begin(), vertLocs_[ii].begin(), std::minus<double>() ); dcopy_(2, vertLocs_[ii].begin(), 1, &invVertMat_[ii], 3); } int info; dgetrf_(3, 3, invVertMat_.data(), 3, invVertIpiv_.data(), &info); d0_ = getLUFactMatDet(invVertMat_, invVertIpiv_, 3); if(d0_ == 0) throw std::logic_error("The triangular base is a line."); std::vector<double>work(9,0.0); dgetri_(3, invVertMat_.data(), 3, invVertIpiv_.data(), work.data(), work.size(), &info); } ters_tip::ters_tip(double eps_infty, double mu_infty, double tellegen, std::vector<LorenzDipoleOscillator> pols, bool ML, std::vector<double> geo, std::array<double,3> loc, std::array<std::array<double,3>,3> unitVec) : Obj(eps_infty, mu_infty, tellegen, pols, ML, geo, loc, unitVec) { radCen_ = {{ 0.0, 0.0, -1.0*geo[2]/2.0 + geo[0]/2.0 }}; } paraboloid::paraboloid(double eps_infty, double mu_infty, double tellegen, std::vector<LorenzDipoleOscillator> pols, bool ML, std::vector<double> geo, std::array<double,3> loc, std::array<std::array<double,3>,3> unitVec) : Obj(eps_infty, mu_infty, tellegen, pols, ML, geo, loc, unitVec) {} torus::torus(double eps_infty, double mu_infty, double tellegen, std::vector<LorenzDipoleOscillator> pols, bool ML, std::vector<double> geo, std::array<double,3> loc, std::array<std::array<double,3>,3> unitVec) : Obj(eps_infty, mu_infty, tellegen, pols, ML, geo, loc, unitVec) {} tetrahedron::tetrahedron(double eps_infty, double mu_infty, double tellegen, std::vector<LorenzDipoleOscillator> pols, bool ML, std::vector<double> geo, std::array<double,3> loc, std::array<std::array<double,3>,3> unitVec) : Obj(eps_infty, mu_infty, tellegen, pols, ML, geo, loc, unitVec), invVertIpiv_(4, 0), invVertMat_(16,1.0) { std::vector<double> vert = {{ std::sqrt(8.0/9.0), 0, -1.0/3.0 }}; dgemv_('T', vert.size(), vert.size(), 1.0, coordTransform_.data(), vert.size(), vert.data(), 1, 0.0, vertLocs_[0].data(), 1 ); vert = {{-1.0*std::sqrt(2.0/9.0), std::sqrt(2.0/3.0), -1.0/3.0 }}; dgemv_('T', vert.size(), vert.size(), 1.0, coordTransform_.data(), vert.size(), vert.data(), 1, 0.0, vertLocs_[1].data(), 1 ); vert = {{-1.0*std::sqrt(2.0/9.0), -1.0*std::sqrt(2.0/3.0), -1.0/3.0 }}; dgemv_('T', vert.size(), vert.size(), 1.0, coordTransform_.data(), vert.size(), vert.data(), 1, 0.0, vertLocs_[2].data(), 1 ); vert = {{ 0, 0, 1}}; dgemv_('T', vert.size(), vert.size(), 1.0, coordTransform_.data(), vert.size(), vert.data(), 1, 0.0, vertLocs_[3].data(), 1 ); for(int ii = 0; ii < 4; ++ii) { dscal_(3, geoParam_[0]*std::sqrt(3.0/8.0), vertLocs_[ii].begin(), 1); daxpy_(3, 1.0, location_.begin(), 1, vertLocs_[ii].begin(), 1); } for(int ii = 0; ii < 4; ++ii) dcopy_(3, vertLocs_[ii].begin(), 1, &invVertMat_[ii], 4); int info; dgetrf_(4, 4, invVertMat_.data(), 4, invVertIpiv_.data(), &info); d0_ = getLUFactMatDet(invVertMat_, invVertIpiv_, 4); if(d0_ == 0) throw std::logic_error("The tetrahedron is planer."); std::vector<double>work(16,0.0); dgetri_(4, invVertMat_.data(), 4, invVertIpiv_.data(), work.data(), work.size(), &info); double heightRat = ( geoParam_[1]/( geoParam_[0]*sqrt(2.0/3.0) )*(5.0/4.0) ) - 1.0/4.0; std::array<double,3>v4(location_); daxpy_(3, heightRat, vertLocs_[3].begin(), 1, v4.data(), 1); std::array<double,4> v4Bary = cart2bary<double,4>(invVertMat_, v4, d0_); geoParam_ = {{ 1.0, 1.0, 1.0, v4Bary[3] }}; } tetrahedron::tetrahedron(double eps_infty, double mu_infty, double tellegen, std::vector<LorenzDipoleOscillator> pols, bool ML, std::vector<double> geo, std::array<std::array<double, 3>, 4> vertLocs, std::array<double,3> loc, std::array<std::array<double,3>,3> unitVec) : Obj(eps_infty, mu_infty, tellegen, pols, ML, geo, loc, unitVec), invVertIpiv_(4, 0), invVertMat_(16,1.0), vertLocs_(vertLocs) { for(int ii = 0; ii < 4; ++ii) dcopy_(3, vertLocs_[ii].begin(), 1, &invVertMat_[ii], 4); int info; dgetrf_(4, 4, invVertMat_.data(), 4, invVertIpiv_.data(), &info); d0_ = getLUFactMatDet(invVertMat_, invVertIpiv_, 4); if(d0_ == 0) throw std::logic_error("The tetrahedron is planer."); std::vector<double>work(16,0.0); dgetri_(4, invVertMat_.data(), 4, invVertIpiv_.data(), work.data(), work.size(), &info); if(d0_ == 0) throw std::logic_error("The tetrahedron is planer."); } sphere::sphere(const sphere &o) : Obj(o) {} hemisphere::hemisphere(const hemisphere &o) : Obj(o) {} cone::cone(const cone &o) : Obj(o) {} cylinder::cylinder(const cylinder &o) : Obj(o) {} block::block(const block &o) : Obj(o) {} rounded_block::rounded_block(const rounded_block &o) : Obj(o), curveCens_(o.curveCens_) {} ellipsoid::ellipsoid(const ellipsoid &o) : Obj(o), axisCutNeg_(o.axisCutNeg_), axisCutPos_(o.axisCutPos_), axisCutGlobal_(o.axisCutGlobal_) {} hemiellipsoid::hemiellipsoid(const hemiellipsoid &o) : Obj(o) {} tri_prism::tri_prism(const tri_prism &o) : Obj(o) {} ters_tip::ters_tip(const ters_tip &o) : Obj(o), radCen_(o.radCen_) {} paraboloid::paraboloid(const paraboloid &o) : Obj(o) {} torus::torus(const torus &o) : Obj(o) {} void Obj::setUpConsts (double dt) { // Converts Lorentzian style functions into constants that can be used for time updates based on Taflove Chapter 9 for(auto& pol : pols_) { if(pol.dipOrE_ != MAT_DIP_ORIENTAITON::ISOTROPIC || pol.dipOrM_ != MAT_DIP_ORIENTAITON::ISOTROPIC) useOrientedDipols_ = true; double sigP = pol.sigP_; double sigM = pol.sigM_; double tau = pol.tau_; double gam = pol.gam_; double omg = pol.omg_; if(std::abs( sigP ) != 0.0) { dipOr_.push_back(pol.dipOrE_); dipE_.push_back(pol.uVecDipE_); dipNormCompE_.push_back(pol.normCompWeightE_); dipTanLatCompE_.push_back(pol.tangentLatCompWeightE_); dipTanLongCompE_.push_back(pol.tangentLongCompWeightE_); alpha_.push_back( ( (2-pow(omg*dt,2.0)) / (1+gam*dt) ) ); xi_.push_back( ( (gam*dt -1) / (1+gam*dt) ) ); gamma_.push_back( ( (sigP*pow(omg*dt,2.0)) / (1+gam*dt) ) ); } if(std::abs( sigM ) != 0.0) { magDipOr_.push_back(pol.dipOrM_); dipM_.push_back(pol.uVecDipM_); dipNormCompM_.push_back(pol.normCompWeightM_); dipTanLatCompM_.push_back(pol.tangentLatCompWeightM_); dipTanLongCompM_.push_back(pol.tangentLongCompWeightM_); magAlpha_.push_back( ( (2-pow(omg*dt,2.0)) / (1+gam*dt) ) ); magXi_.push_back( ( (gam*dt -1) / (1+gam*dt) ) ); magGamma_.push_back( ( (sigM*pow(omg*dt,2.0)) / (1+gam*dt) ) ); } if(std::abs( tau ) != 0.0) { chiEDipOr_.push_back(pol.dipOrE_); chiMDipOr_.push_back(pol.dipOrM_); dipChiE_.push_back(pol.uVecDipE_); dipChiM_.push_back(pol.uVecDipM_); dipNormCompChiE_.push_back(pol.normCompWeightE_); dipTanLatCompChiE_.push_back(pol.tangentLatCompWeightE_); dipTanLongCompChiE_.push_back(pol.tangentLongCompWeightE_); dipNormCompChiM_.push_back(pol.normCompWeightM_); dipTanLatCompChiM_.push_back(pol.tangentLatCompWeightM_); dipTanLongCompChiM_.push_back(pol.tangentLongCompWeightM_); chiAlpha_.push_back( ( (2-pow(omg*dt,2.0)) / (1+gam*dt) ) ); chiXi_.push_back( ( (gam*dt -1) / (1+gam*dt) ) ); chiGamma_.push_back( ( -1.0/dt ) * ( (tau*pow(omg*dt,2.0) ) / ( (1+gam*dt) ) ) ); //!< 1/dt for gamma is due to the time derivative needed for chiral interactions chiGammaPrev_.push_back( ( 1.0/dt ) * ( (tau*pow(omg*dt,2.0) ) / ( (1+gam*dt) ) ) ); //!< 1/dt for gamma is due to the time derivative needed for chiral interactions // chiGamma_.push_back( ( pol.molec_ ? gam/2.0 - 1.0/dt : -1.0/dt ) * ( (tau*pow(omg*dt,2.0) ) / ( (1+gam*dt) ) ) ); //!< 1/dt for gamma is due to the time derivative needed for chiral interactions // chiGammaPrev_.push_back( ( pol.molec_ ? gam/2.0 + 1.0/dt : 1.0/dt ) * ( (tau*pow(omg*dt,2.0) ) / ( (1+gam*dt) ) ) ); //!< 1/dt for gamma is due to the time derivative needed for chiral interactions } } alpha_.reserve( alpha_.size() ); xi_.reserve( xi_.size() ); gamma_.reserve( gamma_.size() ); magAlpha_.reserve( magAlpha_.size() ); magXi_.reserve( magXi_.size() ); magGamma_.reserve( magGamma_.size() ); chiAlpha_.reserve( chiAlpha_.size() ); chiXi_.reserve( chiXi_.size() ); chiGamma_.reserve( chiGamma_.size() ); chiGammaPrev_.reserve( chiGammaPrev_.size() ); } bool sphere::isObj(std::array<double,3> v, double dx, std::vector<double> geo) { if(dist(v,location_) > geo[0] + dx/1.0e6) { return false; } return true; } bool hemisphere::isObj(std::array<double,3> v, double dx, std::vector<double> geo) { if(dist(v,location_) > geo[0] + dx/1.0e6) { // Move origin to object's center return false; } // Convert x, y, z coordinates to coordinates along the object's unit axis std::array<double,3> v_trans; // Do geo checks based on the the object oriented coordinates std::array<double,3> v_cen; std::transform(v.begin(), v.end(), location_.begin(), v_cen.begin(), std::minus<double>() ); dgemv_('T', v_cen.size(), v_cen.size(), 1.0, coordTransform_.data(), v_cen.size(), v_cen.data(), 1, 0.0, v_trans.data(), 1 ); if(v_trans[0] > dx/1e6) return false; return true; } bool block::isObj(std::array<double,3> v, double dx, std::vector<double> geo) { std::array<double,3> v_trans = RealSpace2ObjectSpace(v); // Do geo checks based on the the object oriented coordinates for(int ii = 0; ii < v.size(); ii++) { if((v_trans[ii] > geo[ii]/2.0 + dx/1.0e6) || (v_trans[ii] < -1.0*geo[ii]/2.0 - dx/1.0e6)) return false; } return true; } bool rounded_block::isObj(std::array<double,3> v, double dx, std::vector<double> geo) { std::array<double,3> v_trans = RealSpace2ObjectSpace(v); // Do geo checks based on the the object oriented coordinates double radCurv = geo.back(); for(int ii = 0; ii < v.size(); ii++) { if((v_trans[ii] > geo[ii]/2.0 + dx/1.0e6) || (v_trans[ii] < -1.0*geo[ii]/2.0 - dx/1.0e6)) return false; } if( ( (v_trans[0] > geo[0]/2.0 - radCurv + dx/1.0e6) || (v_trans[0] < -1.0*geo[0]/2.0 + radCurv - dx/1.0e6) ) || ( (v_trans[1] > geo[1]/2.0 - radCurv + dx/1.0e6) || (v_trans[1] < -1.0*geo[1]/2.0 + radCurv - dx/1.0e6) ) || ( (v_trans[2] > geo[2]/2.0 - radCurv + dx/1.0e6) || (v_trans[2] < -1.0*geo[2]/2.0 + radCurv - dx/1.0e6) ) ) { for(int cc = 0; cc < curveCens_.size(); cc++) if( ( std::sqrt( std::pow(v_trans[0] - curveCens_[cc][0], 2.0) + std::pow(v_trans[1] - curveCens_[cc][1], 2.0) ) < radCurv + dx/1.0e6 ) || ( std::sqrt( std::pow(v_trans[2] - curveCens_[cc][2], 2.0) + std::pow(v_trans[1] - curveCens_[cc][1], 2.0) ) < radCurv + dx/1.0e6 ) || ( std::sqrt( std::pow(v_trans[0] - curveCens_[cc][0], 2.0) + std::pow(v_trans[2] - curveCens_[cc][2], 2.0) ) < radCurv + dx/1.0e6 ) ) return true; if( (v_trans[0] < geo[0]/2.0 - radCurv + dx/1.0e6) && (v_trans[0] > -1.0*geo[0]/2.0 + radCurv - dx/1.0e6) && (v_trans[1] < geo[1]/2.0 - radCurv + dx/1.0e6) && (v_trans[1] > -1.0*geo[1]/2.0 + radCurv - dx/1.0e6) || (v_trans[2] < geo[2]/2.0 - radCurv + dx/1.0e6) && (v_trans[2] > -1.0*geo[2]/2.0 + radCurv - dx/1.0e6) && (v_trans[1] < geo[1]/2.0 - radCurv + dx/1.0e6) && (v_trans[1] > -1.0*geo[1]/2.0 + radCurv - dx/1.0e6) || (v_trans[0] < geo[0]/2.0 - radCurv + dx/1.0e6) && (v_trans[0] > -1.0*geo[0]/2.0 + radCurv - dx/1.0e6) && (v_trans[2] < geo[2]/2.0 - radCurv + dx/1.0e6) && (v_trans[2] > -1.0*geo[2]/2.0 + radCurv - dx/1.0e6) ) return true; return false; } return true; } bool ellipsoid::isObj(std::array<double,3> v, double dx, std::vector<double> geo) { std::array<double,3> v_trans = RealSpace2ObjectSpace(v); // Do geo checks based on the the object oriented coordinates double ptSum = 0.0; for( int ii = 0; ii < ( geo[2] != 0.0 ? v_trans.size() : 2 ); ++ii) ptSum += std::pow( (v_trans[ii]-dx/1.0e6) / (geo[ii]/2.0), 2.0 ); if(1.0 < ptSum ) return false; for(int ii = 0; ii < 3; ++ii) { if( (2.0*v_trans[ii]/geo[ii] < axisCutNeg_[ii]) || (2.0*v_trans[ii]/geo[ii] > axisCutPos_[ii]) ) return false; if( axisCutGlobal_[ii] >= 0.0 && (v_trans[ii] + geo[ii]/2.0) / geo[ii] >= axisCutGlobal_[ii]) return false; else if( axisCutGlobal_[ii] <= 0.0 && (v_trans[ii] - geo[ii]/2.0) / geo[ii] <= axisCutGlobal_[ii] ) return false; } return true; } bool hemiellipsoid::isObj(std::array<double,3> v, double dx, std::vector<double> geo) { std::array<double,3> v_trans = RealSpace2ObjectSpace(v); // Do geo checks based on the the object oriented coordinates if(v_trans[0] > dx/1e6) return false; double ptSum = 0.0; for( int ii = 0; ii < ( geo[2] != 0.0 ? v_trans.size() : 2 ); ++ii) ptSum += std::pow( (v_trans[ii]-dx/1.0e6) / (geo[ii]/2.0), 2.0 ); if(1.0 < ptSum ) return false; return true; } bool tri_prism::isObj(std::array<double,3> v, double dx, std::vector<double> geo) { std::array<double,3> v_trans = RealSpace2ObjectSpace(v); // If prism point is outside prism's length return false if( (v_trans[2] < -1.0*geo[3]/2.0 - dx*1e-6) || (v_trans[2] > geo[3]/2.0 + dx*1e-6) ) return false; // Is point within the triangle's cross-section? std::array<double,2> v_transTriFace = {v_trans[0], v_trans[1]}; std::array<double,3> baryCenCoords = cart2bary<double,3>(invVertMat_, v_transTriFace, d0_); // If Barycenteric coordinates are < 0 or > geoParam then they must be outside the cross-section for(int ii = 0; ii < 3; ++ii) if(baryCenCoords[ii] < -1e-13 || baryCenCoords[ii] > geo[ii]+1e-13) return false; // Sum barycenteric coords must = 1 if(std::abs( 1 - std::accumulate( baryCenCoords.begin(), baryCenCoords.end(), 0.0 ) ) > 1e-14 ) { std::cout << std::accumulate( baryCenCoords.begin(), baryCenCoords.end(), 0.0 ) << '\t' << d0_ << '\t' << v[0] << '\t' << v[1] << '\t' << v[2] << std::endl; throw std::logic_error("The sum of the boundary checks for a triangular base does not equal the determinant of the verticies, despite passing the checks. This is an error."); } return true; } bool tetrahedron::isObj(std::array<double,3> v, double dx, std::vector<double> geo) { std::array<double, 4> baryCenCoords = cart2bary<double,4>(invVertMat_, v, d0_); // If Barycenteric coordinates are < 0 or > geoParam then they must be outside the cross-section for(int ii = 0; ii < 4; ++ii) if(baryCenCoords[ii] < -1e-6*dx|| (baryCenCoords[ii] + dx*1e-6) > geo[ii]) return false; // Sum barycenteric coords must = 1 if(std::abs( 1 - std::accumulate( baryCenCoords.begin(), baryCenCoords.end(), 0.0 ) ) > 1e-14 ) { std::cout << std::accumulate( baryCenCoords.begin(), baryCenCoords.end(), 0.0 ) << '\t' << d0_ << '\t' << v[0] << '\t' << v[1] << '\t' << v[2] << std::endl; throw std::logic_error("The sum of the boundary checks for a tetrahedron does not equal the determinant of the verticies, despite passing the checks. This is an error."); } return true; } bool cone::isObj(std::array<double,3> v, double dx, std::vector<double> geo) { std::array<double,3> v_trans = RealSpace2ObjectSpace(v); // Do geo checks based on the the object oriented coordinates if( (v_trans[1] < -1.0*geo[1]/2.0 - dx*1e-6) || (v_trans[1] > geo[1]/2.0 + dx*1e-6) ) return false; else if( dist(std::array<double,3>( {{ v_trans[0], 0.0, v_trans[2] }} ), std::array<double,3>({{0,0,0}}) ) > std::pow(geo[0]/geo[2] * ( v_trans[2] - geo[1]/2.0 ), 2.0) ) return false; return true; } bool cylinder::isObj(std::array<double,3> v, double dx, std::vector<double> geo) { std::array<double,3> v_trans = RealSpace2ObjectSpace(v); // Do geo checks based on the the object oriented coordinates if( (v_trans[1] < -1.0*geo[1]/2.0 - dx*1e-6) || (v_trans[1] > geo[1]/2.0 + dx*1e-6) ) return false; else if( dist(std::array<double,3>( {{ v_trans[0], 0.0, v_trans[2] }} ), std::array<double,3>({{0,0,0}}) ) > geo[0] + 1.0e-6*dx ) return false; return true; } bool ters_tip::isObj(std::array<double,3> v, double dx, std::vector<double> geo) { std::array<double,3> v_trans = RealSpace2ObjectSpace(v); // Do geo checks based on the the object oriented coordinates if( dist(v_trans, radCen_) < geo[0]/2.0 ) return true; if( (v_trans[2] < geo[0] - geo[2]/2.0 - dx*1e-6) || (v_trans[2] > geo[1]/2.0 + dx*1e-6) ) return false; else if( ( std::pow( v_trans[0], 2.0 ) + std::pow( v_trans[1], 2.0 ) ) * std::pow( cos(geo[0]), 2.0 ) - std::pow( v_trans[2] * sin(geo[0]), 2.0) > dx*1e-6 ) return false; return true; } bool paraboloid::isObj(std::array<double,3> v, double dx, std::vector<double> geo) { std::array<double,3> v_trans = RealSpace2ObjectSpace(v); // Do geo checks based on the the object oriented coordinates v_trans[1] += geo[2]/2.0; if(v_trans[1] > geo[2]) return false; else if( std::pow(v_trans[0]/geo[0], 2.0) + std::pow(v_trans[2]/geo[1], 2.0) > v_trans[1] ) return false; return true; } bool torus::isObj(std::array<double,3> v, double dx, std::vector<double> geo) { std::array<double,3> v_trans = RealSpace2ObjectSpace(v); if( std::pow( std::sqrt( std::pow(v_trans[0], 2.0) + std::pow(v_trans[1], 2.0) ) - geo[0] , 2.0) > std::pow(geo[1],2.0) - std::pow(v_trans[2],2.0) ) return false; double phiPt = v_trans[0] !=0 ? std::atan(v_trans[1]/v_trans[0]) : v_trans[1]/std::abs(v_trans[1]) * M_PI / 2.0; if(v_trans[0] < 0) phiPt += M_PI; else if(v_trans[1] < 0) phiPt += 2.0*M_PI; if(phiPt < geo[2] || phiPt > geo[3]) return false; return true; } double Obj::dist(std::array<double,3> pt1, std::array<double,3> pt2) { double sum = 0; for(int cc = 0; cc < pt1.size(); cc ++) sum += std::pow((pt1[cc]-pt2[cc]),2); return sqrt(sum); } std::array<double, 3> sphere::findGradient(std::array<double,3> pt) { std::array<double,3> grad; // Move origin to object's center std::transform(pt.begin(), pt.end(), location_.begin(), grad.begin(), std::minus<double>() ); // Find the magnitude of the gradient vector (grad in this case since the radial and gradient vector are parallel) if(std::accumulate(grad.begin(), grad.end(), 0.0, vecMagAdd<double>() ) < 1e-20) grad = { 0.0, 0.0, 0.0 }; else normalize(grad); return grad; } std::array<double, 3> hemisphere::findGradient(std::array<double,3> pt) { std::array<double,3> grad; // Move origin to object's center std::transform(pt.begin(), pt.end(), location_.begin(), grad.begin(), std::minus<double>() ); // Find the magnitude of the gradient vector (grad in this case since the radial and gradient vector are parallel) if(std::accumulate(grad.begin(), grad.end(), 0.0, vecMagAdd<double>() ) < 1e-20) grad = { 0.0, 0.0, 0.0 }; else normalize(grad); return grad; } std::array<double, 3> ellipsoid::findGradient(std::array<double,3> pt) { std::array<double,3> grad = RealSpace2ObjectSpace(pt); // Find gradient by modifying the v_trans std::transform(grad.begin(), grad.end(), geoParam_.begin(), grad.begin(), [](double g, double geo){return g/std::pow(geo,2.0); } ); // Convert gradient back to real space return ObjectSpace2RealSpace(grad); } std::array<double, 3> hemiellipsoid::findGradient(std::array<double,3> pt) { std::array<double,3> grad = RealSpace2ObjectSpace(pt); // Find gradient by modifying the v_trans std::transform(grad.begin(), grad.end(), geoParam_.begin(), grad.begin(), [](double g, double geo){return g/std::pow(geo,2.0); } ); // Convert gradient back to real space return ObjectSpace2RealSpace(grad); } std::array<double, 3> cone::findGradient(std::array<double,3> pt) { std::array<double,3> v_trans = RealSpace2ObjectSpace(pt); // Find gradient by modifying the v_trans double z_prime = v_trans[2] + geoParam_[1]/2.0; double c = geoParam_[0]/geoParam_[2]; double z0 = z_prime * (1.0 + std::sqrt( (std::pow(v_trans[0],2.0) + std::pow(v_trans[1],2.0) ) / std::pow(c,2.0) ) ); std::array<double,3> grad = {{ 2.0*v_trans[0], 2.0*v_trans[1], -2.0*std::pow(c,2.0) * ( z_prime - z0 ) }}; if(std::abs(v_trans[2]) == std::abs(z0/2.0) ) grad = {{0, 0, -2.0*v_trans[2]/geoParam_[1] }}; // Convert gradient back to real space return ObjectSpace2RealSpace(grad); } std::array<double, 3> cylinder::findGradient(std::array<double,3> pt) { std::array<double,3> v_trans = RealSpace2ObjectSpace(pt); double r = std::sqrt( std::pow(v_trans[0], 2.0) + std::pow(v_trans[2], 2.0) ); double len = geoParam_[1] * (r / geoParam_[0] ); std::array<double,3> grad = {{ v_trans[0], 0.0, v_trans[2] }}; if(std::abs(v_trans[1]) >= len/2.0 ) grad = {{ 0.0, v_trans[1]/std::abs(v_trans[1]), 0.0 }}; return ObjectSpace2RealSpace(grad); } std::array<double, 3> block::findGradient(std::array<double,3> pt) { std::array<double,3> v_trans = RealSpace2ObjectSpace(pt); std::array<double,3> grad = {0.0,0.0,0.0}; std::array<double,3> ptRat; std::transform(v_trans.begin(), v_trans.end(), geoParam_.begin(), ptRat.begin(), std::divides<double>() ); int ptRatMax = idamax_(ptRat.size(), ptRat.data(), 1) - 1; for(int ii = 0; ii < 3; ++ii) if(ptRat[ii] == ptRat[ptRatMax]) grad[ ii ] = v_trans[ii] >=0 ? 1.0 : -1.0; return ObjectSpace2RealSpace(grad); } std::array<double, 3> rounded_block::findGradient(std::array<double,3> pt) { std::array<double,3> v_trans = RealSpace2ObjectSpace(pt); std::array<double,3> grad = {0.0,0.0,0.0}; std::array<double,3> ptRat; std::transform(v_trans.begin(), v_trans.end(), geoParam_.begin(), ptRat.begin(), std::divides<double>() ); int ptRatMax = idamax_(ptRat.size(), ptRat.data(), 1) - 1; double t = ptRat[ptRatMax]; bool atCorner = true; for(int ii = 0; ii < 3; ++ii) if(v_trans[ii] - t * (geoParam_[ii]-geoParam_[3]) <= 0) atCorner = false; if(atCorner) { std::array<double,3> absPt; std::transform(pt.begin(), pt.end(), absPt.begin(), [](double pt){return std::abs(pt);}); double cenPtDot = ddot_(3, absPt.data(), 1, curveCens_[0].data(), 1); double cenMag = std::accumulate(curveCens_[0].begin(), curveCens_[0].end(), 0.0, vecMagAdd<double>() ); double ptMag = std::accumulate(absPt.begin(), absPt.end(), 0.0, vecMagAdd<double>()); t = 1.0/ ( cenMag-std::pow(geoParam_[3],2.0) ) * ( std::pow(cenPtDot,2.0) - std::sqrt(std::pow(cenPtDot, 2.0) - ptMag*(cenMag-std::pow(geoParam_[3],2.0) ) ) ); std::transform(absPt.begin(), absPt.end(), curveCens_[0].begin(), grad.begin(), [=](double p, double cen){return p - t*cen;} ); std::transform(pt.begin(), pt.end(), grad.begin(), grad.begin(), [](double p, double grad){return grad*p/std::abs(p); } ); } else { for(int ii = 0; ii < 3; ++ii) if(ptRat[ii] == ptRat[ptRatMax]) grad[ ii ] = v_trans[ii] >=0 ? 1.0 : -1.0; } return ObjectSpace2RealSpace(grad); } std::array<double, 3> tri_prism::findGradient(std::array<double,3> pt) { std::array<double,3> v_trans = RealSpace2ObjectSpace(pt); std::array<double,2> v_transTriFace = {v_trans[0], v_trans[1]}; std::array<double,3> grad = {0.0,0.0,0.0}; double scalRat = std::abs(2*v_trans[2]/geoParam_[3]); if(scalRat > 0) { std::array<std::array<double, 2>, 3> scaledVertLocs_(vertLocs_); std::vector<double> invScalVertMat(9,1.0); for(int ii = 0; ii < 3; ++ii) { dscal_(2, scalRat, scaledVertLocs_[ii].begin(), 1); dcopy_(2, scaledVertLocs_[ii].begin(), 1, &invScalVertMat[ii], 3); } int info; std::vector<int>ivip(3, 0); dgetrf_(3, 3, invScalVertMat.data(), 3, ivip.data(), &info); double d0Scaled = getLUFactMatDet(invScalVertMat, ivip, 3); std::vector<double>work(9,0.0); dgetri_(3, invScalVertMat.data(), 3, ivip.data(), work.data(), work.size(), &info); std::array<double, 3> baryScaled = cart2bary<double,3>(invScalVertMat, v_transTriFace, d0Scaled); bool inTri = true; bool onEdge = false; for(int ii = 0; ii < 3; ++ii) { if( baryScaled[ii] < -1e-15 || baryScaled[ii] > geoParam_[ii]+1e-15 ) inTri = false; if( baryScaled[ii] == 0 || baryScaled[ii] == geoParam_[ii] ) onEdge = true; } // If the point is in the scaled triangle's cross section then it is on the cap face if(inTri) { grad = { 0.0, 0.0, (v_trans[2] >= 0 ? 1.0 : -1.0 ) } ; // If it's not on the edge then no need to calculate which triangle face is closest if(!onEdge) return ObjectSpace2RealSpace(grad); } } // Calculate the barycenteric coordinates std::array<double, 3> baryCenCoords = cart2bary<double,3>(invVertMat_, v_transTriFace, d0_); // Calculate the ratio from the base surface and truncated surace std::array<double, 3> baseRat; std::array<double, 3> truncRat; for(int ii = 0; ii < 3; ++ii) { baseRat[ii] = baryCenCoords[ii] / geoParam_[ii]; truncRat[ii] = ( geoParam_[ii] - baryCenCoords[ii] ) / geoParam_[ii]; } // Find the min distance to the base and truncated faces int indMinBaseRat = idamin_(baseRat.size(), baseRat.begin(), 1 ); int indMinTruncRat = idamin_(truncRat.size(), truncRat.begin(), 1 ); // Determine which of the two is closest and get it's distance int closestFace = ( truncRat[indMinTruncRat-1] < baseRat[indMinBaseRat-1] ) ? -1*indMinTruncRat : indMinBaseRat; double dist2ClosestFace = (closestFace < 0) ? truncRat[indMinTruncRat-1] : baseRat[indMinBaseRat-1]; // Collect all faces equidistant to the closest face std::vector<int> equiDistFaces; for(int ii = 0; ii < 3; ++ii) { // If both the truncated face and base face are equidistant give presidence to the base if(baseRat[ii] == dist2ClosestFace) equiDistFaces.push_back(ii+1); if(truncRat[ii] == dist2ClosestFace) equiDistFaces.push_back(-1*ii-1); } std::vector<std::vector<int>> activeVerts(equiDistFaces.size()); // Average over all faces for(int ff = 0; ff < equiDistFaces.size(); ++ff) { // Find the vertices needed to calculate the surface normal std::vector<int> activeVerts; for(int ii = 0; ii < 3; ++ii) { if( ii != std::abs(equiDistFaces[ff])-1 ) activeVerts.push_back(ii); } // Calculate the gradient for that face and add it to grad std::array<double, 3> tempGrad; double xSign = ( vertLocs_[ activeVerts[1] ][0]+vertLocs_[ activeVerts[0] ][0] )/2.0 - ( vertLocs_[ activeVerts[1] ][0]+vertLocs_[ activeVerts[0] ][0]+vertLocs_[closestFace][0] )/3.0; xSign /= -1.0*std::abs(xSign) * equiDistFaces[ff] / std::abs(equiDistFaces[ff]); double slopePerp = -1.0*(vertLocs_[ activeVerts[1] ][0]-vertLocs_[ activeVerts[0] ][0])/(vertLocs_[ activeVerts[1] ][1]-vertLocs_[ activeVerts[0] ][1]); if( std::abs(vertLocs_[ activeVerts[1] ][1]-vertLocs_[ activeVerts[0] ][1]) < 1e-14) tempGrad = { 0.0, xSign, 0.0 } ; else tempGrad = { xSign, xSign*slopePerp, 0.0 } ; normalize(tempGrad); std::transform(tempGrad.begin(), tempGrad.end(), grad.begin(), grad.begin(), std::plus<double>() ); } return ObjectSpace2RealSpace(grad); } std::array<double, 3> tetrahedron::findGradient(std::array<double,3> pt) { // Convert pt to barycentric coodrinates std::array<double, 4> baryCenCoords = cart2bary<double,4>(invVertMat_, pt, d0_); // Get the ratios from of face distance to the geo_params std::array<double, 4> truncRat; std::array<double, 4> baseRat; for(int ii = 0; ii < 4; ++ii) { baseRat[ii] = baryCenCoords[ii] / geoParam_[ii]; truncRat[ii] = ( geoParam_[ii] - baryCenCoords[ii] ) / geoParam_[ii]; } // Get the minimum distance to a base and truncated surface int indMinBaseDist = idamin_(4, baseRat.begin(), 1); int indMinTruncDist = idamin_(4, truncRat.begin(), 1 ); // Which is closer, and what is that distance int closestFace = ( truncRat[indMinTruncDist-1] < baseRat[indMinBaseDist-1] ) ? -1*indMinTruncDist : indMinBaseDist; double dist2ClosestFace = (closestFace < 0) ? truncRat[indMinTruncDist-1] : baseRat[indMinBaseDist-1]; // Find all faces equidistant to the closest face std::vector<int> equiDistFaces; for(int ii = 0; ii < 4; ++ii) { // If both the truncated face and base face are equidistant give presidence to the base if(baseRat[ii] == dist2ClosestFace) equiDistFaces.push_back(ii+1); if(truncRat[ii] == dist2ClosestFace) equiDistFaces.push_back(-1*ii-1); } std::array<double,3> grad = {0.0, 0.0, 0.0}; // Loop over all faces and add average their gradients for(int ff = 0; ff < equiDistFaces.size(); ++ff) { std::vector<int> activeVerts; // Find the vertices needed to calculate the surface normal in the correct order (https://math.stackexchange.com/questions/183030/given-a-tetrahedron-how-to-find-the-outward-surface-normals-for-each-side) for(int ii = 0; ii < 4; ++ii) { int index = ( static_cast<int>( std::pow( -1, std::abs(equiDistFaces[ff])-1 ) * ii) % 4 ) * static_cast<int>(equiDistFaces[ff] / std::abs(equiDistFaces[ff]) ); index += (index < 0) ? 4 : 0; if( index != std::abs(equiDistFaces[ff])-1 ) activeVerts.push_back(index); } // Calculate the gradient for that face and add it to grad std::array<double,3> v1; std::array<double,3> v2; std::transform(vertLocs_[activeVerts[1]].begin(), vertLocs_[activeVerts[1]].end(), vertLocs_[activeVerts[0]].begin(), v1.begin(), std::minus<double>()); std::transform(vertLocs_[activeVerts[2]].begin(), vertLocs_[activeVerts[2]].end(), vertLocs_[activeVerts[1]].begin(), v2.begin(), std::minus<double>()); std::array<double, 3> tempGrad = {{ v1[1]*v2[2]-v1[2]*v2[1], v1[2]*v2[0]-v1[0]*v2[2], v1[0]*v2[1]-v1[1]*v2[0] }}; normalize(tempGrad); std::transform(tempGrad.begin(), tempGrad.end(), grad.begin(), grad.begin(), std::plus<double>() ); } // If 0 return 0; otherwise normalize and return if( std::abs( std::accumulate(grad.begin(), grad.end(), 0.0, vecMagAdd<double>() ) ) < 1.0e-20 ) grad ={0.0, 0.0, 0.0}; else normalize(grad); return grad; } std::array<double, 3> ters_tip::findGradient(std::array<double,3> pt) { throw std::logic_error("Gradient is not defined for this object yet defined"); return std::array<double,3>({{0.0,0.0,0.0}}); } std::array<double, 3> paraboloid::findGradient(std::array<double,3> pt) { std::array<double,3> v_trans = RealSpace2ObjectSpace(pt); v_trans[1] += geoParam_[2]/2.0; std::array<double,3> grad = {2*v_trans[0]/std::pow(geoParam_[0],2.0), -1.0, 2.0*v_trans[2]/std::pow(geoParam_[2],2.0) }; normalize(grad); return grad; } std::array<double, 3> torus::findGradient(std::array<double,3> pt) { std::array<double,3> v_trans = RealSpace2ObjectSpace(pt); double radRing = std::sqrt( std::pow(v_trans[0], 2.0) + std::pow(v_trans[1], 2.0) ); double radRingTerm = (radRing - geoParam_[0]) / radRing; std::array<double,3> grad = { 2.0*v_trans[0] * radRingTerm, 2.0*v_trans[1] * radRingTerm, 2.0*v_trans[2]}; normalize(grad); return grad; }
49.394527
420
0.619266
Seideman-Group
9da2a8d7e37201fb04c8db639dbc4318fec1fdad
7,363
cpp
C++
VideoCube/VideoCubeCV/libs/app7-master/3PartyLibs/qwt-6.1.4/examples/legends/panel.cpp
Kvazikot/VideoProjects
899cd047dd791b0e2f33d40cf6e11fe949333329
[ "MIT" ]
1
2021-06-23T08:41:55.000Z
2021-06-23T08:41:55.000Z
VideoCube/VideoCubeCV/libs/app7-master/3PartyLibs/qwt-6.1.4/examples/legends/panel.cpp
Kvazikot/VideoProjects
899cd047dd791b0e2f33d40cf6e11fe949333329
[ "MIT" ]
null
null
null
VideoCube/VideoCubeCV/libs/app7-master/3PartyLibs/qwt-6.1.4/examples/legends/panel.cpp
Kvazikot/VideoProjects
899cd047dd791b0e2f33d40cf6e11fe949333329
[ "MIT" ]
null
null
null
#include "panel.h" #include "settings.h" #include <qcheckbox.h> #include <qspinbox.h> #include <qcombobox.h> #include <qgroupbox.h> #include <qlayout.h> #include <qlabel.h> #include <qlineedit.h> #include <qwt_plot.h> #include <qwt_plot_legenditem.h> Panel::Panel( QWidget *parent ): QWidget( parent ) { // create widgets d_legend.checkBox = new QCheckBox( "Enabled" ); d_legend.positionBox = new QComboBox(); d_legend.positionBox->addItem( "Left", QwtPlot::LeftLegend ); d_legend.positionBox->addItem( "Right", QwtPlot::RightLegend ); d_legend.positionBox->addItem( "Bottom", QwtPlot::BottomLegend ); d_legend.positionBox->addItem( "Top", QwtPlot::TopLegend ); d_legend.positionBox->addItem( "External", QwtPlot::TopLegend + 1 ); d_legendItem.checkBox = new QCheckBox( "Enabled" ); d_legendItem.numColumnsBox = new QSpinBox(); d_legendItem.numColumnsBox->setRange( 0, 10 ); d_legendItem.numColumnsBox->setSpecialValueText( "Unlimited" ); d_legendItem.hAlignmentBox = new QComboBox(); d_legendItem.hAlignmentBox->addItem( "Left", Qt::AlignLeft ); d_legendItem.hAlignmentBox->addItem( "Centered", Qt::AlignHCenter ); d_legendItem.hAlignmentBox->addItem( "Right", Qt::AlignRight ); d_legendItem.vAlignmentBox = new QComboBox(); d_legendItem.vAlignmentBox->addItem( "Top", Qt::AlignTop ); d_legendItem.vAlignmentBox->addItem( "Centered", Qt::AlignVCenter ); d_legendItem.vAlignmentBox->addItem( "Bottom", Qt::AlignBottom ); d_legendItem.backgroundBox = new QComboBox(); d_legendItem.backgroundBox->addItem( "Legend", QwtPlotLegendItem::LegendBackground ); d_legendItem.backgroundBox->addItem( "Items", QwtPlotLegendItem::ItemBackground ); d_legendItem.sizeBox = new QSpinBox(); d_legendItem.sizeBox->setRange( 8, 22 ); d_curve.numCurves = new QSpinBox(); d_curve.numCurves->setRange( 0, 99 ); d_curve.title = new QLineEdit(); // layout QGroupBox *legendBox = new QGroupBox( "Legend" ); QGridLayout *legendBoxLayout = new QGridLayout( legendBox ); int row = 0; legendBoxLayout->addWidget( d_legend.checkBox, row, 0, 1, -1 ); row++; legendBoxLayout->addWidget( new QLabel( "Position" ), row, 0 ); legendBoxLayout->addWidget( d_legend.positionBox, row, 1 ); QGroupBox *legendItemBox = new QGroupBox( "Legend Item" ); QGridLayout *legendItemBoxLayout = new QGridLayout( legendItemBox ); row = 0; legendItemBoxLayout->addWidget( d_legendItem.checkBox, row, 0, 1, -1 ); row++; legendItemBoxLayout->addWidget( new QLabel( "Columns" ), row, 0 ); legendItemBoxLayout->addWidget( d_legendItem.numColumnsBox, row, 1 ); row++; legendItemBoxLayout->addWidget( new QLabel( "Horizontal" ), row, 0 ); legendItemBoxLayout->addWidget( d_legendItem.hAlignmentBox, row, 1 ); row++; legendItemBoxLayout->addWidget( new QLabel( "Vertical" ), row, 0 ); legendItemBoxLayout->addWidget( d_legendItem.vAlignmentBox, row, 1 ); row++; legendItemBoxLayout->addWidget( new QLabel( "Background" ), row, 0 ); legendItemBoxLayout->addWidget( d_legendItem.backgroundBox, row, 1 ); row++; legendItemBoxLayout->addWidget( new QLabel( "Size" ), row, 0 ); legendItemBoxLayout->addWidget( d_legendItem.sizeBox, row, 1 ); QGroupBox *curveBox = new QGroupBox( "Curves" ); QGridLayout *curveBoxLayout = new QGridLayout( curveBox ); row = 0; curveBoxLayout->addWidget( new QLabel( "Number" ), row, 0 ); curveBoxLayout->addWidget( d_curve.numCurves, row, 1 ); row++; curveBoxLayout->addWidget( new QLabel( "Title" ), row, 0 ); curveBoxLayout->addWidget( d_curve.title, row, 1 ); QVBoxLayout *layout = new QVBoxLayout( this ); layout->addWidget( legendBox ); layout->addWidget( legendItemBox ); layout->addWidget( curveBox ); layout->addStretch( 10 ); connect( d_legend.checkBox, SIGNAL( stateChanged( int ) ), SIGNAL( edited() ) ); connect( d_legend.positionBox, SIGNAL( currentIndexChanged( int ) ), SIGNAL( edited() ) ); connect( d_legendItem.checkBox, SIGNAL( stateChanged( int ) ), SIGNAL( edited() ) ); connect( d_legendItem.numColumnsBox, SIGNAL( valueChanged( int ) ), SIGNAL( edited() ) ); connect( d_legendItem.hAlignmentBox, SIGNAL( currentIndexChanged( int ) ), SIGNAL( edited() ) ); connect( d_legendItem.vAlignmentBox, SIGNAL( currentIndexChanged( int ) ), SIGNAL( edited() ) ); connect( d_legendItem.backgroundBox, SIGNAL( currentIndexChanged( int ) ), SIGNAL( edited() ) ); connect( d_curve.numCurves, SIGNAL( valueChanged( int ) ), SIGNAL( edited() ) ); connect( d_legendItem.sizeBox, SIGNAL( valueChanged( int ) ), SIGNAL( edited() ) ); connect( d_curve.title, SIGNAL( textEdited( const QString & ) ), SIGNAL( edited() ) ); } void Panel::setSettings( const Settings &settings) { blockSignals( true ); d_legend.checkBox->setCheckState( settings.legend.isEnabled ? Qt::Checked : Qt::Unchecked ); d_legend.positionBox->setCurrentIndex( settings.legend.position ); d_legendItem.checkBox->setCheckState( settings.legendItem.isEnabled ? Qt::Checked : Qt::Unchecked ); d_legendItem.numColumnsBox->setValue( settings.legendItem.numColumns ); int align = settings.legendItem.alignment; if ( align & Qt::AlignLeft ) d_legendItem.hAlignmentBox->setCurrentIndex( 0 ); else if ( align & Qt::AlignRight ) d_legendItem.hAlignmentBox->setCurrentIndex( 2 ); else d_legendItem.hAlignmentBox->setCurrentIndex( 1 ); if ( align & Qt::AlignTop ) d_legendItem.vAlignmentBox->setCurrentIndex( 0 ); else if ( align & Qt::AlignBottom ) d_legendItem.vAlignmentBox->setCurrentIndex( 2 ); else d_legendItem.vAlignmentBox->setCurrentIndex( 1 ); d_legendItem.backgroundBox->setCurrentIndex( settings.legendItem.backgroundMode ); d_legendItem.sizeBox->setValue( settings.legendItem.size ); d_curve.numCurves->setValue( settings.curve.numCurves ); d_curve.title->setText( settings.curve.title ); blockSignals( false ); } Settings Panel::settings() const { Settings s; s.legend.isEnabled = d_legend.checkBox->checkState() == Qt::Checked; s.legend.position = d_legend.positionBox->currentIndex(); s.legendItem.isEnabled = d_legendItem.checkBox->checkState() == Qt::Checked; s.legendItem.numColumns = d_legendItem.numColumnsBox->value(); int align = 0; int hIndex = d_legendItem.hAlignmentBox->currentIndex(); if ( hIndex == 0 ) align |= Qt::AlignLeft; else if ( hIndex == 2 ) align |= Qt::AlignRight; else align |= Qt::AlignHCenter; int vIndex = d_legendItem.vAlignmentBox->currentIndex(); if ( vIndex == 0 ) align |= Qt::AlignTop; else if ( vIndex == 2 ) align |= Qt::AlignBottom; else align |= Qt::AlignVCenter; s.legendItem.alignment = align; s.legendItem.backgroundMode = d_legendItem.backgroundBox->currentIndex(); s.legendItem.size = d_legendItem.sizeBox->value(); s.curve.numCurves = d_curve.numCurves->value(); s.curve.title = d_curve.title->text(); return s; }
33.930876
75
0.674046
Kvazikot
9da3b09e1a93b0754c74478164e21ecc778a5ab5
3,174
cpp
C++
files/win32/MyProgram.cpp
keejelo/c_cpp_wrappers
d330999319effe88b6279fbc84de0db5a2da04fe
[ "MIT" ]
null
null
null
files/win32/MyProgram.cpp
keejelo/c_cpp_wrappers
d330999319effe88b6279fbc84de0db5a2da04fe
[ "MIT" ]
null
null
null
files/win32/MyProgram.cpp
keejelo/c_cpp_wrappers
d330999319effe88b6279fbc84de0db5a2da04fe
[ "MIT" ]
null
null
null
//--------------------------------------------------------------------------------------------- // ** MyProgram.cpp (template) //--------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------- // ** INCLUDE FILES //--------------------------------------------------------------------------------------------- #include "resource.h" #include "MyProgram.h" //--------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------- // ** VARIABLES //--------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------- // ** FUNCTIONS //--------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------- // ** OnCreate //--------------------------------------------------------------------------------------------- void OnCreate(HWND hWnd) { // ..add controls etc. }; //--------------------------------------------------------------------------------------------- // ** END: OnCreate //--------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------- // ** OnMouseButtonClick //--------------------------------------------------------------------------------------------- void OnMouseButtonClick(HWND hWnd, HWND hBtnCtrl) { // ** Check which button was clicked /* if (hBtnCtrl == hBtnOk) { // The OK button was clicked } else if (hBtnCtrl == hBtnCancel) { // The Cancel button was clicked } */ }; //--------------------------------------------------------------------------------------------- // ** END: OnMouseButtonClick //--------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------- // ** OnPaint //--------------------------------------------------------------------------------------------- void OnPaint(HWND hWnd) { }; //--------------------------------------------------------------------------------------------- // ** END: OnPaint //--------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------- // ** OnQuit //--------------------------------------------------------------------------------------------- void OnQuit() { }; //--------------------------------------------------------------------------------------------- // ** END: OnQuit //---------------------------------------------------------------------------------------------
37.341176
96
0.122873
keejelo
9da7e5986a644987832bbb833567d0a0ae347426
1,152
cpp
C++
Leetcode/String/sort-characters-by-frequency.cpp
susantabiswas/competitive_coding
49163ecdc81b68f5c1bd90988cc0dfac34ad5a31
[ "MIT" ]
2
2021-04-29T14:44:17.000Z
2021-10-01T17:33:22.000Z
Leetcode/String/sort-characters-by-frequency.cpp
adibyte95/competitive_coding
a6f084d71644606c21840875bad78d99f678a89d
[ "MIT" ]
null
null
null
Leetcode/String/sort-characters-by-frequency.cpp
adibyte95/competitive_coding
a6f084d71644606c21840875bad78d99f678a89d
[ "MIT" ]
1
2021-10-01T17:33:29.000Z
2021-10-01T17:33:29.000Z
/* https://leetcode.com/problems/sort-characters-by-frequency/ TC: O(N), SC: O(1) Sorting 256 chars is constant + linear traversal */ class Solution { public: string frequencySort(string s) { // (char, frequency) vector<pair<int, int>> char_freq(256); for(int i = 0; i < char_freq.size(); i++) { char_freq[i].first = i; char_freq[i].second = 0; } // for each char, store its frequency for(const char &c: s) char_freq[c].second += 1; // sort the chars based on their frequencies sort(char_freq.begin(), char_freq.end(), [](const pair<int, int>& a, const pair<int, int>& b) { return a.second > b.second; }); string result; for(int i = 0; i < char_freq.size(); i++) // if current char is present in string if(char_freq[i].second) { char c = char_freq[i].first; // add the chars while(char_freq[i].second--) result += c; } return result; } };
29.538462
67
0.493924
susantabiswas
9da85d29f03c6d235c353b11fc41eb1872a07c5e
692
cpp
C++
Tools/file/Archive.cpp
liangjisheng/C-Cpp
8b33ba1f43580a7bdded8bb4ce3d92983ccedb81
[ "MIT" ]
5
2019-09-17T09:12:15.000Z
2021-05-29T10:54:39.000Z
Tools/file/Archive.cpp
liangjisheng/C-Cpp
8b33ba1f43580a7bdded8bb4ce3d92983ccedb81
[ "MIT" ]
null
null
null
Tools/file/Archive.cpp
liangjisheng/C-Cpp
8b33ba1f43580a7bdded8bb4ce3d92983ccedb81
[ "MIT" ]
2
2021-07-26T06:36:12.000Z
2022-01-23T15:20:30.000Z
void CArchiveDlg::OnButtonWrite() { CFile file("demo.txt", CFile::modeCreate | CFile::modeWrite); CArchive ar(&file,CArchive::store); // 定义一个存档对象 int idata = 100; char ch = 'a'; double fdata = 12.12; CString str = "lishuyu"; ar << idata << ch << fdata << str; // 写入数据 MessageBox("Write success", "title",MB_OKCANCEL | MB_ICONINFORMATION); } void CArchiveDlg::OnButtonRead() { CFile file("demo.txt", CFile::modeRead); CArchive ar(&file,CArchive::load); int idata; char ch; double fdata; CString str; ar >> idata >> ch >> fdata >> str; CString strText; strText.Format("%d,%c,%lf,%s", idata, ch, fdata, str); MessageBox(strText, "title", MB_OKCANCEL | MB_ICONINFORMATION); }
26.615385
71
0.674855
liangjisheng
9dabe1d4d4d94f67d267e0d54f58eb76c97c761c
536
cpp
C++
DecodeWays.cpp
yplusplus/LeetCode
122bd31b291af1e97ee4e9349a8e65bba6e04c96
[ "MIT" ]
3
2017-11-27T03:01:50.000Z
2021-03-13T08:14:00.000Z
DecodeWays.cpp
yplusplus/LeetCode
122bd31b291af1e97ee4e9349a8e65bba6e04c96
[ "MIT" ]
null
null
null
DecodeWays.cpp
yplusplus/LeetCode
122bd31b291af1e97ee4e9349a8e65bba6e04c96
[ "MIT" ]
null
null
null
class Solution { public: bool check(char a, char b) { if (a == '1') return true; if (a == '2' && b <= '6') return true; return false; } int numDecodings(string s) { if (s.length() == 0) return 0; vector<int> dp(s.length() + 1, 0); dp[0] = 1; for (int i = 1; i <= s.length(); i++) { if (s[i - 1] != '0') dp[i] += dp[i - 1]; if (i >= 2 && check(s[i - 2], s[i - 1])) dp[i] += dp[i - 2]; } return dp.back(); } };
28.210526
52
0.384328
yplusplus
9dae75ade553c29842a0fc35a9b07e7ad7a74d16
1,369
cpp
C++
CProgramming/Syntax (Lab 8)/Syntax/Syntax.cpp
KvanTTT/Education
e9dc00bfc25ccf0e25c4e7ec187bccb680f126f9
[ "MIT" ]
1
2018-04-06T19:47:37.000Z
2018-04-06T19:47:37.000Z
CProgramming/Syntax (Lab 8)/Syntax/Syntax.cpp
KvanTTT/Education
e9dc00bfc25ccf0e25c4e7ec187bccb680f126f9
[ "MIT" ]
null
null
null
CProgramming/Syntax (Lab 8)/Syntax/Syntax.cpp
KvanTTT/Education
e9dc00bfc25ccf0e25c4e7ec187bccb680f126f9
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "pol.h" #include <iostream> using namespace std; int enter_size(); char *enter_symbols(int &size); int *enter_numbers(int &size); char *enter_expression(); void main(void) { int size; char *str = NULL; char *dstr = NULL; char *symbols = NULL; int *numbers = NULL; while (1) { size = enter_size(); symbols = enter_symbols(size); numbers = enter_numbers(size); str = enter_expression(); dstr = replace(str, symbols, numbers); cout << "\nExpression with replaced coefs and deleted spaces: " << dstr; cout << "\nResult = " << solve(dstr); cout << "\n**************************************************\n\n"; delete str; delete symbols; } } int enter_size() { int result; cout << "Enter count of symbols: "; cin >> result; return result; } char *enter_symbols(int &size) { char *result = new char[size]; result = new char[size]; cout << "Enter " << size << " symbols: "; for (int i = 0; i < size; i++) cin >> result[i]; return result; } int *enter_numbers(int &size) { int *result = new int[size]; cout << "Enter " << size << " coefs: "; for (int i = 0; i < size; i++) cin >> result[i]; return result; } char *enter_expression() { char *result = new char[MAX_LENGTH]; cout << "Enter expression: "; cin >> result; //*dstr = replace(str, symbols, numbers); return result; }
17.551282
75
0.598247
KvanTTT
9db771ef7a346888dc281b44f5ba4945dd06e884
410
hpp
C++
Oscillators/SinWave.hpp
jamestiller/Rain
1e55d90065be7ada9455029ad735dd285e7d2266
[ "Zlib" ]
1
2016-04-05T12:20:47.000Z
2016-04-05T12:20:47.000Z
Oscillators/SinWave.hpp
jamestiller/Rain
1e55d90065be7ada9455029ad735dd285e7d2266
[ "Zlib" ]
null
null
null
Oscillators/SinWave.hpp
jamestiller/Rain
1e55d90065be7ada9455029ad735dd285e7d2266
[ "Zlib" ]
null
null
null
// // SinWave.hpp // Rain // // Created by James Tiller on 2/25/16. // // #ifndef SinWave_hpp #define SinWave_hpp #include <stdio.h> #include "IWave.hpp" class SinWave : public IWave { public: friend class Oscillator; protected: SinWave() : IWave() { updateIncrement(); }; virtual void generate(double* buffer, int nFrames); virtual double nextSample(); }; #endif /* SinWave_hpp */
14.642857
55
0.656098
jamestiller
9dbc3fea2fb7076bf8259d701c1e6dfb5a07ef6a
1,816
cpp
C++
EditWidgets/CheckBox.cpp
sielicki/PothosFlow
61487651f3718fc75fd2da6ef36e90c8537c8dd3
[ "BSL-1.0" ]
null
null
null
EditWidgets/CheckBox.cpp
sielicki/PothosFlow
61487651f3718fc75fd2da6ef36e90c8537c8dd3
[ "BSL-1.0" ]
null
null
null
EditWidgets/CheckBox.cpp
sielicki/PothosFlow
61487651f3718fc75fd2da6ef36e90c8537c8dd3
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2017-2017 Josh Blum // SPDX-License-Identifier: BSL-1.0 #include <Pothos/Plugin.hpp> #include <QJsonObject> #include <QJsonArray> #include <QCheckBox> /*********************************************************************** * Check box with labels **********************************************************************/ class CheckBox : public QCheckBox { Q_OBJECT public: CheckBox(QWidget *parent, const QString &onText, const QString &offText): QCheckBox(parent), _onText(onText), _offText(offText) { connect(this, SIGNAL(toggled(bool)), this, SLOT(handleToggled(bool))); } public slots: QString value(void) const { return this->isChecked()?"true":"false"; } void setValue(const QString &s) { this->setChecked(s=="true"); this->updateText(s=="true"); } signals: void commitRequested(void); void widgetChanged(void); void entryChanged(void); private slots: void handleToggled(const bool checked) { this->updateText(checked); emit this->entryChanged(); } private: void updateText(const bool checked) { this->setText(checked?_onText:_offText); } const QString _onText; const QString _offText; }; /*********************************************************************** * Factory function and registration **********************************************************************/ static QWidget *makeCheckBox(const QJsonArray &, const QJsonObject &kwargs, QWidget *parent) { return new CheckBox(parent, kwargs["on"].toString(), kwargs["off"].toString()); } pothos_static_block(registerCheckBox) { Pothos::PluginRegistry::add("/flow/EntryWidgets/CheckBox", Pothos::Callable(&makeCheckBox)); } #include "CheckBox.moc"
25.222222
96
0.558921
sielicki
9dbe6c9252209cf4541f8b45480ebf5f62357b67
1,585
cc
C++
test.cc
raymond-w-ko/xkokokeys
45a2a4b8cd6964c5f623bf09b4918fe113fda559
[ "MIT" ]
null
null
null
test.cc
raymond-w-ko/xkokokeys
45a2a4b8cd6964c5f623bf09b4918fe113fda559
[ "MIT" ]
null
null
null
test.cc
raymond-w-ko/xkokokeys
45a2a4b8cd6964c5f623bf09b4918fe113fda559
[ "MIT" ]
null
null
null
#include <cstdio> #include <cstdlib> #include <cstring> #include <fcntl.h> #include <linux/input.h> #include <linux/uinput.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> class VirtualKeyboard { public: VirtualKeyboard() { ssize_t ret; fd_ = open("/dev/uinput", O_WRONLY | O_NONBLOCK); if (fd_ < 0) { exit(EXIT_FAILURE); } struct uinput_user_dev uidev; memset(&uidev, 0, sizeof(uidev)); snprintf(uidev.name, UINPUT_MAX_NAME_SIZE, "Virtual uinput Keyboard"); uidev.id.bustype = BUS_USB; uidev.id.vendor = 0x01; uidev.id.product = 0x01; uidev.id.version = 1; ret = ioctl(fd_, UI_SET_EVBIT, EV_KEY); for (int i = 0; i < 255; ++i) { ret = ioctl(fd_, UI_SET_KEYBIT, i); } ret = ioctl(fd_, UI_SET_EVBIT, EV_SYN); ret = write(fd_, &uidev, sizeof(uidev)); ret = ioctl(fd_, UI_DEV_CREATE); sleep(1); if (ret) { ret = 0; } } ~VirtualKeyboard() { ssize_t ret; ret = ioctl(fd_, UI_DEV_DESTROY); sleep(1); if (ret) { ret = 0; } } void TypeKey() { ssize_t ret; struct input_event ev; memset(&ev, 0, sizeof(ev)); ev.type = EV_KEY; ev.code = KEY_Q; ev.value = 1; ret = write(fd_, &ev, sizeof(ev)); ev.value = 0; ret = write(fd_, &ev, sizeof(ev)); ev.type = EV_SYN; ev.code = 0; ev.value = 0; ret = write(fd_, &ev, sizeof(ev)); if (ret) { ret = 0; } } private: int fd_; }; int main() { { VirtualKeyboard keyboard; keyboard.TypeKey(); } return 0; }
18.218391
74
0.572871
raymond-w-ko
9dbf7f57d091a57739a12ce9e64c5061e73216ad
3,886
cpp
C++
third_party/WebKit/Source/bindings/core/v8/JSONValuesForV8.cpp
Wzzzx/chromium-crosswalk
768dde8efa71169f1c1113ca6ef322f1e8c9e7de
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2019-01-28T08:09:58.000Z
2021-11-15T15:32:10.000Z
third_party/WebKit/Source/bindings/core/v8/JSONValuesForV8.cpp
maidiHaitai/haitaibrowser
a232a56bcfb177913a14210e7733e0ea83a6b18d
[ "BSD-3-Clause" ]
null
null
null
third_party/WebKit/Source/bindings/core/v8/JSONValuesForV8.cpp
maidiHaitai/haitaibrowser
a232a56bcfb177913a14210e7733e0ea83a6b18d
[ "BSD-3-Clause" ]
6
2020-09-23T08:56:12.000Z
2021-11-18T03:40:49.000Z
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "bindings/core/v8/JSONValuesForV8.h" #include "bindings/core/v8/ExceptionState.h" #include "bindings/core/v8/ScriptState.h" #include "bindings/core/v8/V8Binding.h" namespace blink { static String coreString(v8::Local<v8::String> v8String) { int length = v8String->Length(); UChar* buffer; String result = String::createUninitialized(length, buffer); v8String->Write(reinterpret_cast<uint16_t*>(buffer), 0, length); return result; } PassRefPtr<JSONValue> toJSONValue(v8::Local<v8::Context> context, v8::Local<v8::Value> value, int maxDepth) { if (value.IsEmpty()) { ASSERT_NOT_REACHED(); return nullptr; } if (!maxDepth) return nullptr; maxDepth--; if (value->IsNull() || value->IsUndefined()) return JSONValue::null(); if (value->IsBoolean()) return JSONBasicValue::create(value.As<v8::Boolean>()->Value()); if (value->IsNumber()) return JSONBasicValue::create(value.As<v8::Number>()->Value()); if (value->IsString()) return JSONString::create(coreString(value.As<v8::String>())); if (value->IsArray()) { v8::Local<v8::Array> array = value.As<v8::Array>(); RefPtr<JSONArray> inspectorArray = JSONArray::create(); uint32_t length = array->Length(); for (uint32_t i = 0; i < length; i++) { v8::Local<v8::Value> value; if (!array->Get(context, i).ToLocal(&value)) return nullptr; RefPtr<JSONValue> element = toJSONValue(context, value, maxDepth); if (!element) return nullptr; inspectorArray->pushValue(element); } return inspectorArray; } if (value->IsObject()) { RefPtr<JSONObject> jsonObject = JSONObject::create(); v8::Local<v8::Object> object = v8::Local<v8::Object>::Cast(value); v8::Local<v8::Array> propertyNames; if (!object->GetPropertyNames(context).ToLocal(&propertyNames)) return nullptr; uint32_t length = propertyNames->Length(); for (uint32_t i = 0; i < length; i++) { v8::Local<v8::Value> name; if (!propertyNames->Get(context, i).ToLocal(&name)) return nullptr; // FIXME(yurys): v8::Object should support GetOwnPropertyNames if (name->IsString()) { v8::Maybe<bool> hasRealNamedProperty = object->HasRealNamedProperty(context, v8::Local<v8::String>::Cast(name)); if (!hasRealNamedProperty.IsJust() || !hasRealNamedProperty.FromJust()) continue; } v8::Local<v8::String> propertyName; if (!name->ToString(context).ToLocal(&propertyName)) continue; v8::Local<v8::Value> property; if (!object->Get(context, name).ToLocal(&property)) return nullptr; RefPtr<JSONValue> propertyValue = toJSONValue(context, property, maxDepth); if (!propertyValue) return nullptr; jsonObject->setValue(coreString(propertyName), propertyValue); } return jsonObject; } ASSERT_NOT_REACHED(); return nullptr; } v8::Local<v8::Value> fromJSONString(ScriptState* scriptState, const String& stringifiedJSON, ExceptionState& exceptionState) { v8::Isolate* isolate = scriptState->isolate(); v8::Local<v8::Value> parsed; v8::TryCatch tryCatch(isolate); if (!v8Call(v8::JSON::Parse(isolate, v8String(isolate, stringifiedJSON)), parsed, tryCatch)) { if (tryCatch.HasCaught()) exceptionState.rethrowV8Exception(tryCatch.Exception()); } return parsed; } } // namespace blink
37.365385
128
0.61683
Wzzzx
9dc08595b6810d6047ae90db9126288b77ddc439
1,009
cpp
C++
Algorithm/ACM/Orientation Training Round #2 Div.3/A.cpp
XJDKC/University-Code-Archive
2dd9c6edb2164540dc50db1bb94940fe53c6eba0
[ "MIT" ]
4
2019-04-01T17:33:38.000Z
2022-01-08T04:07:52.000Z
Algorithm/ACM/Orientation Training Round #2 Div.3/A.cpp
XJDKC/University-Code-Archive
2dd9c6edb2164540dc50db1bb94940fe53c6eba0
[ "MIT" ]
null
null
null
Algorithm/ACM/Orientation Training Round #2 Div.3/A.cpp
XJDKC/University-Code-Archive
2dd9c6edb2164540dc50db1bb94940fe53c6eba0
[ "MIT" ]
1
2021-01-06T11:04:31.000Z
2021-01-06T11:04:31.000Z
#include<iostream> #include<cstdio> #include<algorithm> #include<cstring> using namespace std; int n,k,ans; bool map[8][8],used[8]; void dfs(int row,int num) { if (num==k) { ans++; return ; } else if (row>=n) return ; else if (num+n-row<k) return ; else { if (row+1<n) dfs(row+1,num); for (int i=0;i<n;i++) { if (map[row][i]&&!used[i]) { used[i]=true; dfs(row+1,num+1); used[i]=false; } } } } int main() { char c; while (cin>>n>>k&&n!=-1&&k!=-1) { getchar(); ans=0; memset(map,0,sizeof(map)); memset(used,0,sizeof(used)); for (int i=0;i<n;i++) { for (int j=0;j<n;j++) { scanf("%c",&c); map[i][j]=c=='.'?false:true; } getchar(); } dfs(0,0); printf("%d\n",ans); } return 0; }
19.037736
44
0.390486
XJDKC
9dc3596075ad8409b242741de5bd33f0a24724ef
3,164
hpp
C++
myvector.hpp
mino2357/Hello_OpenSiv3D
c12cdc08da63d5d3d4ab377e8aa32d69167ed0eb
[ "MIT" ]
null
null
null
myvector.hpp
mino2357/Hello_OpenSiv3D
c12cdc08da63d5d3d4ab377e8aa32d69167ed0eb
[ "MIT" ]
1
2017-07-01T15:26:42.000Z
2018-04-23T08:25:49.000Z
myvector.hpp
mino2357/Hello_OpenSiv3D
c12cdc08da63d5d3d4ab377e8aa32d69167ed0eb
[ "MIT" ]
null
null
null
#include <iostream> #include <limits> #include <iomanip> #include <cmath> namespace mino2357{ template<typename T = double> class vector{ private: T componentX; T componentY; public: vector(T x, T y) noexcept : componentX(x), componentY(y) {} vector() noexcept : vector{T{}, T{}} {} inline void setComponetX(T) noexcept; inline void setComponetY(T) noexcept; inline T getComponentX() const noexcept; inline T getComponentY() const noexcept; inline vector& operator=( const vector<T>&) noexcept; inline vector& operator+=(const vector<T>&) noexcept; inline vector& operator-=(const vector<T>&) noexcept; inline T norm() noexcept; inline void printPosition() noexcept; }; template <typename T> inline void vector<T>::setComponetX(T x) noexcept { componentX = x; } template <typename T> inline void vector<T>::setComponetY(T y) noexcept { componentY = y; } template <typename T> inline T vector<T>::getComponentX() const noexcept { return this->componentX; } template <typename T> inline T vector<T>::getComponentY() const noexcept { return this->componentY; } template <typename T> inline void vector<T>::printPosition() noexcept{ std::cout << std::fixed << std::setprecision(std::numeric_limits<double>::digits10 + 1); std::cout << componentX << " " << componentY << std::endl; } template <typename T> inline vector<T>& vector<T>::operator=(const vector<T>& v) noexcept { this->componentX = v.getComponentX(); this->componentY = v.getComponentY(); return *this; } template <typename T> inline vector<T>& vector<T>::operator+=(const vector<T>& v) noexcept { this->componentX += v.getComponentX(); this->componentY += v.getComponentY(); return *this; } template <typename T> inline vector<T>& vector<T>::operator-=(const vector<T>& v) noexcept { this->componentX -= v.getComponentX(); this->componentY -= v.getComponentY(); return *this; } template <typename T> inline T vector<T>::norm() noexcept { return std::sqrt(componentX * componentX + componentY * componentY); } template <typename T> inline vector<T> operator+(const vector<T>& a, const vector<T>& b) noexcept { return vector<T>{ a.getComponentX() + b.getComponentX(), a.getComponentY() + b.getComponentY(), }; } template <typename T> inline vector<T> operator-(const vector<T>& a, const vector<T>& b) noexcept { return vector<T>{ a.getComponentX() - b.getComponentX(), a.getComponentY() - b.getComponentY(), }; } template <typename T> inline T operator*(const vector<T>& a, const vector<T>& b) noexcept { return a.getComponentX() * b.getComponentX() + a.getComponentY() * b.getComponentY(); } }
29.849057
96
0.581858
mino2357
9dc4bb85ccbfb05f0735589c059e53852a1be17a
6,901
hpp
C++
include/boost/cgi/cgi/request_service.hpp
Sil3ntStorm/libtelegram
a0c52ba4aac5519a3031dba506ad4a64cd8fca83
[ "MIT" ]
118
2016-10-02T10:49:02.000Z
2022-03-23T14:32:05.000Z
include/boost/cgi/cgi/request_service.hpp
Sil3ntStorm/libtelegram
a0c52ba4aac5519a3031dba506ad4a64cd8fca83
[ "MIT" ]
21
2017-04-21T13:34:36.000Z
2021-12-08T17:00:40.000Z
include/boost/cgi/cgi/request_service.hpp
Sil3ntStorm/libtelegram
a0c52ba4aac5519a3031dba506ad4a64cd8fca83
[ "MIT" ]
35
2016-06-08T15:31:03.000Z
2022-03-23T16:43:28.000Z
// -- cgi_service_impl.hpp -- // // Copyright (c) Darren Garvey 2007-2009. // 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 CGI_CGI_SERVICE_IMPL_HPP_INCLUDED__ #define CGI_CGI_SERVICE_IMPL_HPP_INCLUDED__ #include "boost/cgi/detail/push_options.hpp" #include "boost/cgi/common/tags.hpp" #include "boost/cgi/common/map.hpp" #include "boost/cgi/import/io_service.hpp" #include "boost/cgi/detail/service_base.hpp" #include "boost/cgi/detail/extract_params.hpp" #include "boost/cgi/connections/async_stdio.hpp" #include <boost/bind.hpp> #include <boost/assert.hpp> #include <boost/regex.hpp> #include <boost/tokenizer.hpp> #include <boost/lexical_cast.hpp> #include <boost/version.hpp> #include <boost/system/error_code.hpp> #include <boost/algorithm/string/find.hpp> /////////////////////////////////////////////////////////// #include "boost/cgi/common/map.hpp" #include "boost/cgi/basic_client.hpp" #include "boost/cgi/common/is_async.hpp" #include "boost/cgi/common/role_type.hpp" #include "boost/cgi/common/form_part.hpp" #include "boost/cgi/detail/throw_error.hpp" #include "boost/cgi/common/form_parser.hpp" #include "boost/cgi/common/request_base.hpp" #include "boost/cgi/common/parse_options.hpp" #include "boost/cgi/common/request_status.hpp" #include "boost/cgi/connections/async_stdio.hpp" #include "boost/cgi/detail/extract_params.hpp" #include "boost/cgi/detail/save_environment.hpp" BOOST_CGI_NAMESPACE_BEGIN class cgi_request_service : public common::request_base<common::tags::cgi> , public detail::service_base<cgi_request_service> { public: typedef common::tags::cgi protocol_type; typedef cgi_service protocol_service_type; typedef cgi_request_service self_type; struct implementation_type : base_type::impl_base { implementation_type() : stdin_data_read_(false) , stdin_bytes_left_(-1) { } protocol_service_type* service_; conn_ptr& connection() { return connection_; } bool stdin_data_read_; std::size_t stdin_bytes_left_; conn_ptr connection_; }; template<typename Service> struct callback_functor { callback_functor(implementation_type& impl, Service* service) : impl_(impl) , service_(service) { } std::size_t operator()(boost::system::error_code& ec) { return service_->read_some(impl_, ec); } private: implementation_type& impl_; Service* service_; }; cgi_request_service(common::io_context& ios) : detail::service_base<cgi_request_service>(ios) { } void construct(implementation_type& impl) { impl.client_.set_connection( connection_type::create(this->get_io_context()) ); } void shutdown_service() { } void clear(implementation_type& impl) { } int request_id(implementation_type& impl) { return 1; } /// Close the request. int close(implementation_type& impl, common::http::status_code http_s = http::ok , int program_status = 0) { int s(0); boost::system::error_code ec; s = close(impl, http_s, program_status, ec); detail::throw_error(ec); return s; } /// Close the request. int close(implementation_type& impl, common::http::status_code http_s , int program_status, boost::system::error_code& ec) { status(impl, common::closed); impl.http_status() = http_s; impl.all_done_ = true; return program_status; } /// Synchronously read/parse the request data boost::system::error_code& load(implementation_type& impl, common::parse_options parse_opts , boost::system::error_code& ec) { if (parse_opts & common::parse_env) { if (read_env_vars(impl, ec)) // returns an error_code return ec; } std::string const& cl = env_vars(impl.vars_)["CONTENT_LENGTH"]; impl.bytes_left_ = cl.empty() ? 0 : boost::lexical_cast<std::size_t>(cl); impl.client_.bytes_left() = impl.bytes_left_; std::string const& request_method = env_vars(impl.vars_)["REQUEST_METHOD"]; if ((request_method == "GET" || request_method == "HEAD") && parse_opts > common::parse_env && parse_opts & common::parse_get_only) { parse_get_vars(impl, ec); } else if ((request_method == "POST" || request_method == "PUT") && (parse_opts & common::parse_post_only)) { parse_post_vars(impl, ec); } if (ec) return ec; if (parse_opts & common::parse_cookie_only) { if (parse_cookie_vars(impl, "HTTP_COOKIE", ec)) // returns an error_code return ec; } status(impl, common::loaded); return ec; } /// CGI is always a responser. common::role_type role(implementation_type const& impl) const { return common::responder; } std::size_t read_some(implementation_type& impl, boost::system::error_code& ec) { return impl.client_.read_some(impl.prepare(64), ec); } protected: /// Read the environment variables into an internal map. template<typename RequestImpl> boost::system::error_code read_env_vars(RequestImpl& impl, boost::system::error_code& ec) { // Only call this once. if (!(status(impl) & common::env_read)) { detail::save_environment(env_vars(impl.vars_)); status(impl, (common::request_status)(status(impl) | common::env_read)); } return ec; } /// Read and parse the cgi POST meta variables (greedily) template<typename RequestImpl> boost::system::error_code parse_post_vars(RequestImpl& impl, boost::system::error_code& ec) { // **FIXME** use callback_functor<> in form_parser instead. std::size_t& bytes_left (impl.client_.bytes_left_); std::size_t bytes_read (0); do { bytes_read = read_some(impl, ec); bytes_left -= bytes_read; } while (!ec && bytes_left); // Return an error, except ignore EOF, as this is expected. if (ec) { if (ec == boost::cgi::common::error::eof) ec = boost::system::error_code(); else return ec; } return base_type::parse_post_vars( impl, callback_functor<self_type>(impl, this), ec ); } }; BOOST_CGI_NAMESPACE_END #include "boost/cgi/detail/pop_options.hpp" #endif // CGI_CGI_SERVICE_IMPL_HPP_INCLUDED__
28.167347
80
0.62759
Sil3ntStorm
9dc50cef694ae9903ab16d4a6a3f88eafe7f37c5
24,661
cpp
C++
src/third_party/mozjs/extract/js/src/jsfriendapi.cpp
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
src/third_party/mozjs/extract/js/src/jsfriendapi.cpp
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
src/third_party/mozjs/extract/js/src/jsfriendapi.cpp
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- * vim: set ts=8 sts=2 et sw=2 tw=80: * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "jsfriendapi.h" #include "mozilla/Atomics.h" #include "mozilla/Maybe.h" #include "mozilla/PodOperations.h" #include "mozilla/TimeStamp.h" #include <stdint.h> #include "builtin/BigInt.h" #include "builtin/MapObject.h" #include "builtin/TestingFunctions.h" #include "gc/GC.h" #include "gc/PublicIterators.h" #include "gc/WeakMap.h" #include "js/CharacterEncoding.h" #include "js/experimental/CodeCoverage.h" #include "js/experimental/CTypes.h" // JS::AutoCTypesActivityCallback, JS::SetCTypesActivityCallback #include "js/experimental/Intl.h" // JS::AddMoz{DateTimeFormat,DisplayNames}Constructor #include "js/friend/ErrorMessages.h" // js::GetErrorMessage, JSMSG_* #include "js/friend/StackLimits.h" // JS_STACK_GROWTH_DIRECTION #include "js/friend/WindowProxy.h" // js::ToWindowIfWindowProxy #include "js/Object.h" // JS::GetClass #include "js/Printf.h" #include "js/Proxy.h" #include "js/shadow/Object.h" // JS::shadow::Object #include "js/String.h" // JS::detail::StringToLinearStringSlow #include "js/Wrapper.h" #include "proxy/DeadObjectProxy.h" #include "util/Poison.h" #include "vm/ArgumentsObject.h" #include "vm/BooleanObject.h" #include "vm/DateObject.h" #include "vm/ErrorObject.h" #include "vm/FrameIter.h" // js::FrameIter #include "vm/JSContext.h" #include "vm/JSObject.h" #include "vm/NumberObject.h" #include "vm/PlainObject.h" // js::PlainObject #include "vm/Printer.h" #include "vm/PromiseObject.h" // js::PromiseObject #include "vm/Realm.h" #include "vm/StringObject.h" #include "vm/Time.h" #include "vm/WrapperObject.h" #include "gc/Nursery-inl.h" #include "vm/Compartment-inl.h" // JS::Compartment::wrap #include "vm/EnvironmentObject-inl.h" #include "vm/JSObject-inl.h" #include "vm/JSScript-inl.h" #include "vm/NativeObject-inl.h" using namespace js; using mozilla::PodArrayZero; JS::RootingContext::RootingContext() : realm_(nullptr), zone_(nullptr) { for (auto& listHead : stackRoots_) { listHead = nullptr; } for (auto& listHead : autoGCRooters_) { listHead = nullptr; } PodArrayZero(nativeStackLimit); #if JS_STACK_GROWTH_DIRECTION > 0 for (int i = 0; i < StackKindCount; i++) { nativeStackLimit[i] = UINTPTR_MAX; } #endif } JS_PUBLIC_API void JS_SetGrayGCRootsTracer(JSContext* cx, JSTraceDataOp traceOp, void* data) { cx->runtime()->gc.setGrayRootsTracer(traceOp, data); } JS_PUBLIC_API JSObject* JS_FindCompilationScope(JSContext* cx, HandleObject objArg) { cx->check(objArg); RootedObject obj(cx, objArg); /* * We unwrap wrappers here. This is a little weird, but it's what's being * asked of us. */ if (obj->is<WrapperObject>()) { obj = UncheckedUnwrap(obj); } /* * Get the Window if `obj` is a WindowProxy so that we compile in the * correct (global) scope. */ return ToWindowIfWindowProxy(obj); } JS_PUBLIC_API JSFunction* JS_GetObjectFunction(JSObject* obj) { if (obj->is<JSFunction>()) { return &obj->as<JSFunction>(); } return nullptr; } JS_PUBLIC_API JSObject* JS_NewObjectWithoutMetadata( JSContext* cx, const JSClass* clasp, JS::Handle<JSObject*> proto) { cx->check(proto); AutoSuppressAllocationMetadataBuilder suppressMetadata(cx); return JS_NewObjectWithGivenProto(cx, clasp, proto); } JS_PUBLIC_API bool JS::GetIsSecureContext(JS::Realm* realm) { return realm->creationOptions().secureContext(); } JS_PUBLIC_API JSPrincipals* JS::GetRealmPrincipals(JS::Realm* realm) { return realm->principals(); } JS_PUBLIC_API void JS::SetRealmPrincipals(JS::Realm* realm, JSPrincipals* principals) { // Short circuit if there's no change. if (principals == realm->principals()) { return; } // We'd like to assert that our new principals is always same-origin // with the old one, but JSPrincipals doesn't give us a way to do that. // But we can at least assert that we're not switching between system // and non-system. const JSPrincipals* trusted = realm->runtimeFromMainThread()->trustedPrincipals(); bool isSystem = principals && principals == trusted; MOZ_RELEASE_ASSERT(realm->isSystem() == isSystem); // Clear out the old principals, if any. if (realm->principals()) { JS_DropPrincipals(TlsContext.get(), realm->principals()); realm->setPrincipals(nullptr); } // Set up the new principals. if (principals) { JS_HoldPrincipals(principals); realm->setPrincipals(principals); } } JS_PUBLIC_API JSPrincipals* JS_GetScriptPrincipals(JSScript* script) { return script->principals(); } JS_PUBLIC_API bool JS_ScriptHasMutedErrors(JSScript* script) { return script->mutedErrors(); } JS_PUBLIC_API bool JS_WrapPropertyDescriptor( JSContext* cx, JS::MutableHandle<JS::PropertyDescriptor> desc) { return cx->compartment()->wrap(cx, desc); } JS_PUBLIC_API bool JS_WrapPropertyDescriptor( JSContext* cx, JS::MutableHandle<mozilla::Maybe<JS::PropertyDescriptor>> desc) { return cx->compartment()->wrap(cx, desc); } JS_PUBLIC_API void JS_TraceShapeCycleCollectorChildren(JS::CallbackTracer* trc, JS::GCCellPtr shape) { MOZ_ASSERT(shape.is<Shape>()); TraceCycleCollectorChildren(trc, &shape.as<Shape>()); } static bool DefineHelpProperty(JSContext* cx, HandleObject obj, const char* prop, const char* value) { RootedAtom atom(cx, Atomize(cx, value, strlen(value))); if (!atom) { return false; } return JS_DefineProperty(cx, obj, prop, atom, JSPROP_READONLY | JSPROP_PERMANENT); } JS_PUBLIC_API bool JS_DefineFunctionsWithHelp( JSContext* cx, HandleObject obj, const JSFunctionSpecWithHelp* fs) { MOZ_ASSERT(!cx->zone()->isAtomsZone()); CHECK_THREAD(cx); cx->check(obj); for (; fs->name; fs++) { JSAtom* atom = Atomize(cx, fs->name, strlen(fs->name)); if (!atom) { return false; } Rooted<jsid> id(cx, AtomToId(atom)); RootedFunction fun(cx, DefineFunction(cx, obj, id, fs->call, fs->nargs, fs->flags | JSPROP_RESOLVING)); if (!fun) { return false; } if (fs->jitInfo) { fun->setJitInfo(fs->jitInfo); } if (fs->usage) { if (!DefineHelpProperty(cx, fun, "usage", fs->usage)) { return false; } } if (fs->help) { if (!DefineHelpProperty(cx, fun, "help", fs->help)) { return false; } } } return true; } JS_PUBLIC_API bool JS::GetBuiltinClass(JSContext* cx, HandleObject obj, js::ESClass* cls) { if (MOZ_UNLIKELY(obj->is<ProxyObject>())) { return Proxy::getBuiltinClass(cx, obj, cls); } if (obj->is<PlainObject>()) { *cls = ESClass::Object; } else if (obj->is<ArrayObject>()) { *cls = ESClass::Array; } else if (obj->is<NumberObject>()) { *cls = ESClass::Number; } else if (obj->is<StringObject>()) { *cls = ESClass::String; } else if (obj->is<BooleanObject>()) { *cls = ESClass::Boolean; } else if (obj->is<RegExpObject>()) { *cls = ESClass::RegExp; } else if (obj->is<ArrayBufferObject>()) { *cls = ESClass::ArrayBuffer; } else if (obj->is<SharedArrayBufferObject>()) { *cls = ESClass::SharedArrayBuffer; } else if (obj->is<DateObject>()) { *cls = ESClass::Date; } else if (obj->is<SetObject>()) { *cls = ESClass::Set; } else if (obj->is<MapObject>()) { *cls = ESClass::Map; } else if (obj->is<PromiseObject>()) { *cls = ESClass::Promise; } else if (obj->is<MapIteratorObject>()) { *cls = ESClass::MapIterator; } else if (obj->is<SetIteratorObject>()) { *cls = ESClass::SetIterator; } else if (obj->is<ArgumentsObject>()) { *cls = ESClass::Arguments; } else if (obj->is<ErrorObject>()) { *cls = ESClass::Error; } else if (obj->is<BigIntObject>()) { *cls = ESClass::BigInt; } else if (obj->is<JSFunction>()) { *cls = ESClass::Function; } else { *cls = ESClass::Other; } return true; } JS_PUBLIC_API bool js::IsArgumentsObject(HandleObject obj) { return obj->is<ArgumentsObject>(); } JS_PUBLIC_API JS::Zone* js::GetRealmZone(JS::Realm* realm) { return realm->zone(); } JS_PUBLIC_API bool js::IsSystemCompartment(JS::Compartment* comp) { // Realms in the same compartment must either all be system realms or // non-system realms. We assert this in NewRealm and SetRealmPrincipals, // but do an extra sanity check here. MOZ_ASSERT(comp->realms()[0]->isSystem() == comp->realms().back()->isSystem()); return comp->realms()[0]->isSystem(); } JS_PUBLIC_API bool js::IsSystemRealm(JS::Realm* realm) { return realm->isSystem(); } JS_PUBLIC_API bool js::IsSystemZone(Zone* zone) { return zone->isSystemZone(); } JS_PUBLIC_API bool js::IsFunctionObject(JSObject* obj) { return obj->is<JSFunction>(); } JS_PUBLIC_API bool js::IsSavedFrame(JSObject* obj) { return obj->is<SavedFrame>(); } JS_PUBLIC_API bool js::UninlinedIsCrossCompartmentWrapper(const JSObject* obj) { return js::IsCrossCompartmentWrapper(obj); } JS_PUBLIC_API void js::AssertSameCompartment(JSContext* cx, JSObject* obj) { cx->check(obj); } JS_PUBLIC_API void js::AssertSameCompartment(JSContext* cx, JS::HandleValue v) { cx->check(v); } #ifdef DEBUG JS_PUBLIC_API void js::AssertSameCompartment(JSObject* objA, JSObject* objB) { MOZ_ASSERT(objA->compartment() == objB->compartment()); } #endif JS_PUBLIC_API void js::NotifyAnimationActivity(JSObject* obj) { MOZ_ASSERT(obj->is<GlobalObject>()); auto timeNow = mozilla::TimeStamp::Now(); obj->as<GlobalObject>().realm()->lastAnimationTime = timeNow; obj->runtimeFromMainThread()->lastAnimationTime = timeNow; } JS_PUBLIC_API bool js::IsObjectInContextCompartment(JSObject* obj, const JSContext* cx) { return obj->compartment() == cx->compartment(); } JS_PUBLIC_API bool js::AutoCheckRecursionLimit::runningWithTrustedPrincipals( JSContext* cx) const { return cx->runningWithTrustedPrincipals(); } JS_PUBLIC_API JSFunction* js::DefineFunctionWithReserved( JSContext* cx, JSObject* objArg, const char* name, JSNative call, unsigned nargs, unsigned attrs) { RootedObject obj(cx, objArg); MOZ_ASSERT(!cx->zone()->isAtomsZone()); CHECK_THREAD(cx); cx->check(obj); JSAtom* atom = Atomize(cx, name, strlen(name)); if (!atom) { return nullptr; } Rooted<jsid> id(cx, AtomToId(atom)); return DefineFunction(cx, obj, id, call, nargs, attrs, gc::AllocKind::FUNCTION_EXTENDED); } JS_PUBLIC_API JSFunction* js::NewFunctionWithReserved(JSContext* cx, JSNative native, unsigned nargs, unsigned flags, const char* name) { MOZ_ASSERT(!cx->zone()->isAtomsZone()); CHECK_THREAD(cx); RootedAtom atom(cx); if (name) { atom = Atomize(cx, name, strlen(name)); if (!atom) { return nullptr; } } return (flags & JSFUN_CONSTRUCTOR) ? NewNativeConstructor(cx, native, nargs, atom, gc::AllocKind::FUNCTION_EXTENDED) : NewNativeFunction(cx, native, nargs, atom, gc::AllocKind::FUNCTION_EXTENDED); } JS_PUBLIC_API JSFunction* js::NewFunctionByIdWithReserved( JSContext* cx, JSNative native, unsigned nargs, unsigned flags, jsid id) { MOZ_ASSERT(id.isAtom()); MOZ_ASSERT(!cx->zone()->isAtomsZone()); CHECK_THREAD(cx); cx->check(id); RootedAtom atom(cx, id.toAtom()); return (flags & JSFUN_CONSTRUCTOR) ? NewNativeConstructor(cx, native, nargs, atom, gc::AllocKind::FUNCTION_EXTENDED) : NewNativeFunction(cx, native, nargs, atom, gc::AllocKind::FUNCTION_EXTENDED); } JS_PUBLIC_API const Value& js::GetFunctionNativeReserved(JSObject* fun, size_t which) { MOZ_ASSERT(fun->as<JSFunction>().isNativeFun()); return fun->as<JSFunction>().getExtendedSlot(which); } JS_PUBLIC_API void js::SetFunctionNativeReserved(JSObject* fun, size_t which, const Value& val) { MOZ_ASSERT(fun->as<JSFunction>().isNativeFun()); MOZ_ASSERT_IF(val.isObject(), val.toObject().compartment() == fun->compartment()); fun->as<JSFunction>().setExtendedSlot(which, val); } JS_PUBLIC_API bool js::FunctionHasNativeReserved(JSObject* fun) { MOZ_ASSERT(fun->as<JSFunction>().isNativeFun()); return fun->as<JSFunction>().isExtended(); } bool js::GetObjectProto(JSContext* cx, JS::Handle<JSObject*> obj, JS::MutableHandle<JSObject*> proto) { cx->check(obj); if (obj->is<ProxyObject>()) { return JS_GetPrototype(cx, obj, proto); } proto.set(obj->staticPrototype()); return true; } JS_PUBLIC_API JSObject* js::GetStaticPrototype(JSObject* obj) { MOZ_ASSERT(obj->hasStaticPrototype()); return obj->staticPrototype(); } JS_PUBLIC_API bool js::GetRealmOriginalEval(JSContext* cx, MutableHandleObject eval) { return GlobalObject::getOrCreateEval(cx, cx->global(), eval); } void JS::detail::SetReservedSlotWithBarrier(JSObject* obj, size_t slot, const Value& value) { if (obj->is<ProxyObject>()) { obj->as<ProxyObject>().setReservedSlot(slot, value); } else { obj->as<NativeObject>().setSlot(slot, value); } } void js::SetPreserveWrapperCallbacks( JSContext* cx, PreserveWrapperCallback preserveWrapper, HasReleasedWrapperCallback hasReleasedWrapper) { cx->runtime()->preserveWrapperCallback = preserveWrapper; cx->runtime()->hasReleasedWrapperCallback = hasReleasedWrapper; } JS_PUBLIC_API unsigned JS_PCToLineNumber(JSScript* script, jsbytecode* pc, unsigned* columnp) { return PCToLineNumber(script, pc, columnp); } JS_PUBLIC_API bool JS_IsDeadWrapper(JSObject* obj) { return IsDeadProxyObject(obj); } JS_PUBLIC_API JSObject* JS_NewDeadWrapper(JSContext* cx, JSObject* origObj) { return NewDeadProxyObject(cx, origObj); } void js::TraceWeakMaps(WeakMapTracer* trc) { WeakMapBase::traceAllMappings(trc); } extern JS_PUBLIC_API bool js::AreGCGrayBitsValid(JSRuntime* rt) { return rt->gc.areGrayBitsValid(); } JS_PUBLIC_API bool js::ZoneGlobalsAreAllGray(JS::Zone* zone) { for (RealmsInZoneIter realm(zone); !realm.done(); realm.next()) { JSObject* obj = realm->unsafeUnbarrieredMaybeGlobal(); if (!obj || !JS::ObjectIsMarkedGray(obj)) { return false; } } return true; } JS_PUBLIC_API bool js::IsCompartmentZoneSweepingOrCompacting( JS::Compartment* comp) { MOZ_ASSERT(comp); return comp->zone()->isGCSweepingOrCompacting(); } JS_PUBLIC_API void js::TraceGrayWrapperTargets(JSTracer* trc, Zone* zone) { JS::AutoSuppressGCAnalysis nogc; for (CompartmentsInZoneIter comp(zone); !comp.done(); comp.next()) { for (Compartment::ObjectWrapperEnum e(comp); !e.empty(); e.popFront()) { JSObject* target = e.front().key(); if (target->isMarkedGray()) { TraceManuallyBarrieredEdge(trc, &target, "gray CCW target"); MOZ_ASSERT(target == e.front().key()); } } } } JSLinearString* JS::detail::StringToLinearStringSlow(JSContext* cx, JSString* str) { return str->ensureLinear(cx); } static bool CopyProxyObject(JSContext* cx, Handle<ProxyObject*> from, Handle<ProxyObject*> to) { MOZ_ASSERT(from->getClass() == to->getClass()); if (from->is<WrapperObject>() && (Wrapper::wrapperHandler(from)->flags() & Wrapper::CROSS_COMPARTMENT)) { to->setCrossCompartmentPrivate(GetProxyPrivate(from)); } else { RootedValue v(cx, GetProxyPrivate(from)); if (!cx->compartment()->wrap(cx, &v)) { return false; } to->setSameCompartmentPrivate(v); } MOZ_ASSERT(from->numReservedSlots() == to->numReservedSlots()); RootedValue v(cx); for (size_t n = 0; n < from->numReservedSlots(); n++) { v = GetProxyReservedSlot(from, n); if (!cx->compartment()->wrap(cx, &v)) { return false; } SetProxyReservedSlot(to, n, v); } return true; } JS_PUBLIC_API JSObject* JS_CloneObject(JSContext* cx, HandleObject obj, HandleObject proto) { // |obj| might be in a different compartment. cx->check(proto); if (!obj->is<NativeObject>() && !obj->is<ProxyObject>()) { JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_CANT_CLONE_OBJECT); return nullptr; } RootedObject clone(cx); if (obj->is<NativeObject>()) { // JS_CloneObject is used to create the target object for JSObject::swap(). // swap() requires its arguments are tenured, so ensure tenure allocation. clone = NewTenuredObjectWithGivenProto(cx, obj->getClass(), proto); if (!clone) { return nullptr; } if (clone->is<JSFunction>() && (obj->compartment() != clone->compartment())) { JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_CANT_CLONE_OBJECT); return nullptr; } if (obj->as<NativeObject>().hasPrivate()) { clone->as<NativeObject>().setPrivate( obj->as<NativeObject>().getPrivate()); } } else { auto* handler = GetProxyHandler(obj); // Same as above, require tenure allocation of the clone. This means for // proxy objects we need to reject nursery allocatable proxies. if (handler->canNurseryAllocate()) { JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_CANT_CLONE_OBJECT); return nullptr; } clone = ProxyObject::New(cx, handler, JS::NullHandleValue, AsTaggedProto(proto), obj->getClass()); if (!clone) { return nullptr; } if (!CopyProxyObject(cx, obj.as<ProxyObject>(), clone.as<ProxyObject>())) { return nullptr; } } return clone; } extern JS_PUBLIC_API bool JS::ForceLexicalInitialization(JSContext* cx, HandleObject obj) { AssertHeapIsIdle(); CHECK_THREAD(cx); cx->check(obj); bool initializedAny = false; NativeObject* nobj = &obj->as<NativeObject>(); for (ShapePropertyIter<NoGC> iter(nobj->shape()); !iter.done(); iter++) { Value v = nobj->getSlot(iter->slot()); if (iter->isDataProperty() && v.isMagic() && v.whyMagic() == JS_UNINITIALIZED_LEXICAL) { nobj->setSlot(iter->slot(), UndefinedValue()); initializedAny = true; } } return initializedAny; } extern JS_PUBLIC_API int JS::IsGCPoisoning() { #ifdef JS_GC_ALLOW_EXTRA_POISONING return js::gExtraPoisoningEnabled; #else return false; #endif } JS_PUBLIC_API void JS::NotifyGCRootsRemoved(JSContext* cx) { cx->runtime()->gc.notifyRootsRemoved(); } JS_PUBLIC_API JS::Realm* js::GetAnyRealmInZone(JS::Zone* zone) { if (zone->isAtomsZone()) { return nullptr; } RealmsInZoneIter realm(zone); MOZ_ASSERT(!realm.done()); return realm.get(); } JS_PUBLIC_API bool js::IsSharableCompartment(JS::Compartment* comp) { // If this compartment has nuked outgoing wrappers (because all its globals // got nuked), we won't be able to create any useful CCWs out of it in the // future, and so we shouldn't use it for any new globals. if (comp->nukedOutgoingWrappers) { return false; } // If this compartment has no live globals, it might be in the middle of being // GCed. Don't create any new Realms inside. There's no point to doing that // anyway, since the idea would be to avoid CCWs from existing Realms in the // compartment to the new Realm, and there are no existing Realms. if (!CompartmentHasLiveGlobal(comp)) { return false; } // Good to go. return true; } JS_PUBLIC_API JSObject* js::GetTestingFunctions(JSContext* cx) { RootedObject obj(cx, JS_NewPlainObject(cx)); if (!obj) { return nullptr; } if (!DefineTestingFunctions(cx, obj, false, false)) { return nullptr; } return obj; } JS_PUBLIC_API void js::SetDOMCallbacks(JSContext* cx, const DOMCallbacks* callbacks) { cx->runtime()->DOMcallbacks = callbacks; } JS_PUBLIC_API const DOMCallbacks* js::GetDOMCallbacks(JSContext* cx) { return cx->runtime()->DOMcallbacks; } JS_PUBLIC_API void js::PrepareScriptEnvironmentAndInvoke( JSContext* cx, HandleObject global, ScriptEnvironmentPreparer::Closure& closure) { MOZ_ASSERT(!cx->isExceptionPending()); MOZ_ASSERT(global->is<GlobalObject>()); MOZ_RELEASE_ASSERT( cx->runtime()->scriptEnvironmentPreparer, "Embedding needs to set a scriptEnvironmentPreparer callback"); cx->runtime()->scriptEnvironmentPreparer->invoke(global, closure); } JS_PUBLIC_API void js::SetScriptEnvironmentPreparer( JSContext* cx, ScriptEnvironmentPreparer* preparer) { cx->runtime()->scriptEnvironmentPreparer = preparer; } JS_PUBLIC_API void JS::SetCTypesActivityCallback(JSContext* cx, CTypesActivityCallback cb) { cx->runtime()->ctypesActivityCallback = cb; } JS::AutoCTypesActivityCallback::AutoCTypesActivityCallback( JSContext* cx, CTypesActivityType beginType, CTypesActivityType endType) : cx(cx), callback(cx->runtime()->ctypesActivityCallback), endType(endType) { if (callback) { callback(cx, beginType); } } JS_PUBLIC_API void js::SetAllocationMetadataBuilder( JSContext* cx, const AllocationMetadataBuilder* callback) { cx->realm()->setAllocationMetadataBuilder(callback); } JS_PUBLIC_API JSObject* js::GetAllocationMetadata(JSObject* obj) { ObjectWeakMap* map = ObjectRealm::get(obj).objectMetadataTable.get(); if (map) { return map->lookup(obj); } return nullptr; } JS_PUBLIC_API bool js::ReportIsNotFunction(JSContext* cx, HandleValue v) { cx->check(v); return ReportIsNotFunction(cx, v, -1); } #ifdef DEBUG bool js::HasObjectMovedOp(JSObject* obj) { return !!JS::GetClass(obj)->extObjectMovedOp(); } #endif JS_PUBLIC_API bool js::ForwardToNative(JSContext* cx, JSNative native, const CallArgs& args) { return native(cx, args.length(), args.base()); } AutoAssertNoContentJS::AutoAssertNoContentJS(JSContext* cx) : context_(cx), prevAllowContentJS_(cx->runtime()->allowContentJS_) { cx->runtime()->allowContentJS_ = false; } AutoAssertNoContentJS::~AutoAssertNoContentJS() { context_->runtime()->allowContentJS_ = prevAllowContentJS_; } JS_PUBLIC_API void js::EnableCodeCoverage() { js::coverage::EnableLCov(); } JS_PUBLIC_API JS::Value js::MaybeGetScriptPrivate(JSObject* object) { if (!object->is<ScriptSourceObject>()) { return UndefinedValue(); } return object->as<ScriptSourceObject>().canonicalPrivate(); } JS_PUBLIC_API uint64_t js::GetGCHeapUsageForObjectZone(JSObject* obj) { return obj->zone()->gcHeapSize.bytes(); } #ifdef DEBUG JS_PUBLIC_API bool js::RuntimeIsBeingDestroyed() { JSRuntime* runtime = TlsContext.get()->runtime(); MOZ_ASSERT(js::CurrentThreadCanAccessRuntime(runtime)); return runtime->isBeingDestroyed(); } #endif // No-op implementations of public API that would depend on --with-intl-api #ifndef JS_HAS_INTL_API static bool IntlNotEnabled(JSContext* cx) { JS_ReportErrorNumberASCII(cx, js::GetErrorMessage, nullptr, JSMSG_SUPPORT_NOT_ENABLED, "Intl"); return false; } bool JS::AddMozDateTimeFormatConstructor(JSContext* cx, JS::HandleObject intl) { return IntlNotEnabled(cx); } bool JS::AddMozDisplayNamesConstructor(JSContext* cx, JS::HandleObject intl) { return IntlNotEnabled(cx); } #endif // !JS_HAS_INTL_API JS_PUBLIC_API JS::Zone* js::GetObjectZoneFromAnyThread(const JSObject* obj) { return MaybeForwarded(obj)->zoneFromAnyThread(); }
30.82625
101
0.661125
benety
e384c915a2b8460e440f68af771de381c90e2cfb
229
cpp
C++
problem/10000~19999/11721/11721.cpp14.cpp
njw1204/BOJ-AC
1de41685725ae4657a7ff94e413febd97a888567
[ "MIT" ]
1
2019-04-19T16:37:44.000Z
2019-04-19T16:37:44.000Z
problem/10000~19999/11721/11721.cpp14.cpp
njw1204/BOJ-AC
1de41685725ae4657a7ff94e413febd97a888567
[ "MIT" ]
1
2019-04-20T11:42:44.000Z
2019-04-20T11:42:44.000Z
problem/10000~19999/11721/11721.cpp14.cpp
njw1204/BOJ-AC
1de41685725ae4657a7ff94e413febd97a888567
[ "MIT" ]
3
2019-04-19T16:37:47.000Z
2021-10-25T00:45:00.000Z
#include <stdio.h> int main (){ char a[101]; int i; scanf("%s",a); for(i=0;a[i]!=NULL;i++){ printf("%c",a[i]); if(i % 10 ==9) {printf("\n");} } return 0; }
13.470588
28
0.349345
njw1204
e3853519478efa481dbaf3ad6adca8f24e6cb673
594
cpp
C++
#1077 Kuchiguse.cpp
ZachVec/PAT-Advanced
52ba5989c095ddbee3c297e82a4b3d0d2e0cd449
[ "MIT" ]
1
2021-12-26T08:34:47.000Z
2021-12-26T08:34:47.000Z
#1077 Kuchiguse.cpp
ZachVec/PAT-Advanced
52ba5989c095ddbee3c297e82a4b3d0d2e0cd449
[ "MIT" ]
null
null
null
#1077 Kuchiguse.cpp
ZachVec/PAT-Advanced
52ba5989c095ddbee3c297e82a4b3d0d2e0cd449
[ "MIT" ]
null
null
null
#include <iostream> #include <cstring> using namespace std; constexpr size_t MAX = 258; int main() { size_t n, orilen, len; char str[MAX], suffix[MAX]; if(!scanf("%zu\n", &n)) return 0; cin.getline(suffix, MAX); orilen = len = strlen(suffix); for(size_t i = 1, slen, j; i < n; ++i, len = j) { cin.getline(str, MAX); slen = strlen(str); for(j = 0; j < len && j < slen; ++j) { if(suffix[orilen - j - 1] != str[slen - j - 1]) break; } } if(len) printf("%s\n", suffix + orilen - len); else printf("nai\n"); return 0; }
25.826087
66
0.526936
ZachVec
e385465fd6aa11da88d1d249aa6dc3b258d41b69
2,145
hpp
C++
Habitat.hpp
ambotaku/Urknall-lite
79d812c0c895294699d9857415d3850f29f1b8a5
[ "MIT" ]
1
2022-03-07T20:33:13.000Z
2022-03-07T20:33:13.000Z
Habitat.hpp
ambotaku/Urknall-lite
79d812c0c895294699d9857415d3850f29f1b8a5
[ "MIT" ]
null
null
null
Habitat.hpp
ambotaku/Urknall-lite
79d812c0c895294699d9857415d3850f29f1b8a5
[ "MIT" ]
null
null
null
#ifndef _HABITAT_H_ #define _HABITAT_H_ #include "GFX.hpp" class Habitat : public GFX { public: /** * @brief create lifegame habitat (playfield) * * @param devAddr device i2c address. * @param size oled display size (W128xH64 or W128xH32) * @param i2c i2c instance */ Habitat(uint16_t const devAddr, Size size, i2c_inst_t * i2c); /* * @brief fill display with random pixels * @param seed seed for random generator * @param density divisor limiting start pixel count */ void randomFill(uint seed=12345, uint density=32); /** * @brief build next habitat generation */ void nextGen(); #ifdef EXPORT_GENERATION #include "base64.hpp" /* * export last rendered buffer as Base64 string */ std::basic_string<unsigned char> exportGeneration() { return base64::encode(readBuffer, bufferSize()); } #endif private: // return buffersize needed uint32_t bufferSize() { return width * height / 8; } // copy of current habitat for nondestructive analysis unsigned char * readBuffer; uint generation; // generation counter /* * @brief check pixel's neighborhood (2-3 pixels needed to survive) * param x horizontal pixel position * param y vertical pixel position * @return true if neighbor pixel is not set */ bool isEmptyPixel(int16_t x, int16_t y); /* * @brief align neighbor's horizontal offset (wrapping around) * pos horizontal position of test pixel * offset -1 for left, +1 for right neighbor * @return aligned x */ int8_t offsetWidth(int8_t pos, int8_t offset); /* * @brief calculate neighbor's vertical offset * pos vertical position of test pixel * offset -1 for upper, +1 for lower neighbor * @return aligned y */ int8_t offsetHeight(int8_t pos, int8_t offset); /* * @brief check pixel's complete neighborhood * @param x horizontal pixel position * @param y vertical pixel position * @return neighbor count */ uint8_t checkCell(uint8_t x, uint8_t y); }; #endif
25.843373
71
0.649883
ambotaku
e385779dfa269d48c8d7f12dc40075d8f3fd7879
1,303
cpp
C++
CUDA(Matrices)/src/Main.cpp
Samir55/SearchEngineRanker
690425fd5afce216ab75cd10f8288b702fd5805c
[ "MIT" ]
1
2020-10-23T20:54:06.000Z
2020-10-23T20:54:06.000Z
CUDA(Matrices)/src/Main.cpp
Samir55/SearchEngineRanker
690425fd5afce216ab75cd10f8288b702fd5805c
[ "MIT" ]
null
null
null
CUDA(Matrices)/src/Main.cpp
Samir55/SearchEngineRanker
690425fd5afce216ab75cd10f8288b702fd5805c
[ "MIT" ]
null
null
null
#include "GPUTimer.h" #include "Kernel.h" #include "GraphReader.h" using namespace PageRank; int main(int argc, char **argv) { if (argc <= 1) return 0; string path = argv[1]; Matrix g_matrix, i_vector; int *out_degrees; int nodes_count; GPUTimer gpu_timer; // Read graph file. vector<vector<int> > nodesList = GraphReader::read_graph(path); nodes_count = int(nodesList.size()); // Construct S = H + A matrix GraphReader::construct_h_matrix(nodesList, g_matrix, i_vector, out_degrees); // Free resources. GraphReader::free_resources(); // Create page rank kernel object Kernel page_rank(nodes_count); // Allocate matrices in the gpu memory page_rank.allocate_matrices(g_matrix, i_vector); // Run PageRank algorithm gpu_timer.start(); page_rank.run_kernel(); gpu_timer.stop(); // Save Result in output.txt file ofstream file; file.open("output.txt"); double *res = page_rank.get_result(), check_sum = 0.0; for (int i = 0; i < int(nodesList.size()); i++) { file << i << " = " << setprecision(20) << res[i] << endl; check_sum += res[i]; } // Print Elapsed time cout << "Elapsed PageRank time in gpu " << gpu_timer.elapsed() << " ms" << endl; return 0; }
23.267857
84
0.630084
Samir55
e387ee6d08bbad2a7ed33e7add5b35dfb9ed8375
10,977
hpp
C++
filter/bloom_filter.hpp
yuchen1024/Kunlun
f1a4a6a1efcb81905df4f0c3ffe5e863fa0dfacf
[ "MIT" ]
33
2021-08-29T00:19:14.000Z
2022-03-30T02:40:36.000Z
filter/bloom_filter.hpp
yuchen1024/Kunlun
f1a4a6a1efcb81905df4f0c3ffe5e863fa0dfacf
[ "MIT" ]
null
null
null
filter/bloom_filter.hpp
yuchen1024/Kunlun
f1a4a6a1efcb81905df4f0c3ffe5e863fa0dfacf
[ "MIT" ]
3
2021-09-09T11:34:35.000Z
2022-01-12T11:10:05.000Z
/* ** Modified from https://github.com/ArashPartow/bloom ** (1) simplify the design ** (2) add serialize/deserialize interfaces */ #ifndef KUNLUN_BLOOM_FILTER_HPP #define KUNLUN_BLOOM_FILTER_HPP #include "../include/std.inc" #include "../crypto/ec_point.hpp" #include "../utility/murmurhash3.hpp" #include "../utility/print.hpp" //00000001 00000010 00000100 00001000 00010000 00100000 01000000 10000000 static const uint8_t bit_mask[8] = {0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80}; // selection of keyed hash for bloom filter #define FastKeyedHash LiteMurmurHash // an alternative choice is MurmurHash3 /* Note:A distinct hash function need not be implementation-wise distinct. In the current implementation "seeding" a common hash function with different values seems to be adequate. */ std::vector<uint32_t> GenUniqueSaltVector(size_t hash_num, uint32_t random_seed){ const size_t predefined_salt_num = 128; static const uint32_t predefined_salt[predefined_salt_num] = { 0xAAAAAAAA, 0x55555555, 0x33333333, 0xCCCCCCCC, 0x66666666, 0x99999999, 0xB5B5B5B5, 0x4B4B4B4B, 0xAA55AA55, 0x55335533, 0x33CC33CC, 0xCC66CC66, 0x66996699, 0x99B599B5, 0xB54BB54B, 0x4BAA4BAA, 0xAA33AA33, 0x55CC55CC, 0x33663366, 0xCC99CC99, 0x66B566B5, 0x994B994B, 0xB5AAB5AA, 0xAAAAAA33, 0x555555CC, 0x33333366, 0xCCCCCC99, 0x666666B5, 0x9999994B, 0xB5B5B5AA, 0xFFFFFFFF, 0xFFFF0000, 0xB823D5EB, 0xC1191CDF, 0xF623AEB3, 0xDB58499F, 0xC8D42E70, 0xB173F616, 0xA91A5967, 0xDA427D63, 0xB1E8A2EA, 0xF6C0D155, 0x4909FEA3, 0xA68CC6A7, 0xC395E782, 0xA26057EB, 0x0CD5DA28, 0x467C5492, 0xF15E6982, 0x61C6FAD3, 0x9615E352, 0x6E9E355A, 0x689B563E, 0x0C9831A8, 0x6753C18B, 0xA622689B, 0x8CA63C47, 0x42CC2884, 0x8E89919B, 0x6EDBD7D3, 0x15B6796C, 0x1D6FDFE4, 0x63FF9092, 0xE7401432, 0xEFFE9412, 0xAEAEDF79, 0x9F245A31, 0x83C136FC, 0xC3DA4A8C, 0xA5112C8C, 0x5271F491, 0x9A948DAB, 0xCEE59A8D, 0xB5F525AB, 0x59D13217, 0x24E7C331, 0x697C2103, 0x84B0A460, 0x86156DA9, 0xAEF2AC68, 0x23243DA5, 0x3F649643, 0x5FA495A8, 0x67710DF8, 0x9A6C499E, 0xDCFB0227, 0x46A43433, 0x1832B07A, 0xC46AFF3C, 0xB9C8FFF0, 0xC9500467, 0x34431BDF, 0xB652432B, 0xE367F12B, 0x427F4C1B, 0x224C006E, 0x2E7E5A89, 0x96F99AA5, 0x0BEB452A, 0x2FD87C39, 0x74B2E1FB, 0x222EFD24, 0xF357F60C, 0x440FCB1E, 0x8BBE030F, 0x6704DC29, 0x1144D12F, 0x948B1355, 0x6D8FD7E9, 0x1C11A014, 0xADD1592F, 0xFB3C712E, 0xFC77642F, 0xF9C4CE8C, 0x31312FB9, 0x08B0DD79, 0x318FA6E7, 0xC040D23D, 0xC0589AA7, 0x0CA5C075, 0xF874B172, 0x0CF914D5, 0x784D3280, 0x4E8CFEBC, 0xC569F575, 0xCDB2A091, 0x2CC016B4, 0x5C5F4421}; std::vector<uint32_t> vec_salt; if (hash_num <= predefined_salt_num){ std::copy(predefined_salt, predefined_salt + hash_num, std::back_inserter(vec_salt)); // integrate the user defined random seed to allow for the generation of unique bloom filter instances. for (auto i = 0; i < hash_num; i++){ vec_salt[i] = vec_salt[i] * vec_salt[(i+3) % vec_salt.size()] + random_seed; } } else{ std::copy(predefined_salt, predefined_salt + predefined_salt_num, std::back_inserter(vec_salt)); srand(random_seed); while (vec_salt.size() < hash_num){ uint32_t current_salt = rand() * rand(); if (0 == current_salt) continue; if (vec_salt.end() == std::find(vec_salt.begin(), vec_salt.end(), current_salt)){ vec_salt.emplace_back(current_salt); } } } return vec_salt; } class BloomFilter{ public: uint32_t hash_num; // number of keyed hash functions std::vector<uint32_t> vec_salt; // to change it uint64_t, you should also modify the range of hash uint32_t table_size; // m std::vector<uint8_t> bit_table; size_t projected_element_num; // n uint32_t random_seed; //double desired_false_positive_probability; size_t inserted_element_num; /* find the number of hash functions and minimum amount of storage bits required to construct a bloom filter consistent with the user defined false positive probability and estimated element insertion num */ BloomFilter() {}; BloomFilter(size_t projected_element_num, double desired_false_positive_probability) { hash_num = static_cast<size_t>(-log2(desired_false_positive_probability)); random_seed = static_cast<uint32_t>(0xA5A5A5A55A5A5A5A * 0xA5A5A5A5 + 1); vec_salt = GenUniqueSaltVector(hash_num, random_seed); table_size = static_cast<uint32_t>(projected_element_num * (-1.44 * log2(desired_false_positive_probability))); bit_table.resize(table_size/8, static_cast<uint8_t>(0x00)); // naive implementation inserted_element_num = 0; } ~BloomFilter() {}; size_t ObjectSize() { // hash_num + random_seed + table_size + table_content return 3 * sizeof(uint32_t) + table_size/8; } inline void PlainInsert(const void* input, size_t LEN) { size_t bit_index = 0; for (auto i = 0; i < hash_num; i++){ bit_index = FastKeyedHash(vec_salt[i], input, LEN) % table_size; //bit_table[bit_index / 8] |= bit_mask[bit_index % 8]; // naive implementation bit_table[bit_index >> 3] |= bit_mask[bit_index & 0x07]; // more efficient implementation } inserted_element_num++; } template <typename ElementType> // Note: T must be a C++ POD type. inline void Insert(const ElementType& element) { PlainInsert(&element, sizeof(ElementType)); } inline void Insert(const std::string& str) { PlainInsert(str.data(), str.size()); } /* ** You can insert any custom-type data you like as below */ inline void Insert(const ECPoint &A) { unsigned char buffer[POINT_BYTE_LEN]; EC_POINT_point2oct(group, A.point_ptr, POINT_CONVERSION_COMPRESSED, buffer, POINT_BYTE_LEN, nullptr); PlainInsert(buffer, POINT_BYTE_LEN); } inline void Insert(const std::vector<ECPoint> &vec_A) { size_t num = vec_A.size(); unsigned char *buffer = new unsigned char[num*POINT_BYTE_LEN]; for(auto i = 0; i < num; i++){ EC_POINT_point2oct(group, vec_A[i].point_ptr, POINT_CONVERSION_COMPRESSED, buffer+i*POINT_BYTE_LEN, POINT_BYTE_LEN, nullptr); PlainInsert(buffer+i*POINT_BYTE_LEN, POINT_BYTE_LEN); } delete[] buffer; } template <typename InputIterator> inline void Insert(const InputIterator begin, const InputIterator end) { InputIterator itr = begin; while (end != itr) { Insert(*(itr++)); } } template <class T, class Allocator, template <class,class> class Container> inline void Insert(Container<T, Allocator>& container) { #ifdef OMP #pragma omp parallel for #endif for(auto i = 0; i < container.size(); i++) Insert(container[i]); } inline bool PlainContain(const void* input, size_t LEN) const { size_t bit_index = 0; size_t local_bit_index = 0; for(auto i = 0; i < vec_salt.size(); i++) { bit_index = FastKeyedHash(vec_salt[i], input, LEN) % table_size; local_bit_index = bit_index & 0x07; if ((bit_table[bit_index >> 3] & bit_mask[local_bit_index]) != bit_mask[local_bit_index]) return false; } return true; } template <typename ElementType> inline bool Contain(const ElementType& element) const { return PlainContain(&element, sizeof(ElementType)); } inline bool Contain(const std::string& str) const { return PlainContain(str.data(), str.size()); } inline bool Contain(const ECPoint& A) const { unsigned char buffer[POINT_BYTE_LEN]; EC_POINT_point2oct(group, A.point_ptr, POINT_CONVERSION_COMPRESSED, buffer, POINT_BYTE_LEN, nullptr); return PlainContain(buffer, POINT_BYTE_LEN); } inline void Clear() { std::fill(bit_table.begin(), bit_table.end(), static_cast<uint8_t>(0x00)); inserted_element_num = 0; } inline bool WriteObject(std::string file_name) { std::ofstream fout; fout.open(file_name, std::ios::binary); if(!fout){ std::cerr << file_name << " open error" << std::endl; return false; } fout.write(reinterpret_cast<char *>(&hash_num), 8); fout.write(reinterpret_cast<char *>(&random_seed), 8); fout.write(reinterpret_cast<char *>(&table_size), 8); fout.write(reinterpret_cast<char *>(bit_table.data()), table_size/8); fout.close(); #ifdef DEBUG std::cout << "'" <<file_name << "' size = " << ObjectSize() << " bytes" << std::endl; #endif return true; } inline bool ReadObject(std::string file_name) { std::ifstream fin; fin.open(file_name, std::ios::binary); if(!fin){ std::cerr << file_name << " open error" << std::endl; return false; } fin.read(reinterpret_cast<char *>(&hash_num), sizeof(hash_num)); fin.read(reinterpret_cast<char *>(&random_seed), sizeof(random_seed)); vec_salt = GenUniqueSaltVector(hash_num, random_seed); fin.read(reinterpret_cast<char *>(&table_size), sizeof(table_size)); bit_table.resize(table_size/8, static_cast<uint8_t>(0x00)); fin.read(reinterpret_cast<char *>(bit_table.data()), table_size/8); return true; } inline bool WriteObject(char* buffer) { if(buffer == nullptr){ std::cerr << "allocate memory for bloom filter fails" << std::endl; return false; } memcpy(buffer, &hash_num, sizeof(uint32_t)); memcpy(buffer+ sizeof(uint32_t), &random_seed, sizeof(uint32_t)); memcpy(buffer+2*sizeof(uint32_t), &table_size, sizeof(uint32_t)); memcpy(buffer+3*sizeof(uint32_t), bit_table.data(), table_size/8); return true; } inline bool ReadObject(char* buffer) { if(buffer == nullptr){ std::cerr << "allocate memory for bloom filter fails" << std::endl; return false; } memcpy(&hash_num, buffer, sizeof(uint32_t)); memcpy(&random_seed, buffer+sizeof(uint32_t), sizeof(uint32_t)); vec_salt = GenUniqueSaltVector(hash_num, random_seed); memcpy(&table_size, buffer+2*sizeof(uint32_t), sizeof(uint32_t)); bit_table.resize(table_size/8, static_cast<uint8_t>(0x00)); memcpy(bit_table.data(), buffer+3*sizeof(uint32_t), table_size/8); return true; } void PrintInfo() const{ PrintSplitLine('-'); std::cout << "BloomFilter Status:" << std::endl; std::cout << "inserted element num = " << inserted_element_num << std::endl; std::cout << "hashtable size = " << (bit_table.size() >> 10) << " KB\n" << std::endl; std::cout << "bits per element = " << double(bit_table.size()) * 8 / inserted_element_num << std::endl; PrintSplitLine('-'); } }; #endif
36.959596
117
0.67277
yuchen1024
e3881f3aaec7ee44ad74e29a4e1c3b63a48a9892
2,727
cc
C++
calendar/calendar_service_factory.cc
careylam/vivaldi
bff2a435c35fe2cb3327d8d4a76430d4be5f666e
[ "BSD-3-Clause" ]
null
null
null
calendar/calendar_service_factory.cc
careylam/vivaldi
bff2a435c35fe2cb3327d8d4a76430d4be5f666e
[ "BSD-3-Clause" ]
null
null
null
calendar/calendar_service_factory.cc
careylam/vivaldi
bff2a435c35fe2cb3327d8d4a76430d4be5f666e
[ "BSD-3-Clause" ]
1
2020-05-12T23:54:41.000Z
2020-05-12T23:54:41.000Z
// Copyright (c) 2017 Vivaldi Technologies AS. All rights reserved // // Based on code that is: // // Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "calendar_service_factory.h" #include "base/memory/ptr_util.h" #include "chrome/browser/profiles/incognito_helpers.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/pref_names.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" #include "components/keyed_service/core/service_access_type.h" #include "components/prefs/pref_service.h" #include "calendar/calendar_service.h" #include "prefs/vivaldi_pref_names.h" namespace calendar { CalendarServiceFactory::CalendarServiceFactory() : BrowserContextKeyedServiceFactory( "CalendarService", BrowserContextDependencyManager::GetInstance()) {} CalendarServiceFactory::~CalendarServiceFactory() {} // static CalendarService* CalendarServiceFactory::GetForProfile(Profile* profile) { return static_cast<CalendarService*>( GetInstance()->GetServiceForBrowserContext(profile, true)); } // static CalendarService* CalendarServiceFactory::GetForProfileIfExists( Profile* profile, ServiceAccessType sat) { return static_cast<CalendarService*>( GetInstance()->GetServiceForBrowserContext(profile, false)); } // static CalendarService* CalendarServiceFactory::GetForProfileWithoutCreating( Profile* profile) { return static_cast<CalendarService*>( GetInstance()->GetServiceForBrowserContext(profile, false)); } // static CalendarServiceFactory* CalendarServiceFactory::GetInstance() { return base::Singleton<CalendarServiceFactory>::get(); } // static void CalendarServiceFactory::ShutdownForProfile(Profile* profile) { CalendarServiceFactory* factory = GetInstance(); factory->BrowserContextDestroyed(profile); } content::BrowserContext* CalendarServiceFactory::GetBrowserContextToUse( content::BrowserContext* context) const { return chrome::GetBrowserContextRedirectedInIncognito(context); } KeyedService* CalendarServiceFactory::BuildServiceInstanceFor( content::BrowserContext* context) const { std::unique_ptr<calendar::CalendarService> cal_service( new calendar::CalendarService()); Profile* profile = Profile::FromBrowserContext(context); calendar::CalendarDatabaseParams param = calendar::CalendarDatabaseParams(profile->GetPath()); if (!cal_service->Init(false, param)) { return nullptr; } return cal_service.release(); } bool CalendarServiceFactory::ServiceIsNULLWhileTesting() const { return true; } } // namespace calendar
30.640449
80
0.776678
careylam
e389ba62153c526e57ba9cc7082ce7552bac865b
324
hpp
C++
Hazel/src/Hazel/Core/Timestep.hpp
Ligh7bringer/Hazel
a7b8da66bae3817ba74398b40db5ba1ed989e691
[ "Apache-2.0" ]
1
2020-12-21T08:41:03.000Z
2020-12-21T08:41:03.000Z
Hazel/src/Hazel/Core/Timestep.hpp
Ligh7bringer/Hazel
a7b8da66bae3817ba74398b40db5ba1ed989e691
[ "Apache-2.0" ]
null
null
null
Hazel/src/Hazel/Core/Timestep.hpp
Ligh7bringer/Hazel
a7b8da66bae3817ba74398b40db5ba1ed989e691
[ "Apache-2.0" ]
null
null
null
#pragma once namespace Hazel { class Timestep { public: Timestep() = default; Timestep(float time) : m_Time(time) { } operator float() const { return m_Time; } float GetSeconds() const { return m_Time; } float GetMilliseconds() const { return m_Time * 1000.f; } private: float m_Time; }; } // namespace Hazel
13.5
58
0.682099
Ligh7bringer
e389ef611cb456374037d099a45ff7cbc55dea6f
9,590
cpp
C++
src/Lib/rfc3550/RtpSessionBase.cpp
miseri/rtp_plus_plus
244ddd86f40f15247dd39ae7f9283114c2ef03a2
[ "BSD-3-Clause" ]
1
2021-07-14T08:15:05.000Z
2021-07-14T08:15:05.000Z
src/Lib/rfc3550/RtpSessionBase.cpp
7956968/rtp_plus_plus
244ddd86f40f15247dd39ae7f9283114c2ef03a2
[ "BSD-3-Clause" ]
null
null
null
src/Lib/rfc3550/RtpSessionBase.cpp
7956968/rtp_plus_plus
244ddd86f40f15247dd39ae7f9283114c2ef03a2
[ "BSD-3-Clause" ]
2
2021-07-14T08:15:02.000Z
2021-07-14T08:56:10.000Z
#include "CorePch.h" #include <rtp++/rfc3550/RtpSessionBase.h> #include <boost/exception/all.hpp> #include <rtp++/rfc3550/RtcpPacketBase.h> #include <rtp++/util/ApplicationParameters.h> #ifndef EXIT_ON_TRUE #define EXIT_ON_TRUE(condition, log_message) if ((condition)){\ LOG(WARNING) << log_message;return false;} #endif namespace rfc3550 { RtpSessionBase::RtpSessionBase(const RtpSessionParameters& parameters, const GenericParameters& applicationParameters) :m_parameters(parameters), m_applicationParameters(applicationParameters), m_state(SS_STOPPED), m_uiByeSentCount(0) { } RtpSessionBase::~RtpSessionBase() { } bool RtpSessionBase::initialise() { try { m_state = SS_STOPPED; // create components m_vPayloadPacketisers = createPayloadPacketisers(m_parameters, m_applicationParameters); if (m_vPayloadPacketisers.empty()) { // create default packetiser LOG(WARNING) << "Unable to create suitable packetiser, creating default packetiser"; m_vPayloadPacketisers.push_back(PayloadPacketiserBase::create()); } m_vSessionDbs = createSessionDatabases(m_parameters); EXIT_ON_TRUE(m_vSessionDbs.empty(), "Failed to construct session database(s)"); m_vRtpInterfaces = createRtpNetworkInterfaces(m_parameters); EXIT_ON_TRUE(m_vRtpInterfaces.empty(), "Failed to create RTP network interfaces"); initialiseRtpNetworkInterfaces(m_parameters); // create playout buffer m_vReceiverBuffers = createRtpPlayoutBuffers(m_parameters); EXIT_ON_TRUE(m_vReceiverBuffers.empty(), "Failed to construct receiver buffers"); configureReceiverBuffers(m_parameters, m_applicationParameters); // TODO: abstract and define interface for receiver buffer // TODO: then move the following to RtpPlayoutBuffer implementation // set receiver buffer clock frequency so that we can adjust the jitter buffer #if 0 m_pPlayoutBuffer->setClockFrequency(m_parameters.getRtpTimestampFrequency()); // set buffer latency if configured in application parameters boost::optional<uint32_t> uiBufferLatency = m_applicationParameters.getUintParameter(ApplicationParameters::buf_lat); if (uiBufferLatency) m_pPlayoutBuffer->setPlayoutBufferLatency(*uiBufferLatency); #endif // RTCP inialisation MUST only occur after network interface initialisation // which is after the RTP network interfaces have been constructed m_vRtcpReportManagers = createRtcpReportManagers(m_parameters, m_applicationParameters, m_vSessionDbs); EXIT_ON_TRUE(m_vRtcpReportManagers.empty(), "Failed to construct RTCP report managers"); initialiseRtcp(); // RTP session state m_vRtpSessionStates = createRtpSessionStates(m_parameters); EXIT_ON_TRUE(m_vRtpSessionStates.empty(), "Failed to create RTP session states"); // RTP flows: linking up all the previously constructed objects m_vRtpFlows = createRtpFlows(m_parameters); EXIT_ON_TRUE(m_vRtpFlows.empty(), "Failed to create RTP flows"); return true; } catch (boost::exception& e) { LOG(ERROR) << "Exception: %1%" << boost::diagnostic_information(e); } catch (std::exception& e) { LOG(ERROR) << "Exception: %1%" << e.what(); } catch (...) { LOG(ERROR) << "Unknown exception!!!"; } return false; } boost::system::error_code RtpSessionBase::start() { if (m_state == SS_STOPPED) { if (initialise()) { boost::system::error_code ec = doStart(); if (!ec) { m_state = SS_STARTED; } return ec; } return boost::system::error_code(boost::system::errc::invalid_argument, boost::system::get_generic_category()); } else { return boost::system::error_code(boost::system::errc::invalid_argument, boost::system::get_generic_category()); } } boost::system::error_code RtpSessionBase::stop() { if (m_state == SS_STARTED) { VLOG(2) << "Shutting down RTP session"; m_state = SS_SHUTTING_DOWN; VLOG(2) << "Shutting down RTCP"; shutdownRtcp(); // let subclasses shutdown boost::system::error_code ec = doStop(); VLOG(2) << "Waiting for shutdown to complete"; // FIXME: this should only be reset once the shutdown is complete // i.e. all asynchronous handlers have been called // Commenting this out: for now the solution is to manually call reset // which will reset all session state // m_state = SS_STOPPED; return ec; } else { LOG(WARNING) << "Invalid state to call stop: " << m_state; return boost::system::error_code(boost::system::errc::invalid_argument, boost::system::get_generic_category()); } } boost::system::error_code RtpSessionBase::reset() { // reset state so that the session can be started again m_state = SS_STOPPED; // TODO: reinit all components return boost::system::error_code(); } void RtpSessionBase::sendSample(MediaSample::ptr pSample) { if (m_state == SS_STARTED) { doSendSample(pSample); } else if (m_state == SS_STOPPED) { LOG_FIRST_N(WARNING, 1) << "Session has not been started."; } else if (m_state == SS_SHUTTING_DOWN) { LOG_FIRST_N(INFO, 1) << "Shutting down, not sending any more samples."; } } void RtpSessionBase::sendSamples(const std::vector<MediaSample::ptr>& vMediaSamples) { if (m_state == SS_STARTED) { doSendSamples(vMediaSamples); } else if (m_state == SS_STOPPED) { LOG_FIRST_N(WARNING, 1) << "Session has not been started."; } else if (m_state == SS_SHUTTING_DOWN) { LOG_FIRST_N(INFO, 1) << "Shutting down, not sending any more samples."; } } void RtpSessionBase::doSendSamples(const std::vector<MediaSample::ptr>& vMediaSamples) { for (MediaSample::ptr pMediaSample: vMediaSamples) { doSendSample(pMediaSample); } } void RtpSessionBase::onIncomingRtp( const RtpPacket& rtpPacket, const EndPoint& ep ) { #ifdef DEBUG_INCOMING_RTP VLOG(10) << "Received RTP from " << ep.getAddress() << ":" << ep.getPort(); #endif // convert arrival time to RTP time uint32_t uiRtpTime = convertTimeToRtpTimestamp(rtpPacket.getArrivalTime(), m_parameters.getRtpTimestampFrequency(), m_parameters.getRtpTimestampBase()); RtpPacket& rPacket = const_cast<RtpPacket&>(rtpPacket); rPacket.setRtpArrivalTimestamp(uiRtpTime); if (m_incomingRtp) m_incomingRtp(rtpPacket, ep); doHandleIncomingRtp(rtpPacket, ep); } void RtpSessionBase::onOutgoingRtp( const RtpPacket& rtpPacket, const EndPoint& ep ) { doHandleOutgoingRtp(rtpPacket, ep); if (m_parameters.getRetransmissionTimeout() > 0) { storeRtpPacketForRetransmissionAndSchedulePacketRemoval(rtpPacket, ep, m_parameters.getRetransmissionTimeout()); } } void RtpSessionBase::onIncomingRtcp( const CompoundRtcpPacket& compoundRtcp, const EndPoint& ep ) { #ifdef DEBUG_INCOMING_RTP VLOG(10) << "Received RTCP from " << ep.getAddress() << ":" << ep.getPort(); #endif if (m_incomingRtcp) m_incomingRtcp(compoundRtcp, ep); doHandleIncomingRtcp(compoundRtcp, ep); } void RtpSessionBase::onOutgoingRtcp( const CompoundRtcpPacket& compoundRtcp, const EndPoint& ep ) { doHandleOutgoingRtcp(compoundRtcp, ep); // This code forms an integral part of the event loop: it assumes that each RtcpReportManager // must send a BYE at the end of the session and that each sent BYE results in this method being // called. // check if the outgoing packet contains an RTCP BYE: if so, shutdown the network interfaces // If all required BYEs have been sent, shutdown the network interfaces std::for_each(compoundRtcp.begin(), compoundRtcp.end(), [this](RtcpPacketBase::ptr pRtcpPacket) { if (pRtcpPacket->getPacketType() == PT_RTCP_BYE) { ++m_uiByeSentCount; } }); VLOG_IF(5, m_uiByeSentCount > 0) << m_uiByeSentCount << " RTCP BYE(s) sent. " << m_vRtcpReportManagers.size() << " report managers."; if (m_uiByeSentCount == m_vRtcpReportManagers.size()) { LOG(INFO) << "RTCP BYE(s) sent: shutting down RTP interface"; shutdownNetworkInterfaces(); } } void RtpSessionBase::initialiseRtpNetworkInterfaces(const RtpSessionParameters &rtpParameters) { std::for_each(m_vRtpInterfaces.begin(), m_vRtpInterfaces.end(), [this, &rtpParameters](std::unique_ptr<RtpNetworkInterface>& pRtpInterface) { configureNetworkInterface(pRtpInterface, rtpParameters); pRtpInterface->setIncomingRtpHandler(boost::bind(&RtpSessionBase::onIncomingRtp, this, _1, _2) ); pRtpInterface->setIncomingRtcpHandler(boost::bind(&RtpSessionBase::onIncomingRtcp, this, _1, _2) ); pRtpInterface->setOutgoingRtpHandler(boost::bind(&RtpSessionBase::onOutgoingRtp, this, _1, _2) ); pRtpInterface->setOutgoingRtcpHandler(boost::bind(&RtpSessionBase::onOutgoingRtcp, this, _1, _2) ); pRtpInterface->recv(); }); } void RtpSessionBase::shutdownNetworkInterfaces() { std::for_each(m_vRtpInterfaces.begin(), m_vRtpInterfaces.end(), [this](std::unique_ptr<RtpNetworkInterface>& pRtpInterface) { pRtpInterface->shutdown(); }); VLOG(10) << "RTP network interfaces shutdown"; } void RtpSessionBase::initialiseRtcp() { std::for_each(m_vRtcpReportManagers.begin(), m_vRtcpReportManagers.end(), [this](std::unique_ptr<rfc3550::RtcpReportManager>& pRtcpReportManager) { pRtcpReportManager->startReporting(); }); m_uiByeSentCount = 0; } void RtpSessionBase::shutdownRtcp() { std::for_each(m_vRtcpReportManagers.begin(), m_vRtcpReportManagers.end(), [this](std::unique_ptr<rfc3550::RtcpReportManager>& pRtcpReportManager) { pRtcpReportManager->scheduleFinalReportAndShutdown(); }); VLOG(10) << "RTCP report managers shutdown"; } }
32.730375
154
0.72951
miseri
e38a397590ea4d9e9eaa297ae75d2c15875804d7
3,122
cpp
C++
Queue/Circular_Queue.cpp
DeepthiTabithaBennet/Cpp_TheDataStructuresSurvivalKit
2819feeaabb6c65c1f89d592b89e25e2fca5261f
[ "BSD-3-Clause" ]
2
2021-05-21T17:15:10.000Z
2021-05-21T17:22:14.000Z
Queue/Circular_Queue.cpp
DeepthiTabithaBennet/Cpp_TheDataStructuresSurvivalKit
2819feeaabb6c65c1f89d592b89e25e2fca5261f
[ "BSD-3-Clause" ]
null
null
null
Queue/Circular_Queue.cpp
DeepthiTabithaBennet/Cpp_TheDataStructuresSurvivalKit
2819feeaabb6c65c1f89d592b89e25e2fca5261f
[ "BSD-3-Clause" ]
1
2022-01-11T07:52:42.000Z
2022-01-11T07:52:42.000Z
#include <iostream> using namespace std; /*---------------------------------------------------------------------------*/ class QUEUE{ private: int cqueue[5]; int front, rear, n; public: QUEUE(); //default constructor void insertCQ(int); void deleteCQ(); void displayCQ(); }; /*---------------------------------------------------------------------------*/ QUEUE :: QUEUE(){ front = -1; rear = -1; n = 5; } /*---------------------------------------------------------------------------*/ void QUEUE :: insertCQ(int val){ if (front == (rear + 1) % n){ cout << "Queue Overflow\n"; return; } if (front == -1){ front = 0; rear = 0; } else{ rear = (rear + 1) % n; } cqueue[rear] = val; } /*---------------------------------------------------------------------------*/ void QUEUE::deleteCQ(){ if(front == -1){ cout << "Queue Underflow\n"; return; } cout << "Element deleted from queue is " << cqueue[front] << endl; if (front == rear){ front = -1; rear = -1; } else{ front = (front + 1) % n; } } /*---------------------------------------------------------------------------*/ void QUEUE :: displayCQ(){ int f = front; int r = rear; if(f <= r){ while(f <= r){ cout << cqueue[f] << " "; f++; } } else{ while(f <= (n - 1)){ cout << cqueue[f] << " "; f++; } f = 0; while(f <= r){ cout << cqueue[f] << " "; f++; } } cout << endl; } /*---------------------------------------------------------------------------*/ // Objects QUEUE q1; QUEUE q2; /*---------------------------------------------------------------------------*/ int main(){ int ch, val; cout << "1 —————> Insert in Queue 1\n"; cout << "2 —————> Insert in Queue 2\n"; cout << "3 —————> Delete from Queue 1\n"; cout << "4 —————> Delete from Queue 2\n"; cout << "5 —————> Display Queue 1\n"; cout << "6 —————> Display Queue 2\n"; cout << "7 —————> Exit\n"; do{ cout << "\nEnter your choice : "; cin >> ch; switch(ch){ case (1): cout << "Enter the value to be inserted : "; cin >> val; q1.insertCQ(val); break; case (2): cout << "Enter the value to be inserted : "; cin >> val; q2.insertCQ(val); break; case (3): q1.deleteCQ(); break; case (4): q2.deleteCQ(); break; case (5): q1.displayCQ(); break; case (6): q2.displayCQ(); break; } }while(ch != 7); } /*---------------------------------------------------------------------------*/
22.955882
79
0.295324
DeepthiTabithaBennet
e38bbbaa928dc305c356492a00fc0d1b4563c169
1,898
cpp
C++
Numerical Methods/bisection.cpp
TashreefMuhammad/University_Miscellaneous_Codes
8ac444f51dfdbfeee5f0af54944df0ed3a52e832
[ "MIT" ]
3
2021-08-28T16:42:57.000Z
2022-03-20T15:04:08.000Z
Numerical Methods/bisection.cpp
TashreefMuhammad/University_Miscellaneous_Codes
8ac444f51dfdbfeee5f0af54944df0ed3a52e832
[ "MIT" ]
null
null
null
Numerical Methods/bisection.cpp
TashreefMuhammad/University_Miscellaneous_Codes
8ac444f51dfdbfeee5f0af54944df0ed3a52e832
[ "MIT" ]
null
null
null
#include <stdio.h> #include <math.h> double hornerequation(int n,double x,double a[]); double bisection(double x1,double x2,int n,double a[]); int main(void) { int i,n; printf("Enter the highest order of polynomial equation: "); scanf("%d",&n); double a[n+1]; printf("Please provide value of following co-efficients:\n"); for(i=n;i>=0;i--) { printf("a%d : ",i); scanf("%lf",&a[i]); } printf("So the horner's rule equation of the given polynomial:\n"); for(i=0;i<n-1;i++) printf("("); printf("%fx",a[n]); for(i=n-1;i>0;i--) { if(a[i]>=0) printf("+%f)x",a[i]); else printf("-%f)x",-a[i]); } if(a[i]>=0) printf("+%f = 0\n\n",a[0]); else printf("-%f = 0\n\n",-a[0]); double x=fabs(sqrt((pow(a[n-1]/a[n],2))-2.0*(a[n-2]/a[n]))); x=bisection(x,-x,n,a); printf("%f is the solution root.",x); return 0; } double hornerequation(int n,double x,double a[]) { double result=a[n]; int i; for(i=n-1;i>=0;i--) result=result*x+a[i]; return result; } double bisection(double x1,double x2,int n,double a[]) { double x0,f0,f1,f2; f1=hornerequation(n,x1,a); f2=hornerequation(n,x2,a); printf("Iteration\tx2\t\tx1\t\tx0\t\tf2\t\tf1\t\tf0\t\tError\n"); int i=0; while(abs((x2-x1)/x2)>=0.0001) { x0=(x1+x2)/2.0; f0=hornerequation(n,x0,a); printf("%d\t\t%f\t%f\t%f\t%f\t%f\t%f\t%f\n",++i,x2,x1,x0,f2,f1,f0,abs((x2-x1)/x2)); if(f0==0) { x2=x1=x0; break; } else if(f2*f0<0) { x1=x0; f1=hornerequation(n,x1,a); } else { x2=x0; f2=hornerequation(n,x2,a); } } printf("Final Error: %f\n",fabs((x2-x1)/x2)); return (x1+x2)/2.0; }
22.86747
91
0.490516
TashreefMuhammad
e38c53990ea48c3e802370dfdc430427f094e97c
767
cpp
C++
code/Unique Paths.cpp
htfy96/leetcode-solutions
4736e87958d7e5aea3cbd999f88c7a86de13205a
[ "Apache-2.0" ]
1
2021-02-21T15:43:13.000Z
2021-02-21T15:43:13.000Z
code/Unique Paths.cpp
htfy96/leetcode-solutions
4736e87958d7e5aea3cbd999f88c7a86de13205a
[ "Apache-2.0" ]
null
null
null
code/Unique Paths.cpp
htfy96/leetcode-solutions
4736e87958d7e5aea3cbd999f88c7a86de13205a
[ "Apache-2.0" ]
1
2018-12-13T07:14:09.000Z
2018-12-13T07:14:09.000Z
#define FORTIFY_SOURCE 2 class Solution { public: int uniquePaths(int m, int n) { int all = n-1+m-1; int mi = min(n-1, m-1); vector<int> f(2 * (mi+1)); for (int i=0; i<=all; ++i) for (int j=0; j<=mi; ++j) { if (!j) { f[(i%2) * (mi+1) + j] = 1; continue; } if (j>i) { f[(i%2) * (mi+1) + j] = 0; continue; } f[(i%2) * (mi+1) + j] = f[((i+1)%2) * (mi+1) + j] + f[((i+1)%2) * (mi+1) + j-1]; // cout << "C(" << i << "," << j << ")= " << f[(i%2) * (mi+1) + j] << endl; } /* cout << "finished" << endl; cout << f.size() << " " << f.capacity() << endl; */ return f[(all % 2) * (mi+1) + mi]; } };
36.52381
96
0.336375
htfy96
e38c7b9542c5cc8d35e79878ec13965f9b52a4d4
5,336
cpp
C++
willow/src/popx/op/l1x.cpp
gglin001/popart
3225214343f6d98550b6620e809a3544e8bcbfc6
[ "MIT" ]
61
2020-07-06T17:11:46.000Z
2022-03-12T14:42:51.000Z
willow/src/popx/op/l1x.cpp
gglin001/popart
3225214343f6d98550b6620e809a3544e8bcbfc6
[ "MIT" ]
1
2021-02-25T01:30:29.000Z
2021-11-09T11:13:14.000Z
willow/src/popx/op/l1x.cpp
gglin001/popart
3225214343f6d98550b6620e809a3544e8bcbfc6
[ "MIT" ]
6
2020-07-15T12:33:13.000Z
2021-11-07T06:55:00.000Z
// Copyright (c) 2018 Graphcore Ltd. All rights reserved. #include <numeric> #include <popart/error.hpp> #include <popart/ir.hpp> #include <popart/op/l1.hpp> #include <popart/popx/devicex.hpp> #include <popart/popx/op/l1x.hpp> #include <popart/popx/opxmanager.hpp> #include <popart/tensor.hpp> #include <popops/ElementWise.hpp> #include <popops/Expr.hpp> #include <popops/Reduce.hpp> namespace pe = popops::expr; namespace popart { namespace popx { L1Opx::L1Opx(Op *op, Devicex *devicex) : PopOpx(op, devicex) { verifyOp<L1Op>(op, Onnx::CustomOperators::L1); } void L1GradOpx::grow(snap::program::Sequence &prog) const { L1GradOp &l1gradop = getOp<L1GradOp>(); double lambda = static_cast<double>(l1gradop.getLambda()); // Signum : +1 of positive, -1 if negative, 0 if zero. poplar::Tensor signumTensor = popops::map(graph().getPoplarGraph(), popops::expr::UnaryOpType::SIGNUM, getInTensor(L1GradOp::getFwdActInIndex()).getPoplarTensor(), prog.getPoplarSequence(), debugContext("Signum")); double scale = lambda; switch (l1gradop.getReductionType()) { case ReductionType::NoReduction: break; case ReductionType::Sum: break; case ReductionType::Mean: { double totalSamples = static_cast<double>(getInTensor(0).numElements()); scale = lambda / totalSamples; break; } default: throw error("Unsupported reduction type for Loss {}", debugContext().getPathName()); } auto t_scale = getConst(getInTensor(0).elementType(), {}, scale, "scale") .getPoplarTensor(); // scale the signum tensor: // - first by 'scale', so +scale if positive, -scale if negative, 0 if zero // - by loss scaling factor // - then by input gradient auto gradTensor = popops::map(graph().getPoplarGraph(), pe::Mul(pe::_1, pe::_2), {signumTensor, t_scale}, prog.getPoplarSequence(), debugContext("multiply")); auto gradIn = getInTensor(L1GradOp::getGradInIndex()).getPoplarTensor(); popops::mapInPlace(graph().getPoplarGraph(), pe::Mul(pe::_1, pe::_2), {gradTensor, gradIn}, prog.getPoplarSequence(), debugContext("scaledGradIn")); setOutTensor(0, snap::Tensor{gradTensor, graph()}); } InputCreatorType L1Opx::getInputCreatorType(InIndex) const { return InputCreatorType::CanUnwind; } // lambda * sum_{0,..rank-1} |v| void L1Opx::grow(snap::program::Sequence &prog) const { const L1Op &l1op = getOp<L1Op>(); poplar::Tensor absTensor = popops::map(graph().getPoplarGraph(), popops::expr::UnaryOpType::ABSOLUTE, getInTensor(0).getPoplarTensor(), prog.getPoplarSequence(), debugContext("abs")); if (absTensor.rank() == 0) { throw error("invalid tensor (rank-0) in L1Opx"); } double lambda = static_cast<double>(l1op.getLambda()); if (l1op.getReductionType() == ReductionType::NoReduction) { auto t_scale = getConst(absTensor.elementType(), {}, lambda, "scale") .getPoplarTensor(); auto scaled = popops::map(graph().getPoplarGraph(), popops::expr::BinaryOpType::MULTIPLY, absTensor, t_scale, prog.getPoplarSequence(), debugContext("add")); setOutTensor(0, snap::Tensor{scaled, graph()}); } else { auto absTensor1D = absTensor.flatten(); double scale = lambda; switch (l1op.getReductionType()) { case ReductionType::Sum: { break; } case ReductionType::Mean: { double totalSamples = static_cast<double>(absTensor1D.dim(0)); scale = lambda / totalSamples; break; } // Making it explicit which data types we're not handling. Note that // the logic will fall through to the error. case ReductionType::NoReduction: default: { throw error("Unsupported reduction type for Loss {}", debugContext().getPathName()); } } // t_scale is always expected to be FLOAT, regardless of the input type // to the reduction auto t_scale = getConst(poplar::FLOAT, {}, scale, "scale").getPoplarTensor(); auto reduction = popops::reduce(graph().getPoplarGraph(), absTensor1D, {0}, {popops::Operation::ADD, false, t_scale}, prog.getPoplarSequence(), debugContext("add")); setOutTensor(0, snap::Tensor{reduction, graph()}); } } L1GradOpx::L1GradOpx(Op *op, Devicex *devicex) : PopOpx(op, devicex) { verifyOp<L1GradOp>(op, Onnx::CustomGradOperators::L1Grad); } namespace { OpxCreator<L1Opx> l1OpxCreator(Onnx::CustomOperators::L1); OpxCreator<L1GradOpx> l1GradOpxCreator(Onnx::CustomGradOperators::L1Grad); } // namespace } // namespace popx } // namespace popart
34.649351
78
0.582271
gglin001
e3917d5cf12b3fc4abeac17e1870106c71260220
1,669
cpp
C++
src/test/middlewares/Volume/marshaller.cpp
kennymalac/tinyCDN
5227ce336e54fe8c74a9b4a5910e324f9ff913ac
[ "Apache-2.0" ]
16
2018-04-15T15:06:01.000Z
2020-06-04T08:54:01.000Z
src/test/middlewares/Volume/marshaller.cpp
kennymalac/tinyCDN
5227ce336e54fe8c74a9b4a5910e324f9ff913ac
[ "Apache-2.0" ]
2
2019-09-09T20:13:52.000Z
2019-09-17T23:52:54.000Z
src/test/middlewares/Volume/marshaller.cpp
kennymalac/tinyCDN
5227ce336e54fe8c74a9b4a5910e324f9ff913ac
[ "Apache-2.0" ]
2
2018-05-18T12:31:34.000Z
2019-09-15T18:38:08.000Z
#include "../../include/catch.hpp" #include <string> #include <iostream> #include "src/utility.hpp" #include "src/middlewares/Volume/volume.hpp" #include "src/middlewares/Volume/marshaller.hpp" using namespace TinyCDN; using namespace TinyCDN::Utility; using namespace TinyCDN::Middleware::Volume; TEST_CASE("VolumeParams") { VolumeParams params{VolumeId{"a32b8963a2084ba7"}, 1000_kB}; REQUIRE(params.id.str() == std::string{"a32b8963a2084ba7"}); REQUIRE(params.size == 1000_kB); } TEST_CASE("VirtualVolumeParams") { VirtualVolumeParams params{VolumeId{"a32b8963a2084ba7"}, fs::current_path(), fs::current_path() / "volumes.db", 1_gB, 4}; REQUIRE(params.id.str() == std::string{"a32b8963a2084ba7"}); REQUIRE(params.size == 4_gB); REQUIRE(params.location == fs::current_path()); REQUIRE(params.fbVolDbLocation == fs::current_path() / "volumes.db"); REQUIRE(params.defaultVolumeSize == 1_gB); REQUIRE(params.volumeLimit == 4); } // TEST_CASE("VolumeCSVMarshaller") {} TEST_CASE("VirtualVolumeMarshaller") { VirtualVolumeMarshaller marshaller{}; SECTION("getInstance returns unique_ptr of VirtualVolume") { VirtualVolumeParams params{VolumeId{"a32b8963a2084ba7"}, fs::current_path(), fs::current_path() / "volumes.db", 1_gB, 4}; auto volume = marshaller.getInstance(params); REQUIRE(typeid(volume) == typeid(std::unique_ptr<VirtualVolume>)); REQUIRE(volume->id.str() == std::string{"a32b8963a2084ba7"}); REQUIRE(volume->getSize() == 4_gB); REQUIRE(volume->location == fs::current_path()); // REQUIRE(volume->fbVolDbLocation == fs::current_path() / "volumes.db"); // REQUIRE(volume->volumeLimit == 4); } }
35.510638
125
0.717196
kennymalac
e392427e348c50e09b86eac68fb9ad3f8ec3e13b
6,525
cpp
C++
test/FrequencyGovernorTest.cpp
avilcheslopez/geopm
35ad0af3f17f42baa009c97ed45eca24333daf33
[ "MIT", "BSD-3-Clause" ]
null
null
null
test/FrequencyGovernorTest.cpp
avilcheslopez/geopm
35ad0af3f17f42baa009c97ed45eca24333daf33
[ "MIT", "BSD-3-Clause" ]
null
null
null
test/FrequencyGovernorTest.cpp
avilcheslopez/geopm
35ad0af3f17f42baa009c97ed45eca24333daf33
[ "MIT", "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2015 - 2022, Intel Corporation * SPDX-License-Identifier: BSD-3-Clause */ #include <memory> #include "gtest/gtest.h" #include "gmock/gmock.h" #include "FrequencyGovernorImp.hpp" #include "geopm/Helper.hpp" #include "geopm_test.hpp" #include "MockPlatformIO.hpp" #include "MockPlatformTopo.hpp" using geopm::FrequencyGovernor; using geopm::FrequencyGovernorImp; using testing::NiceMock; using testing::_; using testing::Return; using testing::Throw; class FrequencyGovernorTest : public ::testing::Test { protected: void SetUp(void); NiceMock<MockPlatformIO> m_platio; NiceMock<MockPlatformTopo> m_topo; std::unique_ptr<FrequencyGovernor> m_gov; const int M_CTL_DOMAIN = GEOPM_DOMAIN_CORE; const int M_NUM_CORE = 4; const double M_PLAT_MAX_FREQ = 3.7e9; const double M_PLAT_STICKER_FREQ = 2.0e9; const double M_PLAT_MIN_FREQ = 1.0e9; const double M_PLAT_STEP_FREQ = 1e8; const std::vector<int> M_FREQ_CTL_IDX = {42, 43, 44, 45}; }; void FrequencyGovernorTest::SetUp(void) { ON_CALL(m_platio, control_domain_type("CPU_FREQUENCY_CONTROL")).WillByDefault(Return(M_CTL_DOMAIN)); ON_CALL(m_topo, num_domain(M_CTL_DOMAIN)).WillByDefault(Return(M_NUM_CORE)); ON_CALL(m_topo, num_domain(GEOPM_DOMAIN_CPU)).WillByDefault(Return(2*M_NUM_CORE)); ON_CALL(m_platio, read_signal("CPUINFO::FREQ_STEP", _, _)).WillByDefault(Return(M_PLAT_STEP_FREQ)); ON_CALL(m_platio, read_signal("CPUINFO::FREQ_MIN", _, _)).WillByDefault(Return(M_PLAT_MIN_FREQ)); ON_CALL(m_platio, read_signal("CPUINFO::FREQ_STICKER", _, _)).WillByDefault(Return(M_PLAT_STICKER_FREQ)); ON_CALL(m_platio, read_signal("CPU_FREQUENCY_MAX", _, _)).WillByDefault(Return(M_PLAT_MAX_FREQ)); ASSERT_EQ(M_NUM_CORE, (int)M_FREQ_CTL_IDX.size()); for (int idx = 0; idx < M_NUM_CORE; ++idx) { ON_CALL(m_platio, push_control("CPU_FREQUENCY_CONTROL", M_CTL_DOMAIN, idx)). WillByDefault(Return(M_FREQ_CTL_IDX[idx])); } ON_CALL(m_platio, push_control("CPU_FREQUENCY_CONTROL", GEOPM_DOMAIN_CPU, _)) .WillByDefault(Throw(geopm::Exception("invalid domain for frequency control", GEOPM_ERROR_INVALID, __FILE__, __LINE__))); m_gov = geopm::make_unique<FrequencyGovernorImp>(m_platio, m_topo); m_gov->init_platform_io(); } TEST_F(FrequencyGovernorTest, frequency_control_domain_default) { auto gov = geopm::make_unique<FrequencyGovernorImp>(m_platio, m_topo); gov->init_platform_io(); int domain = gov->frequency_domain_type(); EXPECT_EQ(M_CTL_DOMAIN, domain); } TEST_F(FrequencyGovernorTest, adjust_platform) { std::vector<double> request; int domain = m_gov->frequency_domain_type(); EXPECT_EQ(M_CTL_DOMAIN, domain); // todo: should caller use platform topo, or get this through governor? int num_domain = m_topo.num_domain(domain); EXPECT_EQ(M_NUM_CORE, num_domain); request = {1.1e9, 1.2e9, 1.5e9, 1.7e9}; ASSERT_EQ(num_domain, (int)request.size()); // check that controls are actually applied for (int idx = 0; idx < num_domain; ++idx) { EXPECT_CALL(m_platio, adjust(M_FREQ_CTL_IDX[idx], request[idx])); } m_gov->adjust_platform(request); bool result = m_gov->do_write_batch(); EXPECT_TRUE(result); } TEST_F(FrequencyGovernorTest, adjust_platform_clamping) { std::vector<double> request; int domain = m_gov->frequency_domain_type(); EXPECT_EQ(M_CTL_DOMAIN, domain); int num_domain = m_topo.num_domain(domain); EXPECT_EQ(M_NUM_CORE, num_domain); request = {4.1e9, 1.2e9, 1.5e9, 0.7e9}; ASSERT_EQ(num_domain, (int)request.size()); std::vector<double> expected = {M_PLAT_MAX_FREQ, 1.2e9, 1.5e9, M_PLAT_MIN_FREQ}; // check that controls are actually applied for (int idx = 0; idx < num_domain; ++idx) { EXPECT_CALL(m_platio, adjust(M_FREQ_CTL_IDX[idx], expected[idx])); } m_gov->adjust_platform(request); bool result = m_gov->do_write_batch(); EXPECT_TRUE(result); } TEST_F(FrequencyGovernorTest, adjust_platform_error) { std::vector<double> request; GEOPM_EXPECT_THROW_MESSAGE(m_gov->adjust_platform(request), GEOPM_ERROR_INVALID, "size of request vector"); } TEST_F(FrequencyGovernorTest, frequency_bounds_in_range) { // default settings EXPECT_DOUBLE_EQ(M_PLAT_MIN_FREQ, m_gov->get_frequency_min()); EXPECT_DOUBLE_EQ(M_PLAT_MAX_FREQ, m_gov->get_frequency_max()); EXPECT_DOUBLE_EQ(M_PLAT_STEP_FREQ, m_gov->get_frequency_step()); // change settings double new_min = M_PLAT_MIN_FREQ + M_PLAT_STEP_FREQ; double new_max = M_PLAT_MAX_FREQ - M_PLAT_STEP_FREQ; bool result = m_gov->set_frequency_bounds(new_min, new_max); EXPECT_TRUE(result); EXPECT_DOUBLE_EQ(new_min, m_gov->get_frequency_min()); EXPECT_DOUBLE_EQ(new_max, m_gov->get_frequency_max()); // same settings result = m_gov->set_frequency_bounds(new_min, new_max); EXPECT_FALSE(result); EXPECT_DOUBLE_EQ(new_min, m_gov->get_frequency_min()); EXPECT_DOUBLE_EQ(new_max, m_gov->get_frequency_max()); } TEST_F(FrequencyGovernorTest, frequency_bounds_invalid) { GEOPM_EXPECT_THROW_MESSAGE(m_gov->set_frequency_bounds(M_PLAT_MIN_FREQ - 1, M_PLAT_MAX_FREQ), GEOPM_ERROR_INVALID, "invalid frequency bounds"); GEOPM_EXPECT_THROW_MESSAGE(m_gov->set_frequency_bounds(M_PLAT_MIN_FREQ, M_PLAT_MAX_FREQ + 1), GEOPM_ERROR_INVALID, "invalid frequency bounds"); GEOPM_EXPECT_THROW_MESSAGE(m_gov->set_frequency_bounds(M_PLAT_MAX_FREQ, M_PLAT_MIN_FREQ), GEOPM_ERROR_INVALID, "invalid frequency bounds"); } TEST_F(FrequencyGovernorTest, validate_policy) { double min = NAN; double max = NAN; m_gov->validate_policy(min, max); EXPECT_FALSE(std::isnan(min)); EXPECT_FALSE(std::isnan(max)); min = M_PLAT_MIN_FREQ + 1; max = M_PLAT_MAX_FREQ - 1; m_gov->validate_policy(min, max); EXPECT_DOUBLE_EQ(M_PLAT_MIN_FREQ + 1, min); EXPECT_DOUBLE_EQ(M_PLAT_MAX_FREQ - 1, max); min = M_PLAT_MIN_FREQ - 1; max = M_PLAT_MAX_FREQ + 1; m_gov->validate_policy(min, max); // clamp to min and max EXPECT_DOUBLE_EQ(M_PLAT_MIN_FREQ, min); EXPECT_DOUBLE_EQ(M_PLAT_MAX_FREQ, max); }
37.285714
109
0.697778
avilcheslopez
e392d203a40d6d5df2be7f0399e8b18e79f75ccb
4,679
cpp
C++
Tests/src/Log/Logger.cpp
BlockProject3D/Framework
1c27ef19d9a12d158a2b53f6bd28dd2d8e678912
[ "BSD-3-Clause" ]
2
2019-02-02T20:48:17.000Z
2019-02-22T09:59:40.000Z
Tests/src/Log/Logger.cpp
BlockProject3D/Framework
1c27ef19d9a12d158a2b53f6bd28dd2d8e678912
[ "BSD-3-Clause" ]
125
2020-01-14T18:26:38.000Z
2021-02-23T15:33:55.000Z
Tests/src/Log/Logger.cpp
BlockProject3D/Framework
1c27ef19d9a12d158a2b53f6bd28dd2d8e678912
[ "BSD-3-Clause" ]
1
2020-05-26T08:55:10.000Z
2020-05-26T08:55:10.000Z
// Copyright (c) 2020, BlockProject 3D // // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of BlockProject 3D nor the names of its contributors // may be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include <Framework/Log/Logger.hpp> #include <Framework/Memory/Utility.hpp> #include <gtest/gtest.h> class MemoryLog final : public bpf::log::ILogAdapter { private: bpf::collection::List<bpf::String> &_log; public: explicit MemoryLog(bpf::collection::List<bpf::String> &log) : _log(log) { } void LogMessage(bpf::log::ELogLevel level, const bpf::String &category, const bpf::String &msg) final { _log.Add(bpf::String('[') + category + "] " + bpf::String::ValueOf((int)level) + ' ' + msg); } }; TEST(Logger, Basic) { bpf::collection::List<bpf::String> log; auto lg = bpf::log::Logger("UT"); lg.AddHandler(bpf::memory::MakeUnique<MemoryLog>(log)); lg.SetLevel(bpf::log::ELogLevel::DEBUG); lg.Debug("Test"); EXPECT_STREQ(*log.Last(), "[UT] 3 Test"); lg.Info("Test"); EXPECT_STREQ(*log.Last(), "[UT] 2 Test"); lg.Warning("Test"); EXPECT_STREQ(*log.Last(), "[UT] 1 Test"); lg.Error("Test"); EXPECT_STREQ(*log.Last(), "[UT] 0 Test"); } TEST(Logger, Move_1) { bpf::collection::List<bpf::String> log; auto lg = bpf::log::Logger("UT"); auto lg1 = bpf::log::Logger("UT1"); lg.AddHandler(bpf::memory::MakeUnique<MemoryLog>(log)); lg1.SetLevel(bpf::log::ELogLevel::DEBUG); lg1.AddHandler(bpf::memory::MakeUnique<MemoryLog>(log)); lg = std::move(lg1); lg.Debug("Test"); EXPECT_STREQ(*log.Last(), "[UT1] 3 Test"); lg.Info("Test"); EXPECT_STREQ(*log.Last(), "[UT1] 2 Test"); lg.Warning("Test"); EXPECT_STREQ(*log.Last(), "[UT1] 1 Test"); lg.Error("Test"); EXPECT_STREQ(*log.Last(), "[UT1] 0 Test"); } TEST(Logger, Move_2) { bpf::collection::List<bpf::String> log; auto lg1 = bpf::log::Logger("UT"); auto lg = std::move(lg1); lg.AddHandler(bpf::memory::MakeUnique<MemoryLog>(log)); lg.SetLevel(bpf::log::ELogLevel::DEBUG); lg.Debug("Test"); EXPECT_STREQ(*log.Last(), "[UT] 3 Test"); lg.Info("Test"); EXPECT_STREQ(*log.Last(), "[UT] 2 Test"); lg.Warning("Test"); EXPECT_STREQ(*log.Last(), "[UT] 1 Test"); lg.Error("Test"); EXPECT_STREQ(*log.Last(), "[UT] 0 Test"); } TEST(Logger, MinLevel_1) { bpf::collection::List<bpf::String> log; auto lg = bpf::log::Logger("UT"); lg.AddHandler(bpf::memory::MakeUnique<MemoryLog>(log)); lg.SetLevel(bpf::log::ELogLevel::ERROR); lg.Debug("Test"); EXPECT_EQ(log.Size(), 0u); lg.Info("Test"); EXPECT_EQ(log.Size(), 0u); lg.Warning("Test"); EXPECT_EQ(log.Size(), 0u); lg.Error("Test"); EXPECT_STREQ(*log.Last(), "[UT] 0 Test"); } TEST(Logger, MinLevel_2) { bpf::collection::List<bpf::String> log; auto lg = bpf::log::Logger("UT"); lg.AddHandler(bpf::memory::MakeUnique<MemoryLog>(log)); lg.SetLevel(bpf::log::ELogLevel::INFO); lg.Debug("Test"); EXPECT_EQ(log.Size(), 0u); lg.Info("Test"); EXPECT_STREQ(*log.Last(), "[UT] 2 Test"); lg.Warning("Test"); EXPECT_STREQ(*log.Last(), "[UT] 1 Test"); lg.Error("Test"); EXPECT_STREQ(*log.Last(), "[UT] 0 Test"); }
33.905797
105
0.6542
BlockProject3D
e393189d7ab79fd80db02390c7d2ad6e36707119
932
hh
C++
src/motor/world/api/motor/world/event/event.hh
motor-dev/Motor
98cb099fe1c2d31e455ed868cc2a25eae51e79f0
[ "BSD-3-Clause" ]
null
null
null
src/motor/world/api/motor/world/event/event.hh
motor-dev/Motor
98cb099fe1c2d31e455ed868cc2a25eae51e79f0
[ "BSD-3-Clause" ]
null
null
null
src/motor/world/api/motor/world/event/event.hh
motor-dev/Motor
98cb099fe1c2d31e455ed868cc2a25eae51e79f0
[ "BSD-3-Clause" ]
null
null
null
/* Motor <motor.devel@gmail.com> see LICENSE for detail */ #ifndef MOTOR_WORLD_WORLD_EVENT_EVENT_HH_ #define MOTOR_WORLD_WORLD_EVENT_EVENT_HH_ /**************************************************************************************************/ #include <motor/world/stdafx.h> #ifndef MOTOR_COMPUTE namespace Motor { namespace World { template < typename T1 = void, typename T2 = void, typename T3 = void, typename T4 = void > struct Event { public: u32 const index; void raise(); }; }} // namespace Motor::World # include <motor/world/event/event.factory.hh> #else namespace Motor { namespace World { template < typename T1 = void, typename T2 = void, typename T3 = void, typename T4 = void > struct Event { public: u32 const index; void raise(); }; }} // namespace Motor::World #endif /**************************************************************************************************/ #endif
20.711111
100
0.550429
motor-dev
e3961a411be58af43857ea8e9c44b116cacb52f6
46
cpp
C++
source/Graphics/Color.cpp
Dante12129/Pancake
35282814e2f3b2d5e155a539ca5ddee32e240d3e
[ "Zlib" ]
null
null
null
source/Graphics/Color.cpp
Dante12129/Pancake
35282814e2f3b2d5e155a539ca5ddee32e240d3e
[ "Zlib" ]
null
null
null
source/Graphics/Color.cpp
Dante12129/Pancake
35282814e2f3b2d5e155a539ca5ddee32e240d3e
[ "Zlib" ]
null
null
null
#include "include/Pancake/Graphics/Color.hpp"
23
45
0.804348
Dante12129
e3971d733659d1e8c2f3b625207d207c7eb4be67
423
hpp
C++
ext/src/org/w3c/dom/NodeList.hpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
ext/src/org/w3c/dom/NodeList.hpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
ext/src/org/w3c/dom/NodeList.hpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
// Generated from /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/jre/lib/rt.jar #pragma once #include <fwd-POI.hpp> #include <org/w3c/dom/fwd-POI.hpp> #include <java/lang/Object.hpp> struct org::w3c::dom::NodeList : public virtual ::java::lang::Object { virtual int32_t getLength() = 0; virtual Node* item(int32_t index) = 0; // Generated static ::java::lang::Class *class_(); };
22.263158
97
0.685579
pebble2015
e398d68f287168c7053fc2ef3859441a4fec7312
2,120
cpp
C++
modules/emu.nes/test/apps/test_nes_cartridge.cpp
LCClyde/nyra
f8280db2633e888ab62e929a2c238a33755ff694
[ "MIT" ]
null
null
null
modules/emu.nes/test/apps/test_nes_cartridge.cpp
LCClyde/nyra
f8280db2633e888ab62e929a2c238a33755ff694
[ "MIT" ]
1
2016-01-25T13:03:03.000Z
2016-01-25T13:03:03.000Z
modules/emu.nes/test/apps/test_nes_cartridge.cpp
LCClyde/nyra
f8280db2633e888ab62e929a2c238a33755ff694
[ "MIT" ]
null
null
null
/* * Copyright (c) 2016 Clyde Stanfield * * 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 <nyra/test/Test.h> #include <nyra/emu/nes/Cartridge.h> #include <nyra/core/Path.h> namespace nyra { namespace emu { namespace nes { TEST(Cartridge, Read) { Cartridge cart(core::path::join(core::DATA_PATH, "roms/nestest.nes")); const Header& header = cart.getHeader(); EXPECT_EQ("NES", header.getNESIdentifier()); EXPECT_EQ(static_cast<size_t>(1), header.getProgRomSize()); EXPECT_EQ(static_cast<size_t>(1), header.getChrRomSize()); EXPECT_EQ(static_cast<size_t>(0), header.getMapperNumber()); EXPECT_FALSE(header.getIsFourScreenMode()); EXPECT_FALSE(header.getHasTrainer()); EXPECT_FALSE(header.getHasBatteryBack()); EXPECT_EQ(HORIZONTAL, header.getMirroring()); EXPECT_FALSE(header.getIsPlayChoice10()); EXPECT_FALSE(header.getIsVsUnisystem()); EXPECT_FALSE(header.getIsNes2_0()); EXPECT_EQ(header.getProgRomSize(), cart.getProgROM().size()); EXPECT_EQ(header.getChrRomSize() * 2, cart.getChrROM().size()); } } } } NYRA_TEST()
37.857143
79
0.741509
LCClyde
e39ace3f2096d8e8525ae349b18a565e047b846e
890
hh
C++
Alignment/Geners/interface/IOIsUnsigned.hh
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
1
2019-08-09T08:42:11.000Z
2019-08-09T08:42:11.000Z
Alignment/Geners/interface/IOIsUnsigned.hh
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
null
null
null
Alignment/Geners/interface/IOIsUnsigned.hh
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
1
2019-04-03T19:23:27.000Z
2019-04-03T19:23:27.000Z
#ifndef GENERS_IOISUNSIGNED_HH_ #define GENERS_IOISUNSIGNED_HH_ namespace gs { template <class T> struct IOIsUnsigned { enum {value = 0}; }; } #define gs_declare_type_as_unsigned(T) /**/ \ namespace gs { \ template <> struct IOIsUnsigned<T> {enum {value = 1};}; \ template <> struct IOIsUnsigned<T const> {enum {value = 1};}; \ template <> struct IOIsUnsigned<T volatile> {enum {value = 1};}; \ template <> struct IOIsUnsigned<T const volatile> {enum {value = 1};}; \ } gs_declare_type_as_unsigned(unsigned char) gs_declare_type_as_unsigned(unsigned short) gs_declare_type_as_unsigned(unsigned int) gs_declare_type_as_unsigned(unsigned long) gs_declare_type_as_unsigned(unsigned long long) #endif // GENERS_IOISUNSIGNED_HH_
31.785714
76
0.625843
nistefan
e39b753b6cabd5be0caf1cfb97206065fdc29e2f
445
cpp
C++
src/register/ProgramRegister.cpp
openx86/emulator
829454a2dbc99ffa3ccdf81f7473e69f8b8ce896
[ "Apache-2.0" ]
1
2022-01-16T18:24:32.000Z
2022-01-16T18:24:32.000Z
src/register/ProgramRegister.cpp
openx86/emulator
829454a2dbc99ffa3ccdf81f7473e69f8b8ce896
[ "Apache-2.0" ]
null
null
null
src/register/ProgramRegister.cpp
openx86/emulator
829454a2dbc99ffa3ccdf81f7473e69f8b8ce896
[ "Apache-2.0" ]
null
null
null
// // Created by 86759 on 2022-01-14. // #include "ProgramRegister.h" //uint32_t ProgramRegister::IP_r = 0x1234FFF0; uint32_t ProgramRegister::IP_r = 0x0000FFF0; uint16_t ProgramRegister::IP() { return (uint16_t)IP_r; } uint32_t ProgramRegister::EIP() { return (uint32_t)IP_r; } void ProgramRegister::IP(uint16_t value) { auto* tmp = (uint16_t *)(&IP_r); *tmp = value; } void ProgramRegister::EIP(uint32_t value) { IP_r = value; }
34.230769
92
0.703371
openx86
e3a602a3aef9e02c33f422efc535c9a5d9eb82e6
3,467
cpp
C++
dialogs/dialoginfocontent.cpp
avttrue/fungus
c6ca9ef94317ecbe930da25606ca7331f048ef60
[ "MIT" ]
null
null
null
dialogs/dialoginfocontent.cpp
avttrue/fungus
c6ca9ef94317ecbe930da25606ca7331f048ef60
[ "MIT" ]
2
2020-08-20T05:04:33.000Z
2020-09-22T17:10:39.000Z
dialogs/dialoginfocontent.cpp
avttrue/fungus
c6ca9ef94317ecbe930da25606ca7331f048ef60
[ "MIT" ]
null
null
null
#include "dialoginfocontent.h" #include "properties.h" #include "helpers/helper.h" #include "helpers/widgethelper.h" #include "controls/separators.h" #include <QDebug> #include <QApplication> #include <QIcon> #include <QToolBar> #include <QVBoxLayout> #include <QTextBrowser> #include <QScrollBar> DialogInfoContent::DialogInfoContent(QWidget *parent, const QString& title) : DialogBody(parent, title, ":/resources/img/info.svg") { m_Content = new QTextBrowser(this); m_Content->setOpenLinks(false); QObject::connect(m_Content, &QTextBrowser::forwardAvailable, [=](bool value) { m_ActionForward->setEnabled(value); }); QObject::connect(m_Content, &QTextBrowser::backwardAvailable, [=](bool value) { m_ActionBackward->setEnabled(value); }); QObject::connect(m_Content, &QTextBrowser::anchorClicked, this, &DialogInfoContent::slotAnchorClicked); ToolBar()->setIconSize(QSize(config->ButtonSize(), config->ButtonSize())); m_ActionBackward = new QAction(QIcon(":/resources/img/left_arrow.svg"),tr("Backward")); QObject::connect(m_ActionBackward, &QAction::triggered, [=](){ m_Content->backward(); }); m_ActionBackward->setAutoRepeat(false); m_ActionBackward->setEnabled(false); addToolBarAction(ToolBar(), m_ActionBackward, CSS_TOOLBUTTON); m_ActionForward = new QAction(QIcon(":/resources/img/right_arrow.svg"), tr("Forward")); QObject::connect(m_ActionForward, &QAction::triggered, [=](){ m_Content->forward(); }); m_ActionForward->setAutoRepeat(false); m_ActionForward->setEnabled(false); addToolBarAction(ToolBar(), m_ActionForward, CSS_TOOLBUTTON); auto m_ActionHome = new QAction(QIcon(":/resources/img/up_arrow.svg"), tr("Main page")); QObject::connect(m_ActionHome, &QAction::triggered, [=](){ m_Content->home(); }); m_ActionHome->setAutoRepeat(false); addToolBarAction(ToolBar(), m_ActionHome, CSS_TOOLBUTTON); ToolBar()->addWidget(new WidgetSpacer()); addDialogContent(m_Content); resize(DIC_WINDOW_SIZE); QObject::connect(this, &QObject::destroyed, [=]() { qDebug() << "DialogInfoContent" << windowTitle() << "destroyed"; }); qDebug() << "DialogInfoContent" << windowTitle() << "created"; } void DialogInfoContent::slotAnchorClicked(const QUrl &link) { qDebug() << __func__; if(!link.isValid()) return; if(!link.toString().contains(QRegExp(EXTERN_URL_RG))) { auto source_page = m_Content->source().toString(); auto target_page = link.toString(); qDebug() << "Source page:" << source_page; qDebug() << "Target page:" << target_page; if(source_page.endsWith(HELP_PAGE_TRIGGER)) config->setHelpPage(target_page); auto res_type = m_Content->sourceType(); m_Content->setSource(link, res_type); return; } OpenUrl(link); } void DialogInfoContent::setHtmlContent(const QString& content) { m_Content->setHtml(content); } void DialogInfoContent::setMarkdownSource(const QString &source) { m_Content->setSource(QUrl(source), QTextDocument::MarkdownResource); } void DialogInfoContent::setMarkdownContent(const QString &content) { m_Content->document()->setMarkdown(content, QTextDocument::MarkdownDialectCommonMark); } void DialogInfoContent::scrollUp() { auto vScrollBar = m_Content->verticalScrollBar(); vScrollBar->triggerAction(QScrollBar::SliderToMinimum); }
34.326733
107
0.697721
avttrue
e3a76a7d5a9ad27f7f5c11215c2b9968dee26da7
1,123
cpp
C++
Knottenbelt/Week5/printpyramid.cpp
AnthonyChuah/CPPscripts
c8376c4bf191949fc31b4e70226a2c42f8e7f1c2
[ "bzip2-1.0.6" ]
null
null
null
Knottenbelt/Week5/printpyramid.cpp
AnthonyChuah/CPPscripts
c8376c4bf191949fc31b4e70226a2c42f8e7f1c2
[ "bzip2-1.0.6" ]
null
null
null
Knottenbelt/Week5/printpyramid.cpp
AnthonyChuah/CPPscripts
c8376c4bf191949fc31b4e70226a2c42f8e7f1c2
[ "bzip2-1.0.6" ]
null
null
null
#include <iostream> using namespace std; void print_pyramid(int height); // Prints a pyramid of specified height. Must be between 1 to 30 inclusive. int main() { int desired_height = 0; bool acceptable_input = false; cout << "This program prints a 'pyramid' shape of\n" << "a specified height on the screen.\n\n"; while (!(acceptable_input)) { cout << "How high would you like the pyramid? (1 to 30 inclusive): "; cin >> desired_height; if (desired_height >= 1 && desired_height <= 30) { acceptable_input = true; } else { acceptable_input = false; } } print_pyramid(desired_height); return 0; } void print_pyramid(int height) { int preceding_spaces = 0; int rownum = 0, num_stars = 0; for (int i = 0; i < height; i++) { preceding_spaces = height - 1 - i; // Print the preceding spaces. for (int j = 0; j < preceding_spaces; j++) cout << " "; // Print the stars. rownum = i + 1; num_stars = rownum * 2; for (int k = 0; k < num_stars; k++) cout << "*"; // Print a newline. cout << "\n"; } }
22.918367
75
0.593054
AnthonyChuah
e3ab727a12ecd7a103417cb4164ae11c8f1cbcb2
371
hpp
C++
include/vengine/core/ICvar.hpp
BlackPhrase/V-Engine
ee9a9c63a380732dace75bcc1e398cabc444feba
[ "MIT" ]
1
2018-06-22T15:46:42.000Z
2018-06-22T15:46:42.000Z
include/vengine/core/ICvar.hpp
BlackPhrase/V-Engine
ee9a9c63a380732dace75bcc1e398cabc444feba
[ "MIT" ]
3
2018-05-13T14:15:53.000Z
2018-05-29T08:06:26.000Z
include/vengine/core/ICvar.hpp
BlackPhrase/V-Engine
ee9a9c63a380732dace75bcc1e398cabc444feba
[ "MIT" ]
null
null
null
/// @file /// @brief console variable #pragma once struct ICvar { /// virtual const char *GetName() const = 0; /// virtual const char *GetDescription() const = 0; /// virtual void SetValue(const char *asValue) = 0; /// virtual const char *GetValue() const = 0; /// virtual const char *GetDefValue() const = 0; /// virtual void ResetValue() = 0; };
14.84
48
0.622642
BlackPhrase
e3af0bcfa99893069bb658d4565f8036db45a21a
1,128
cpp
C++
tests/basic_bvalue/test_events.cpp
fbdtemme/bencode
edf7dd5b580c44723821dbf737c8412d628294e4
[ "MIT" ]
25
2020-08-24T01:54:10.000Z
2021-12-22T08:55:54.000Z
tests/basic_bvalue/test_events.cpp
fbdtemme/bencode
edf7dd5b580c44723821dbf737c8412d628294e4
[ "MIT" ]
1
2021-12-29T05:38:56.000Z
2021-12-29T05:38:56.000Z
tests/basic_bvalue/test_events.cpp
fbdtemme/bencode
edf7dd5b580c44723821dbf737c8412d628294e4
[ "MIT" ]
4
2020-08-18T19:31:26.000Z
2022-02-01T18:57:51.000Z
// // Created by fbdtemme on 8/17/20. // #include <catch2/catch.hpp> #include <bencode/traits/all.hpp> #include "bencode/bvalue.hpp" #include <bencode/events/debug_to.hpp> #include <sstream> namespace bc = bencode; static const bc::bvalue b{ {"a", 1}, {"b", 1u}, {"d", false}, {"e", "string"}, {"f", std::vector{1, 2, 3, 4}} }; constexpr std::string_view b_events = R"(begin dict (size=5) string (const&) (size=1, value="a") dict key integer (1) dict value string (const&) (size=1, value="b") dict key integer (1) dict value string (const&) (size=1, value="d") dict key integer (0) dict value string (const&) (size=1, value="e") dict key string (const&) (size=6, value="string") dict value string (const&) (size=1, value="f") dict key begin list (size=4) integer (1) list item integer (2) list item integer (3) list item integer (4) list item end list dict value end dict )"; TEST_CASE("producing events from bvalue", "[bvalue][events]") { std::ostringstream os {}; auto consumer = bc::events::debug_to(os); bc::connect(consumer, b); CHECK(os.str() == b_events); }
17.625
61
0.636525
fbdtemme
e3b0dd6a5575aea71ec80c5b75359167d8ad7ff8
78
cpp
C++
test/llvm_test_code/inst_interaction/heap_01.cpp
janniclas/phasar
324302ae96795e6f0a065c14d4f7756b1addc2a4
[ "MIT" ]
1
2022-02-15T07:56:29.000Z
2022-02-15T07:56:29.000Z
test/llvm_test_code/inst_interaction/heap_01.cpp
fabianbs96/phasar
5b8acd046d8676f72ce0eb85ca20fdb0724de444
[ "MIT" ]
null
null
null
test/llvm_test_code/inst_interaction/heap_01.cpp
fabianbs96/phasar
5b8acd046d8676f72ce0eb85ca20fdb0724de444
[ "MIT" ]
null
null
null
int main() { int *i = new int(42); int j = *i; delete i; return j; }
9.75
23
0.487179
janniclas
e3b1e32d04537c57f52fc794a90899e447be8cf9
4,605
cpp
C++
src/Pegasus/Repository/tests/QualifierDeclRep/QualifierDeclRep.cpp
ncultra/Pegasus-2.5
4a0b9a1b37e2eae5c8105fdea631582dc2333f9a
[ "MIT" ]
null
null
null
src/Pegasus/Repository/tests/QualifierDeclRep/QualifierDeclRep.cpp
ncultra/Pegasus-2.5
4a0b9a1b37e2eae5c8105fdea631582dc2333f9a
[ "MIT" ]
null
null
null
src/Pegasus/Repository/tests/QualifierDeclRep/QualifierDeclRep.cpp
ncultra/Pegasus-2.5
4a0b9a1b37e2eae5c8105fdea631582dc2333f9a
[ "MIT" ]
1
2022-03-07T22:54:02.000Z
2022-03-07T22:54:02.000Z
//%2005//////////////////////////////////////////////////////////////////////// // // Copyright (c) 2000, 2001, 2002 BMC Software; Hewlett-Packard Development // Company, L.P.; IBM Corp.; The Open Group; Tivoli Systems. // Copyright (c) 2003 BMC Software; Hewlett-Packard Development Company, L.P.; // IBM Corp.; EMC Corporation, The Open Group. // Copyright (c) 2004 BMC Software; Hewlett-Packard Development Company, L.P.; // IBM Corp.; EMC Corporation; VERITAS Software Corporation; The Open Group. // Copyright (c) 2005 Hewlett-Packard Development Company, L.P.; IBM Corp.; // EMC Corporation; VERITAS Software Corporation; The Open Group. // // 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. // //============================================================================== // // Author: Mike Brasher (mbrasher@bmc.com) // // Modified By: Carol Ann Krug Graves, Hewlett-Packard Company // (carolann_graves@hp.com) // //%///////////////////////////////////////////////////////////////////////////// #include <Pegasus/Common/Config.h> #include <cassert> #include <Pegasus/Repository/CIMRepository.h> PEGASUS_USING_PEGASUS; PEGASUS_USING_STD; static const char* tmpDir; static char * verbose; String repositoryRoot; void test(CIMRepository_Mode mode) { CIMRepository r (repositoryRoot, mode); // Create a namespace: const String NAMESPACE = "/zzz"; const String ABSTRACT = "abstract"; r.createNameSpace(NAMESPACE); // Create a qualifier declaration: CIMQualifierDecl q1(ABSTRACT, Boolean(true), CIMScope::CLASS); r.setQualifier(NAMESPACE, q1); // Get it back and check to see if it is identical: CIMConstQualifierDecl q2 = r.getQualifier(NAMESPACE, ABSTRACT); assert(q1.identical(q2)); // Remove it now: r.deleteQualifier(NAMESPACE, ABSTRACT); // Try to get it again (this should fail with a not-found error): try { q2 = r.getQualifier(NAMESPACE, ABSTRACT); } catch (CIMException& e) { assert(e.getCode() == CIM_ERR_NOT_FOUND); } // Create two qualifiers: CIMQualifierDecl q3(CIMName ("q3"), Uint32(66), CIMScope::CLASS); CIMQualifierDecl q4(CIMName ("q4"), String("Hello World"), CIMScope::CLASS); r.setQualifier(NAMESPACE, q3); r.setQualifier(NAMESPACE, q4); // Enumerate the qualifier names: Array<CIMQualifierDecl> qualifiers = r.enumerateQualifiers(NAMESPACE); assert(qualifiers.size() == 2); for (Uint32 i = 0, n = qualifiers.size(); i < n; i++) { // qualifiers[i].print(); assert(qualifiers[i].identical(q3) || qualifiers[i].identical(q4)); } } int main(int argc, char** argv) { verbose = getenv("PEGASUS_TEST_VERBOSE"); tmpDir = getenv ("PEGASUS_TMP"); if (tmpDir == NULL) { repositoryRoot = "."; } else { repositoryRoot = tmpDir; } repositoryRoot.append("/repository"); try { CIMRepository_Mode mode; if (!strcmp(argv[1],"XML") ) { mode.flag = CIMRepository_Mode::NONE; if (verbose) cout << argv[0]<< ": using XML mode repository" << endl; } else if (!strcmp(argv[1],"BIN") ) { mode.flag = CIMRepository_Mode::BIN; if (verbose) cout << argv[0]<< ": using BIN mode repository" << endl; } else { cout << argv[0] << ": invalid argument: " << argv[1] << endl; return 0; } test(mode); } catch (Exception& e) { cout << argv[0] << " " << argv[1] << " " << e.getMessage() << endl; exit(1); } cout << argv[0] << " " << argv[1] << " +++++ passed all tests" << endl; return 0; }
30.7
80
0.638002
ncultra
e3b29b3ec003afca116f3c9e3d6618eb0bd3b6f7
3,083
cpp
C++
tc 160+/PrimeSequences.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
3
2015-05-25T06:24:37.000Z
2016-09-10T07:58:00.000Z
tc 160+/PrimeSequences.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
null
null
null
tc 160+/PrimeSequences.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
5
2015-05-25T06:24:40.000Z
2021-08-19T19:22:29.000Z
#include <algorithm> #include <cassert> #include <cstdio> #include <iostream> #include <sstream> #include <string> #include <vector> #include <cstring> using namespace std; #define MAX_NUM_ 10000001 // 6bits = 1parity bit + 32 different offsets in the same int int P_[(MAX_NUM_>>6) + 1]; // negative logic (1 bit marks a non-prime) // for x >= 0 inline bool is_prime(int x) { return x==2 ? true : (x&1 ? !((P_[(x>>6)]>>((x>>1)&0x1f))&1) : false); } // only call for odd x inline void mark_nonprime(int x) { x >>= 1; P_[x>>5] |= (1<<(x&0x1f)); } void init_primes() { for (long long x=3; x<=MAX_NUM_; x+=2) { if (is_prime(x) && x<=MAX_NUM_/x) { const long long z = x<<1; for (long long y=x*x; y<=MAX_NUM_; y+=z) { mark_nonprime(y); } } } } char cnt[10000001]; class PrimeSequences { public: int getLargestGenerator(int N, int D) { init_primes(); memset(cnt, 0, sizeof cnt); cnt[2] = 1; for (int i=3; i<=N; ++i) { if (is_prime(i)) { const int x = i/2; cnt[i] = cnt[x] + 1; } } for (int i=N; i>=1; --i) { if (cnt[i] >= D) { return i; } } return -1; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); if ((Case == -1) || (Case == 5)) test_case_5(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { int Arg0 = 10; int Arg1 = 2; int Arg2 = 7; verify_case(0, Arg2, getLargestGenerator(Arg0, Arg1)); } void test_case_1() { int Arg0 = 42; int Arg1 = 3; int Arg2 = 23; verify_case(1, Arg2, getLargestGenerator(Arg0, Arg1)); } void test_case_2() { int Arg0 = 666; int Arg1 = 7; int Arg2 = -1; verify_case(2, Arg2, getLargestGenerator(Arg0, Arg1)); } void test_case_3() { int Arg0 = 1337; int Arg1 = 5; int Arg2 = 47; verify_case(3, Arg2, getLargestGenerator(Arg0, Arg1)); } void test_case_4() { int Arg0 = 100000; int Arg1 = 5; int Arg2 = 2879; verify_case(4, Arg2, getLargestGenerator(Arg0, Arg1)); } void test_case_5() { int Arg0 = 40000; int Arg1 = 1; int Arg2 = 39989; verify_case(5, Arg2, getLargestGenerator(Arg0, Arg1)); } // END CUT HERE }; // BEGIN CUT HERE int main() { PrimeSequences ___test; ___test.run_test(-1); } // END CUT HERE
41.662162
317
0.560817
ibudiselic
e3b5558af7210b6a155636a5a85cb56a32de785f
3,941
hpp
C++
libs/core/font/include/bksge/core/font/otf/feature_variations.hpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
4
2018-06-10T13:35:32.000Z
2021-06-03T14:27:41.000Z
libs/core/font/include/bksge/core/font/otf/feature_variations.hpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
566
2017-01-31T05:36:09.000Z
2022-02-09T05:04:37.000Z
libs/core/font/include/bksge/core/font/otf/feature_variations.hpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
1
2018-07-05T04:40:53.000Z
2018-07-05T04:40:53.000Z
/** * @file feature_variations.hpp * * @brief FeatureVariations の定義 * * @author myoukaku */ #ifndef BKSGE_CORE_FONT_OTF_FEATURE_VARIATIONS_HPP #define BKSGE_CORE_FONT_OTF_FEATURE_VARIATIONS_HPP #include <bksge/core/font/otf/read_big_endian.hpp> #include <bksge/core/font/otf/types.hpp> #include <bksge/fnd/memory/unique_ptr.hpp> #include <bksge/fnd/memory/make_unique.hpp> #include <cstdint> #include <vector> namespace bksge { namespace otf { struct FeatureVariations { struct FeatureTableSubstitutionRecord { friend std::uint8_t const* ReadBigEndian( std::uint8_t const* ptr, FeatureTableSubstitutionRecord* dst, std::uint8_t const* start) { ptr = ReadBigEndian(ptr, &dst->featureIndex); ptr = ReadBigEndian(ptr, &dst->alternateFeatureOffset); if (dst->alternateFeatureOffset != 0) { // TODO //alternateFeature = bksge::make_unique<AlternateFeature>( // start + alternateFeatureOffset); (void)start; } return ptr; } uint16 featureIndex; Offset32 alternateFeatureOffset; }; struct FeatureTableSubstitution { explicit FeatureTableSubstitution(std::uint8_t const* ptr) { auto const start = ptr; uint16 majorVersion; uint16 minorVersion; uint16 substitutionCount; ptr = ReadBigEndian(ptr, &majorVersion); ptr = ReadBigEndian(ptr, &minorVersion); ptr = ReadBigEndian(ptr, &substitutionCount); substitutions.resize(substitutionCount); ptr = ReadBigEndian(ptr, &substitutions, start); } std::vector<FeatureTableSubstitutionRecord> substitutions; }; struct Condition { explicit Condition(std::uint8_t const* ptr) { ptr = ReadBigEndian(ptr, &Format); ptr = ReadBigEndian(ptr, &AxisIndex); ptr = ReadBigEndian(ptr, &FilterRangeMinValue); ptr = ReadBigEndian(ptr, &FilterRangeMaxValue); } uint16 Format; uint16 AxisIndex; F2DOT14 FilterRangeMinValue; F2DOT14 FilterRangeMaxValue; }; struct ConditionSet { explicit ConditionSet(std::uint8_t const* ptr) { auto const start = ptr; uint16 conditionCount; ptr = ReadBigEndian(ptr, &conditionCount); for (uint16 i = 0; i < conditionCount; ++i) { Offset32 conditionOffset; ptr = ReadBigEndian(ptr, &conditionOffset); conditions.emplace_back(start + conditionOffset); } } std::vector<Condition> conditions; }; struct FeatureVariationRecord { friend std::uint8_t const* ReadBigEndian( std::uint8_t const* ptr, FeatureVariationRecord* dst, std::uint8_t const* start) { Offset32 conditionSetOffset; Offset32 featureTableSubstitutionOffset; ptr = ReadBigEndian(ptr, &conditionSetOffset); ptr = ReadBigEndian(ptr, &featureTableSubstitutionOffset); if (conditionSetOffset != 0) { dst->conditionSet = bksge::make_unique<ConditionSet>( start + conditionSetOffset); } if (featureTableSubstitutionOffset != 0) { dst->featureTableSubstitution = bksge::make_unique<FeatureTableSubstitution>( start + featureTableSubstitutionOffset); } return ptr; } bksge::unique_ptr<ConditionSet> conditionSet; bksge::unique_ptr<FeatureTableSubstitution> featureTableSubstitution; }; explicit FeatureVariations(std::uint8_t const* ptr) { auto const start = ptr; uint16 majorVersion; uint16 minorVersion; uint32 featureVariationRecordCount; ptr = ReadBigEndian(ptr, &majorVersion); ptr = ReadBigEndian(ptr, &minorVersion); ptr = ReadBigEndian(ptr, &featureVariationRecordCount); featureVariationRecords.resize(featureVariationRecordCount); ptr = ReadBigEndian(ptr, &featureVariationRecords, start); } std::vector<FeatureVariationRecord> featureVariationRecords; }; } // namespace otf } // namespace bksge #endif // BKSGE_CORE_FONT_OTF_FEATURE_VARIATIONS_HPP
23.884848
72
0.700584
myoukaku