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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ed003a579b727db1c52ef8c442fafcd3068a77b8 | 2,121 | cpp | C++ | Playlist.cpp | Kazmi007/Music-Streaming-Platform | 78cd7d66c36332659e2dd0df5828c6331e177e0c | [
"OLDAP-2.7",
"OLDAP-2.8"
] | null | null | null | Playlist.cpp | Kazmi007/Music-Streaming-Platform | 78cd7d66c36332659e2dd0df5828c6331e177e0c | [
"OLDAP-2.7",
"OLDAP-2.8"
] | null | null | null | Playlist.cpp | Kazmi007/Music-Streaming-Platform | 78cd7d66c36332659e2dd0df5828c6331e177e0c | [
"OLDAP-2.7",
"OLDAP-2.8"
] | null | null | null | #include "Playlist.h"
Playlist::Playlist(const std::string &name) { // Custom consructor.
static int playlistId = 1;
this->name = name;
this->shared = false;
this->playlistId = playlistId;
playlistId += 1;
}
int Playlist::getPlaylistId() const { // Returns playlist ID.
return this->playlistId;
}
const std::string &Playlist::getName() const { // Returns playlist name.
return this->name;
}
bool Playlist::isShared() const { // Returns whether the playlist is shared or not.
return this->shared;
}
LinkedList<Song *> &Playlist::getSongs() { // Returns the list of songs.
return this->songs;
}
void Playlist::setShared(bool shared) { // Sets whether the playlist is shared.
this->shared = shared;
}
void Playlist::addSong(Song *song) { // Adds song to the end of the playlist
this->songs.insertAtTheEnd(song);
}
void Playlist::dropSong(Song *song) { // Removes given song from the playlist.
this->songs.removeNode(song);
}
void Playlist::shuffle(int seed) { // Shuffles the songs in the playlist with a given seed.
this->songs.shuffle(seed);
}
bool Playlist::operator==(const Playlist &rhs) const { // Overloaded equality operator.
return this->playlistId == rhs.playlistId && this->name == rhs.name && this->shared == rhs.shared;
}
bool Playlist::operator!=(const Playlist &rhs) const { // Overloaded inequality operator.
return !(rhs == *this);
}
std::ostream &operator<<(std::ostream &os, const Playlist &playlist) { // Overloaded operator to print playlist to output stream.
os << "playlistId: " << playlist.playlistId << " |";
os << " name: " << playlist.name << " |";
os << " shared: " << (playlist.shared ? "yes" : "no") << " |";
os << " songs: [";
Node<Song *> *firstSongNode = playlist.songs.getFirstNode();
Node<Song *> *songNode = firstSongNode;
if (songNode) {
do {
os << *(songNode->data);
if (songNode->next != firstSongNode) os << ", ";
songNode = songNode->next;
} while (songNode != firstSongNode);
}
os << "]";
return os;
}
| 29.458333 | 130 | 0.631306 | Kazmi007 |
ed01c56783d7c5aea9003ea35ea64f6145225a0e | 1,331 | cpp | C++ | unittests/BuildSystem/TempDir.cpp | dmbryson/swift-llbuild | 91f2c5dbeef135113c6574f5797c9e87ef8c3fe8 | [
"Apache-2.0"
] | 427 | 2018-05-29T14:21:02.000Z | 2022-03-16T03:17:54.000Z | unittests/BuildSystem/TempDir.cpp | dmbryson/swift-llbuild | 91f2c5dbeef135113c6574f5797c9e87ef8c3fe8 | [
"Apache-2.0"
] | 25 | 2018-07-23T08:34:15.000Z | 2021-11-05T07:13:36.000Z | unittests/BuildSystem/TempDir.cpp | dmbryson/swift-llbuild | 91f2c5dbeef135113c6574f5797c9e87ef8c3fe8 | [
"Apache-2.0"
] | 52 | 2018-07-19T19:57:32.000Z | 2022-03-11T16:05:38.000Z | //===- unittests/BuildSystem/TempDir.cpp --------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "TempDir.h"
#include "llbuild/Basic/FileSystem.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/SourceMgr.h"
llbuild::TmpDir::TmpDir(llvm::StringRef namePrefix) {
llvm::SmallString<256> tempDirPrefix;
llvm::sys::path::system_temp_directory(true, tempDirPrefix);
llvm::sys::path::append(tempDirPrefix, namePrefix);
std::error_code ec = llvm::sys::fs::createUniqueDirectory(
tempDirPrefix.str(), tempDir);
assert(!ec);
(void)ec;
}
llbuild::TmpDir::~TmpDir() {
auto fs = basic::createLocalFileSystem();
bool result = fs->remove(tempDir.c_str());
assert(result);
(void)result;
}
const char *llbuild::TmpDir::c_str() { return tempDir.c_str(); }
std::string llbuild::TmpDir::str() const { return tempDir.str(); }
| 32.463415 | 80 | 0.643877 | dmbryson |
ed01f0bfc602fbadf8c3dfa7f86b8c977d7e3049 | 2,691 | cpp | C++ | src/padamose/BranchInspector.cpp | young-developer/padamose | ad827c67ed10125b6f1af3c9300ca122c5d4fcf2 | [
"BSD-3-Clause"
] | null | null | null | src/padamose/BranchInspector.cpp | young-developer/padamose | ad827c67ed10125b6f1af3c9300ca122c5d4fcf2 | [
"BSD-3-Clause"
] | null | null | null | src/padamose/BranchInspector.cpp | young-developer/padamose | ad827c67ed10125b6f1af3c9300ca122c5d4fcf2 | [
"BSD-3-Clause"
] | 1 | 2021-12-07T13:28:58.000Z | 2021-12-07T13:28:58.000Z | // Copyright (c) 2017-2018, Cryptogogue Inc. All Rights Reserved.
// http://cryptogogue.com
#include <padamose/AbstractVersionedBranch.h>
#include <padamose/BranchInspector.h>
namespace Padamose {
//================================================================//
// BranchInspector
//================================================================//
//----------------------------------------------------------------//
BranchInspector::BranchInspector ( shared_ptr < AbstractVersionedBranch > branch ) :
mBranch ( branch ) {
}
//----------------------------------------------------------------//
BranchInspector::BranchInspector ( const BranchInspector& branchInspector ) :
mBranch ( branchInspector.mBranch ) {
}
//----------------------------------------------------------------//
BranchInspector::~BranchInspector () {
}
//----------------------------------------------------------------//
size_t BranchInspector::countDependencies () const {
shared_ptr < AbstractVersionedBranch > branch = this->mBranch.lock ();
assert ( branch );
return branch->countDependencies ();
}
//----------------------------------------------------------------//
size_t BranchInspector::getBaseVersion () const {
shared_ptr < AbstractVersionedBranch > branch = this->mBranch.lock ();
assert ( branch );
return branch->getVersion ();
}
//----------------------------------------------------------------//
size_t BranchInspector::getImmutableTop () const {
shared_ptr < AbstractVersionedBranch > branch = this->mBranch.lock ();
assert ( branch );
return branch->findImmutableTop ();
}
//----------------------------------------------------------------//
size_t BranchInspector::getTopVersion () const {
shared_ptr < AbstractVersionedBranch > branch = this->mBranch.lock ();
assert ( branch );
return branch->getTopVersion ();
}
//----------------------------------------------------------------//
bool BranchInspector::hasKey ( size_t version, string key ) const {
shared_ptr < AbstractVersionedBranch > branch = this->mBranch.lock ();
assert ( branch );
return branch->hasKey ( version, key );
}
//----------------------------------------------------------------//
bool BranchInspector::isLocked () const {
shared_ptr < AbstractVersionedBranch > branch = this->mBranch.lock ();
assert ( branch );
return branch->isLocked ();
}
//----------------------------------------------------------------//
bool BranchInspector::isPersistent () const {
shared_ptr < AbstractVersionedBranch > branch = this->mBranch.lock ();
assert ( branch );
return branch->isPersistent ();
}
} // namespace Padamose
| 32.035714 | 84 | 0.487923 | young-developer |
ed0269150e8aeec7c323422b4a231fc979611d5b | 15,219 | cpp | C++ | uring/relay.cpp | Mutinifni/urn | 9708606e05e8d4487ae9fd88654ef53dff413c07 | [
"MIT"
] | null | null | null | uring/relay.cpp | Mutinifni/urn | 9708606e05e8d4487ae9fd88654ef53dff413c07 | [
"MIT"
] | null | null | null | uring/relay.cpp | Mutinifni/urn | 9708606e05e8d4487ae9fd88654ef53dff413c07 | [
"MIT"
] | 2 | 2021-08-24T11:04:46.000Z | 2021-08-24T11:07:50.000Z | #include <arpa/inet.h>
#include <array>
#include <condition_variable>
#include <cstring>
#include <liburing.h>
#include <netdb.h>
#include <signal.h>
#include <string>
#include <sys/socket.h>
#include <thread>
#include <unistd.h>
#include <uring/relay.hpp>
#include <vector>
#define ENABLE_FIXED_BUFFERS 1
#define ENABLE_FIXED_FILE 1
#define ENABLE_SQPOLL 0
namespace urn_uring {
config::config(int argc, const char* argv[])
: threads{static_cast<uint16_t>(std::thread::hardware_concurrency())} {
for (int i = 1; i < argc; i++) {
std::string_view arg(argv[i]);
if (arg == "--threads") {
threads = atoi(argv[++i]);
} else if (arg == "--client.port") {
client.port = argv[++i];
} else if (arg == "--peer.port") {
peer.port = argv[++i];
} else {
printf("unused flag: %s\n", argv[i]);
}
}
if (!threads) {
threads = 1;
}
std::cout << "threads = " << threads << "\nclient.port = " << client.port
<< "\npeer.port = " << peer.port << '\n';
}
namespace {
void ensure_success(int code) {
if (code >= 0) {
return;
}
fprintf(stderr, "%s\n", strerror(-code));
abort();
}
struct listen_context;
constexpr int32_t num_events = 16; // per thread
constexpr int32_t memory_per_packet = 1024;
volatile sig_atomic_t has_sigint = 0;
thread_local listen_context* local_io = nullptr;
enum ring_event_type {
ring_event_type_invalid = 0,
ring_event_type_client_rx = 1,
ring_event_type_peer_rx = 2,
ring_event_type_peer_tx = 3,
ring_event_type_timer = 4,
ring_event_MAX
};
struct ring_event {
ring_event_type type;
int32_t index;
union {
struct {
struct iovec iov;
struct sockaddr_in address;
struct msghdr message;
} rx;
__kernel_timespec timeout;
};
};
constexpr int64_t k_statistics_timeout_ms = 5000;
struct countdown_latch {
countdown_latch(int64_t count) : count{count} {}
void wait() {
std::unique_lock<std::mutex> lock(mtx);
int64_t gen = generation;
if (--count == 0) {
++generation;
cond.notify_all();
return;
}
cond.wait(lock, [&]() { return gen != generation; });
}
int64_t count;
int64_t generation = 0;
std::mutex mtx = {};
std::condition_variable cond = {};
};
struct worker_args {
urn_uring::relay* relay = nullptr;
struct addrinfo* local_client_address = nullptr;
struct addrinfo* local_peer_address = nullptr;
int32_t thread_index = 0;
countdown_latch* startup_latch = nullptr;
};
struct listen_context {
// Either FD or ID depending on the usage of registered fds
int peer_socket = -1;
int client_socket = -1;
struct io_uring ring = {};
urn_uring::relay* relay = nullptr;
uint8_t* messages_buffer = nullptr;
std::array<ring_event, num_events> io_events = {};
std::vector<int32_t> free_event_ids = {};
int peer_socket_fd = -1;
int client_socket_fd = -1;
int sockets[2] = {};
worker_args worker_info = {};
struct iovec buffers_mem = {};
};
void print_address(const struct addrinfo* address) {
char readable_ip[INET6_ADDRSTRLEN] = {0};
if (address->ai_family == AF_INET) {
struct sockaddr_in* ipv4 = (struct sockaddr_in*) address->ai_addr;
inet_ntop(ipv4->sin_family, &ipv4->sin_addr, readable_ip, sizeof(readable_ip));
printf("%s:%d\n", readable_ip, ntohs(ipv4->sin_port));
} else if (address->ai_family == AF_INET6) {
struct sockaddr_in6* ipv6 = (struct sockaddr_in6*) address->ai_addr;
inet_ntop(ipv6->sin6_family, &ipv6->sin6_addr, readable_ip, sizeof(readable_ip));
printf("[%s]:%d\n", readable_ip, ntohs(ipv6->sin6_port));
}
}
int create_udp_socket(struct addrinfo* address_list) {
// quickhack: only use the first address
struct addrinfo* address = address_list;
int socket_fd = socket(address->ai_family, address->ai_socktype, address->ai_protocol);
ensure_success(socket_fd);
{
int size = 4129920;
ensure_success(setsockopt(socket_fd, SOL_SOCKET, SO_RCVBUF, &size, sizeof(size)));
}
{
int size = 4129920;
ensure_success(setsockopt(socket_fd, SOL_SOCKET, SO_SNDBUF, &size, sizeof(size)));
}
{
int enable = 1;
ensure_success(setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable)));
}
{
int enable = 1;
ensure_success(setsockopt(socket_fd, SOL_SOCKET, SO_REUSEPORT, &enable, sizeof(enable)));
}
return socket_fd;
}
void bind_socket(int fd, struct addrinfo* address) {
int bind_status = bind(fd, address->ai_addr, address->ai_addrlen);
if (bind_status == 0) {
return;
}
printf("error binding socket: %s\n", strerror(bind_status));
abort();
}
ring_event* alloc_event(listen_context* context, ring_event_type type) {
if (context->free_event_ids.size() == 0) {
printf("[thread %d] out of free events\n", context->worker_info.thread_index);
abort();
return nullptr;
}
int32_t free_id = context->free_event_ids.back();
context->free_event_ids.pop_back();
ring_event* event = &context->io_events[free_id];
event->type = type;
event->index = free_id;
event->rx.iov.iov_base = &context->messages_buffer[free_id * memory_per_packet];
event->rx.iov.iov_len = memory_per_packet;
event->rx.message.msg_name = &event->rx.address;
event->rx.message.msg_namelen = sizeof(event->rx.address);
event->rx.message.msg_iov = &event->rx.iov;
event->rx.message.msg_iovlen = 1;
return event;
}
void release_event(listen_context* context, ring_event* ev) {
context->free_event_ids.push_back(ev->index);
}
void report_features(const struct io_uring_params* params) {
uint32_t features = params->features;
auto get_name = [](uint32_t feature) {
switch (feature) {
case IORING_FEAT_SINGLE_MMAP:
return "IORING_FEAT_SINGLE_MMAP";
case IORING_FEAT_NODROP:
return "IORING_FEAT_NODROP";
case IORING_FEAT_SUBMIT_STABLE:
return "IORING_FEAT_SUBMIT_STABLE";
case IORING_FEAT_CUR_PERSONALITY:
return "IORING_FEAT_CUR_PERSONALITY";
case IORING_FEAT_FAST_POLL:
return "IORING_FEAT_FAST_POLL";
case IORING_FEAT_POLL_32BITS:
return "IORING_FEAT_POLL_32BITS";
case IORING_FEAT_SQPOLL_NONFIXED:
return "IORING_FEAT_SQPOLL_NONFIXED";
default:
return "unknown";
}
};
const uint32_t known_features[] = {IORING_FEAT_SINGLE_MMAP, IORING_FEAT_NODROP,
IORING_FEAT_SUBMIT_STABLE, IORING_FEAT_CUR_PERSONALITY,
IORING_FEAT_FAST_POLL, IORING_FEAT_POLL_32BITS,
IORING_FEAT_SQPOLL_NONFIXED};
printf("supported features:\n");
for (uint32_t feature : known_features) {
if (features & feature) {
printf("\t%s\n", get_name(feature));
}
}
}
bool is_main_worker(const listen_context* io) { return io->worker_info.thread_index == 0; }
void listen_context_initialize(listen_context* io, worker_args args) {
io->worker_info = args;
io->relay = args.relay;
struct io_uring_params params;
memset(¶ms, 0, sizeof(params));
if (ENABLE_SQPOLL) {
params.flags |= IORING_SETUP_SQPOLL;
params.sq_thread_idle = 1000;
printf("[thread %d] using SQPOLL\n", args.thread_index);
}
ensure_success(io_uring_queue_init_params(4096, &io->ring, ¶ms));
if (is_main_worker(io)) {
report_features(¶ms);
}
io->client_socket_fd = create_udp_socket(args.local_client_address);
io->peer_socket_fd = create_udp_socket(args.local_peer_address);
printf("[thread %d] sockets: %d %d\n", args.thread_index, io->client_socket_fd,
io->peer_socket_fd);
if (ENABLE_FIXED_FILE) {
io->sockets[0] = io->peer_socket_fd;
io->sockets[1] = io->client_socket_fd;
ensure_success(io_uring_register_files(&io->ring, io->sockets, 2));
io->peer_socket = 0;
io->client_socket = 1;
printf("[thread %d] using fixed files\n", args.thread_index);
} else {
io->client_socket = io->client_socket_fd;
io->peer_socket = io->peer_socket_fd;
}
io->messages_buffer = (uint8_t*) calloc(num_events, memory_per_packet);
io->free_event_ids.reserve(num_events);
for (int32_t i = 0; i < num_events; i++) {
io->free_event_ids.push_back(i);
}
if (ENABLE_FIXED_BUFFERS) {
io->buffers_mem.iov_base = io->messages_buffer;
io->buffers_mem.iov_len = num_events * memory_per_packet;
ensure_success(io_uring_register_buffers(&io->ring, &io->buffers_mem, 1));
printf("[thread %d] using fixed buffers\n", args.thread_index);
}
}
struct addrinfo* bindable_address(const char* port) {
struct addrinfo hints;
std::memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_DGRAM;
hints.ai_flags = AI_PASSIVE;
struct addrinfo* addr = nullptr;
ensure_success(getaddrinfo(nullptr, port, &hints, &addr));
return addr;
}
__kernel_timespec create_timeout(int64_t milliseconds) {
__kernel_timespec spec;
spec.tv_sec = milliseconds / 1000;
spec.tv_nsec = (milliseconds % 1000) * 1000000;
return spec;
}
#if ENABLE_FIXED_FILE
void enable_fixed_file(struct io_uring_sqe* sqe) { sqe->flags |= IOSQE_FIXED_FILE; }
#else
void enable_fixed_file(struct io_uring_sqe*) {}
#endif
#if ENABLE_FIXED_BUFFERS
void enable_fixed_buffers(struct io_uring_sqe* sqe) {
// One huge slab is registered and then partitioned manually
sqe->buf_index = 0;
}
#else
void enable_fixed_buffers(struct io_uring_sqe*) {}
#endif
void add_recvmsg(struct io_uring* ring, ring_event* ev, int32_t socket_id) {
struct io_uring_sqe* sqe = io_uring_get_sqe(ring);
if (!sqe)
abort();
io_uring_prep_recvmsg(sqe, socket_id, &ev->rx.message, 0);
io_uring_sqe_set_data(sqe, ev);
enable_fixed_file(sqe);
enable_fixed_buffers(sqe);
}
void add_sendmsg(struct io_uring* ring, ring_event* ev, int32_t socket_id) {
struct io_uring_sqe* sqe = io_uring_get_sqe(ring);
if (!sqe)
abort();
io_uring_prep_sendmsg(sqe, socket_id, &ev->rx.message, 0);
io_uring_sqe_set_data(sqe, ev);
enable_fixed_file(sqe);
enable_fixed_buffers(sqe);
}
void add_timeout(struct io_uring* ring, ring_event* ev, int64_t milliseconds) {
ev->timeout = create_timeout(milliseconds);
struct io_uring_sqe* sqe = io_uring_get_sqe(ring);
if (!sqe)
abort();
io_uring_prep_timeout(sqe, &ev->timeout, 0, 0);
io_uring_sqe_set_data(sqe, ev);
}
void worker(worker_args args) {
auto iop = std::make_unique<listen_context>();
listen_context* io = iop.get();
local_io = io;
listen_context_initialize(io, args);
struct io_uring* ring = &io->ring;
args.startup_latch->wait();
bind_socket(io->client_socket_fd, args.local_client_address);
bind_socket(io->peer_socket_fd, args.local_peer_address);
io->relay->on_thread_start(args.thread_index);
{
ring_event* ev = alloc_event(io, ring_event_type_client_rx);
add_recvmsg(ring, ev, io->client_socket);
}
{
ring_event* ev = alloc_event(io, ring_event_type_peer_rx);
add_recvmsg(ring, ev, io->peer_socket);
}
if (is_main_worker(io)) {
ring_event* ev = alloc_event(io, ring_event_type_timer);
add_timeout(ring, ev, k_statistics_timeout_ms);
}
for (;;) {
io_uring_submit_and_wait(ring, 1);
struct io_uring_cqe* cqe;
uint32_t head;
uint32_t count = 0;
io_uring_for_each_cqe(ring, head, cqe) {
++count;
ring_event* event = (ring_event*) cqe->user_data;
switch (event->type) {
case ring_event_type_peer_rx: {
if (cqe->res < 0) {
printf("thread [%d] peer rx %s\n", args.thread_index, strerror(-cqe->res));
abort();
}
const msghdr* message = &event->rx.message;
uring::packet packet{(const std::byte*) message->msg_iov->iov_base, (uint32_t) cqe->res};
io->relay->on_peer_received(uring::endpoint(event->rx.address, io), packet);
release_event(io, event);
ring_event* rx_event = alloc_event(io, ring_event_type_peer_rx);
add_recvmsg(ring, rx_event, io->peer_socket);
break;
}
case ring_event_type_peer_tx: {
uring::packet packet{(const std::byte*) event->rx.message.msg_iov->iov_base,
(uint32_t) cqe->res};
io->relay->on_session_sent(packet);
release_event(io, event);
break;
}
case ring_event_type_client_rx: {
if (cqe->res < 0) {
printf("thread [%d] client rx: %s\n", args.thread_index, strerror(-cqe->res));
abort();
}
const msghdr* message = &event->rx.message;
io->relay->on_client_received(
uring::endpoint(event->rx.address, io),
uring::packet((const std::byte*) message->msg_iov->iov_base, cqe->res));
release_event(io, event);
ring_event* rx_event = alloc_event(io, ring_event_type_client_rx);
add_recvmsg(ring, rx_event, io->client_socket);
break;
}
case ring_event_type_timer: {
io->relay->on_statistics_tick();
add_timeout(ring, event, k_statistics_timeout_ms); // reuse
break;
}
default: {
printf("unhandled ev\n");
release_event(io, event);
break;
}
}
}
io_uring_cq_advance(ring, count);
if (has_sigint) {
break;
}
}
printf("%d worker exiting \n", io->worker_info.thread_index);
io_uring_queue_exit(ring);
}
void handle_sigint(int) { has_sigint = 1; }
} // namespace
relay::relay(const urn_uring::config& conf) noexcept
: config_{conf}, logic_{config_.threads, client_, peer_} {}
int relay::run() noexcept {
if (ENABLE_SQPOLL) {
if (geteuid() != 0) {
printf("SQPOLL needs sudo\n");
return 1;
}
}
signal(SIGINT, handle_sigint);
int32_t thread_count = std::max(uint16_t(1), config_.threads);
struct addrinfo* local_client_address = bindable_address("3478");
struct addrinfo* local_peer_address = bindable_address("3479");
print_address(local_client_address);
print_address(local_peer_address);
countdown_latch latch(thread_count);
auto make_worker_args = [=, &latch](int32_t thread_index) {
worker_args args;
args.relay = this;
args.local_client_address = local_client_address;
args.local_peer_address = local_peer_address;
args.thread_index = thread_index;
args.startup_latch = &latch;
return args;
};
std::vector<std::thread> worker_threads;
for (int32_t i = 1; i < thread_count; i++) {
worker_threads.emplace_back(worker, make_worker_args(i));
}
worker_args main_thread_args = make_worker_args(0);
worker(main_thread_args);
printf("joining\n");
for (auto& t : worker_threads) {
t.join();
}
printf("joined\n");
return 0;
}
void uring::session::start_send(const uring::packet& packet) noexcept {
listen_context* io = local_io;
ring_event* tx_event = alloc_event(io, ring_event_type_peer_tx);
tx_event->rx.address = client_endpoint.address;
memcpy(tx_event->rx.iov.iov_base, packet.data(), packet.size());
tx_event->rx.iov.iov_len = packet.size();
add_sendmsg(&io->ring, tx_event, io->client_socket);
}
} // namespace urn_uring
| 27.873626 | 99 | 0.67304 | Mutinifni |
ed0277bd2f37f0c7598d51e56627b22f5b7d4890 | 194 | hpp | C++ | include/sql/fusion/common.hpp | cviebig/lib-sql | fed42f80b5866503c5f5710d791feec213c051a1 | [
"MIT"
] | 4 | 2017-09-25T00:03:31.000Z | 2020-04-02T07:06:24.000Z | include/sql/fusion/common.hpp | cviebig/lib-sql | fed42f80b5866503c5f5710d791feec213c051a1 | [
"MIT"
] | 1 | 2018-05-16T20:00:42.000Z | 2018-05-30T13:21:20.000Z | include/sql/fusion/common.hpp | cviebig/lib-sql | fed42f80b5866503c5f5710d791feec213c051a1 | [
"MIT"
] | 1 | 2022-01-05T20:49:47.000Z | 2022-01-05T20:49:47.000Z | #ifndef SQL_PARSER_FUSION_COMMON_HPP
#define SQL_PARSER_FUSION_COMMON_HPP
#include "sql/ast/common.hpp"
#include <boost/fusion/include/adapt_struct.hpp>
#endif //SQL_PARSER_FUSION_COMMON_HPP
| 21.555556 | 48 | 0.840206 | cviebig |
ed05c033f63aea0e80feac1d7795b93ee266cbb5 | 15,059 | cpp | C++ | source/Image/JPEGLoader.cpp | badbrainz/pme | 1c8e6f3d154cc59613f5ef3f2f8293f488c64b28 | [
"WTFPL"
] | null | null | null | source/Image/JPEGLoader.cpp | badbrainz/pme | 1c8e6f3d154cc59613f5ef3f2f8293f488c64b28 | [
"WTFPL"
] | null | null | null | source/Image/JPEGLoader.cpp | badbrainz/pme | 1c8e6f3d154cc59613f5ef3f2f8293f488c64b28 | [
"WTFPL"
] | null | null | null | #include "image.h"
#include <stdio.h>
#ifndef max
#define max(a, b) (((a)>(b))?(a):(b))
#endif
#ifndef min
#define min(a, b) (((a)<(b))?(a):(b))
#endif
unsigned char getByte();
char fileOpen(const char *);
void decodeQTable(int);
void strmSkip(int n);
void decodeBlock();
void fileClose();
void getInfo();
void fidct();
int wordDec(int);
typedef unsigned short qTable[64];
typedef struct
{
struct tables
{
unsigned char size;
unsigned char code;
} small[512], large[65536];
} HuffTable;
void decodeHuffTable(int);
typedef struct
{
HuffTable *huffAC, *huffDC;
qTable *qTab;
int dcPrev,smpx, smpy;
float t[256];
}ComponentTable;
ComponentTable component[4];
HuffTable huffTableAC[4],
huffTableDC[4];
qTable qtable[4];
int xblock, yblock, blockx, blocky,
bsize, restartInt, bfree;
unsigned int dt;
unsigned char *data, *bpos , *dend,
eof , ssStart, ssEnd,
sbits, prec , ncomp;
float dctt[64];
int zigzag[64]=
{
0, 1, 8, 16, 9, 2, 3, 10,
17, 24, 32, 25, 18, 11, 4, 5,
12, 19, 26, 33, 40, 48, 41, 34,
27, 20, 13, 6, 7, 14, 21, 28,
35, 42, 49, 56, 57, 50, 43, 36,
29, 22, 15, 23, 30, 37, 44, 51,
58, 59, 52, 45, 38, 31, 39, 46,
53, 60, 61, 54, 47, 55, 62, 63
};
char fileOpen(const char *filename)
{
FILE *stream;
data = NULL;
if ((stream=fopen(filename, "rb"))==NULL)
return 0;
else
{
fseek(stream, 0, SEEK_END);
bsize = ftell(stream);
fseek(stream, 0, SEEK_SET);
data = new unsigned char[bsize];
fread(data, 1, bsize, stream);
fclose(stream);
return 1;
}
}
void fileClose(void)
{
if (data)
delete[] data;
}
unsigned char getByte(void)
{
if (bpos>=dend)
{
eof = 1;
return 0;
}
else
return *bpos++;
}
void strmSkip(int n)
{
unsigned char a, b;
bfree+=n;
dt<<=n;
while (bfree>=8)
{
bfree-=8;
b = getByte();
if (b==255)
a=getByte();
dt|=(b<<bfree);
}
}
int huffDec(HuffTable *h)
{
unsigned int id, n, c;
id = (dt>>(23));
n = h->small[id].size;
c = h->small[id].code;
if (n==255)
{
id = (dt>>(16));
n = h->large[id].size;
c = h->large[id].code;
}
strmSkip(n);
return c;
}
int wordDec(int n)
{
int w;
unsigned int s;
if (n==0)
return 0;
else
{
s= (dt>>(31));
w= (dt>>(32-n));
strmSkip(n);
if (s==0)
w = (w|(0xffffffff<<n))+1;
}
return w;
}
void Image::getJPGInfo()
{
unsigned char cn, sf, qt;
int i;
prec = getByte();
if (prec!=8)
return;
height = ((getByte()<<8)+getByte());
width = ((getByte()<<8)+getByte());
ncomp = getByte();
if ((ncomp!=3)&&(ncomp!=1))
return;
for (i=0;i<ncomp;i++)
{
cn = getByte();
sf = getByte();
qt = getByte();
component[cn-1].qTab = &qtable[qt];
component[cn-1].smpy = sf&15;
component[cn-1].smpx = (sf>>4)&15;
}
if (component[0].smpx == 1)
blockx = 8;
else
blockx = 16;
if (component[0].smpy==1)
blocky = 8;
else
blocky = 16;
xblock=width/blockx;
if ((width & (blockx-1))!=0)
xblock++;
yblock = height/blocky;
if ((height&(blocky-1))!=0)
yblock++;
}
void decodeHuffTable(int len)
{
int length[257], i, j, n, code, codelen, delta, rcode, cd, rng;
unsigned char lengths[16], b, symbol[257];
HuffTable *h;
len-=2;
while (len>0)
{
b = getByte();
len--;
h = &huffTableDC[0];
switch (b)
{
case 0:
h = &huffTableDC[0];
break;
case 1:
h = &huffTableDC[1];
break;
case 16:
h = &huffTableAC[0];
break;
case 17:
h=&huffTableAC[1];
break;
}
for (i=0;i<16;i++)
lengths[i] = getByte();
len -= 16;
n = 0;
for (i=0;i<16;i++)
{
len-=lengths[i];
for (j=0;j<lengths[i];j++)
{
symbol[n] = getByte();
length[n++] = i+1;
}
}
code = 0;
codelen = length[0];
for (i=0;i<n;i++)
{
rcode = code<<(16-codelen);
cd = rcode>>7;
if (codelen<=9)
{
rng = 1 <<(9-codelen);
for (j=cd;j<cd+rng;j++)
{
h->small[j].code = (unsigned char)symbol[i];
h->small[j].size = (unsigned char)codelen;
}
}
else
{
h->small[cd].size=(unsigned char)255;
rng = 1<<(16-codelen);
for (j=rcode;j<rcode+rng;j++)
{
h->large[j].code=(unsigned char)symbol[i];
h->large[j].size=(unsigned char)codelen;
}
}
code++;
delta=length[i+1]-codelen;
code<<=delta;
codelen+=delta;
}
}
}
void fidct(void)
{
float a = 0.353553385f,
b = 0.490392625f,
c = 0.415734798f,
d = 0.277785122f,
e = 0.097545162f,
f = 0.461939752f,
g = 0.191341713f,
cd =0.6935199499f,
be =0.5879377723f,
bc =0.9061274529f,
de =0.3753302693f,
a0, f2, g2, a4, f6, g6, s0, s1, s2, s3,
t0, t1, t2, t3, m0, m1, m2, m3,
h0, h1, h2, h3, r0, r1, r2, r3, w;
int i;
for (i=0;i<64;i+=8)
{
if ((dctt[i+1]!=0)||(dctt[i+2]!=0)||(dctt[i+3]!=0)||(dctt[i+4]!=0)||(dctt[i+5]!=0)||(dctt[i+6]!=0)||(dctt[i+7]!=0))
{
a0 = a*dctt[i];
f2 = f*dctt[i+2];
g2 = g*dctt[i+2];
a4 = a*dctt[i+4];
g6 = g*dctt[i+6];
f6 = f*dctt[i+6];
m0 = a0+a4;
m1 = a0-a4;
m2 = f2+g6;
m3 = g2-f6;
s0 = m0+m2;
s1 = m1+m3;
s2 = m1-m3;
s3 = m0-m2;
h2 = dctt[i+7]+dctt[i+1];
h3 = dctt[i+7]-dctt[i+1];
r2 = dctt[i+3]+dctt[i+5];
r3 = dctt[i+3]-dctt[i+5];
h0 = cd*dctt[i+1];
h1 = be*dctt[i+1];
r0 = be*dctt[i+5];
r1 = cd*dctt[i+3];
w = de*r3;
t0 = h1+r1+e*(h3+r3)-w;
t1 = h0-r0-d*(h2-r3)-w;
w = bc*r2;
t2 = h0+r0+c*(h3+r2)-w;
t3 = h1-r1-b*(h2+r2)+w;
dctt[i] = s0+t0;
dctt[i+1] = s1+t1;
dctt[i+2] = s2+t2;
dctt[i+3] = s3+t3;
dctt[i+4] = s3-t3;
dctt[i+5] = s2-t2;
dctt[i+6] = s1-t1;
dctt[i+7] = s0-t0;
}
else
{
a0 = dctt[i]*a;
dctt[i]=dctt[i+1]=dctt[i+2]=dctt[i+3]=dctt[i+4]=dctt[i+5]=dctt[i+6]=dctt[i+7]=a0;
}
}
for (i=0;i<8;i++)
{
if ((dctt[8+i]!=0)||(dctt[16+i]!=0)||(dctt[24+i]!=0)||(dctt[32+i]!=0)||(dctt[40+i]!=0)||(dctt[48+i]!=0)||(dctt[56+i]!=0))
{
a0 = a*dctt[i];
f2 = f*dctt[16+i];
g2 = g*dctt[16+i];
a4 = a*dctt[32+i];
g6 = g*dctt[48+i];
f6 = f*dctt[48+i];
m0 = a0+a4;
m1 = a0-a4;
m2 = f2+g6;
m3 = g2-f6;
s0 = m0+m2;
s1 = m1+m3;
s2 = m1-m3;
s3 = m0-m2;
h2 = dctt[56+i]+dctt[8+i];
h3 = dctt[56+i]-dctt[8+i];
r2 = dctt[24+i]+dctt[40+i];
r3 = dctt[24+i]-dctt[40+i];
h0 = cd*dctt[8+i];
h1 = be*dctt[8+i];
r0 = be*dctt[40+i];
r1 = cd*dctt[24+i];
w = de*r3;
t0 = h1+r1+e*(h3+r3)-w;
t1 = h0-r0-d*(h2-r3)-w;
w = bc*r2;
t2 = h0+r0+c*(h3+r2)-w;
t3 = h1-r1-b*(h2+r2)+w;
dctt[i] = s0+t0;
dctt[i+8] = s1+t1;
dctt[i+16] = s2+t2;
dctt[i+24] = s3+t3;
dctt[i+32] = s3-t3;
dctt[i+40] = s2-t2;
dctt[i+48] = s1-t1;
dctt[i+56] = s0-t0;
}
else
{
a0 = dctt[i]*a;
dctt[i]=dctt[i+8]=dctt[i+16]=dctt[i+24]=dctt[i+32]=dctt[i+40]=dctt[i+48]=dctt[i+56]=a0;
}
}
}
void decodeQTable(int len)
{
int i;
unsigned char b;
len-=2;
while (len>0)
{
b = (unsigned char)getByte();
len--;
if ((b&16)==0)
{
for (i=0;i<64;i++)
qtable[b&15][i]=getByte();
len-=64;
}
else
{
for (i=0;i<64;i++)
qtable[b&15][i]=((getByte()<<8)+getByte());
len-=128;
}
}
}
void decodeBlock(void)
{
int compn, i, j, b, p, codelen, code, cx, cy, otab[64];
qTable *qtab;
for (compn=0;compn<ncomp;compn++)
{
qtab = component[compn].qTab;
for (cy=0;cy<component[compn].smpy;cy++)
{
for (cx=0;cx<component[compn].smpx;cx++)
{
for (i=0;i<64;i++)
otab[i]=0;
codelen= huffDec(component[compn].huffDC);
code=wordDec(codelen);
otab[0] = code+component[compn].dcPrev;
component[compn].dcPrev = otab[0];
i=1;
while (i<64)
{
codelen=huffDec(component[compn].huffAC);
if (codelen==0)
i=64;
else
if (codelen==0xf0)
i+=16;
else
{
code = wordDec(codelen&15);
i = i+(codelen>>4);
otab[i++]=code;
}
}
for (i=0;i<64;i++)
dctt[zigzag[i]]=(float)((*qtab)[i]*otab[i]);
fidct();
b=(cy<<7)+(cx<<3);
p=0;
for (i=0;i<8;i++)
{
for (j=0;j<8;j++)
component[compn].t[b++]=dctt[p++]+128;
b+=8;
}
}
}
}
}
int Image::decodeScanJPG()
{
int nnx, nny, i, j;
int xmin, ymin, xmax, ymax, blockn, adr1, adr2;
int y1, u1, v1, y2, u2, v2, u3, v3;
int dux, duy, dvx, dvy;
unsigned char sc, ts;
float cy, cu, cv;
components = int(getByte());
setFormat(GL_BGR);
setInternalFormat(GL_RGB8);
if (dataBuffer)
deleteArray(dataBuffer);
dataBuffer = new GLubyte[width*height*components];
for (i=0;i<components;i++)
{
sc = getByte();
ts = getByte();
component[sc-1].huffDC = &huffTableDC[ts>>4];
component[sc-1].huffAC = &huffTableAC[ts&15];
}
ssStart = getByte();
ssEnd = getByte();
sbits = getByte();
if ((ssStart!=0)||(ssEnd!=63))
return 0;
if (components == 3)
{
dux = 2+component[1].smpx-component[0].smpx;
duy = 2+component[1].smpy-component[0].smpy;
dvx = 2+component[2].smpx-component[0].smpx;
dvy = 2+component[2].smpy-component[0].smpy;
}
dt = 0;
bfree = 0;
strmSkip(32);
blockn=0;
ymin=0;
for (nny=0;nny<yblock;nny++)
{
ymax = ymin+blocky;
if (ymax>height)
ymax = height;
xmin=0;
for (nnx=0;nnx<xblock;nnx++)
{
xmax=xmin+blockx;
if (xmax>width)
xmax=width;
decodeBlock();
blockn++;
if ((blockn==restartInt)&&((nnx<xblock-1)||(nny<yblock-1)))
{
blockn=0;
if (bfree!=0)
strmSkip(8-bfree);
if (wordDec(8)!=255)
return 0;
for (i=0;i<components;i++)
component[i].dcPrev=0;
}
if (components ==3)
{
y1=u1=v1=0;
adr1=(height-1-ymin)*width+xmin;
for (i=ymin;i<ymax;i++)
{
adr2=adr1;
adr1-=width;
y2=y1;
y1+=16;
u3=(u1>>1)<<4;
u1+=duy;
v3=(v1>>1)<<4;
v1+=dvy;
u2=v2=0;
for (j=xmin;j<xmax;j++)
{
int cr, cg, cb;
cy=component[0].t[y2++];
cu=component[1].t[u3+(u2>>1)]-128.0f;
cv=component[2].t[v3+(v2>>1)]-128.0f;
cr=(int)(cy+1.402f*cv);
cg=(int)(cy-0.34414f*cu-0.71414f*cv);
cb=(int)(cy+1.772f*cu);
dataBuffer[3*adr2] = max(0, min(255, cb));
dataBuffer[3*adr2+1] = max(0, min(255, cg));
dataBuffer[3*adr2+2] = max(0, min(255, cr));
adr2++;
u2+=dux;
v2+=dvx;
}
}
}
else
if (components==1)
{
y1=0;
adr1=(height-1-ymin)*width+xmin;
for (i=ymin;i<ymax;i++)
{
adr2=adr1;
adr1-=width;
y2=y1;
y1+=16;
for (j=xmin;j<xmax;j++)
{
int lum=(int)component[0].t[y2++];
dataBuffer[adr2++]=max(0, min(255, lum));
}
}
}
xmin=xmax;
}
ymin=ymax;
}
return 1;
}
int Image::decodeJPG()
{
int w;
unsigned char a, hdr=0, scan=0;
eof=0;
bpos=data;
dend=bpos+bsize;
w=((getByte()<<8)+getByte());
if (w!=0xffd8)
return 0;
while (eof==0)
{
a=(unsigned char)getByte();
if (a!=0xff)
return 0;
a=(unsigned char)getByte();
w=((getByte()<<8)+getByte());
switch (a)
{
case 0xe0:
if (hdr!=0)
break;
if (getByte()!='J')
return 0;
if (getByte()!='F')
return 0;
if (getByte()!='I')
return 0;
if (getByte()!='F')
return 0;
hdr=1;
w-=4;
break;
case 0xc0:
getJPGInfo();
w=0;
break;
case 0xc4:
decodeHuffTable(w);
w=0;
break;
case 0xd9:
w=0;
break;
case 0xda:
if (scan!=0)
break;
scan=1;
if (!decodeScanJPG())
return 0;
w=0;
eof=1;
break;
case 0xdb:
decodeQTable(w);
w=0;
break;
case 0xdd:
restartInt=((getByte()<<8)+getByte());
w=0;
break;
}
while (w>2)
{
getByte();
w--;
}
}
return 1;
}
bool Image::loadJPG(const char *filename)
{
int i;
for (i=0;i<4;i++)
component[i].dcPrev=0;
restartInt=-1;
if (fileOpen(filename))
{
int ret= decodeJPG();
fileClose();
if (!ret)
return false;
return true;
}
else
return false;
}
| 19.972149 | 126 | 0.413042 | badbrainz |
ed071d70b090b858997f13c621bf69600b645a14 | 572 | cc | C++ | bucket_79/mariadb103/patches/patch-client_mysql.cc | jrmarino/ravensource | 91d599fd1f2af55270258d15e72c62774f36033e | [
"FTL"
] | 17 | 2017-04-22T21:53:52.000Z | 2021-01-21T16:57:55.000Z | bucket_79/mariadb103/patches/patch-client_mysql.cc | jrmarino/ravensource | 91d599fd1f2af55270258d15e72c62774f36033e | [
"FTL"
] | 186 | 2017-09-12T20:46:52.000Z | 2021-11-27T18:15:14.000Z | bucket_79/mariadb103/patches/patch-client_mysql.cc | jrmarino/ravensource | 91d599fd1f2af55270258d15e72c62774f36033e | [
"FTL"
] | 74 | 2017-09-06T14:48:01.000Z | 2021-08-28T02:48:27.000Z | --- client/mysql.cc.orig 2021-08-02 10:58:55 UTC
+++ client/mysql.cc
@@ -61,8 +61,8 @@ static char *server_version= NULL;
extern "C" {
#if defined(HAVE_CURSES_H) && defined(HAVE_TERM_H)
-#include <curses.h>
-#include <term.h>
+#include <ncurses/curses.h>
+#include <ncurses/term.h>
#else
#if defined(HAVE_TERMIOS_H)
#include <termios.h>
@@ -81,7 +81,7 @@ extern "C" {
#endif
#undef SYSV // hack to avoid syntax error
#ifdef HAVE_TERM_H
-#include <term.h>
+#include <ncurses/term.h>
#endif
#endif
#endif /* defined(HAVE_CURSES_H) && defined(HAVE_TERM_H) */
| 24.869565 | 60 | 0.673077 | jrmarino |
ed0879b779ba5ea353dc810488ac6cd9ebefd369 | 874 | cpp | C++ | src/test/seq/select.cpp | LaudateCorpus1/sequences | 637e0abe60bee381a58e2a933829f39b4459587a | [
"MIT"
] | 103 | 2015-10-11T18:42:16.000Z | 2022-02-25T18:56:07.000Z | src/test/seq/select.cpp | LaudateCorpus1/sequences | 637e0abe60bee381a58e2a933829f39b4459587a | [
"MIT"
] | 7 | 2017-10-11T10:58:02.000Z | 2021-11-10T10:55:44.000Z | src/test/seq/select.cpp | LaudateCorpus1/sequences | 637e0abe60bee381a58e2a933829f39b4459587a | [
"MIT"
] | 12 | 2015-11-17T12:34:47.000Z | 2022-02-02T00:47:50.000Z | // Copyright (c) 2015-2020 Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/sequences/
#include <tao/seq/integer_sequence.hpp>
#include <tao/seq/select.hpp>
#include <type_traits>
int main()
{
using namespace tao::seq;
using S = integer_sequence< int, 4, 7, -2, 0, 3 >;
using U = integer_sequence< unsigned, 42 >;
static_assert( select< 0, S >::value == 4, "oops" );
static_assert( select< 1, S >::value == 7, "oops" );
static_assert( select< 2, S >::value == -2, "oops" );
static_assert( select< 3, S >::value == 0, "oops" );
static_assert( select< 4, S >::value == 3, "oops" );
static_assert( std::is_same< select< 0, S >::value_type, int >::value, "oops" );
static_assert( select< 0, U >::value == 42, "oops" );
static_assert( std::is_same< select< 0, U >::value_type, unsigned >::value, "oops" );
}
| 33.615385 | 88 | 0.628146 | LaudateCorpus1 |
ed094f8a08cf666a711aa970196395f4cf0dd3e5 | 3,612 | cc | C++ | chrome/browser/ui/app_list/search/files/drive_search_browsertest.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | chrome/browser/ui/app_list/search/files/drive_search_browsertest.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86 | 2015-10-21T13:02:42.000Z | 2022-03-14T07:50:50.000Z | chrome/browser/ui/app_list/search/files/drive_search_browsertest.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2021 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 "chrome/browser/ash/drive/drive_integration_service.h"
#include "chrome/browser/ash/drive/drivefs_test_support.h"
#include "chrome/browser/ash/file_manager/path_util.h"
#include "chrome/browser/ui/app_list/search/app_list_search_test_helper.h"
namespace app_list {
// This class contains additional logic to set up DriveFS and enable testing for
// Drive file search in the launcher.
class AppListDriveSearchBrowserTest : public AppListSearchBrowserTest {
public:
void SetUpInProcessBrowserTestFixture() override {
create_drive_integration_service_ = base::BindRepeating(
&AppListDriveSearchBrowserTest::CreateDriveIntegrationService,
base::Unretained(this));
service_factory_for_test_ = std::make_unique<
drive::DriveIntegrationServiceFactory::ScopedFactoryForTest>(
&create_drive_integration_service_);
}
protected:
virtual drive::DriveIntegrationService* CreateDriveIntegrationService(
Profile* profile) {
base::ScopedAllowBlockingForTesting allow_blocking;
base::FilePath mount_path = profile->GetPath().Append("drivefs");
fake_drivefs_helpers_[profile] =
std::make_unique<drive::FakeDriveFsHelper>(profile, mount_path);
auto* integration_service = new drive::DriveIntegrationService(
profile, std::string(), mount_path,
fake_drivefs_helpers_[profile]->CreateFakeDriveFsListenerFactory());
return integration_service;
}
private:
drive::DriveIntegrationServiceFactory::FactoryCallback
create_drive_integration_service_;
std::unique_ptr<drive::DriveIntegrationServiceFactory::ScopedFactoryForTest>
service_factory_for_test_;
std::map<Profile*, std::unique_ptr<drive::FakeDriveFsHelper>>
fake_drivefs_helpers_;
};
// Test that Drive files can be searched.
IN_PROC_BROWSER_TEST_F(AppListDriveSearchBrowserTest, DriveSearchTest) {
base::ScopedAllowBlockingForTesting allow_blocking;
drive::DriveIntegrationService* drive_service =
drive::DriveIntegrationServiceFactory::FindForProfile(GetProfile());
ASSERT_TRUE(drive_service->IsMounted());
base::FilePath mount_path = drive_service->GetMountPointPath();
ASSERT_TRUE(base::WriteFile(mount_path.Append("my_file.gdoc"), "content"));
ASSERT_TRUE(
base::WriteFile(mount_path.Append("other_file.gsheet"), "content"));
SearchAndWaitForProviders("my", {ResultType::kDriveSearch});
const auto results = PublishedResultsForProvider(ResultType::kDriveSearch);
ASSERT_EQ(results.size(), 1u);
ASSERT_TRUE(results[0]);
EXPECT_EQ(base::UTF16ToASCII(results[0]->title()), "my_file");
}
// Test that Drive folders can be searched.
IN_PROC_BROWSER_TEST_F(AppListDriveSearchBrowserTest, DriveFolderTest) {
base::ScopedAllowBlockingForTesting allow_blocking;
drive::DriveIntegrationService* drive_service =
drive::DriveIntegrationServiceFactory::FindForProfile(GetProfile());
ASSERT_TRUE(drive_service->IsMounted());
base::FilePath mount_path = drive_service->GetMountPointPath();
ASSERT_TRUE(base::CreateDirectory(mount_path.Append("my_folder")));
ASSERT_TRUE(base::CreateDirectory(mount_path.Append("other_folder")));
SearchAndWaitForProviders("my", {ResultType::kDriveSearch});
const auto results = PublishedResultsForProvider(ResultType::kDriveSearch);
ASSERT_EQ(results.size(), 1u);
ASSERT_TRUE(results[0]);
EXPECT_EQ(base::UTF16ToASCII(results[0]->title()), "my_folder");
}
} // namespace app_list
| 40.58427 | 80 | 0.777409 | zealoussnow |
ed0abd8c3d8ed4a09cd6b81ccbeb73e70dbf8c62 | 1,160 | hpp | C++ | bt/ActiveSelector.hpp | river34/game-bt | a0464ae782ebcddd638633016cd65c5b5db14cc3 | [
"MIT"
] | 1 | 2018-11-08T09:56:11.000Z | 2018-11-08T09:56:11.000Z | bt/ActiveSelector.hpp | river34/game-bt | a0464ae782ebcddd638633016cd65c5b5db14cc3 | [
"MIT"
] | null | null | null | bt/ActiveSelector.hpp | river34/game-bt | a0464ae782ebcddd638633016cd65c5b5db14cc3 | [
"MIT"
] | null | null | null | //
// ActiveSelector.hpp
// GameBT
//
// Created by River Liu on 15/1/2018.
// Copyright © 2018 River Liu. All rights reserved.
//
// ActiveSelector is a Selector that actively rechecks
// its children.
#ifndef ActiveSelector_hpp
#define ActiveSelector_hpp
#include "Selector.hpp"
namespace BT
{
class ActiveSelector : public Selector
{
public:
ActiveSelector() : Selector("ActiveSelector") { }
ActiveSelector(const std::string& _name) : Selector(_name) { }
virtual ~ActiveSelector() { }
inline virtual void onInitialize(Blackboard* _blackboard) override { m_CurrentChild = m_Children.end(); }
virtual Status onUpdate(Blackboard* _blackboard) override
{
auto prev = m_CurrentChild;
Selector::onInitialize(_blackboard);
Status status = Selector::onUpdate(_blackboard);
if (prev != m_Children.end() && prev != m_CurrentChild)
{
(*prev)->abort();
}
return status;
}
inline static Behavior* create(const BehaviorParams& _params) { return new ActiveSelector; }
};
}
#endif /* ActiveSelector_hpp */
| 28.292683 | 113 | 0.642241 | river34 |
ed0b42afdf4690552f97094a3d0668aaf3beed6d | 59,826 | cpp | C++ | tools/winmd2objc/lib/ObjectModel.cpp | crossmob/WinObjC | 7bec24671c4c18b81aaf85eff2887438f18a697c | [
"MIT"
] | 6,717 | 2015-08-06T18:04:37.000Z | 2019-05-04T12:38:51.000Z | tools/winmd2objc/lib/ObjectModel.cpp | Michael-Young48/WinObjC | 7bec24671c4c18b81aaf85eff2887438f18a697c | [
"MIT"
] | 2,711 | 2015-08-06T18:41:09.000Z | 2019-04-29T12:14:23.000Z | tools/winmd2objc/lib/ObjectModel.cpp | Michael-Young48/WinObjC | 7bec24671c4c18b81aaf85eff2887438f18a697c | [
"MIT"
] | 1,021 | 2015-08-06T18:08:56.000Z | 2019-04-14T06:50:57.000Z | //******************************************************************************
//
// Copyright (c) Microsoft. All rights reserved.
//
// This code is licensed under the MIT License (MIT).
//
// 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 "Precompiled.h"
#include <ObjectModel.h>
#include <MetadataScope.h>
using namespace std;
//#include <utility.h>
//#include <WexTestClass.h>
//
//#define LOGFILE_OUTPUT(ftm, ...) \
// { \
// String output = L"<DebugOutput>"; \
// output += EscapeXml(String().Format(ftm, __VA_ARGS__)); \
// output += L"</DebugOutput>"; \
// WEX::Logging::Log::Xml(output); \
// }
namespace ObjectModel {
class DecodeMetadata : public Visitor {
MetaDataConvert* _converter;
wstring _currentNameSpace;
ULONG GetMethodSigSize(PCCOR_SIGNATURE signature);
ULONG DecodeEncodeSig(PCCOR_SIGNATURE signature,
ULONG signatureLength,
mdParamDef parameterToken = mdTokenNil,
bool returnParameter = false,
shared_ptr<ObjectModel::Symbol>* sym = nullptr);
ULONG DecodeEncodeFieldSigs(PCCOR_SIGNATURE signature, ULONG signatureLength, ObjectModel::FieldInfo& elementInfo);
ULONG DecodeEncodeMethodSigs(mdMethodDef methodTokenm,
PCCOR_SIGNATURE signature,
ULONG signatureLength,
ObjectModel::MemberInfo& memberInfo);
ULONG DecodeEncodeTypeSpecSigs(PCCOR_SIGNATURE signature, ULONG signatureLength, shared_ptr<ObjectModel::Symbol>* sym = nullptr);
void NameFromToken(mdToken token, bool nameForParameter = true, shared_ptr<ObjectModel::Symbol>* sym = nullptr);
void DecodeMetadata::DecodeParamAttrs(ULONG attrs, ObjectModel::ParameterInfo& paramInfo);
public:
DecodeMetadata(MetaDataConvert* converter, const wstring& currentNameSpace)
: _converter(converter),
_currentNameSpace(currentNameSpace)
{
}
virtual void Visit(const shared_ptr<NameSpace>& nameSpace) {
for (auto it = nameSpace->Enums.begin(); it != nameSpace->Enums.end(); it++) {
(*it)->Visit(this);
}
for (auto it = nameSpace->Structs.begin(); it != nameSpace->Structs.end(); it++) {
(*it)->Visit(this);
}
for (auto it = nameSpace->Delegates.begin(); it != nameSpace->Delegates.end(); it++) {
(*it)->Visit(this);
}
for (auto it = nameSpace->Interfaces.begin(); it != nameSpace->Interfaces.end(); it++) {
(*it)->Visit(this);
}
for (auto it = nameSpace->RuntimeClasses.begin(); it != nameSpace->RuntimeClasses.end(); it++) {
(*it)->Visit(this);
}
for (auto it = nameSpace->ApiContracts.begin(); it != nameSpace->ApiContracts.end(); it++) {
(*it)->Visit(this);
}
for (auto it = nameSpace->AttributeDefs.begin(); it != nameSpace->AttributeDefs.end(); it++) {
(*it)->Visit(this);
}
}
virtual void Visit(const shared_ptr<Enum>& e) {
if (e->Category & ObjectModel::TypeCategory::WinRtGeneric) {
return;
}
PopulateAttributes(e->Token, e->Attributes);
wchar_t name[MaxTypeNameLen];
name[0] = 0;
ULONG nameLen = 0;
DWORD attrs = 0;
PCCOR_SIGNATURE sig;
ULONG sigLen;
UVCP_CONSTANT constValue;
ULONG constValueLen;
e->FlagsEnum = HasAttribute(e->Token, L"System.FlagsAttribute");
size_t maxNameLen = 0;
CMetadataFieldEnumerator enumFields(_converter->Scope(), e->Token);
for (auto it = enumFields.begin(); it != enumFields.end(); ++it) {
_converter->Scope()
->GetFieldProps(*it, nullptr, name, MaxTypeNameLen, &nameLen, &attrs, &sig, &sigLen, nullptr, &constValue, &constValueLen);
// Gather any types defined in the enumeration
if (IsFdSpecialName(attrs)) {
ObjectModel::FieldInfo specialTypeInfo;
DecodeEncodeFieldSigs(sig, sigLen, specialTypeInfo);
specialTypeInfo.ElementName = name;
specialTypeInfo.IsPublic = IsFdPublic(attrs);
e->SpecialNameFieldInfo.push_back(std::move(specialTypeInfo));
} else {
ObjectModel::Enum::EnumerationLabel enumerationLabel = { name, *(unsigned int const*)constValue };
if (maxNameLen < enumerationLabel.EnumerationName.length()) {
maxNameLen = enumerationLabel.EnumerationName.length();
}
PopulateAttributes(*it, enumerationLabel.Attributes);
enumerationLabel.IsPublic = IsFdPublic(attrs);
enumerationLabel.HasDefault = (IsFdHasDefault(attrs) != 0);
enumerationLabel.IsStatic = (IsFdStatic(attrs) != 0);
enumerationLabel.IsLiteral = (IsFdLiteral(attrs) != 0);
e->EnumerationLabels.push_back(std::move(enumerationLabel));
}
}
e->MaxElementNameLen = maxNameLen;
}
virtual void Visit(const shared_ptr<Struct>& s) {
if (s->Category & ObjectModel::TypeCategory::WinRtGeneric) {
return;
}
PopulateAttributes(s->Token, s->Attributes);
PopulateFields(s->Token, s->Fields);
}
virtual void Visit(const shared_ptr<Delegate>& d) {
if (d->Category & ObjectModel::TypeCategory::WinRtGeneric) {
return;
}
PopulateAttributes(d->Token, d->Attributes);
// EmitCustomAttributes(d.Token, false);
PopulateMembers(d->Token, d->Members);
}
bool HasAttribute(mdToken token, const wchar_t* attributeName) {
const void* attributeValue = nullptr;
ULONG attributeLen = 0;
_converter->Scope()->GetCustomAttributeByName(token, attributeName, &attributeValue, &attributeLen);
if (attributeLen != 0) {
return true;
}
return false;
}
void PopulateAttributes(mdToken token, multimap<const wstring, shared_ptr<Attribute>>& attributes) {
if (!IsNilToken(token)) {
wchar_t name[MaxTypeNameLen];
name[0] = 0;
CMetadataAttributeEnumerator enumAttribs(_converter->Scope(), token, 0);
for (auto it = enumAttribs.begin(); it != enumAttribs.end(); ++it) {
auto attribute = make_shared<Attribute>(L"", mdTokenNil, nullptr, _converter->FileName());
if (_converter->GetCustomAttributeInformation(*it, attribute)) {
attributes.insert(std::move(make_pair(attribute->Name, attribute)));
}
}
}
}
void PopulateInterfaceImplInfo(mdToken tdef, vector<InterfaceImplInfo>& interfaceImplInfo) {
CMetadataInterfaceImplEnumerator iiEnum(_converter->Scope(), tdef);
for (auto it = iiEnum.begin(); it != iiEnum.end(); ++it) {
mdToken implementsToken;
_converter->Scope()->GetInterfaceImplProps(*it, nullptr, &implementsToken);
shared_ptr<Symbol> symbol;
NameFromToken(implementsToken, false, &symbol);
InterfaceImplInfo interfaceImpl = { symbol };
PopulateAttributes(*it, interfaceImpl.Attributes);
interfaceImplInfo.push_back(std::move(interfaceImpl));
}
}
void PopulateMembers(mdToken tdef, map<mdToken, shared_ptr<MemberInfo>>& members) {
CMetadataMethodEnumerator enumMethods(_converter->Scope(), tdef);
for (auto it = enumMethods.begin(); it != enumMethods.end(); ++it) {
wchar_t name[MaxTypeNameLen];
name[0] = 0;
ULONG nameLen = 0;
DWORD attrs = 0;
PCCOR_SIGNATURE sig;
ULONG sigLen;
_converter->Scope()->GetMemberProps(
*it, nullptr, name, MaxTypeNameLen, &nameLen, &attrs, &sig, &sigLen, nullptr, nullptr, nullptr, nullptr, nullptr);
auto memberInfo = make_shared<MemberInfo>();
memberInfo->Name = name;
PopulateAttributes(*it, memberInfo->Attributes);
memberInfo->IsPublic = IsMdPublic(attrs);
memberInfo->IsStatic = (IsMdStatic(attrs) != 0);
memberInfo->IsProtected = (IsMdFamily(attrs) != 0);
memberInfo->IsCtor = IsMdInstanceInitializerW(attrs, name);
memberInfo->IsHideBySig = (IsMdHideBySig(attrs) != 0);
memberInfo->IsSpecialName = (IsMdSpecialName(attrs) != 0);
memberInfo->IsRtSpecialName = (IsMdRTSpecialName(attrs) != 0);
if (HasAttribute(*it, L"Windows.Foundation.Metadata.OverloadAttribute")) {
memberInfo->HasOverload = true;
}
if (HasAttribute(*it, L"Windows.Foundation.Metadata.DefaultOverloadAttribute")) {
memberInfo->HasDefaultOverload = true;
}
DecodeEncodeMethodSigs(*it, sig, sigLen, *memberInfo);
members.insert(std::move(std::make_pair(*it, std::move(memberInfo))));
}
}
void PopulateFields(mdToken tdef, vector<FieldInfo>& fields) {
CMetadataFieldEnumerator enumFields(_converter->Scope(), tdef);
for (auto it = enumFields.begin(); it != enumFields.end(); ++it) {
wchar_t name[MaxTypeNameLen];
name[0] = 0;
ULONG nameLen = 0;
DWORD attrs = 0;
PCCOR_SIGNATURE sig;
ULONG sigLen;
UVCP_CONSTANT constValue;
ULONG constValueLen;
PCCOR_SIGNATURE marshalSig;
ULONG marshalSigLen = 0;
_converter->Scope()
->GetFieldProps(*it, nullptr, name, MaxTypeNameLen, &nameLen, &attrs, &sig, &sigLen, nullptr, &constValue, &constValueLen);
ObjectModel::FieldInfo fieldInfo;
fieldInfo.ElementName = name;
fieldInfo.IsPublic = IsFdPublic(attrs);
fieldInfo.HasFieldMarshalTableRow = _converter->Scope()->GetFieldMarshal(*it, &marshalSig, &marshalSigLen);
PopulateAttributes(*it, fieldInfo.Attributes);
DecodeEncodeFieldSigs(sig, sigLen, fieldInfo);
if (!IsFdSpecialName(attrs)) {
// Add to Fields
fields.push_back(std::move(fieldInfo));
}
}
}
void GetEvents(mdToken token, vector<shared_ptr<EventInfo>>& info) {
CMetadataEventEnumerator eventEnum(_converter->Scope(), token);
for (auto it = eventEnum.begin(); it != eventEnum.end(); ++it) {
mdMethodDef eventAdd = mdTokenNil;
mdMethodDef eventRemove = mdTokenNil;
wchar_t name[MaxTypeNameLen];
name[0] = 0;
ULONG nameLen = 0;
_converter->Scope()->GetEventProps(
*it, nullptr, name, MaxTypeNameLen, &nameLen, nullptr, nullptr, &eventAdd, &eventRemove, nullptr, nullptr, 0, nullptr);
{
auto event = make_shared<EventInfo>();
event->Name = name;
if (eventAdd != mdTokenNil) {
event->Adder.Token = eventAdd;
}
if (eventRemove != mdTokenNil) {
event->Remover.Token = eventRemove;
}
info.push_back(std::move(event));
}
}
}
void GetProperties(mdToken token, vector<shared_ptr<PropertyInfo>>& info) {
CMetadataPropertyEnumerator propertyEnum(_converter->Scope(), token);
for (auto it = propertyEnum.begin(); it != propertyEnum.end(); ++it) {
mdMethodDef propertyGet = mdTokenNil;
mdMethodDef propertySet = mdTokenNil;
mdMethodDef other[128];
ULONG otherCount = 0;
wchar_t name[MaxTypeNameLen];
name[0] = 0;
ULONG nameLen = 0;
_converter->Scope()->GetPropertyProps(*it,
nullptr,
name,
MaxTypeNameLen,
&nameLen,
nullptr,
nullptr,
nullptr,
nullptr,
nullptr,
nullptr,
&propertySet,
&propertyGet,
other,
128,
&otherCount);
{
auto property(std::make_shared<PropertyInfo>());
property->Name = name;
if (propertyGet != mdTokenNil) {
property->Getter.Token = propertyGet;
}
if (propertySet != mdTokenNil) {
property->Setter.Token = propertySet;
}
info.push_back(std::move(property));
}
}
}
void HandleEventMethods(vector<shared_ptr<EventInfo>>& info, map<mdToken, shared_ptr<MemberInfo>>& members) {
for (auto it : info) {
auto adderMember = members.find(it->Adder.Token);
if (adderMember != members.end()) {
it->Adder.Info = adderMember->second;
}
auto removerMember = members.find(it->Remover.Token);
if (removerMember != members.end()) {
it->Remover.Info = removerMember->second;
}
}
}
void HandlePropertyMethods(vector<shared_ptr<PropertyInfo>>& info, map<mdToken, shared_ptr<MemberInfo>>& members) {
for (auto it : info) {
auto getterMember = members.find(it->Getter.Token);
if (getterMember != members.end()) {
it->Getter.Info = getterMember->second;
}
auto setterMember = members.find(it->Setter.Token);
if (setterMember != members.end()) {
it->Setter.Info = setterMember->second;
}
}
}
virtual void Visit(const shared_ptr<Interface>& iface) {
if (iface->Category & ObjectModel::TypeCategory::WinRtGeneric) {
return;
}
GetEvents(iface->Token, iface->Events);
GetProperties(iface->Token, iface->Properties);
PopulateAttributes(iface->Token, iface->Attributes);
// EmitCustomAttributes(iface.Token, false);
iface->IsExclusiveTo = HasAttribute(iface->Token, L"Windows.Foundation.Metadata.ExclusiveToAttribute");
PopulateInterfaceImplInfo(iface->Token, iface->InterfaceImplements);
PopulateMembers(iface->Token, iface->Members);
HandleEventMethods(iface->Events, iface->Members);
HandlePropertyMethods(iface->Properties, iface->Members);
}
virtual void Visit(const shared_ptr<RuntimeClass>& r) {
if (r->Category & ObjectModel::TypeCategory::WinRtGeneric) {
return;
}
PopulateAttributes(r->Token, r->Attributes);
GetEvents(r->Token, r->Events);
GetProperties(r->Token, r->Properties);
// EmitCustomAttributes(r.Token, false);
PopulateInterfaceImplInfo(r->Token, r->InterfaceImplements);
if (HasAttribute(r->Token, L"Windows.Foundation.Metadata.ActivatableAttribute")) {
r->IsActivatable = true;
}
if (HasAttribute(r->Token, L"Windows.Foundation.Metadata.ComposableAttribute")) {
r->IsComposable = true;
}
PopulateMembers(r->Token, r->Members);
HandleEventMethods(r->Events, r->Members);
HandlePropertyMethods(r->Properties, r->Members);
CMetadataMethodImplEnumerator enumMethodImpl(_converter->Scope(), r->Token);
for (auto it = enumMethodImpl.begin(); it != enumMethodImpl.end(); ++it) {
mdToken tkMethodBody = (*it).first; // The method implementation in the implementation class.
mdToken tkMethodDecl = (*it).second; // The method declaration in this class.
// If this member is the source of the methodimpl table row, hook up its
// implementation type.
if (r->Members[tkMethodBody] != nullptr) {
mdToken tkMemberClass = mdTokenNil;
wchar_t rgchMemberName[MaxTypeNameLen];
ULONG nameLen = 0;
PCCOR_SIGNATURE sig = nullptr;
ULONG sigLen = 0;
if (TypeFromToken(tkMethodDecl) == mdtMemberRef) {
_converter->Scope()->GetMemberRefProps(
tkMethodDecl, &tkMemberClass, rgchMemberName, ARRAYSIZE(rgchMemberName), &nameLen, &sig, &sigLen);
} else if (TypeFromToken(tkMethodDecl) == mdtMethodDef) {
_converter->Scope()->GetMemberProps(tkMethodDecl,
&tkMemberClass,
rgchMemberName,
ARRAYSIZE(rgchMemberName),
&nameLen,
nullptr,
&sig,
&sigLen,
nullptr,
nullptr,
nullptr,
nullptr,
nullptr);
}
//
// Ok, we now have the class which contains the implementation. The
// next step is to figure out which member in that class implements
// this method.
//
auto memberInfoRef = make_shared<MemberInfo>();
memberInfoRef->Name = rgchMemberName; // Remember the method name on the destination type.
DecodeEncodeMethodSigs(mdTokenNil, sig, sigLen, *memberInfoRef);
// Remember the name of the type which implements the method.
NameFromToken(tkMemberClass, false, &r->Members[tkMethodBody]->MethodImplType);
r->Members[tkMethodBody]->MethodImpl = std::move(memberInfoRef);
}
}
}
virtual void Visit(const shared_ptr<AttributeDef>& attrDef) {
if (attrDef->Category & ObjectModel::TypeCategory::WinRtGeneric) {
return;
}
PopulateAttributes(attrDef->Token, attrDef->Attributes);
PopulateMembers(attrDef->Token, attrDef->Members);
PopulateFields(attrDef->Token, attrDef->Fields);
attrDef->IsPublic = IsTdPublic(attrDef->RawType->attrs);
}
virtual void Visit(const shared_ptr<Array>&) {
}
virtual void Visit(const shared_ptr<Generic>& /*generic*/) {
}
virtual void Visit(const shared_ptr<BasicType>&) {
}
};
// Generate a generic specialization name for the generic type implType given the typespec
// description contained in typeSpec. The typeSpec allows us to find the actual types which
// correspond to the generic types listed in the implType.
wstring GenerateGenericSpecializationName(const shared_ptr<ObjectModel::Generic>& implType,
const shared_ptr<ObjectModel::Generic>& typeSpec) {
wstringstream ssTypeName;
ssTypeName << implType->Type->Name << L"<";
for (auto it = implType->Parameters.begin(); it != implType->Parameters.end(); it++) {
if ((*it)->Category == ObjectModel::WinRtGenericParam) {
shared_ptr<ObjectModel::GenericParam> param = static_pointer_cast<ObjectModel::GenericParam>((*it));
ssTypeName << typeSpec->Parameters[param->ParamIndex]->Name;
} else {
ssTypeName << (*it)->Name;
}
// If we're not done, add in a comma.
if (it + 1 != implType->Parameters.end()) {
ssTypeName << L",";
}
}
ssTypeName << L">";
return ssTypeName.str();
}
// Returns true if the types are equal, false if they are not.
//
// Note that when comparing typespecs, the left type is always the method type and the
// right type is always the methodimpl type (and thus may be a generic).
//
// When comparing two types, the first thing you want to do is to check for null (void) types.
// After that, two types are equal iff their names are equal. It's that simple. There are
// two special cases that need to be considered.
//
// The first is when you're comparing a type and a generic. In that case, if you have a
// generic specialization available for the type on the left, calculate the name of the
// generic substituting the generic params for the corresponding types in the typespec.
//
// The second case happens when you compare a type with a generic parameter. In that case, if
// you have a generic specialization, simply use the type from the generic specialization
// instead.
//
// Note that we won't have to recurse on generics - that's because even if an entry in the
// typespec is a generic, it's a specific generic specialization and you can use the name of
// that specialization in the replacement.
//
bool CompareTypes(const shared_ptr<ObjectModel::Symbol>& left,
const shared_ptr<ObjectModel::Symbol>& right,
const shared_ptr<ObjectModel::Generic>& typeSpec) {
// Check for null types - if both left and right are the same pointer (or if both are null
// (void)), it's a match.
if (left == right) {
return true;
}
// If either is null, they don't match (we know that they're not both null.
if (left == nullptr || right == nullptr) {
return false;
}
// Pull out the left and right names.
wstring leftTypeName(left->Name);
wstring rightTypeName(right->Name);
// If the implementation type is a generic, find the corresponding parameter in the
// typespec specification (in the genericImpl)
if (typeSpec != nullptr) {
if (right->Category == ObjectModel::WinRtGeneric) {
rightTypeName = GenerateGenericSpecializationName(static_pointer_cast<ObjectModel::Generic>(right), typeSpec);
}
if (right->Category == ObjectModel::WinRtGenericParam) {
rightTypeName = typeSpec->Parameters[static_pointer_cast<ObjectModel::GenericParam>(right)->ParamIndex]->Name;
}
}
return (leftTypeName == rightTypeName);
}
} // namespace ObjectModel
MetaDataConvert::MetaDataConvert(_In_ wstring filename, map<wstring, shared_ptr<ObjectModel::Symbol>>& fqnMap)
: _fileName(filename), _fqnMap(fqnMap), _scope(new CMetadataScope(filename)) {
}
HRESULT MetaDataConvert::ConvertMetaData(const MetaDataConvert::NamespaceDomain& nsDom) {
HRESULT hr = S_OK;
if (!_scope->CreateScope(CMetadataScope::ScopeType::ReadOnly)) {
return E_FAIL;
}
// Determine the version of the winmd file
wchar_t szVersionString[128];
DWORD cchVersionString;
_scope->GetVersionString(szVersionString, ARRAYSIZE(szVersionString), &cchVersionString);
_scope->DetermineMetadataFormatVersion(szVersionString);
// Collect unique namespaces in the WinMD
EnumerateTypeDefs(&MetaDataConvert::CollectNamespaces);
// Remove wayward namespaces
if (nsDom.incNs.size()) {
auto oldNamespaces = _namespaces;
for (auto it : oldNamespaces) {
bool remove = true;
for (auto ns : nsDom.incNs) {
if (it.first.substr(0, ns.length()) == ns) {
remove = false;
break;
}
}
if (remove) {
_namespaces.erase(it.first);
}
}
}
if (nsDom.rejectNs.size()) {
auto oldNamespaces = _namespaces;
for (auto ns : nsDom.rejectNs) {
for (auto it : oldNamespaces) {
if (it.first.substr(0, ns.length()) == ns) {
_namespaces.erase(it.first);
}
}
}
}
for (auto it = _namespaces.begin(); it != _namespaces.end(); it++) {
// Decode Metadata for types in namespace
{
ObjectModel::DecodeMetadata decodeVisitor(this, it->first);
it->second->Visit(&decodeVisitor);
}
}
// Remove wayward types
for (auto type : nsDom.rejectTypes) {
_fqnMap.erase(type);
}
auto oldTypes = _fqnMap;
if (nsDom.incTypes.size()) {
for (auto type : oldTypes) {
if (nsDom.incTypes.find(type.first) == nsDom.incTypes.end()) {
_fqnMap.erase(type.first);
}
}
}
return hr;
}
void MetaDataConvert::VisitNamespaces(ObjectModel::Visitor* visitor) {
for (auto it = _namespaces.begin(); it != _namespaces.end(); it++) {
it->second->Visit(visitor);
}
}
namespace ObjectModel {
ULONG DecodeMetadata::DecodeEncodeSig(PCCOR_SIGNATURE signature,
ULONG signatureLength,
mdParamDef parameterToken,
bool returnParameter,
shared_ptr<ObjectModel::Symbol>* sym) {
if (sym == nullptr) {
DebugBreak();
}
CorElementType elementType = static_cast<CorElementType>(signature[0]);
ULONG bytesUsed = 1;
bool isOutParam = false;
// If we have a param token, check to see if it's null.
if (parameterToken != mdTokenNil) {
ULONG attrs = 0;
_converter->Scope()->GetParamProps(parameterToken, nullptr, nullptr, nullptr, 0, nullptr, &attrs, nullptr, nullptr, nullptr);
if (IsPdOut(attrs)) {
isOutParam = true;
}
}
switch (elementType) {
case ELEMENT_TYPE_VOID: {
if (returnParameter) {
*sym = nullptr;
break;
}
}
case ELEMENT_TYPE_BOOLEAN:
case ELEMENT_TYPE_CHAR:
case ELEMENT_TYPE_I1:
case ELEMENT_TYPE_U1:
case ELEMENT_TYPE_I2:
case ELEMENT_TYPE_U2:
case ELEMENT_TYPE_I4:
case ELEMENT_TYPE_U4:
case ELEMENT_TYPE_I8:
case ELEMENT_TYPE_U8:
case ELEMENT_TYPE_R4:
case ELEMENT_TYPE_R8: {
shared_ptr<ObjectModel::Symbol> symbol(
new ObjectModel::BasicType(IntrinsicTypeMap[elementType], _converter->FileName(), TypeCategory::WinRtFundamental));
symbol->TypeKind = ElementTypeKind::Value;
*sym = (std::move(symbol));
} break;
case ELEMENT_TYPE_STRING: {
shared_ptr<ObjectModel::Symbol> symbol(
new ObjectModel::BasicType(IntrinsicTypeMap[elementType], _converter->FileName(), TypeCategory::WinRtFundamental));
symbol->TypeKind = ElementTypeKind::String;
*sym = (std::move(symbol));
} break;
case ELEMENT_TYPE_OBJECT: {
*sym = std::move(shared_ptr<ObjectModel::BasicType>(new ObjectModel::BasicType(L"System.Object", _converter->FileName())));
} break;
case ELEMENT_TYPE_ARRAY: {
shared_ptr<ObjectModel::Array> arrayType(new ObjectModel::Array(L"", mdTokenNil, _converter->FileName()));
if (returnParameter || isOutParam) {
arrayType->ArrayCategory = ObjectModel::Array::ArrayCategory::FillArray;
} else {
arrayType->ArrayCategory = ObjectModel::Array::ArrayCategory::InArray;
}
// Decode the type
bytesUsed += DecodeEncodeSig(signature + bytesUsed, signatureLength, mdTokenNil, returnParameter, &arrayType->Type);
// Decode the rank
ULONG rank;
bytesUsed += CorSigUncompressData(signature + bytesUsed, &rank);
// Decode all the dimension sizes
ULONG numSizes;
bytesUsed += CorSigUncompressData(signature + bytesUsed, &numSizes);
for (ULONG i = 0; i < numSizes; i++) {
ULONG size;
bytesUsed += CorSigUncompressData(signature + bytesUsed, &size);
}
// Decode all the dimension lower bounds
ULONG numLoBounds;
bytesUsed += CorSigUncompressData(signature + bytesUsed, &numLoBounds);
for (ULONG i = 0; i < numLoBounds; i++) {
int loBound;
bytesUsed += CorSigUncompressSignedInt(signature + bytesUsed, &loBound);
}
// Invalidate the type. The info parsed above will be discarded; we just needed to go through the motions to get the correct
// bytesUsed.
shared_ptr<ObjectModel::BasicType> tmpSym(
new ObjectModel::BasicType(L"ELEMENT_TYPE_ARRAY", _converter->FileName(), ObjectModel::TypeCategory::InvalidType));
*sym = std::move(tmpSym);
} break;
case ELEMENT_TYPE_SZARRAY: {
shared_ptr<ObjectModel::Array> arrayType(new ObjectModel::Array(L"", mdTokenNil, _converter->FileName()));
if (returnParameter || isOutParam) {
arrayType->ArrayCategory = ObjectModel::Array::ArrayCategory::FillArray;
} else {
arrayType->ArrayCategory = ObjectModel::Array::ArrayCategory::InArray;
}
bytesUsed += DecodeEncodeSig(signature + bytesUsed, signatureLength, mdTokenNil, returnParameter, &arrayType->Type);
*sym = std::move(arrayType);
} break;
case ELEMENT_TYPE_VALUETYPE:
case ELEMENT_TYPE_CLASS: {
mdToken token;
ULONG bytesUsedTemp = CorSigUncompressToken(signature + bytesUsed, &token);
bytesUsed += bytesUsedTemp;
NameFromToken(token, true, sym);
if (elementType == ELEMENT_TYPE_VALUETYPE) {
(*sym)->TypeKind = ElementTypeKind::Value;
} else {
(*sym)->TypeKind = ElementTypeKind::Class;
}
} break;
case ELEMENT_TYPE_CMOD_REQD:
case ELEMENT_TYPE_CMOD_OPT: {
// Custom Modifiers
// Example of format: ELEMENT_TYPE_CUSTOMMOD_OPT TYPEREF1 ELEMENT_TYPE_CUSTOMMOD_OPT TYPEREF2 ELEMENT_TYPE_VALUE_TYPE (or other
// like ELEMENT_TYPE_CLASS)
// A custom modifier is associated with a Type (the last one in the format).
// In some cases there might be something in the middle (last MOD_OPT and Type) which is processed when hitting the type (eg,
// ELEMENT_TYPE_PINNED).
// Upon hitting ELEMENT_TYPE_CMOD_OPT, process them all, process the Type and return the Type with all the custom modifiers
// ECMA II.23.2.10 Param
// There can be multiple Custom Modifiers, for example in parameters
multimap<const wstring, shared_ptr<CustomModifier>> customModifiers;
CorElementType currentElementType = elementType;
do {
mdToken token = mdTokenNil;
shared_ptr<CustomModifier> customModifierSymbol(make_shared<CustomModifier>((currentElementType == ELEMENT_TYPE_CMOD_OPT) ?
CustomModifierKind::Optional :
CustomModifierKind::Required,
_converter->FileName()));
bytesUsed += CorSigUncompressToken(signature + bytesUsed, &token);
NameFromToken(token, true, &customModifierSymbol->Type);
customModifiers.emplace(std::move(make_pair(customModifierSymbol->Type->Name, customModifierSymbol)));
currentElementType = static_cast<CorElementType>((bytesUsed + signature)[0]);
} while ((currentElementType == ELEMENT_TYPE_CMOD_OPT) || (currentElementType == ELEMENT_TYPE_CMOD_REQD));
bytesUsed += DecodeEncodeSig(signature + bytesUsed, signatureLength, mdTokenNil, returnParameter, sym);
(*sym)->CustomModifiers = std::move(customModifiers);
break;
}
case ELEMENT_TYPE_I:
case ELEMENT_TYPE_U: {
shared_ptr<ObjectModel::Symbol> symbol(
new ObjectModel::BasicType(IntrinsicTypeMap[ELEMENT_TYPE_STRING + 2 + (elementType - ELEMENT_TYPE_I)],
_converter->FileName(),
ObjectModel::TypeCategory::InvalidType));
*sym = (std::move(symbol));
} break;
case ELEMENT_TYPE_END:
case ELEMENT_TYPE_SENTINEL: {
shared_ptr<ObjectModel::BasicType> tmpSym(
new ObjectModel::BasicType(L"End/Sentinel", _converter->FileName(), ObjectModel::TypeCategory::InvalidType));
*sym = std::move(tmpSym);
} break;
case ELEMENT_TYPE_VAR:
case ELEMENT_TYPE_MVAR: {
wchar_t buf[128];
ULONG val;
bytesUsed += CorSigUncompressData(signature + bytesUsed, &val);
_ultow_s(val, buf, 10);
shared_ptr<ObjectModel::Symbol> symbol(new ObjectModel::GenericParam(buf, val, _converter->FileName()));
*sym = (std::move(symbol));
} break;
case ELEMENT_TYPE_GENERICINST: {
// Parse the generic instance. Also calculate the name of the generic instance,
// this will later be used to compare type names.
wstringstream strGenericName;
shared_ptr<ObjectModel::Generic> genericSym(new ObjectModel::Generic(_converter->FileName()));
bytesUsed += DecodeEncodeSig(signature + bytesUsed, signatureLength, mdTokenNil, false, &genericSym->Type);
strGenericName << genericSym->Type->Name << L"<";
ULONG argcnt = static_cast<ULONG>(signature[bytesUsed]);
bytesUsed++;
for (ULONG i = 0; i < argcnt; i++) {
shared_ptr<ObjectModel::Symbol> genericArgument;
bytesUsed += DecodeEncodeSig(signature + bytesUsed, signatureLength, mdTokenNil, false, &genericArgument);
strGenericName << genericArgument->Name;
genericSym->Parameters.push_back(std::move(genericArgument));
if (i + 1 < argcnt) {
strGenericName << L",";
}
}
strGenericName << L">";
genericSym->Name = std::move(strGenericName.str());
*sym = std::move(genericSym);
} break;
case ELEMENT_TYPE_PTR: {
bytesUsed += DecodeEncodeSig(signature + bytesUsed, signatureLength, mdTokenNil, false, sym);
(*sym)->PointerKind = ElementPointerKind::Native;
} break;
case ELEMENT_TYPE_BYREF: {
bytesUsed += DecodeEncodeSig(signature + bytesUsed, signatureLength, mdTokenNil, false, sym);
if ((*sym)->Category == TypeCategory::WinRtArray) {
reinterpret_cast<Array*>((*sym).get())->ArrayCategory = Array::ArrayCategory::ReceiveArray;
}
(*sym)->PointerKind = ElementPointerKind::ByRef;
} break;
case ELEMENT_TYPE_INTERNAL:
case ELEMENT_TYPE_PINNED: {
bytesUsed += DecodeEncodeSig(signature + bytesUsed, signatureLength, mdTokenNil, false, sym);
} break;
case ELEMENT_TYPE_FNPTR: {
bytesUsed += GetMethodSigSize(signature + bytesUsed);
shared_ptr<ObjectModel::BasicType> tmpSym(
new ObjectModel::BasicType(L"FunctionPointer", _converter->FileName(), ObjectModel::TypeCategory::InvalidType));
*sym = std::move(tmpSym);
} break;
default: {
// we have no idea what we saw here, so gracefully mark it as such
shared_ptr<ObjectModel::BasicType> tmpSym(
new ObjectModel::BasicType(L"UnknownType", _converter->FileName(), ObjectModel::TypeCategory::InvalidType));
*sym = std::move(tmpSym);
} break;
}
return bytesUsed;
}
ULONG DecodeMetadata::DecodeEncodeFieldSigs(PCCOR_SIGNATURE signature, ULONG signatureLength, ObjectModel::FieldInfo& elementInfo) {
ULONG bytesUsed = 1;
bytesUsed += DecodeEncodeSig(signature + bytesUsed, signatureLength, mdTokenNil, false, &elementInfo.ElementType);
return bytesUsed;
}
void DecodeMetadata::DecodeParamAttrs(ULONG attrs, ObjectModel::ParameterInfo& paramInfo) {
paramInfo.IsOutParam = (IsPdOut(attrs) != 0);
paramInfo.IsInParam = (IsPdIn(attrs) != 0);
paramInfo.IsOptional = (IsPdOptional(attrs) != 0);
paramInfo.HasDefault = (IsPdHasDefault(attrs) != 0);
}
// Determines the length of a method's signature
// This is useful for skipping over a method signature in the case of function pointers
//
// Arguments:
// signature: the signature object to use to determine the length of the sig
//
// Returns:
// the length of the method signature
ULONG DecodeMetadata::GetMethodSigSize(PCCOR_SIGNATURE signature) {
ULONG bytesUsed = 1;
ULONG paramCount = 0;
shared_ptr<ObjectModel::Symbol> spDummy(nullptr);
bytesUsed += CorSigUncompressData(signature + bytesUsed, ¶mCount);
bytesUsed += DecodeEncodeSig(signature + bytesUsed, 0, mdTokenNil, false, &spDummy);
for (unsigned int n = 0; n < paramCount; n++) {
bytesUsed += DecodeEncodeSig(signature + bytesUsed, 0, mdTokenNil, false, &spDummy);
}
return bytesUsed;
}
ULONG DecodeMetadata::DecodeEncodeMethodSigs(mdMethodDef methodToken,
PCCOR_SIGNATURE signature,
ULONG signatureLength,
ObjectModel::MemberInfo& memberInfo) {
ULONG bytesUsed = 1;
// BYTE callingConvention = signature[0];
ULONG paramCount = 0;
ULONG bytesUsedTemp = CorSigUncompressData(signature + bytesUsed, ¶mCount);
bytesUsed += bytesUsedTemp;
mdParamDef paramToken = mdTokenNil;
if (!IsNilToken(methodToken)) {
_converter->Scope()->GetParamForMethodIndex(methodToken, 0, ¶mToken);
}
// Return Type
if (!IsNilToken(paramToken)) {
wchar_t name[MaxTypeNameLen];
name[0] = 0;
ULONG nameLen = 0;
PCCOR_SIGNATURE marshalSig;
ULONG marshalSigLen = 0;
ULONG attrs = 0;
_converter->Scope()->GetParamProps(paramToken, nullptr, nullptr, name, MaxTypeNameLen, &nameLen, &attrs, nullptr, nullptr, nullptr);
memberInfo.ReturnParameter.Name = name;
memberInfo.ReturnParameter.HasFieldMarshalTableRow = _converter->Scope()->GetFieldMarshal(paramToken, &marshalSig, &marshalSigLen);
DecodeParamAttrs(attrs, memberInfo.ReturnParameter);
}
memberInfo.ReturnParameter.IsOutParam = true;
bytesUsed += DecodeEncodeSig(signature + bytesUsed, signatureLength, paramToken, true, &memberInfo.ReturnParameter.Type);
memberInfo.ReturnParameter.IsVoid = (memberInfo.ReturnParameter.Type == nullptr);
// Resize the parameters vector so we don't reallocate on every parameter.
memberInfo.Parameters.reserve(paramCount);
// Parameters
for (unsigned int n = 0; n < paramCount; n++) {
wchar_t name[MaxTypeNameLen];
name[0] = 0;
ULONG nameLen = 0;
ULONG attrs = 0;
bool hasParamTableRow = false;
if (!IsNilToken(methodToken)) {
_converter->Scope()->GetParamForMethodIndex(methodToken, n + 1, ¶mToken);
if (!IsNilToken(paramToken)) {
_converter->Scope()
->GetParamProps(paramToken, nullptr, nullptr, name, MaxTypeNameLen, &nameLen, &attrs, nullptr, nullptr, nullptr);
hasParamTableRow = true;
}
}
ParameterInfo parameterInfo(name);
parameterInfo.HasParamTableRow = hasParamTableRow;
if (!IsNilToken(paramToken)) {
PCCOR_SIGNATURE marshalSig;
ULONG marshalSigLen = 0;
PopulateAttributes(paramToken, parameterInfo.Attributes);
parameterInfo.HasFieldMarshalTableRow = _converter->Scope()->GetFieldMarshal(paramToken, &marshalSig, &marshalSigLen);
}
DecodeParamAttrs(attrs, parameterInfo);
bytesUsed += DecodeEncodeSig(signature + bytesUsed, signatureLength, paramToken, false, ¶meterInfo.Type);
parameterInfo.IsVoid = false;
// If this is an in parameter, account for it.
// There's one strange exception to the "in parameter" rule: For the purposes of
// overload detection, an out parameter which matches the FillArray pattern will also
// count as an "in" parameter.
if (IsPdIn(attrs) ||
(IsPdOut(attrs) && parameterInfo.Type != nullptr && (parameterInfo.Type->Category == WinRtArray) &&
(static_pointer_cast<ObjectModel::Array>(parameterInfo.Type)->ArrayCategory == ObjectModel::Array::FillArray))) {
memberInfo.InParamCount += 1;
} else if (IsPdOut(attrs)) {
memberInfo.OutParamCount += 1;
}
memberInfo.Parameters.push_back(std::move(parameterInfo));
}
return bytesUsed;
}
ULONG DecodeMetadata::DecodeEncodeTypeSpecSigs(PCCOR_SIGNATURE signature, ULONG signatureLength, shared_ptr<ObjectModel::Symbol>* sym) {
ULONG bytesUsed = 0;
bytesUsed += DecodeEncodeSig(signature + bytesUsed, signatureLength, mdTokenNil, false, sym);
return bytesUsed;
}
void DecodeMetadata::NameFromToken(mdToken token, bool nameForParameter, shared_ptr<ObjectModel::Symbol>* sym) {
if (TypeFromToken(token) == mdtTypeSpec) {
PCCOR_SIGNATURE sig;
ULONG sigLen;
_converter->Scope()->GetTypeSpecFromToken(token, &sig, &sigLen);
DecodeEncodeTypeSpecSigs(sig, sigLen, sym);
return;
}
_converter->NameFromToken(token, nameForParameter, sym);
}
} // namespace ObjectModel
void MetaDataConvert::NameFromToken(mdToken token, bool nameForParameter, shared_ptr<ObjectModel::Symbol>* sym) {
if (sym == nullptr) {
DebugBreak();
}
if (IsNilToken(token)) {
return;
}
if (TypeFromToken(token) == mdtTypeDef) {
shared_ptr<ObjectModel::RawType> type;
GetTypeInformation(token,
type); // This should always succeed because it's dealing with a typedef (and thus is within the winmd file).
*sym = std::move(shared_ptr<ObjectModel::Symbol>(new ObjectModel::UnresolvedSymbol(type->typeName, token, type, _fileName)));
if (!nameForParameter && (type->typeCategory & ObjectModel::TypeCategory::WinRtGeneric)) {
shared_ptr<ObjectModel::Generic> typeGeneric(new ObjectModel::Generic(_fileName));
typeGeneric->Type = std::move(*sym);
*sym = std::move(typeGeneric);
}
return;
} else if (TypeFromToken(token) == mdtTypeRef) {
shared_ptr<ObjectModel::RawType> type;
// If we couldn't figure out the type information, it's probably because the type was an
// external typeref.
if (!GetTypeInformation(token, type)) {
mdToken resolutionScope;
wchar_t name[MaxTypeNameLen];
name[0] = 0;
ULONG nameLen = 0;
Scope()->GetTypeRefProps(token, &resolutionScope, name, MaxTypeNameLen, &nameLen);
type =
shared_ptr<ObjectModel::RawType>(new ObjectModel::RawType(token, name, 0, L"", ObjectModel::TypeCategory::UnresolvedType));
}
if (type->typeName.compare(L"System.Guid") == 0) {
*sym = std::move(shared_ptr<ObjectModel::Symbol>(
new ObjectModel::BasicType(L"GUID", _fileName, ObjectModel::TypeCategory::WinRtFundamental)));
return;
}
*sym = std::move(shared_ptr<ObjectModel::Symbol>(new ObjectModel::UnresolvedSymbol(type->typeName, token, type, _fileName)));
if (!nameForParameter && type->typeCategory & ObjectModel::TypeCategory::WinRtGeneric) {
shared_ptr<ObjectModel::Generic> typeGeneric(new ObjectModel::Generic(_fileName));
typeGeneric->Type = std::move(*sym);
*sym = std::move(typeGeneric);
}
return;
}
return;
}
// Returns false if it fails to extract valid data from the CA signature, true otherwise.
bool MetaDataConvert::GetValueFromCustomAttributeSig(CustomAttributeParser& CA,
ULONG elemType,
ObjectModel::CustomAttributeParamInfo& parameter) {
UINT8 u1 = 0;
UINT16 u2 = 0;
UINT32 u4 = 0;
UINT64 u8 = 0;
unsigned __int64 uI64;
bool boolVal;
double dblVal;
bool ret = true;
switch (elemType) {
case ELEMENT_TYPE_I1:
case ELEMENT_TYPE_U1:
CA.GetU1(&u1);
parameter.Type = std::make_shared<ObjectModel::BasicType>(IntrinsicTypeMap[elemType],
_fileName,
ObjectModel::TypeCategory::WinRtFundamental);
parameter.SignedIntValue = u1;
parameter.ElementType = elemType;
break;
case ELEMENT_TYPE_I2:
case ELEMENT_TYPE_U2:
CA.GetU2(&u2);
parameter.Type = std::make_shared<ObjectModel::BasicType>(IntrinsicTypeMap[elemType],
_fileName,
ObjectModel::TypeCategory::WinRtFundamental);
parameter.SignedIntValue = u2;
parameter.ElementType = elemType;
break;
case ELEMENT_TYPE_BOOLEAN:
CA.GetBool(&boolVal);
parameter.Type = std::make_shared<ObjectModel::BasicType>(IntrinsicTypeMap[elemType],
_fileName,
ObjectModel::TypeCategory::WinRtFundamental);
parameter.SignedIntValue = boolVal;
parameter.ElementType = elemType;
break;
case ELEMENT_TYPE_I4:
case ELEMENT_TYPE_U4:
CA.GetU4(&u4);
parameter.Type = std::make_shared<ObjectModel::BasicType>(IntrinsicTypeMap[elemType],
_fileName,
ObjectModel::TypeCategory::WinRtFundamental);
parameter.SignedIntValue = u4;
parameter.ElementType = elemType;
break;
case SERIALIZATION_TYPE_ENUM:
CA.GetU4(&u4);
parameter.Type = std::make_shared<ObjectModel::BasicType>(L"", _fileName, ObjectModel::TypeCategory::UnresolvedType);
parameter.SignedIntValue = u4;
parameter.ElementType = elemType;
break;
case SERIALIZATION_TYPE_TYPE: {
wstring strVal = CA.GetWString();
mdToken token = mdTokenNil;
shared_ptr<ObjectModel::Symbol> tempParam;
if (Scope()->FindTypeDefByName(strVal.c_str(), mdTokenNil, &token) && !IsNilToken(token)) {
NameFromToken(token, false, &tempParam);
} else {
tempParam.reset(new ObjectModel::BasicType(strVal, _fileName));
}
parameter.Type = std::make_shared<ObjectModel::BasicType>(L"System.Type", _fileName, ObjectModel::TypeCategory::UnresolvedType);
parameter.StringValue = std::move(tempParam->Name);
parameter.ElementType = elemType;
} break;
case ELEMENT_TYPE_STRING: {
wstring strVal = CA.GetWString();
parameter.Type = std::make_shared<ObjectModel::BasicType>(IntrinsicTypeMap[elemType],
_fileName,
ObjectModel::TypeCategory::WinRtFundamental);
parameter.StringValue = std::move(strVal);
parameter.ElementType = elemType;
} break;
case ELEMENT_TYPE_I8:
case ELEMENT_TYPE_U8:
CA.GetU8(&u8);
uI64 = u8;
parameter.SignedIntValue = uI64;
parameter.Type = std::make_shared<ObjectModel::BasicType>(IntrinsicTypeMap[elemType],
_fileName,
ObjectModel::TypeCategory::WinRtFundamental);
parameter.ElementType = elemType;
break;
case ELEMENT_TYPE_R4:
dblVal = CA.GetR4();
parameter.DoubleValue = dblVal;
parameter.Type = std::make_shared<ObjectModel::BasicType>(IntrinsicTypeMap[elemType],
_fileName,
ObjectModel::TypeCategory::WinRtFundamental);
parameter.ElementType = elemType;
break;
case ELEMENT_TYPE_R8:
dblVal = CA.GetR8();
parameter.DoubleValue = dblVal;
parameter.Type = std::make_shared<ObjectModel::BasicType>(IntrinsicTypeMap[elemType],
_fileName,
ObjectModel::TypeCategory::WinRtFundamental);
parameter.ElementType = elemType;
break;
default:
ret = false;
break;
}
return ret;
}
typedef LPCSTR LPCUTF8;
bool MetaDataConvert::GetCustomAttributeInformation(mdCustomAttribute token, shared_ptr<ObjectModel::Attribute> attribute) {
const BYTE* pValue; // The custom value.
ULONG cbValue; // Length of the custom value.
mdToken tkObj; // Attributed object.
mdToken tkType; // Type of the custom attribute.
mdToken tk; // For name lookup.
LPCUTF8 pMethName = 0; // Name of custom attribute ctor, if any.
PCCOR_SIGNATURE pSig = 0; // Signature of ctor.
ULONG cbSig; // Size of the signature.
WCHAR rcName[MAX_CLASS_NAME]; // Name of the type.
Scope()->GetCustomAttributeProps( // S_OK or error.
token, // The attribute.
&tkObj, // The attributed object
&tkType, // The attributes type.
(const void**)&pValue, // Put pointer to data here.
&cbValue); // Put size here.
// Get the name of the memberref or methoddef.
tk = tkType;
rcName[0] = L'\0';
// Get the member name, and the parent token.
switch (TypeFromToken(tk)) {
case mdtMemberRef:
Scope()->GetNameFromToken(tk, &pMethName);
Scope()->GetMemberRefProps(tk, &tk, 0, 0, 0, &pSig, &cbSig);
break;
case mdtMethodDef:
Scope()->GetNameFromToken(tk, &pMethName);
Scope()->GetMethodProps(tk, &tk, 0, 0, 0, 0, &pSig, &cbSig, 0, 0);
break;
} // switch
// Get the type name.
switch (TypeFromToken(tk)) {
case mdtTypeDef:
Scope()->GetTypeDefProps(tk, rcName, MAX_CLASS_NAME, 0, 0, 0);
break;
case mdtTypeRef:
Scope()->GetTypeRefProps(tk, 0, rcName, MAX_CLASS_NAME, 0);
break;
} // switch
attribute->Name = rcName;
if (pSig) { // Interpret the signature.
//<TODO> all sig elements </TODO>
PCCOR_SIGNATURE ps = pSig;
ULONG cb;
ULONG ulData;
ULONG cParams;
CustomAttributeParser CA(pValue, cbValue);
CA.ValidateProlog();
// Get the calling convention.
cb = CorSigUncompressData(ps, &ulData);
ps += cb;
// Get the count of params.
cb = CorSigUncompressData(ps, &cParams);
ps += cb;
// Get the return value.
cb = CorSigUncompressData(ps, &ulData);
ps += cb;
if (ulData == ELEMENT_TYPE_VOID) {
try {
// For each fixed param...
for (ULONG i = 0; i < cParams; ++i) { // Get the next param type.
cb = CorSigUncompressData(ps, &ulData);
ps += cb;
wchar_t enumName[MaxTypeNameLen];
ULONG chName = 0;
if (ulData == ELEMENT_TYPE_VALUETYPE) {
// The only value type that we accept are enums. Decompress the TypeDefOrRefOrSpecEncoded from
// the sig.
mdToken typeToken;
cb = CorSigUncompressToken(ps, &typeToken);
memset(enumName, 0, MaxTypeNameLen * sizeof(wchar_t));
// retrieve the name of the enum
if (TypeFromToken(typeToken) == mdtTypeRef) {
_scope->GetTypeRefProps(typeToken, nullptr, enumName, MaxTypeNameLen, &chName);
} else {
_scope->GetTypeDefProps(typeToken, enumName, MaxTypeNameLen, &chName, nullptr, nullptr);
}
ps += cb;
ulData = SERIALIZATION_TYPE_ENUM;
} else if (ulData == ELEMENT_TYPE_CLASS) {
// The only class type that we accept is System.Type. Decompress the TypeDefOrRefOrSpecEncoded
// from the sig.
// Possible TODO: verify that the decompressed token corresponds to the System.Type typeref.
mdToken typeToken;
cb = CorSigUncompressToken(ps, &typeToken);
ps += cb;
ulData = SERIALIZATION_TYPE_TYPE;
}
ObjectModel::CustomAttributeParamInfo parameter;
parameter.Type = std::make_shared<ObjectModel::BasicType>(L"", _fileName, ObjectModel::TypeCategory::UnresolvedType);
if (GetValueFromCustomAttributeSig(CA, ulData, parameter)) {
if (chName > 0) {
parameter.Type->Name = enumName;
}
attribute->FixedParameters.push_back(std::move(parameter));
} else {
// Failed to get the value. Invalidate the attribute.
attribute->Category = ObjectModel::TypeCategory::InvalidType;
}
}
// Now that we've parsed out all of the fixed arguments, we parse the named arguments.
UINT16 numNamed;
CA.GetU2(&numNamed);
for (ULONG i = 0; i < numNamed; i++) {
// This must be 0x53, indicating a field. ECMA 335 also allows it to be 0x54 to indicate a property, but there
// are no legal scenarios for this in winmd files. (ECMA 335 Partition II 23.3)
UINT8 fieldMarker;
CA.GetU1(&fieldMarker);
if (fieldMarker == 0x53) {
UINT8 fieldType;
CA.GetU1(&fieldType);
ObjectModel::CustomAttributeParamInfo parameter;
parameter.Type =
std::make_shared<ObjectModel::BasicType>(L"", _fileName, ObjectModel::TypeCategory::UnresolvedType);
wstring enumName = L"";
// An Enum parameter has the name of the Enum as part of the field type.
if (fieldType == SERIALIZATION_TYPE_ENUM) {
enumName = CA.GetWString();
}
wstring fieldName = CA.GetWString();
if (GetValueFromCustomAttributeSig(CA, fieldType, parameter)) {
if (!enumName.empty()) {
parameter.Type->Name = std::move(enumName);
}
if (attribute->NamedParameters.count(fieldName) == 0) {
attribute->NamedParameters.insert(std::move(std::make_pair(fieldName, parameter)));
} else {
// Multiple parameters with the same name. Invalidate the attribute.
attribute->Category = ObjectModel::TypeCategory::InvalidType;
}
} else {
// Failed to get the value. Invalidate the attribute.
attribute->Category = ObjectModel::TypeCategory::InvalidType;
}
} else {
// Malformed blob. Invalidate the attribute.
attribute->Category = ObjectModel::TypeCategory::InvalidType;
}
}
// After parsing the fixed and named parameters, we should have consumed the entire custom attribute blob. Confirm.
if (CA.BytesLeft() != 0) {
// Malformed blob. Invalidate the attribute.
attribute->Category = ObjectModel::TypeCategory::InvalidType;
}
} catch (HRESULT) {
// Caught error. Invalidate the attribute.
attribute->Category = ObjectModel::TypeCategory::InvalidType;
}
}
}
return true;
}
MultiFileObjectModel::MultiFileObjectModel(vector<wstring> filenames) {
for (auto file = filenames.begin(); file != filenames.end(); ++file) {
_perFileModels[*file] = shared_ptr<MetaDataConvert>(new MetaDataConvert(*file, _fqnMap));
}
for (auto pfModel = _perFileModels.begin(); pfModel != _perFileModels.end(); ++pfModel) {
pfModel->second->ConvertMetaData();
}
}
void MultiFileObjectModel::VisitNamespaces(ObjectModel::Visitor* visitor) {
for (auto pfModel = _perFileModels.begin(); pfModel != _perFileModels.end(); ++pfModel) {
pfModel->second->VisitNamespaces(visitor);
}
}
| 44.447251 | 140 | 0.570003 | crossmob |
ed0bdf697701d499334845ca3e4e059392307d34 | 3,729 | hpp | C++ | ngraph/core/include/openvino/op/util/convert_color_nv12_base.hpp | alexander-shchepetov/openvino | a9dae1e3f2ba8b3fec227c51f4c1948667309efc | [
"Apache-2.0"
] | 1 | 2021-07-14T07:20:24.000Z | 2021-07-14T07:20:24.000Z | ngraph/core/include/openvino/op/util/convert_color_nv12_base.hpp | alexander-shchepetov/openvino | a9dae1e3f2ba8b3fec227c51f4c1948667309efc | [
"Apache-2.0"
] | 34 | 2020-11-19T12:27:40.000Z | 2022-02-21T13:14:04.000Z | ngraph/core/include/openvino/op/util/convert_color_nv12_base.hpp | mznamens/openvino | ec126c6252aa39a6c63ddf124350a92687396771 | [
"Apache-2.0"
] | null | null | null | // Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#pragma once
#include "openvino/op/op.hpp"
#include "openvino/op/util/attr_types.hpp"
namespace ov {
namespace op {
namespace util {
/// \brief Base class for color conversion operation from NV12 to RGB/BGR format.
/// Input:
/// - Operation expects input shape in NHWC layout.
/// - Input NV12 image can be represented in a two ways:
/// a) Single plane: NV12 height dimension is 1.5x bigger than image height. 'C' dimension shall be 1
/// b) Two separate planes: Y and UV. In this case
/// b1) Y plane has height same as image height. 'C' dimension equals to 1
/// b2) UV plane has dimensions: 'H' = image_h / 2; 'W' = image_w / 2; 'C' = 2.
/// - Supported element types: u8 or any supported floating-point type.
/// Output:
/// - Output node will have NHWC layout and shape HxW same as image spatial dimensions.
/// - Number of output channels 'C' will be 3
///
/// \details Conversion of each pixel from NV12 (YUV) to RGB space is represented by following formulas:
/// R = 1.164 * (Y - 16) + 1.596 * (V - 128)
/// G = 1.164 * (Y - 16) - 0.813 * (V - 128) - 0.391 * (U - 128)
/// B = 1.164 * (Y - 16) + 2.018 * (U - 128)
/// Then R, G, B values are clipped to range (0, 255)
///
class OPENVINO_API ConvertColorNV12Base : public Op {
public:
/// \brief Exact conversion format details
/// Currently supports conversion from NV12 to RGB or BGR, in future can be extended with NV21_to_RGBA/BGRA, etc
enum class ColorConversion : int { NV12_TO_RGB = 0, NV12_TO_BGR = 1 };
protected:
ConvertColorNV12Base() = default;
/// \brief Constructs a conversion operation from input image in NV12 format
/// As per NV12 format definition, node height dimension shall be 1.5 times bigger than image height
/// so that image (w=640, h=480) is represented by NHWC shape {N,720,640,1} (height*1.5 x width)
///
/// \param arg Node that produces the input tensor. Input tensor represents image in NV12 format (YUV).
/// \param format Conversion format.
explicit ConvertColorNV12Base(const Output<Node>& arg, ColorConversion format);
/// \brief Constructs a conversion operation from 2-plane input image in NV12 format
/// In general case Y channel of image can be separated from UV channel which means that operation needs two nodes
/// for Y and UV planes respectively. Y plane has one channel, and UV has 2 channels, both expect 'NHWC' layout
///
/// \param arg_y Node that produces the input tensor for Y plane (NHWC layout). Shall have WxH dimensions
/// equal to image dimensions. 'C' dimension equals to 1.
///
/// \param arg_uv Node that produces the input tensor for UV plane (NHWC layout). 'H' is half of image height,
/// 'W' is half of image width, 'C' dimension equals to 2. Channel 0 represents 'U', channel 1 represents 'V'
/// channel
///
/// \param format Conversion format.
ConvertColorNV12Base(const Output<Node>& arg_y, const Output<Node>& arg_uv, ColorConversion format);
public:
OPENVINO_OP("ConvertColorNV12Base", "util");
void validate_and_infer_types() override;
bool visit_attributes(AttributeVisitor& visitor) override;
bool evaluate(const HostTensorVector& outputs, const HostTensorVector& inputs) const override;
bool has_evaluate() const override;
protected:
bool is_type_supported(const ov::element::Type& type) const;
ColorConversion m_format = ColorConversion::NV12_TO_RGB;
};
} // namespace util
} // namespace op
} // namespace ov
| 45.47561 | 120 | 0.668812 | alexander-shchepetov |
ed0c7f67cef02f8dbf3053ec9af2281707ec3773 | 3,657 | cpp | C++ | src/blackfox/modules/scripting/lua/entities/BFLuaRuntimeRegistry.cpp | RLefrancoise/BlackFox | 7814c58dca5c11cb9a80f42d4ed5f43ea7745875 | [
"MIT"
] | 3 | 2020-04-23T06:50:48.000Z | 2022-03-14T17:50:37.000Z | src/blackfox/modules/scripting/lua/entities/BFLuaRuntimeRegistry.cpp | RLefrancoise/BlackFox | 7814c58dca5c11cb9a80f42d4ed5f43ea7745875 | [
"MIT"
] | 1 | 2019-11-29T14:21:11.000Z | 2019-11-29T19:35:53.000Z | src/blackfox/modules/scripting/lua/entities/BFLuaRuntimeRegistry.cpp | RLefrancoise/BlackFox | 7814c58dca5c11cb9a80f42d4ed5f43ea7745875 | [
"MIT"
] | null | null | null | #include "BFLuaRuntimeRegistry.h"
#include <utility>
namespace BlackFox
{
BFLuaRuntimeRegistry::BFLuaRuntimeRegistry()
{
registerComponent<Components::BFLuaRuntimeComponent>();
}
unsigned int BFLuaRuntimeRegistry::identifier()
{
static auto next = runtimeComponentId;
return next++;
}
unsigned int BFLuaRuntimeRegistry::registerRuntimeComponent(const std::string& componentName, const std::string& scriptPath, sol::state* state)
{
BF_PRINT("Register runtime component {} ({})", componentName, scriptPath);
auto id = identifier();
m_runtimeComponentLuaScripts[componentName] = std::make_tuple(id, scriptPath);
return id;
}
sol::object BFLuaRuntimeRegistry::setComponent(const entt::entity entity, const ComponentId typeId, sol::state* state)
{
auto it = std::find_if(m_runtimeComponentLuaScripts.begin(), m_runtimeComponentLuaScripts.end(), [&](const auto& entry) -> bool
{
return std::get<ComponentId>(entry.second) == typeId;
});
const auto componentScript = getComponentScript(typeId);
return invoke<funcMap::funcTypeSet, sol::object, &funcMap::set, sol::state*, const std::string*>(
entity,
typeId,
state,
componentScript);
}
void BFLuaRuntimeRegistry::unsetComponent(const entt::entity entity, const ComponentId typeId)
{
invoke<funcMap::funcTypeUnset, void, &funcMap::unset>(entity, typeId);
}
bool BFLuaRuntimeRegistry::hasComponent(const entt::entity entity, const ComponentId typeId)
{
return invoke<funcMap::funcTypeHas, bool, &funcMap::has>(entity, typeId);
}
sol::object BFLuaRuntimeRegistry::getComponent(const entt::entity entity, const ComponentId typeId, sol::state* state)
{
return invoke<funcMap::funcTypeGet, sol::object, &funcMap::get, sol::state*>(entity, typeId, state);
}
void BFLuaRuntimeRegistry::setEntityManager(EntityManager em)
{
m_entityManager = std::move(em);
}
bool BFLuaRuntimeRegistry::isNativeComponent(ComponentId component) const
{
const auto it = std::find_if(m_runtimeComponentLuaScripts.cbegin(), m_runtimeComponentLuaScripts.cend(), [&](const auto& entry) {
return std::get<ComponentId>(entry.second) == component;
});
return it == m_runtimeComponentLuaScripts.cend();
}
const std::string* BFLuaRuntimeRegistry::getComponentScript(ComponentId component) const
{
const auto it = std::find_if(m_runtimeComponentLuaScripts.cbegin(), m_runtimeComponentLuaScripts.cend(), [&](const auto& entry) {
return std::get<ComponentId>(entry.second) == component;
});
return (it != m_runtimeComponentLuaScripts.cend() ? &std::get<std::string>(it->second) : nullptr);
}
std::tuple<entt::runtime_view, std::vector<ComponentId>, std::vector<ComponentId>> BFLuaRuntimeRegistry::getView(const std::vector<ComponentId>& components) const
{
std::vector<ComponentId> engineComponents;
std::vector<ComponentId> runtimeComponents;
for (const auto& type : components)
{
if (isNativeComponent(type))
{
engineComponents.push_back(type);
}
else
{
if (runtimeComponents.empty())
{
engineComponents.push_back(entt::type_info<Components::BFLuaRuntimeComponent>::id());
}
runtimeComponents.push_back(type);
}
}
return std::make_tuple(m_entityManager->runtime_view(engineComponents.begin(), engineComponents.end()), engineComponents, runtimeComponents);
}
std::vector<sol::object> BFLuaRuntimeRegistry::getComponents(
sol::state* state,
const entt::entity& entity,
const std::vector<ComponentId>& components)
{
std::vector<sol::object> v;
for (const auto& component : components)
{
v.push_back(getComponent(entity, component, state));
}
return v;
}
} | 30.731092 | 163 | 0.735576 | RLefrancoise |
ed0e9f5386aaa1ef57e88ba106cd245c85cd7664 | 16,233 | cpp | C++ | PathNetwork.cpp | jeffreycassidy/osm2bin | 7a6751d1a5045d8fb260aaa723ae85da193b4c93 | [
"Apache-2.0"
] | 4 | 2015-10-31T01:33:25.000Z | 2021-04-29T08:04:51.000Z | PathNetwork.cpp | jeffreycassidy/osm2bin | 7a6751d1a5045d8fb260aaa723ae85da193b4c93 | [
"Apache-2.0"
] | null | null | null | PathNetwork.cpp | jeffreycassidy/osm2bin | 7a6751d1a5045d8fb260aaa723ae85da193b4c93 | [
"Apache-2.0"
] | 2 | 2016-06-14T05:05:04.000Z | 2020-04-11T05:56:39.000Z | /*
* PathNetwork.cpp
*
* Created on: Dec 15, 2015
* Author: jcassidy
*/
#include "PathNetwork.hpp"
#include "OSMDatabase.hpp"
#include <boost/container/flat_map.hpp>
using namespace std;
const char* OSMWayFilterRoads::includeHighwayTagValueStrings_[] = {
"residential",
"primary",
"primary_link",
"secondary",
"secondary_link",
"tertiary",
"tertiary_link",
"motorway",
"motorway_link",
"service",
"trunk",
"living_street",
"unclassified",
"road",
nullptr
};
PathNetwork buildNetwork(const OSMDatabase& db, const OSMEntityFilter<OSMWay>& wayFilter) {
PathNetwork G;
float defaultMax = 50.0f;
struct NodeWithRefCount {
PathNetwork::vertex_descriptor graphVertexDescriptor = -1U;
unsigned nodeVectorIndex = -1U;
unsigned refcount = 0;
};
std::unordered_map<unsigned long long, NodeWithRefCount> nodesByOSMID;
unsigned kiHighway = db.wayTags().getIndexForKeyString("highway");
if (kiHighway == -1U)
std::cerr << "ERROR in buildNetwork(db,wf): failed to find tag key 'highway'" << std::endl;
const std::vector<std::pair<std::string,float>> defaultMaxSpeedByHighwayString
{
std::make_pair("motorway",105.0f),
std::make_pair("trunk",90.0f),
std::make_pair("primary",90.0f),
std::make_pair("secondary",80.0f),
std::make_pair("tertiary",80.0f),
std::make_pair("unclassified",50.0f),
std::make_pair("residential",50.0f),
std::make_pair("living_street",40.0f),
};
// fetch tag numbers for the highway strings
boost::container::flat_map<unsigned,float> defaultMaxSpeedByHighwayTagValue;
for(const auto p : defaultMaxSpeedByHighwayString)
{
unsigned viString = db.wayTags().getIndexForValueString(p.first);
if (viString != -1U)
{
const auto res = defaultMaxSpeedByHighwayTagValue.insert(std::make_pair(viString,p.second));
if (!res.second)
std::cerr << "ERROR in buildNetwork(db,wf): duplicate tag value '" << p.first << "' ID=" << viString << std::endl;
}
}
// create OSM ID -> vector index mapping for all nodes
std::cout << "Computing index map" << std::endl;
for (unsigned i = 0; i < db.nodes().size(); ++i)
nodesByOSMID[db.nodes()[i].id()].nodeVectorIndex = i;
// traverse the listed ways, marking node reference counts
std::cout << "Computing reference counts" << std::endl;
for (const OSMWay& w : db.ways() | boost::adaptors::filtered(std::cref(wayFilter)))
for (const unsigned long long nd : w.ndrefs()) {
auto it = nodesByOSMID.find(nd);
if (it == nodesByOSMID.end())
std::cerr << "WARNING: Dangling reference to node " << nd << " in way " << w.id() << std::endl;
else
it->second.refcount++;
}
// calculate and print reference-count (# way refs for each node) histogram for fun
std::vector<unsigned> refhist;
std::cout << "Computing reference-count frequency histogram" << std::endl;
for (const auto ni : nodesByOSMID | boost::adaptors::map_values) {
if (ni.refcount >= refhist.size())
refhist.resize(ni.refcount + 1, 0);
refhist[ni.refcount]++;
}
for (unsigned i = 0; i < refhist.size(); ++i)
if (refhist[i] > 0)
std::cout << " " << std::setw(3) << i << " refs: " << refhist[i] << " nodes" << std::endl;
// iterate over ways, creating edges in the intersection graph with associated curvepoints)
size_t nCurvePoints = 0;
unsigned k_maxspeed = db.wayTags().getIndexForKeyString("maxspeed");
enum OneWayType {
Bidir, Forward, Backward, Reversible, Unknown
};
unsigned k_oneway = db.wayTags().getIndexForKeyString("oneway");
unsigned v_oneway_yes = db.wayTags().getIndexForValueString("yes");
unsigned v_oneway_one = db.wayTags().getIndexForValueString("1");
unsigned v_oneway_minus_one = db.wayTags().getIndexForValueString("-1");
unsigned v_oneway_reversible = db.wayTags().getIndexForValueString("reversible");
unsigned v_oneway_no = db.wayTags().getIndexForValueString("no");
unsigned nOnewayForward = 0, nOnewayBackward = 0, nOnewayReversible = 0, nBidir = 0, nUnknown = 0;
unsigned nWays = 0;
boost::container::flat_map<unsigned,float> speedValues;
for (const auto& w : db.ways() | boost::adaptors::filtered(std::cref(wayFilter))) {
++nWays;
PathNetwork::vertex_descriptor segmentStartVertex = -1ULL, segmentEndVertex = -1ULL;
vector<LatLon> curvePoints;
// max speed is per way; mark as NaN by default (change NaNs to other value later)
float speed = std::numeric_limits<float>::quiet_NaN();
unsigned v;
if ((v = w.getValueForKey(k_maxspeed)) != -1U) // has maxspeed tag
{
boost::container::flat_map<unsigned, float>::iterator it;
bool inserted;
tie(it, inserted) = speedValues.insert(make_pair(v, std::numeric_limits<float>::quiet_NaN()));
if (inserted) // need to map this string value to a number
{
float spd;
string str = db.wayTags().getValue(v);
stringstream ss(str);
ss >> spd;
if (ss.fail()) {
ss.clear();
cout << "truncating '" << str << "' to substring '";
str = str.substr(str.find_first_of(':') + 1);
cout << str << "'" << endl;
ss.str(str);
ss >> spd;
}
if (ss.fail())
std::cout << "Failed to convert value for maxspeed='" << str << "'" << endl;
else if (!ss.eof()) {
string rem;
ss >> rem;
if (rem == "kph")
it->second = spd;
else if (rem == "mph")
it->second = spd * 1.609f;
else {
std::cout << "Warning: trailing characters in maxspeed='" << str << "'" << endl;
std::cout << " remaining: '" << rem << "'" << endl;
}
} else
it->second = spd;
if (!isnan(it->second))
std::cout << "Added new speed '" << str << "' = " << it->second << endl;
else
std::cout << "Failed to convert speed '" << str << "'" << endl;
}
speed = it->second;
}
else // no maxspeed -> default based on road type
{
unsigned viHighwayValue = w.getValueForKey(kiHighway);
if (viHighwayValue == -1U)
std::cerr << "ERROR in buildNetwork(db,wf): missing highway tag!" << std::endl;
else
{
const auto it = defaultMaxSpeedByHighwayTagValue.find(viHighwayValue);
if (it != defaultMaxSpeedByHighwayTagValue.end())
speed = it->second;
}
}
// assume bidirectional if not specified
OneWayType oneway = Unknown;
if (k_oneway == -1U) {
oneway = Bidir;
++nBidir;
} else {
unsigned v_oneway = w.getValueForKey(k_oneway);
if (v_oneway == -1U || v_oneway == v_oneway_no) {
oneway = Bidir;
++nBidir;
} else if (v_oneway == v_oneway_one) {
oneway = Forward;
++nOnewayForward;
} else if (v_oneway == v_oneway_yes) {
oneway = Forward;
++nOnewayForward;
} else if (v_oneway == v_oneway_minus_one) {
oneway = Backward;
++nOnewayBackward;
} else if (v_oneway == v_oneway_reversible) {
oneway = Reversible;
++nOnewayReversible;
} else {
cout << "Unrecognized tag oneway='" << db.wayTags().getValue(v_oneway);
++nUnknown;
}
}
// hamilton_canada and newyork: k=oneway v=-1 | 1 | yes | no | yes;-1 | reversible
for (unsigned i = 0; i < w.ndrefs().size(); ++i) {
const auto currNodeIt = nodesByOSMID.find(w.ndrefs()[i]);
LatLon prevCurvePoint;
if (currNodeIt == nodesByOSMID.end()) // dangling node reference: discard
{
cout << "WARNING: Dangling node with OSM ID " << w.ndrefs()[i] << " on way with OSM ID " << w.id() << endl;
segmentEndVertex = -1U;
continue;
} else if (currNodeIt->second.refcount == 1) // referenced by only 1 way -> curve point
{
LatLon ll = db.nodes().at(currNodeIt->second.nodeVectorIndex).coords();
curvePoints.push_back(ll);
} else if (currNodeIt->second.refcount > 1 || i == 0 || i == w.ndrefs().size() - 1)
// referenced by >1 way or first/last node ref in a way -> node is an intersection
{
segmentEndVertex = currNodeIt->second.graphVertexDescriptor;
// if vertex hasn't been added yet, add now
if (segmentEndVertex == -1U) {
currNodeIt->second.graphVertexDescriptor = segmentEndVertex = add_vertex(G);
G[segmentEndVertex].latlon = db.nodes().at(currNodeIt->second.nodeVectorIndex).coords();
G[segmentEndVertex].osmid = currNodeIt->first;
}
// arriving at an intersection node via a way
if (segmentStartVertex != -1ULL) {
PathNetwork::edge_descriptor e;
bool inserted;
assert(segmentStartVertex < num_vertices(G));
assert(segmentEndVertex < num_vertices(G));
std::tie(e, inserted) = add_edge(segmentStartVertex, segmentEndVertex, G);
assert(inserted && "Duplicate edge");
G[e].wayOSMID = w.id();
if (oneway == Forward || oneway == Backward) {
// goes towards end vertex; if greater then goes towards greater
// flip it
bool towardsGreater = (segmentEndVertex > segmentStartVertex) ^ (oneway == Backward);
G[e].oneWay = towardsGreater ?
EdgeProperties::ToGreaterVertexNumber :
EdgeProperties::ToLesserVertexNumber;
} else
G[e].oneWay = EdgeProperties::Bidir;
G[e].maxspeed = speed;
nCurvePoints += curvePoints.size();
G[e].curvePoints = std::move(curvePoints);
}
segmentStartVertex = segmentEndVertex;
}
prevCurvePoint = db.nodes().at(currNodeIt->second.nodeVectorIndex).coords();
}
}
std::cout << "PathNetwork created with " << num_vertices(G) << " vertices and " << num_edges(G) << " edges, with " << nCurvePoints << " curve points" << std::endl;
std::cout << " Used " << nWays << "/" << db.ways().size() << " ways" << endl;
std::cout << " One-way streets: " << (nOnewayForward + nOnewayBackward) << "/" << nWays << " (" << nOnewayReversible << " reversible and " << nUnknown << " unknown)" << std::endl;
assert(nOnewayForward + nOnewayBackward + nOnewayReversible + nBidir + nUnknown == nWays);
// create/print edge-degree histogram
std::cout << "Vertex degree histogram:" << std::endl;
std::vector<unsigned> dhist;
for (auto v : boost::make_iterator_range(vertices(G))) {
unsigned d = out_degree(v, G);
if (d >= dhist.size())
dhist.resize(d + 1, 0);
dhist[d]++;
}
unsigned Ndefault = 0;
for (auto e : boost::make_iterator_range(edges(G))) {
if (isnan(G[e].maxspeed)) {
++Ndefault;
G[e].maxspeed = defaultMax;
}
}
cout << "Assigned " << Ndefault << "/" << num_edges(G) << " street segments to default max speed for lack of information" << endl;
for (unsigned i = 0; i < dhist.size(); ++i)
if (dhist[i] > 0)
std::cout << " " << std::setw(3) << i << " refs: " << dhist[i] << " nodes" << std::endl;
return G;
}
class StreetEdgeVisitor {
public:
StreetEdgeVisitor(PathNetwork* G)
: m_G(G) {
}
std::vector<std::string> assign() {
m_streets.clear();
m_streets.push_back("<unknown>");
for (const auto e : edges(*m_G))
if ((*m_G)[e].streetVectorIndex == 0)
startWithEdge(e);
return std::move(m_streets);
}
// pick up the street name from the specified edge, add it to the vertex, and expand the source/target vertices
void startWithEdge(PathNetwork::edge_descriptor e);
// inspect all out-edges of the vertex, assigning and recursively expanding any which match the way ID or street name
void expandVertex(PathNetwork::vertex_descriptor v, OSMID wayID);
void osmDatabase(OSMDatabase* p) {
m_osmDatabase = p;
m_keyIndexName = p->wayTags().getIndexForKeyString("name");
m_keyIndexNameEn = p->wayTags().getIndexForKeyString("name:en");
}
private:
const std::string streetNameForWay(OSMID osmid) {
const OSMWay& w = m_osmDatabase->wayFromID(osmid);
unsigned valTag = -1U;
if ((valTag = w.getValueForKey(m_keyIndexNameEn)) == -1U)
valTag = w.getValueForKey(m_keyIndexName);
if (valTag == -1U)
return std::string();
else
return m_osmDatabase->wayTags().getValue(valTag);
}
static const std::string np;
PathNetwork* m_G = nullptr; // the path network
OSMDatabase* m_osmDatabase = nullptr; // OSM database with source data
unsigned m_keyIndexName = -1U, m_keyIndexNameEn = -1U; // cached values for key-value tables
std::vector<std::string> m_streets; // street name vector being built
unsigned m_currStreetVectorIndex = 0; // index of current street
};
const std::string StreetEdgeVisitor::np = {"<name-not-present>"};
void StreetEdgeVisitor::startWithEdge(PathNetwork::edge_descriptor e) {
// grab OSM ID of this way, look up its name
OSMID wID = (*m_G)[e].wayOSMID;
std::string streetName = streetNameForWay(wID);
if (!streetName.empty()) {
// insert the street name
(*m_G)[e].streetVectorIndex = m_currStreetVectorIndex = m_streets.size();
m_streets.push_back(streetName);
// expand the vertices at both ends
expandVertex(source(e, *m_G), wID);
expandVertex(target(e, *m_G), wID);
}
}
/** Recursively expand the specified vertex, along out-edges which have way OSMID == currWayID, or have the same street name */
void StreetEdgeVisitor::expandVertex(PathNetwork::vertex_descriptor v, OSMID currWayID) {
for (const auto e : out_edges(v, *m_G)) // for all out-edges of this vertex
{
if ((*m_G)[e].streetVectorIndex != 0) // skip if already assigned (prevents infinite recursion back to origin)
continue;
OSMID wID = (*m_G)[e].wayOSMID;
assert(wID != 0 && wID != -1U);
if (wID == currWayID) // (connected,same way -> same name) -> same street
(*m_G)[e].streetVectorIndex = m_currStreetVectorIndex;
else if (streetNameForWay(wID) == m_streets.back()) // (connected,same name) -> same street
(*m_G)[e].streetVectorIndex = m_currStreetVectorIndex;
else // different way, different name -> done expanding
continue;
// this is the fall-through case for the if/elseif above (terminates if reaches a different street)
expandVertex(target(e, *m_G), wID);
}
}
std::vector<std::string> assignStreets(OSMDatabase* db, PathNetwork& G) {
StreetEdgeVisitor sev(&G);
sev.osmDatabase(db);
// blank out existing street names
for (const auto e : edges(G))
G[e].streetVectorIndex = 0;
return sev.assign();
}
| 35.913717 | 184 | 0.56687 | jeffreycassidy |
ed109cc9f75dd7d93d2c930aa5e4705cc9f1448b | 10,076 | cpp | C++ | pandar_pointcloud/src/lib/decoder/pandar64_decoder.cpp | Perception-Engine/hesai_pandar | bbdfdf5d81423715c47c0526ac51084fef029edf | [
"Apache-2.0"
] | null | null | null | pandar_pointcloud/src/lib/decoder/pandar64_decoder.cpp | Perception-Engine/hesai_pandar | bbdfdf5d81423715c47c0526ac51084fef029edf | [
"Apache-2.0"
] | 6 | 2021-05-17T06:48:19.000Z | 2022-02-24T23:43:46.000Z | pandar_pointcloud/src/lib/decoder/pandar64_decoder.cpp | Perception-Engine/hesai_pandar | bbdfdf5d81423715c47c0526ac51084fef029edf | [
"Apache-2.0"
] | 1 | 2021-03-05T00:39:13.000Z | 2021-03-05T00:39:13.000Z | #include "pandar_pointcloud/decoder/pandar64_decoder.hpp"
#include "pandar_pointcloud/decoder/pandar64.hpp"
namespace
{
static inline double deg2rad(double degrees)
{
return degrees * M_PI / 180.0;
}
}
namespace pandar_pointcloud
{
namespace pandar64
{
Pandar64Decoder::Pandar64Decoder(Calibration& calibration, float scan_phase, double dual_return_distance_threshold, ReturnMode return_mode)
{
firing_offset_ = {
23.18, 21.876, 20.572, 19.268, 17.964, 16.66, 11.444, 46.796,
7.532, 36.956, 50.732, 54.668, 40.892, 44.828,31.052, 34.988,
48.764, 52.7, 38.924, 42.86, 29.084, 33.02, 46.796, 25.148,
36.956, 50.732, 27.116, 40.892, 44.828, 31.052, 34.988, 48.764,
25.148, 38.924, 42.86, 29.084, 33.02, 52.7, 6.228, 54.668,
15.356, 27.116, 10.14, 23.18, 4.924, 21.876, 14.052, 17.964,
8.836, 19.268, 3.62, 20.572, 12.748, 16.66, 7.532, 11.444,
6.228, 15.356, 10.14, 4.924, 3.62, 14.052, 8.836, 12.748
};
for (int block = 0; block < BLOCK_NUM; ++block) {
block_offset_single_[block] = 55.56f * (BLOCK_NUM - block - 1) + 28.58f;
block_offset_dual_[block] = 55.56f * ((BLOCK_NUM - block - 1) / 2) + 28.58f;
}
// TODO: add calibration data validation
// if(calibration.elev_angle_map.size() != num_lasers_){
// // calibration data is not valid!
// }
for (size_t laser = 0; laser < UNIT_NUM; ++laser) {
elev_angle_[laser] = calibration.elev_angle_map[laser];
azimuth_offset_[laser] = calibration.azimuth_offset_map[laser];
}
scan_phase_ = static_cast<uint16_t>(scan_phase * 100.0f);
return_mode_ = return_mode;
dual_return_distance_threshold_ = dual_return_distance_threshold;
last_phase_ = 0;
has_scanned_ = false;
scan_pc_.reset(new pcl::PointCloud<PointXYZIRADT>);
overflow_pc_.reset(new pcl::PointCloud<PointXYZIRADT>);
}
bool Pandar64Decoder::hasScanned()
{
return has_scanned_;
}
PointcloudXYZIRADT Pandar64Decoder::getPointcloud()
{
return scan_pc_;
}
void Pandar64Decoder::unpack(const pandar_msgs::PandarPacket& raw_packet)
{
if (!parsePacket(raw_packet)) {
return;
}
if (has_scanned_) {
scan_pc_ = overflow_pc_;
overflow_pc_.reset(new pcl::PointCloud<PointXYZIRADT>);
has_scanned_ = false;
}
bool dual_return = (packet_.return_mode == DUAL_RETURN);
auto step = dual_return ? 2 : 1;
if (!dual_return) {
if ((packet_.return_mode == STRONGEST_RETURN && return_mode_ != ReturnMode::STRONGEST) ||
(packet_.return_mode == LAST_RETURN && return_mode_ != ReturnMode::LAST)) {
ROS_WARN ("Sensor return mode configuration does not match requested return mode");
}
}
for (int block_id = 0; block_id < BLOCK_NUM; block_id += step) {
auto block_pc = dual_return ? convert_dual(block_id) : convert(block_id);
int current_phase = (static_cast<int>(packet_.blocks[block_id].azimuth) - scan_phase_ + 36000) % 36000;
if (current_phase > last_phase_ && !has_scanned_) {
*scan_pc_ += *block_pc;
}
else {
*overflow_pc_ += *block_pc;
has_scanned_ = true;
}
last_phase_ = current_phase;
}
}
PointXYZIRADT Pandar64Decoder::build_point(int block_id, int unit_id, uint8_t return_type)
{
const auto& block = packet_.blocks[block_id];
const auto& unit = block.units[unit_id];
auto unix_second = static_cast<double>(timegm(&packet_.t));
bool dual_return = (packet_.return_mode == DUAL_RETURN);
PointXYZIRADT point{};
double xyDistance = unit.distance * cosf(deg2rad(elev_angle_[unit_id]));
point.x = static_cast<float>(
xyDistance * sinf(deg2rad(azimuth_offset_[unit_id] + (static_cast<double>(block.azimuth)) / 100.0)));
point.y = static_cast<float>(
xyDistance * cosf(deg2rad(azimuth_offset_[unit_id] + (static_cast<double>(block.azimuth)) / 100.0)));
point.z = static_cast<float>(unit.distance * sinf(deg2rad(elev_angle_[unit_id])));
point.intensity = unit.intensity;
point.distance = static_cast<float>(unit.distance);
point.ring = unit_id;
point.azimuth = static_cast<float>(block.azimuth) + round(azimuth_offset_[unit_id] * 100.0f);
point.return_type = return_type;
point.time_stamp = unix_second + (static_cast<double>(packet_.usec)) / 1000000.0;
point.time_stamp += dual_return ? (static_cast<double>(block_offset_dual_[block_id] + firing_offset_[unit_id]) / 1000000.0f) :
(static_cast<double>(block_offset_single_[block_id] + firing_offset_[unit_id]) / 1000000.0f);
return point;
}
PointcloudXYZIRADT Pandar64Decoder::convert(const int block_id)
{
PointcloudXYZIRADT block_pc(new pcl::PointCloud<PointXYZIRADT>);
const auto& block = packet_.blocks[block_id];
for (size_t unit_id = 0; unit_id < UNIT_NUM; ++unit_id) {
PointXYZIRADT point{};
const auto& unit = block.units[unit_id];
// skip invalid points
if (unit.distance <= 0.1 || unit.distance > 200.0) {
continue;
}
block_pc->points.emplace_back(build_point(block_id, unit_id, (packet_.return_mode == STRONGEST_RETURN) ? ReturnType::SINGLE_STRONGEST : ReturnType::SINGLE_LAST));
}
return block_pc;
}
PointcloudXYZIRADT Pandar64Decoder::convert_dual(const int block_id)
{
// Under the Dual Return mode, the ranging data from each firing is stored in two adjacent blocks:
// · The even number block is the first return
// · The odd number block is the last return
// · The Azimuth changes every two blocks
// · Important note: Hesai datasheet block numbering starts from 0, not 1, so odd/even are reversed here
PointcloudXYZIRADT block_pc(new pcl::PointCloud<PointXYZIRADT>);
int even_block_id = block_id;
int odd_block_id = block_id + 1;
const auto& even_block = packet_.blocks[even_block_id];
const auto& odd_block = packet_.blocks[odd_block_id];
for (size_t unit_id = 0; unit_id < UNIT_NUM; ++unit_id) {
const auto& even_unit = even_block.units[unit_id];
const auto& odd_unit = odd_block.units[unit_id];
bool even_usable = !(even_unit.distance <= 0.1 || even_unit.distance > 200.0);
bool odd_usable = !(odd_unit.distance <= 0.1 || odd_unit.distance > 200.0);
if (return_mode_ == ReturnMode::STRONGEST && even_usable) {
// First return is in even block
block_pc->points.emplace_back(build_point(even_block_id, unit_id, ReturnType::SINGLE_STRONGEST));
}
else if (return_mode_ == ReturnMode::LAST && even_usable) {
// Last return is in odd block
block_pc->points.emplace_back(build_point(odd_block_id, unit_id, ReturnType::SINGLE_LAST));
}
else if (return_mode_ == ReturnMode::DUAL) {
// If the two returns are too close, only return the last one
if ((abs(even_unit.distance - odd_unit.distance) < dual_return_distance_threshold_) && odd_usable) {
block_pc->points.emplace_back(build_point(odd_block_id, unit_id, ReturnType::DUAL_ONLY));
}
else {
if (even_usable) {
block_pc->points.emplace_back(build_point(even_block_id, unit_id, ReturnType::DUAL_FIRST));
}
if (odd_usable) {
block_pc->points.emplace_back(build_point(odd_block_id, unit_id, ReturnType::DUAL_LAST));
}
}
}
}
return block_pc;
}
bool Pandar64Decoder::parsePacket(const pandar_msgs::PandarPacket& raw_packet)
{
if (raw_packet.size != PACKET_SIZE && raw_packet.size != PACKET_WITHOUT_UDPSEQ_SIZE) {
return false;
}
const uint8_t* buf = &raw_packet.data[0];
size_t index = 0;
// Parse 12 Bytes Header
packet_.header.sob = (buf[index] & 0xff) << 8| ((buf[index+1] & 0xff));
packet_.header.chLaserNumber = buf[index+2] & 0xff;
packet_.header.chBlockNumber = buf[index+3] & 0xff;
packet_.header.chReturnType = buf[index+4] & 0xff;
packet_.header.chDisUnit = buf[index+5] & 0xff;
index += HEAD_SIZE;
if (packet_.header.sob != 0xEEFF) {
// Error Start of Packet!
return false;
}
for (size_t block = 0; block < packet_.header.chBlockNumber; block++) {
packet_.blocks[block].azimuth = (buf[index] & 0xff) | ((buf[index + 1] & 0xff) << 8);
index += BLOCK_HEADER_AZIMUTH;
for (int unit = 0; unit < packet_.header.chLaserNumber; unit++) {
unsigned int unRange = (buf[index]& 0xff) | ((buf[index + 1]& 0xff) << 8);
packet_.blocks[block].units[unit].distance =
(static_cast<double>(unRange * packet_.header.chDisUnit)) / 1000.;
packet_.blocks[block].units[unit].intensity = (buf[index+2]& 0xff);
index += UNIT_SIZE;
}//end fot laser
}//end for block
index += RESERVED_SIZE; // skip reserved bytes
index += ENGINE_VELOCITY;
packet_.usec = (buf[index] & 0xff)| (buf[index+1] & 0xff) << 8 | ((buf[index+2] & 0xff) << 16) | ((buf[index+3] & 0xff) << 24);
index += TIMESTAMP_SIZE;
packet_.return_mode = buf[index] & 0xff;
index += RETURN_SIZE;
index += FACTORY_SIZE;
packet_.t.tm_year = (buf[index + 0] & 0xff) + 100;
// in case of time error
if (packet_.t.tm_year >= 200) {
packet_.t.tm_year -= 100;
}
packet_.t.tm_mon = (buf[index + 1] & 0xff) - 1;
packet_.t.tm_mday = buf[index + 2] & 0xff;
packet_.t.tm_hour = buf[index + 3] & 0xff;
packet_.t.tm_min = buf[index + 4] & 0xff;
packet_.t.tm_sec = buf[index + 5] & 0xff;
packet_.t.tm_isdst = 0;
index += UTC_SIZE;
return true;
}//parsePacket
}//pandar64
}//pandar_pointcloud | 39.206226 | 170 | 0.629813 | Perception-Engine |
ed131fe5b427cb67d5e58e91813206a3d106ffe5 | 1,634 | cpp | C++ | DXR_SoftShadows_Project/BeLuEngine/src/Renderer/DX12Tasks/RenderTask.cpp | jocke1995/DXR_SoftShadows | 00cb6b1cf560899a010c9e8504578d55e113c22c | [
"MIT"
] | null | null | null | DXR_SoftShadows_Project/BeLuEngine/src/Renderer/DX12Tasks/RenderTask.cpp | jocke1995/DXR_SoftShadows | 00cb6b1cf560899a010c9e8504578d55e113c22c | [
"MIT"
] | null | null | null | DXR_SoftShadows_Project/BeLuEngine/src/Renderer/DX12Tasks/RenderTask.cpp | jocke1995/DXR_SoftShadows | 00cb6b1cf560899a010c9e8504578d55e113c22c | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "RenderTask.h"
// DX12 Specifics
#include "../CommandInterface.h"
#include "../GPUMemory/GPUMemory.h"
#include "../PipelineState/GraphicsState.h"
#include "../RootSignature.h"
#include "../SwapChain.h"
RenderTask::RenderTask(
ID3D12Device5* device,
RootSignature* rootSignature,
const std::wstring& VSName, const std::wstring& PSName,
std::vector<D3D12_GRAPHICS_PIPELINE_STATE_DESC*>* gpsds,
const std::wstring& psoName)
:DX12Task(device, COMMAND_INTERFACE_TYPE::DIRECT_TYPE)
{
if (gpsds != nullptr)
{
for (auto gpsd : *gpsds)
{
m_PipelineStates.push_back(new GraphicsState(device, rootSignature, VSName, PSName, gpsd, psoName));
}
}
m_pRootSig = rootSignature->GetRootSig();
}
RenderTask::~RenderTask()
{
for (auto pipelineState : m_PipelineStates)
delete pipelineState;
}
PipelineState* RenderTask::GetPipelineState(unsigned int index)
{
return m_PipelineStates[index];
}
void RenderTask::AddRenderTargetView(std::string name, const RenderTargetView* renderTargetView)
{
m_RenderTargetViews[name] = renderTargetView;
}
void RenderTask::AddShaderResourceView(std::string name, const ShaderResourceView* shaderResourceView)
{
m_ShaderResourceViews[name] = shaderResourceView;
}
void RenderTask::SetRenderComponents(std::vector<RenderComponent*> *renderComponents)
{
m_RenderComponents = renderComponents;
}
void RenderTask::SetMainDepthStencil(DepthStencil* depthStencil)
{
m_pDepthStencil = depthStencil;
}
void RenderTask::SetCamera(BaseCamera* camera)
{
m_pCamera = camera;
}
void RenderTask::SetSwapChain(SwapChain* swapChain)
{
m_pSwapChain = swapChain;
}
| 22.383562 | 103 | 0.76989 | jocke1995 |
ed1498729e51bb7858cd00d50dd565ab4e53f33e | 568 | cpp | C++ | Permutation/Permutation.cpp | raza6/CSES | cfaec9d7bc103c7349cc17c0a07112d1e245dc3a | [
"MIT"
] | null | null | null | Permutation/Permutation.cpp | raza6/CSES | cfaec9d7bc103c7349cc17c0a07112d1e245dc3a | [
"MIT"
] | null | null | null | Permutation/Permutation.cpp | raza6/CSES | cfaec9d7bc103c7349cc17c0a07112d1e245dc3a | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
using namespace std;
typedef long long ll;
int main()
{
// HACKERMAN
ios::sync_with_stdio(false);
cin.tie(0);
//Read inputs
int value;
cin >> value;
string res = "NO SOLUTION";
if (value > 3) {
res = "";
for (int i = 2; i <= value; i += 2) {
res += to_string(i) + " ";
}
for (int i = 1; i <= value; i += 2) {
res += to_string(i) + " ";
}
}
else if (value == 1) {
res = "1";
}
cout << res << endl;
}
| 16.705882 | 45 | 0.43838 | raza6 |
ed16403f90d5cb98d45293e480b4258b7ad5efee | 3,531 | hpp | C++ | src/utility/Confidence.hpp | wvDevAus/Expert-System-Shell | b0c92b1ecb31066c473e549878a9a157b4ea72c9 | [
"MIT"
] | null | null | null | src/utility/Confidence.hpp | wvDevAus/Expert-System-Shell | b0c92b1ecb31066c473e549878a9a157b4ea72c9 | [
"MIT"
] | null | null | null | src/utility/Confidence.hpp | wvDevAus/Expert-System-Shell | b0c92b1ecb31066c473e549878a9a157b4ea72c9 | [
"MIT"
] | null | null | null | #pragma once
#include "nlohmann/json.hpp"
namespace expert_system::utility {
/**
* @brief A managed confidence factor.
* Ensures that the confidence factor does not exceed the range of 0.0f and 1.0f.
*/
class Confidence {
public:
/**
* @brief Default constructor.
* Initial confidence factor value of 0.0f.
*/
Confidence();
/**
* @brief Parameterized constructor.
* @param [in] value The confidence factor value to assign.
* @note This will be replaced by the closest range bounds if outside them.
*/
explicit Confidence(float value);
/**
* @brief Attempts to assign a confidence factor value.
* @param [in] value The confidence factor value to assign.
* @note This will be replaced by the closest range bounds if outside them.
*/
void Set(float value);
/**
* @brief Provides a read-only access to the private confidence factor value.
* @return A copy of the stored confidence factor value.
*/
float Get() const;
/**
* @brief Creates a new confidence factor from combining this value with another.
* @param [in] value The confidence factor value to assign.
* @return A new Confidence, generated from multiplying the provided value with the stored value.
*/
[[nodiscard]] Confidence Combine(const Confidence& value) const;
/**
* @brief 'More than' relational operator overload.
* @param target A reference to a Confidence factor.
* @return True if the target Confidence factor value is more than this.
*/
bool operator<(const Confidence& target);
/**
* @brief 'Less than' relational operator overload.
* @param target A reference to a Confidence factor.
* @return True if the target Confidence factor value is less than this.
*/
bool operator>(const Confidence& target);
/**
* @brief 'Equal to' relational operator overload.
* @param target A reference to a Confidence factor.
* @return True if the target Confidence factor value is equal to this.
*/
bool operator==(const Confidence& target);
private:
/// The protected confidence factor value.
float confidence_factor_;
/// Enables JSON serializer access to private contents
friend void to_json(nlohmann::json& json_sys, const Confidence& target);
/// Enables JSON serializer access to private contents
friend void from_json(const nlohmann::json& json_sys, Confidence& target);
};
/**
* @brief Confidence serialization to JSON format.
* @param [in,out] json_sys A reference to a JSON object.
* @param [in] target A reference to the Confidence to export.
*/
void to_json(nlohmann::json& json_sys, const Confidence& target);
/**
* @brief Confidence serialization from JSON format.
* @param [in] json_sys A reference to a JSON object.
* @param [in,out] target A reference to the Confidence to import.
*/
void from_json(const nlohmann::json& json_sys, Confidence& target);
} // namespace expert_system::utility
| 37.967742 | 109 | 0.588219 | wvDevAus |
ed182479fd135847b311e09e06377096813da592 | 3,347 | cpp | C++ | src/TRGame/Lighting/Lighting.cpp | CXUtk/TRV2 | 945950012e2385aeb24e80bf5e876703445ba423 | [
"Apache-2.0"
] | null | null | null | src/TRGame/Lighting/Lighting.cpp | CXUtk/TRV2 | 945950012e2385aeb24e80bf5e876703445ba423 | [
"Apache-2.0"
] | 15 | 2021-09-04T13:02:51.000Z | 2021-10-05T05:51:31.000Z | src/TRGame/Lighting/Lighting.cpp | CXUtk/TRV2 | 945950012e2385aeb24e80bf5e876703445ba423 | [
"Apache-2.0"
] | null | null | null | #include "Lighting.h"
#include "LightCalculator/LightCommon.h"
#include "LightCalculator/BFSLightCalculator.h"
#include "LightCalculator/DirectionalLightCalculator.h"
#include <TRGame/TRGame.hpp>
#include <TRGame/Player/Player.h>
#include <TRGame/Worlds/GameWorld.h>
#include <TRGame/Worlds/WorldResources.h>
#include <TRGame/Worlds/Tile.h>
#include <TRGame/Worlds/TileSection.h>
#include <TREngine/Core/Render/SpriteRenderer.h>
#include <TREngine/Core/Utils/Utils.h>
#include <TREngine/Core/Assets/assets.h>
#include <TREngine/Core/Render/render.h>
#include <TREngine/Engine.h>
#include <set>
using namespace trv2;
Lighting::Lighting()
{
_lightCommonData = std::make_unique<LightCommon>();
_bfsCalculator = std::make_unique<BFSLightCalculator>(trv2::ptr(_lightCommonData));
_directionCalculator = std::make_unique<DirectionalLightCalculator>(trv2::ptr(_lightCommonData));
}
Lighting::~Lighting()
{}
static glm::vec3 Gamma(const glm::vec3 color)
{
return glm::pow(color, glm::vec3(2.2));
}
static glm::vec3 InvGamma(const glm::vec3 color)
{
return glm::pow(color, glm::vec3(1 / 2.2));
}
void Lighting::ClearLights()
{
_bfsCalculator->ClearLights();
_directionCalculator->ClearLights();
}
void Lighting::AddNormalLight(const Light& light)
{
_bfsCalculator->AddLight(light);
}
void Lighting::AddDirectionalLight(const Light& light)
{
_directionCalculator->AddLight(light);
}
void Lighting::CalculateLight(const trv2::RectI& tileRectCalc, const trv2::RectI& tileRectScreen)
{
_lightCommonData->TileRectScreen = tileRectScreen;
auto sectionRect = GameWorld::GetTileSectionRect(tileRectCalc);
_lightCommonData->SectionRect = sectionRect;
_lightCommonData->TileRectWorld = trv2::RectI(sectionRect.Position * GameWorld::TILE_SECTION_SIZE,
sectionRect.Size * GameWorld::TILE_SECTION_SIZE);
auto gameWorld = TRGame::GetInstance()->GetGameWorld();
_lightCommonData->GameWorld = gameWorld;
auto common = _lightCommonData.get();
const int totalBlocks = common->TileRectWorld.Size.x * common->TileRectWorld.Size.y;
common->SectionRect.ForEach([this, common](glm::ivec2 sectionCoord) {
const TileSection* section = common->GameWorld->GetSection(sectionCoord);
section->ForEachTile([this, common](glm::ivec2 coord, const Tile& tile) {
int id = common->GetBlockId(coord - common->TileRectWorld.Position);
common->CachedTile[id].Type = tile.Type;
});
});
_bfsCalculator->Calculate();
_directionCalculator->Calculate();
_directionCalculator->RasterizeLightTriangles();
}
void Lighting::DrawLightMap(trv2::SpriteRenderer* renderer, const glm::mat4& projection)
{
trv2::BatchSettings setting{};
renderer->Begin(projection, setting);
{
_lightCommonData->TileRectScreen.ForEach([this, renderer](glm::ivec2 coord) -> void {
auto& common = _lightCommonData;
int id = common->GetBlockId(coord - common->TileRectWorld.Position);
auto color = glm::vec3(common->TileColors[0][id],
common->TileColors[1][id],
common->TileColors[2][id]);
if (color == glm::vec3(0)) return;
renderer->Draw(coord, glm::vec2(1), glm::vec2(0),
0.f, glm::vec4(color, 1.f));
});
}
renderer->End();
}
void Lighting::DrawDirectionalTriangles(const glm::mat4& worldProjection)
{
_directionCalculator->DrawTriangles(worldProjection);
}
float Lighting::GetLight(glm::ivec2 coord)
{
return 0.f;
}
| 26.991935 | 99 | 0.747834 | CXUtk |
ed190a1496f87ff0fa3906b2cc16882613357aad | 3,237 | cpp | C++ | sensors/lidars/velodyne/impl/thin_reader.cpp | jackiecx/snark | 492c1b6f26b9e3e8ea6fc66ad1a8c7f997f90ec6 | [
"BSD-3-Clause"
] | 1 | 2019-06-14T15:21:24.000Z | 2019-06-14T15:21:24.000Z | sensors/lidars/velodyne/impl/thin_reader.cpp | jackiecx/snark | 492c1b6f26b9e3e8ea6fc66ad1a8c7f997f90ec6 | [
"BSD-3-Clause"
] | null | null | null | sensors/lidars/velodyne/impl/thin_reader.cpp | jackiecx/snark | 492c1b6f26b9e3e8ea6fc66ad1a8c7f997f90ec6 | [
"BSD-3-Clause"
] | null | null | null | // This file is part of snark, a generic and flexible library for robotics research
// Copyright (c) 2011 The University of Sydney
// All rights reserved.
//
// 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.
// 3. Neither the name of the University of Sydney nor the
// names of its contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE
// GRANTED BY THIS LICENSE. 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.
#ifdef WIN32
#include <fcntl.h>
#include <io.h>
#endif
#include "thin_reader.h"
namespace snark {
snark::thin_reader::thin_reader() : is_new_scan_( true )
{
#ifdef WIN32
_setmode( _fileno( stdin ), _O_BINARY );
#endif
}
const char* thin_reader::read()
{
if( !std::cin.good() || std::cin.eof() ) { return NULL; }
comma::uint16 size;
std::cin.read( reinterpret_cast< char* >( &size ), 2 );
if( std::cin.gcount() < 2 ) { return NULL; }
std::cin.read( m_buf, size );
if( std::cin.gcount() < size ) { return NULL; }
comma::int64 seconds;
comma::int32 nanoseconds;
::memcpy( &seconds, m_buf, sizeof( comma::int64 ) );
::memcpy( &nanoseconds, m_buf + sizeof( comma::int64 ), sizeof( comma::int32 ) );
m_timestamp = boost::posix_time::ptime( snark::timing::epoch, boost::posix_time::seconds( static_cast< long >( seconds ) ) + boost::posix_time::microseconds( nanoseconds / 1000 ) );
comma::uint32 scan = velodyne::thin::deserialize( m_packet, m_buf + timeSize );
is_new_scan_ = is_new_scan_ || !last_scan_ || *last_scan_ != scan; // quick and dirty; keep it set until we clear it in is_new_scan()
last_scan_ = scan;
return reinterpret_cast< char* >( &m_packet );
}
void thin_reader::close() {}
boost::posix_time::ptime thin_reader::timestamp() const { return m_timestamp; }
bool thin_reader::is_new_scan()
{
bool r = is_new_scan_;
is_new_scan_ = false;
return r;
}
} // namespace snark {
| 42.592105 | 185 | 0.71764 | jackiecx |
ed1921e7476b749d29039fd83c981c329256e9f7 | 6,993 | cc | C++ | aimsdata/src/aimsdata/io/imasparseheader.cc | brainvisa/aims-free | 5852c1164292cadefc97cecace022d14ab362dc4 | [
"CECILL-B"
] | 4 | 2019-07-09T05:34:10.000Z | 2020-10-16T00:03:15.000Z | aimsdata/src/aimsdata/io/imasparseheader.cc | brainvisa/aims-free | 5852c1164292cadefc97cecace022d14ab362dc4 | [
"CECILL-B"
] | 72 | 2018-10-31T14:52:50.000Z | 2022-03-04T11:22:51.000Z | aimsdata/src/aimsdata/io/imasparseheader.cc | brainvisa/aims-free | 5852c1164292cadefc97cecace022d14ab362dc4 | [
"CECILL-B"
] | null | null | null | /* This software and supporting documentation are distributed by
* Institut Federatif de Recherche 49
* CEA/NeuroSpin, Batiment 145,
* 91191 Gif-sur-Yvette cedex
* France
*
* This software is governed by the CeCILL-B license under
* French law and abiding by the rules of distribution of free software.
* You can use, modify and/or redistribute the software under the
* terms of the CeCILL-B license as circulated by CEA, CNRS
* and INRIA at the following URL "http://www.cecill.info".
*
* As a counterpart to the access to the source code and rights to copy,
* modify and redistribute granted by the license, users are provided only
* with a limited warranty and the software's author, the holder of the
* economic rights, and the successive licensors have only limited
* liability.
*
* In this respect, the user's attention is drawn to the risks associated
* with loading, using, modifying and/or developing or reproducing the
* software by the user in light of its specific status of free software,
* that may mean that it is complicated to manipulate, and that also
* therefore means that it is reserved for developers and experienced
* professionals having in-depth computer knowledge. Users are therefore
* encouraged to load and test the software's suitability as regards their
* requirements in conditions enabling the security of their systems and/or
* data to be ensured and, more generally, to use and operate it in the
* same conditions as regards security.
*
* The fact that you are presently reading this means that you have had
* knowledge of the CeCILL-B license and that you accept its terms.
*/
// activate deprecation warning
#ifdef AIMSDATA_CLASS_NO_DEPREC_WARNING
#undef AIMSDATA_CLASS_NO_DEPREC_WARNING
#endif
#include <aims/io/imasparseheader.h>
#include <aims/def/general.h>
#include <aims/io/defaultItemR.h>
#include <cartobase/exception/ioexcept.h>
#include <cartobase/stream/fileutil.h>
#include <soma-io/utilities/asciidatasourcetraits.h>
#include <fstream>
using namespace aims;
using namespace carto;
using namespace std;
ImasHeader::ImasHeader( const string & filename ) :
PythonHeader(),
_filename( filename )
{
}
ImasHeader::~ImasHeader()
{
}
namespace
{
bool testBinFormat( const string & fname, uint32_t & lines, uint32_t & cols,
uint32_t & count )
{
ifstream is( fname.c_str(), ios::in | ios::binary );
if( !is )
io_error::launchErrnoExcept( fname );
is.unsetf( ios::skipws );
static DefaultItemReader<uint32_t> itemR1;
uint32_t size1 = 0U;
uint32_t size2 = 0U;
uint32_t nonZeroElementCount = 0U;
itemR1.read( is, size1 );
if( !is )
return false;
itemR1.read( is, size2 );
if( !is )
return false;
itemR1.read( is, nonZeroElementCount );
if( !is )
return false;
streampos p = is.tellg(), e;
is.seekg( 0, ios_base::end );
e = is.tellg();
is.seekg( p, ios_base::beg );
if( nonZeroElementCount > size1 * size2
|| nonZeroElementCount * 16 != e - p )
return false;
lines = size1;
cols = size2;
count = nonZeroElementCount;
return true;
}
bool testBswapFormat( const string & fname, uint32_t & lines,
uint32_t & cols, uint32_t & count )
{
ifstream is( fname.c_str(), ios::in | ios::binary );
if( !is )
io_error::launchErrnoExcept( fname );
is.unsetf( ios::skipws );
static DefaultBSwapItemReader<uint32_t> itemR1;
uint32_t size1 = 0U;
uint32_t size2 = 0U;
uint32_t nonZeroElementCount = 0U;
itemR1.read( is, size1 );
if( !is )
return false;
itemR1.read( is, size2 );
if( !is )
return false;
itemR1.read( is, nonZeroElementCount );
if( !is )
return false;
streampos p = is.tellg(), e;
is.seekg( 0, ios_base::end );
e = is.tellg();
is.seekg( p, ios_base::beg );
if( nonZeroElementCount > size1 * size2
|| nonZeroElementCount * 16 != e - p )
return false;
lines = size1;
cols = size2;
count = nonZeroElementCount;
return true;
}
bool testAsciiFormat( const string & fname, uint32_t & lines,
uint32_t & cols, uint32_t & count )
{
ifstream is( fname.c_str(), ios::in | ios::binary );
if( !is )
io_error::launchErrnoExcept( fname );
is.unsetf( ios::skipws );
static DefaultAsciiItemReader<uint32_t> itemR1;
uint32_t size1 = 0U;
uint32_t size2 = 0U;
uint32_t nonZeroElementCount = 0U;
itemR1.read( is, size1 );
if( !is )
return false;
itemR1.read( is, size2 );
if( !is )
return false;
itemR1.read( is, nonZeroElementCount );
if( !is )
return false;
streampos p = is.tellg(), e;
is.seekg( 0, ios_base::end );
e = is.tellg();
is.seekg( p, ios_base::beg );
if( nonZeroElementCount > size1 * size2
|| nonZeroElementCount * 16 != e - p )
return false;
lines = size1;
cols = size2;
count = nonZeroElementCount;
return true;
}
}
bool ImasHeader::read( uint32_t* )
{
string fname = filename();
if( FileUtil::fileStat( fname ).find( '+' ) == string::npos )
throw file_not_found_error( fname );
bool ascii = false;
bool bswap = false;
uint32_t lines = 0, cols = 0, count = 0;
if( testBinFormat( fname, lines, cols, count ) )
{
ascii = false;
bswap = false;
}
else if( testBswapFormat( fname, lines, cols, count ) )
{
ascii = false;
bswap = true;
}
else if( testAsciiFormat( fname, lines, cols, count ) )
{
ascii = true;
bswap = false;
}
else
throw wrong_format_error( "Wrong format or corrupted .imas format",
"<?>" );
setProperty( "file_type", string( "IMASPARSE" ) );
setProperty( "object_type", "SparseMatrix" );
setProperty( "data_type", "DOUBLE" );
setProperty( "ascii", (int) ascii );
if( !ascii )
setProperty( "byte_swapping", (int) bswap );
vector<int> dims(2);
dims[0] = (int) lines;
dims[1] = (int) cols;
setProperty( "dimensions", dims );
setProperty( "non_zero_elements", (int) count );
// add meta-info to header
readMinf( removeExtension( fname ) + extension() + ".minf" );
return true;
}
string ImasHeader::openMode() const
{
int om = 0;
getProperty( "ascii", om );
if ( om )
return string("ascii");
return string("binar");
}
bool ImasHeader::byteSwapping() const
{
int bswap = 0;
getProperty( "byte_swapping", bswap );
return bswap ? true : false;
}
string ImasHeader::filename() const
{
if( _filename.length() > 5
&& _filename.substr( _filename.length()-5, 5 ) == ".imas" )
return _filename;
else
{
if( FileUtil::fileStat( _filename ).find( 'r' ) != string::npos )
return _filename;
return _filename + ".imas";
}
}
set<string> ImasHeader::extensions() const
{
set<string> exts;
exts.insert( ".imas" );
return exts;
}
| 25.521898 | 78 | 0.646075 | brainvisa |
ed1a79bdc801741558e76b1f925ccf3a814cb406 | 1,807 | cpp | C++ | soundmanager.cpp | hckr/space-logic-adventure | 7465c7ffb70b0488ce4ff88620e3d35742f4fb06 | [
"MIT"
] | 6 | 2017-09-15T16:15:03.000Z | 2020-01-09T04:31:26.000Z | soundmanager.cpp | hckr/space-logic-adventure | 7465c7ffb70b0488ce4ff88620e3d35742f4fb06 | [
"MIT"
] | null | null | null | soundmanager.cpp | hckr/space-logic-adventure | 7465c7ffb70b0488ce4ff88620e3d35742f4fb06 | [
"MIT"
] | 1 | 2017-12-05T05:22:02.000Z | 2017-12-05T05:22:02.000Z | #include "soundmanager.hpp"
void SoundManager::lowerMusicVolume(bool lower) {
if (lower) {
sounds.at(MENU).setVolume(50);
sounds.at(LEVEL).setVolume(50);
} else {
sounds.at(MENU).setVolume(100);
sounds.at(LEVEL).setVolume(100);
}
}
SoundManager::SoundManager()
{
menuSB.loadFromFile(SOUNDS_DIR + "menu.ogg");
levelSB.loadFromFile(SOUNDS_DIR + "level.ogg");
levelCompletedSB.loadFromFile(SOUNDS_DIR + "level_completed.ogg");
gameOverSB.loadFromFile(SOUNDS_DIR + "game_over.ogg");
sounds.at(MENU).setLoop(true);
sounds.at(LEVEL).setLoop(true);
}
SoundManager* SoundManager::instance = 0;
SoundManager& SoundManager::getInstance() {
if (!instance) {
instance = new SoundManager();
}
return *instance;
}
void SoundManager::destroyInstance() {
if (instance) {
delete instance;
instance = 0;
}
}
void SoundManager::changeMusic(Sound music) {
if (musicPlaying == music) {
return;
}
switch (music) {
case NONE:
sounds.at(musicPlaying).stop();
break;
case MENU:
case LEVEL:
if (musicPlaying != NONE) {
sounds.at(musicPlaying).stop();
}
sounds.at(music).play();
musicPlaying = music;
break;
default:
break;
}
}
void SoundManager::playEffect(Sound effect) {
switch (effect) {
case LEVEL_COMPLETED:
case GAME_OVER:
lowerMusicVolume(true);
sounds.at(effect).play();
effectPlaying = effect;
break;
default:
break;
}
}
void SoundManager::update() {
if (effectPlaying != NONE && sounds.at(effectPlaying).getStatus() == sf::SoundSource::Stopped) {
lowerMusicVolume(false);
effectPlaying = NONE;
}
}
| 21.511905 | 100 | 0.60653 | hckr |
ed1bfd33453e41f099287ac92d62cd0efef6729a | 10,530 | cpp | C++ | rosflight_utils/src/turbomath.cpp | WangGY-Pro/rosflight | 000e3d79383e05d7cc574129644a12c694a876eb | [
"BSD-3-Clause"
] | 80 | 2017-05-27T16:21:32.000Z | 2022-03-09T13:24:38.000Z | rosflight_utils/src/turbomath.cpp | WangGY-Pro/rosflight | 000e3d79383e05d7cc574129644a12c694a876eb | [
"BSD-3-Clause"
] | 82 | 2017-05-17T17:10:04.000Z | 2021-06-06T04:25:44.000Z | rosflight_utils/src/turbomath.cpp | WangGY-Pro/rosflight | 000e3d79383e05d7cc574129644a12c694a876eb | [
"BSD-3-Clause"
] | 67 | 2017-05-16T19:26:53.000Z | 2022-03-27T15:04:34.000Z | /*
* Copyright (c) 2017 James Jackson, BYU MAGICC Lab.
* 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 copyright holder 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 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 <rosflight_utils/turbomath.h>
#include <cstdint>
static const int16_t atan_lookup_table[250] = {
0, 40, 80, 120, 160, 200, 240, 280, 320, 360, 400, 440, 480, 520, 559, 599, 639, 679,
719, 759, 798, 838, 878, 917, 957, 997, 1036, 1076, 1115, 1155, 1194, 1234, 1273, 1312, 1352, 1391,
1430, 1469, 1508, 1548, 1587, 1626, 1664, 1703, 1742, 1781, 1820, 1858, 1897, 1935, 1974, 2012, 2051, 2089,
2127, 2166, 2204, 2242, 2280, 2318, 2355, 2393, 2431, 2469, 2506, 2544, 2581, 2618, 2656, 2693, 2730, 2767,
2804, 2841, 2878, 2915, 2951, 2988, 3024, 3061, 3097, 3133, 3169, 3206, 3241, 3277, 3313, 3349, 3385, 3420,
3456, 3491, 3526, 3561, 3596, 3631, 3666, 3701, 3736, 3771, 3805, 3839, 3874, 3908, 3942, 3976, 4010, 4044,
4078, 4112, 4145, 4179, 4212, 4245, 4278, 4311, 4344, 4377, 4410, 4443, 4475, 4508, 4540, 4572, 4604, 4636,
4668, 4700, 4732, 4764, 4795, 4827, 4858, 4889, 4920, 4951, 4982, 5013, 5044, 5074, 5105, 5135, 5166, 5196,
5226, 5256, 5286, 5315, 5345, 5375, 5404, 5434, 5463, 5492, 5521, 5550, 5579, 5608, 5636, 5665, 5693, 5721,
5750, 5778, 5806, 5834, 5862, 5889, 5917, 5944, 5972, 5999, 6026, 6053, 6080, 6107, 6134, 6161, 6187, 6214,
6240, 6267, 6293, 6319, 6345, 6371, 6397, 6422, 6448, 6473, 6499, 6524, 6549, 6574, 6599, 6624, 6649, 6674,
6698, 6723, 6747, 6772, 6796, 6820, 6844, 6868, 6892, 6916, 6940, 6963, 6987, 7010, 7033, 7057, 7080, 7103,
7126, 7149, 7171, 7194, 7217, 7239, 7261, 7284, 7306, 7328, 7350, 7372, 7394, 7416, 7438, 7459, 7481, 7502,
7524, 7545, 7566, 7587, 7608, 7629, 7650, 7671, 7691, 7712, 7733, 7753, 7773, 7794, 7814, 7834};
static const int16_t asin_lookup_table[250] = {
0, 40, 80, 120, 160, 200, 240, 280, 320, 360, 400, 440, 480, 520, 560, 600,
640, 681, 721, 761, 801, 841, 881, 921, 961, 1002, 1042, 1082, 1122, 1163, 1203, 1243,
1284, 1324, 1364, 1405, 1445, 1485, 1526, 1566, 1607, 1647, 1688, 1729, 1769, 1810, 1851, 1891,
1932, 1973, 2014, 2054, 2095, 2136, 2177, 2218, 2259, 2300, 2341, 2382, 2424, 2465, 2506, 2547,
2589, 2630, 2672, 2713, 2755, 2796, 2838, 2880, 2921, 2963, 3005, 3047, 3089, 3131, 3173, 3215,
3257, 3300, 3342, 3384, 3427, 3469, 3512, 3554, 3597, 3640, 3683, 3726, 3769, 3812, 3855, 3898,
3941, 3985, 4028, 4072, 4115, 4159, 4203, 4246, 4290, 4334, 4379, 4423, 4467, 4511, 4556, 4601,
4645, 4690, 4735, 4780, 4825, 4870, 4916, 4961, 5007, 5052, 5098, 5144, 5190, 5236, 5282, 5329,
5375, 5422, 5469, 5515, 5562, 5610, 5657, 5704, 5752, 5800, 5848, 5896, 5944, 5992, 6041, 6089,
6138, 6187, 6236, 6286, 6335, 6385, 6435, 6485, 6535, 6586, 6637, 6687, 6739, 6790, 6841, 6893,
6945, 6997, 7050, 7102, 7155, 7208, 7262, 7315, 7369, 7423, 7478, 7532, 7587, 7643, 7698, 7754,
7810, 7867, 7923, 7981, 8038, 8096, 8154, 8213, 8271, 8331, 8390, 8450, 8511, 8572, 8633, 8695,
8757, 8820, 8883, 8947, 9011, 9076, 9141, 9207, 9273, 9340, 9407, 9476, 9545, 9614, 9684, 9755,
9827, 9900, 9973, 10047, 10122, 10198, 10275, 10353, 10432, 10512, 10593, 10675, 10759, 10844, 10930, 11018,
11107, 11198, 11290, 11385, 11481, 11580, 11681, 11784, 11890, 11999, 12111, 12226, 12346, 12469, 12597, 12730,
12870, 13017, 13171, 13336, 13513, 13705, 13917, 14157, 14442, 14813};
static const int16_t sin_lookup_table[250] = {
0, 63, 126, 188, 251, 314, 377, 440, 502, 565, 628, 691, 753, 816, 879, 941, 1004, 1066,
1129, 1191, 1253, 1316, 1378, 1440, 1502, 1564, 1626, 1688, 1750, 1812, 1874, 1935, 1997, 2059, 2120, 2181,
2243, 2304, 2365, 2426, 2487, 2548, 2608, 2669, 2730, 2790, 2850, 2910, 2970, 3030, 3090, 3150, 3209, 3269,
3328, 3387, 3446, 3505, 3564, 3623, 3681, 3740, 3798, 3856, 3914, 3971, 4029, 4086, 4144, 4201, 4258, 4315,
4371, 4428, 4484, 4540, 4596, 4652, 4707, 4762, 4818, 4873, 4927, 4982, 5036, 5090, 5144, 5198, 5252, 5305,
5358, 5411, 5464, 5516, 5569, 5621, 5673, 5724, 5776, 5827, 5878, 5929, 5979, 6029, 6079, 6129, 6179, 6228,
6277, 6326, 6374, 6423, 6471, 6518, 6566, 6613, 6660, 6707, 6753, 6800, 6845, 6891, 6937, 6982, 7026, 7071,
7115, 7159, 7203, 7247, 7290, 7333, 7375, 7417, 7459, 7501, 7543, 7584, 7624, 7665, 7705, 7745, 7785, 7824,
7863, 7902, 7940, 7978, 8016, 8053, 8090, 8127, 8163, 8200, 8235, 8271, 8306, 8341, 8375, 8409, 8443, 8477,
8510, 8543, 8575, 8607, 8639, 8671, 8702, 8733, 8763, 8793, 8823, 8852, 8881, 8910, 8938, 8966, 8994, 9021,
9048, 9075, 9101, 9127, 9152, 9178, 9202, 9227, 9251, 9274, 9298, 9321, 9343, 9365, 9387, 9409, 9430, 9451,
9471, 9491, 9511, 9530, 9549, 9567, 9585, 9603, 9620, 9637, 9654, 9670, 9686, 9701, 9716, 9731, 9745, 9759,
9773, 9786, 9799, 9811, 9823, 9834, 9846, 9856, 9867, 9877, 9887, 9896, 9905, 9913, 9921, 9929, 9936, 9943,
9950, 9956, 9961, 9967, 9972, 9976, 9980, 9984, 9987, 9990, 9993, 9995, 9997, 9998, 9999, 10000};
float sign(float y)
{
return (0 < y) - (y < 0);
}
float asin_lookup(float x)
{
static const float max = 1.0;
static const float min = 0.0;
static const int16_t num_entries = 250;
static float dx = 0.0;
static const float scale = 10000.0;
float t = (x - min) / (max - min) * num_entries;
uint8_t index = (uint8_t)t;
dx = t - (float)index;
if (index >= num_entries)
{
return max;
}
else if (index < num_entries - 1)
{
return (float)asin_lookup_table[index] / scale
+ dx * (float)(asin_lookup_table[index + 1] - asin_lookup_table[index]) / scale;
}
else
{
return (float)asin_lookup_table[index] / scale
+ dx * (float)(asin_lookup_table[index] - asin_lookup_table[index - 1]) / scale;
}
}
float turboacos(float x)
{
if (x < 0)
return M_PI + asin_lookup(-x);
else
return M_PI - asin_lookup(x);
}
float turboasin(float x)
{
if (x < 0)
return -asin_lookup(-x);
else
return asin_lookup(x);
}
float sin_lookup(float x)
{
static const float max = 1.0;
static const float min = 0.0;
static const int16_t num_entries = 250;
static float dx = 0.0;
static const float scale = 10000.0;
float t = (x - min) / (max - min) * num_entries;
uint8_t index = (uint8_t)t;
dx = t - (float)index;
if (index >= num_entries)
return max;
else if (index < num_entries - 1)
return (float)sin_lookup_table[index] / scale
+ dx * (float)(sin_lookup_table[index + 1] - sin_lookup_table[index]) / scale;
else
return (float)sin_lookup_table[index] / scale
+ dx * (float)(sin_lookup_table[index] - sin_lookup_table[index - 1]) / scale;
}
float turbosin(float x)
{
while (x > M_PI) x -= 2.0 * M_PI;
while (x <= -M_PI) x += 2.0 * M_PI;
if (0 <= x && x <= M_PI / 2.0)
return sin_lookup(x);
else if (-M_PI / 2.0 <= x && x < 0)
return -sin_lookup(-x);
else if (M_PI / 2.0 < x)
return sin_lookup(M_PI - x);
else
return -sin_lookup(x + M_PI);
}
float turbocos(float x)
{
return turbosin(x + M_PI);
}
float atan_lookup(float x)
{
if (x < 0)
return -1 * atan_lookup(-1 * x);
if (x > 1.0)
return M_PI - atan_lookup(1.0 / x);
static const float max = 1.0;
static const float min = 0.0;
static const int16_t num_entries = 250;
static float dx = 0.0;
static const float scale = 10000.0;
float t = (x - min) / (max - min) * num_entries;
uint8_t index = (uint8_t)t;
dx = t - (float)index;
if (index >= num_entries)
return max;
else if (index < num_entries - 1)
return (float)atan_lookup_table[index] / scale
+ dx * (float)(atan_lookup_table[index + 1] - atan_lookup_table[index]) / scale;
else
return (float)atan_lookup_table[index] / scale
+ dx * (float)(atan_lookup_table[index] - atan_lookup_table[index - 1]) / scale;
}
float turboatan2(float y, float x)
{
if (y == 0)
{
if (x < 0)
return M_PI;
else
return 0;
}
else if (x == 0)
{
return M_PI / 2.0 * sign(y);
}
else
{
float arctan = atan_lookup(x / y);
if (y > 0)
return M_PI / 2.0 - arctan;
else if (y < 0)
return -M_PI / 2.0 - arctan;
else if (x < 0)
return arctan + M_PI;
else
return arctan;
}
}
double turbopow(double a, double b)
{
union
{
double d;
int x[2];
} u = {a};
u.x[1] = (int)(b * (u.x[1] - 1072632447) + 1072632447);
u.x[0] = 0;
return u.d;
}
float turboInvSqrt(float x)
{
long i;
float x2, y;
const float threehalfs = 1.5F;
x2 = x * 0.5F;
y = x;
i = *(long*)&y; // evil floating point bit level hacking
i = 0x5f3759df - (i >> 1);
y = *(float*)&i;
y = y * (threehalfs - (x2 * y * y)); // 1st iteration
// y = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed
return y;
}
| 40.19084 | 115 | 0.624501 | WangGY-Pro |
ed201517a7219380c6e1a83f6a97c561e43cc1bd | 10,608 | cpp | C++ | code/lib/usart.cpp | ian-ross/mini-mapper | 797db70b9b619a0bdd4f1bf0def101dcfaa57452 | [
"MIT"
] | null | null | null | code/lib/usart.cpp | ian-ross/mini-mapper | 797db70b9b619a0bdd4f1bf0def101dcfaa57452 | [
"MIT"
] | null | null | null | code/lib/usart.cpp | ian-ross/mini-mapper | 797db70b9b619a0bdd4f1bf0def101dcfaa57452 | [
"MIT"
] | null | null | null | #include "dma.hpp"
#include "events.hpp"
#include "usart.hpp"
static USART_TypeDef *usart_base(int iusart);
static DMA_Stream_TypeDef *usart_dma_stream(int iusart);
static IRQn_Type usart_irqn(int iusart);
// Set up USART for interrupt-driven RX, DMA-driven TX.
void USART::init(void) {
volatile uint32_t &apbenr_reg = RCC->APB1ENR;
const uint32_t apbenr_bit = RCC_APB1ENR_USART3EN;
volatile uint32_t &ahbenr_dma_reg = RCC->AHB1ENR;
const uint32_t ahbenr_dma_bit = RCC_AHB1ENR_DMA1EN + _dma_chan.dma - 1;
// Disable USART.
CLEAR_BIT(_usart->CR1, USART_CR1_UE);
// Enable USART APB clock.
SET_BIT(apbenr_reg, apbenr_bit);
(void)READ_BIT(apbenr_reg, apbenr_bit);
// Select system clock (216 MHz) as clock source for USART.
const uint32_t dckcfgr2_pos = 2 * (_iusart - 1);
const uint32_t dckcfgr2_mask = 0x03 << dckcfgr2_pos;
MODIFY_REG(RCC->DCKCFGR2, dckcfgr2_mask, 0x01 << dckcfgr2_pos);
// Set word length (M1 = 0, M0 = 0 => 1 start bit, 8 data bits, n
// stop bits).
CLEAR_BIT(_usart->CR1, USART_CR1_M0);
CLEAR_BIT(_usart->CR1, USART_CR1_M1);
// Disable parity.
CLEAR_BIT(_usart->CR1, USART_CR1_PCE);
// Disable auto baudrate detection.
CLEAR_BIT(_usart->CR2, USART_CR2_ABREN);
// Send/receive LSB first.
CLEAR_BIT(_usart->CR2, USART_CR2_MSBFIRST);
// Set oversampling rate to 16 and select baud rate 115200 based on
// USART clock running at 216 MHz (value taken from Table 220 in
// STM32F767ZI reference manual). (216000000 / 115200 = 0x0753)
CLEAR_BIT(_usart->CR1, USART_CR1_OVER8);
_usart->BRR = 0x0753;
// One stop bit (USART.CR2.STOP[1:0] = 0 => 1 stop bit).
MODIFY_REG(_usart->CR2, USART_CR2_STOP_Msk, 0);
// Enable USART, receiver and transmitter.
SET_BIT(_usart->CR1, USART_CR1_UE);
SET_BIT(_usart->CR1, USART_CR1_RE);
SET_BIT(_usart->CR1, USART_CR1_TE);
// Pin configuration: set TX to output (PP, pull-up), RX to input,
// set both to the appropriate alternate function.
_tx.output(GPIO_SPEED_VERY_HIGH, GPIO_TYPE_PUSH_PULL, GPIO_PUPD_PULL_UP);
_rx.input(GPIO_SPEED_VERY_HIGH);
_tx.alternate(_tx_af);
_rx.alternate(_rx_af);
// Receive interrupt setup: enable USART interrupts in NVIC and
// enable RX interrupt (also handles overrun errors).
NVIC_EnableIRQ(usart_irqn(_iusart));
SET_BIT(_usart->CR1, USART_CR1_RXNEIE);
// Transmit DMA setup. (Following procedure in Section 8.3.18 of
// reference manual.)
// TODO: SOME OF THIS IS STILL SPECIFIC TO USART3, I THINK.
// Enable DMA transmitter for UART.
SET_BIT(_usart->CR3, USART_CR3_DMAT);
// Enable clock for DMA1.
SET_BIT(ahbenr_dma_reg, ahbenr_dma_bit);
// 2. Set the peripheral port register address in the DMA_SxPAR
// register.
_dma->PAR = (uintptr_t)&_usart->TDR;
// 5. Select the DMA channel (request) using CHSEL[3:0] in the
// DMA_SxCR register.
MODIFY_REG(_dma->CR, DMA_SxCR_CHSEL_Msk,
_dma_chan.channel << DMA_SxCR_CHSEL_Pos);
// DMA is flow controller.
CLEAR_BIT(_dma->CR, DMA_SxCR_PFCTRL);
// 7. Configure the stream priority using the PL[1:0] bits in the
// DMA_SxCR register.
// Medium priority.
MODIFY_REG(_dma->CR, DMA_SxCR_PL_Msk, 0x02 << DMA_SxCR_PL_Pos);
// 8. Configure the FIFO usage (enable or disable, threshold in
// transmission and reception).
CLEAR_BIT(_dma->FCR, DMA_SxFCR_DMDIS); // No FIFO: direct mode.
// 9. Configure the data transfer direction, peripheral and memory
// incremented/fixed mode, single or burst transactions,
// peripheral and memory data widths, circular mode,
// double-buffer mode and interrupts after half and/or full
// transfer, and/or errors in the DMA_SxCR register.
// Memory-to-peripheral.
MODIFY_REG(_dma->CR, DMA_SxCR_DIR_Msk, 0x01 << DMA_SxCR_DIR_Pos);
// Increment memory, no increment peripheral.
SET_BIT(_dma->CR, DMA_SxCR_MINC);
CLEAR_BIT(_dma->CR, DMA_SxCR_PINC);
// No burst at either end.
MODIFY_REG(_dma->CR, DMA_SxCR_MBURST_Msk, 0x00 << DMA_SxCR_MBURST_Pos);
MODIFY_REG(_dma->CR, DMA_SxCR_PBURST_Msk, 0x00 << DMA_SxCR_PBURST_Pos);
// Byte size at both ends.
MODIFY_REG(_dma->CR, DMA_SxCR_MSIZE_Msk, 0x00 << DMA_SxCR_MSIZE_Pos);
MODIFY_REG(_dma->CR, DMA_SxCR_PSIZE_Msk, 0x00 << DMA_SxCR_PSIZE_Pos);
// No circular mode, no double buffering.
CLEAR_BIT(_dma->CR, DMA_SxCR_CIRC);
CLEAR_BIT(_dma->CR, DMA_SxCR_DBM);
// Transfer complete interrupt, no half-transfer interrupt, transfer
// error interrupt and direct mode error interrupt.
SET_BIT(_dma->CR, DMA_SxCR_TCIE);
CLEAR_BIT(_dma->CR, DMA_SxCR_HTIE);
SET_BIT(_dma->CR, DMA_SxCR_TEIE);
SET_BIT(_dma->CR, DMA_SxCR_DMEIE);
// Transmit DMA interrupt setup: enable DMA interrupts for DMA
// channel attached to USART.
NVIC_EnableIRQ(dma_irqn(_dma_chan));
}
// Buffer a single character for transmission.
void USART::tx(char c) {
// Buffer overflow: clear buffer, post error.
if (_tx_size >= USART_TX_BUFSIZE) {
_tx_size = 0;
if (mgr) mgr->post(Events::USART_TX_OVERFLOW);
return;
}
// Buffer character.
_tx_buff[_tx_size++] = c;
}
// Event handler: this checks whether we need to fire off a DMA TX on
// every SysTick. To force a flush, we just call the `flush` method,
// which sets the `need_flush` flag, and a DMA TX is started at the
// next SysTick.
void USART::dispatch(const Events::Event &e) {
switch (e.tag) {
case Events::EVENT_LOOP_STARTED:
init();
mgr->post(Events::USART_INIT, _iusart);
break;
case Events::SYSTICK:
// Skip conditions that don't require us to start a DMA TX.
if (_need_flush && _tx_size != 0 && !_tx_sending)
start_tx_dma();
break;
default:
break;
}
}
// Start a DMA transmission.
void USART::start_tx_dma(void) {
// Set DMA request to send _tx_size bytes starting at _tx_buff.
// (Following procedure in Section 8.3.18 of reference manual.)
// 1. If the stream is enabled, disable it by resetting the EN bit
// in the DMA_SxCR register, then read this bit in order to
// confirm that there is no ongoing stream operation.
CLEAR_BIT(_dma->CR, DMA_SxCR_EN);
while (READ_BIT(_dma->CR, DMA_SxCR_EN)) { __asm("nop"); }
// 3. Set the memory address in the DMA_SxMA0R register.
_dma->M0AR = (uintptr_t)_tx_buff;
// 4. Configure the total number of data items to be transferred in
// the DMA_SxNDTR register.
_dma->NDTR = _tx_size;
// Clear all interrupt pending flags.
SET_BIT(DMA1->LIFCR, DMA_LIFCR_CTCIF3);
SET_BIT(DMA1->LIFCR, DMA_LIFCR_CHTIF3);
SET_BIT(DMA1->LIFCR, DMA_LIFCR_CTEIF3);
SET_BIT(DMA1->LIFCR, DMA_LIFCR_CDMEIF3);
// Ensure all relevant interrupts are enabled.
SET_BIT(_dma->CR, DMA_SxCR_TCIE);
// 10. Activate the stream by setting the EN bit in the DMA_SxCR
// register.
SET_BIT(_dma->CR, DMA_SxCR_EN);
// TODO: SOME OF THIS SHOULD BE DONE *BEFORE* ENABLING THE DMA!
// Swap DMA buffers for writing and mark that a DMA is in progress.
_tx_buff_idx = 1 - _tx_buff_idx;
_tx_buff = _tx_buffs[_tx_buff_idx];
_tx_size = 0;
_tx_sending = true;
_need_flush = false;
}
// USART RX interrupt handler.
void USART::rx_irq(void) {
// Overrun: clear buffer, return error.
if (_usart->ISR & USART_ISR_ORE) {
SET_BIT(_usart->ICR, USART_ICR_ORECF);
if (mgr) mgr->post(Events::USART_RX_OVERRUN);
return;
}
// Byte received.
if (_usart->ISR & USART_ISR_RXNE) {
char c = _usart->RDR;
if (mgr) mgr->post(Events::USART_RX_CHAR, c);
}
}
// DMA stream interrupt handler.
void USART::tx_dma_irq(void) {
// Permit another flush.
_tx_sending = false;
// Errors.
if (DMA1->LISR & DMA_LISR_TEIF3) {
_tx_error = true;
SET_BIT(DMA1->LIFCR, DMA_LIFCR_CTEIF3);
}
if (DMA1->LISR & DMA_LISR_DMEIF3) {
_tx_error = true;
SET_BIT(DMA1->LIFCR, DMA_LIFCR_CDMEIF3);
}
// Transfer complete.
if (DMA1->LISR & DMA_LISR_TCIF3) {
SET_BIT(DMA1->LIFCR, DMA_LIFCR_CTCIF3);
}
if (_tx_error) {
if (mgr) mgr->post(Events::USART_TX_ERROR);
}
}
// The addresses for these aren't assigned systematically, hence the
// need for a switch statement here.
USART_TypeDef *USART::usart_base(int iusart) {
switch (iusart) {
case 1: return USART1;
case 2: return USART2;
case 3: return USART3;
case 4: return UART4;
case 5: return UART5;
case 6: return USART6;
default: return nullptr;
}
}
// TODO: DO THIS BETTER -- THERE ARE MULTIPLE POSSIBLE DMA STREAMS FOR
// MOST PERIPHERALS. FOR EXAMPLE, USART3_TX IS ON DMA1_Stream3,
// CHANNEL 4 AND ON DMA1_Stream4, CHANNEL 7.
DMA_Stream_TypeDef *USART::usart_dma_stream(int iusart) {
switch (iusart) {
case 1: return DMA2_Stream7;
case 2: return DMA1_Stream6;
case 3: return DMA1_Stream3;
case 4: return DMA1_Stream4;
case 5: return DMA1_Stream7;
case 6: return DMA2_Stream6;
default: return nullptr;
}
}
static IRQn_Type usart_irqn(int iusart) {
switch (iusart) {
case 1: return USART1_IRQn;
case 2: return USART2_IRQn;
case 3: return USART3_IRQn;
case 4: return UART4_IRQn;
case 5: return UART5_IRQn;
case 6: return USART6_IRQn;
default: return NonMaskableInt_IRQn;
}
}
//----------------------------------------------------------------------
//
// TESTS
//
#ifdef TEST
#include "doctest.h"
#include "doctest/trompeloeil.hpp"
#include "events_mock.hpp"
TEST_CASE("USART") {
using trompeloeil::_;
MockEventWaiter waiter;
Events::Manager ev(MockEventWaiter::wait_for_event);
USART usart(3, PD8, GPIO_AF_7, PD9, GPIO_AF_7, DMAChannel { 1, 3, 4 });
ev += usart;
MockEventConsumer consumer;
ev += consumer;
SUBCASE("RX ISR enqueues correct event") {
ALLOW_CALL(consumer, dispatch(_));
ev.drain();
USART3->RDR = 'x';
SET_BIT(USART3->ISR, USART_ISR_RXNE);
usart.rx_irq();
REQUIRE_CALL(consumer, dispatch(_))
.WITH(_1.tag == Events::USART_RX_CHAR && _1.param1 == 'x');
ev.drain();
CHECK(ev.pending_count() == 0);
}
SUBCASE("RX overrun enqueues correct event") {
ALLOW_CALL(consumer, dispatch(_));
ev.drain();
SET_BIT(USART3->ISR, USART_ISR_ORE);
usart.rx_irq();
REQUIRE_CALL(consumer, dispatch(_))
.WITH(_1.tag == Events::USART_RX_OVERRUN);
ev.drain();
CHECK(ev.pending_count() == 0);
}
SUBCASE("SysTick triggers TX DMA") {
ALLOW_CALL(consumer, dispatch(_));
ev.drain();
memset(DMA1_Stream3, 0, sizeof(DMA_Stream_TypeDef));
for (auto c : "abcdef") {
usart.tx(c);
}
usart.flush();
ev.post(Events::SYSTICK);
ev.drain();
CHECK(READ_BIT(DMA1_Stream3->CR, DMA_SxCR_EN) != 0);
}
}
#endif
| 28.747967 | 76 | 0.692496 | ian-ross |
ed2119ecde8ec8c9bf3d4dccf72f6ccd1df69b85 | 2,736 | cc | C++ | mojo/examples/apptest/example_apptest.cc | Fusion-Rom/android_external_chromium_org | d8b126911c6ea9753e9f526bee5654419e1d0ebd | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2015-08-13T21:04:58.000Z | 2015-08-13T21:04:58.000Z | mojo/examples/apptest/example_apptest.cc | Fusion-Rom/android_external_chromium_org | d8b126911c6ea9753e9f526bee5654419e1d0ebd | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | mojo/examples/apptest/example_apptest.cc | Fusion-Rom/android_external_chromium_org | d8b126911c6ea9753e9f526bee5654419e1d0ebd | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2020-11-04T06:34:36.000Z | 2020-11-04T06:34:36.000Z | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "mojo/examples/apptest/example_client_application.h"
#include "mojo/examples/apptest/example_client_impl.h"
#include "mojo/examples/apptest/example_service.mojom.h"
#include "mojo/public/c/system/main.h"
#include "mojo/public/cpp/application/application_delegate.h"
#include "mojo/public/cpp/application/application_impl.h"
#include "mojo/public/cpp/bindings/callback.h"
#include "mojo/public/cpp/environment/environment.h"
#include "mojo/public/cpp/system/macros.h"
#include "mojo/public/cpp/utility/run_loop.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
// TODO(msw): Remove this once we can get ApplicationImpl from TLS.
mojo::ApplicationImpl* g_application_impl_hack = NULL;
} // namespace
namespace mojo {
namespace {
class ExampleServiceTest : public testing::Test {
public:
ExampleServiceTest() {
g_application_impl_hack->ConnectToService("mojo:mojo_example_service",
&example_service_);
example_service_.set_client(&example_client_);
}
virtual ~ExampleServiceTest() MOJO_OVERRIDE {}
protected:
ExampleServicePtr example_service_;
ExampleClientImpl example_client_;
private:
MOJO_DISALLOW_COPY_AND_ASSIGN(ExampleServiceTest);
};
TEST_F(ExampleServiceTest, Ping) {
EXPECT_EQ(0, example_client_.last_pong_value());
example_service_->Ping(1);
RunLoop::current()->Run();
EXPECT_EQ(1, example_client_.last_pong_value());
}
template <typename T>
struct SetAndQuit : public Callback<void()>::Runnable {
SetAndQuit(T* val, T result) : val_(val), result_(result) {}
virtual ~SetAndQuit() {}
virtual void Run() const MOJO_OVERRIDE{
*val_ = result_;
RunLoop::current()->Quit();
}
T* val_;
T result_;
};
TEST_F(ExampleServiceTest, RunCallback) {
bool was_run = false;
example_service_->RunCallback(SetAndQuit<bool>(&was_run, true));
RunLoop::current()->Run();
EXPECT_TRUE(was_run);
}
} // namespace
} // namespace mojo
MojoResult MojoMain(MojoHandle shell_handle) {
mojo::Environment env;
mojo::RunLoop loop;
// TODO(tim): Perhaps the delegate should be the thing that provides
// the ExampleServiceTest with the ApplicationImpl somehow.
mojo::ApplicationDelegate* delegate = new mojo::ExampleClientApplication();
mojo::ApplicationImpl app(delegate, shell_handle);
g_application_impl_hack = &app;
// TODO(msw): Get actual commandline arguments.
int argc = 0;
char** argv = NULL;
testing::InitGoogleTest(&argc, argv);
mojo_ignore_result(RUN_ALL_TESTS());
delete delegate;
return MOJO_RESULT_OK;
}
| 28.8 | 77 | 0.740497 | Fusion-Rom |
ed2361d4d9657c4cf13a717dbaa5fc190ed17e7b | 19,733 | cpp | C++ | ImageDetectionAccessPoint/CardAreaDetection.cpp | rWarder4/ImageDetectionAccessPoint | 43e4d1ece0f82e8b336fe99573432d3d26abdb69 | [
"MIT"
] | null | null | null | ImageDetectionAccessPoint/CardAreaDetection.cpp | rWarder4/ImageDetectionAccessPoint | 43e4d1ece0f82e8b336fe99573432d3d26abdb69 | [
"MIT"
] | null | null | null | ImageDetectionAccessPoint/CardAreaDetection.cpp | rWarder4/ImageDetectionAccessPoint | 43e4d1ece0f82e8b336fe99573432d3d26abdb69 | [
"MIT"
] | null | null | null | #include "CardAreaDetection.h"
#include <opencv2/videostab/ring_buffer.hpp>
// defines includes
#include <opencv2\imgcodecs\imgcodecs_c.h>
#include <opencv2\imgproc\types_c.h>
using namespace cv;
IDAP::CardAreaDetection::CardAreaDetection(int _id, int _playerID, int _sizeID, int _xPos, int _yPos, int _width, int _height, int imageWidth, int imageHeight, float mmInPixel, bool turn)
{
id = _id;
playerID = _playerID;
sizeID = _sizeID;
posX = _xPos;
posY = _yPos;
turned = turn;
// to over come the inaccuracy of calibration, the roi is 40 % bigger
const float bigger = 0.4;
const float deltaWidth = (_width / mmInPixel) * bigger;
const float deltaHeight = (_height / mmInPixel) * bigger;
const float newPosX = (posX * (imageWidth / 100.f)) - deltaWidth / 2.f;
const float newPosY = (posY * (imageHeight / 100.f)) - deltaHeight / 2.f;
if (!turned)
{
roi = cv::Rect(newPosX, newPosY, (_width / mmInPixel) + deltaWidth, (_height / mmInPixel) + deltaHeight);
const float ratio = static_cast<float>(roi.height) / static_cast<float>(roi.width);
sizeTM = cv::Size(CARD_MATCHING_WIDTH*(1.f + bigger), CARD_MATCHING_WIDTH*(1.f + bigger)*ratio);
}
else
{
roi = cv::Rect(newPosX, newPosY, (_height / mmInPixel) + deltaHeight, (_width / mmInPixel) + deltaWidth);
const float ratio = static_cast<float>(roi.width) / static_cast<float>(roi.height);
sizeTM = cv::Size(CARD_MATCHING_WIDTH*(1.f + bigger)*ratio, CARD_MATCHING_WIDTH*(1.f + bigger));
}
initState = true;
results = new TopThree();
}
IDAP::CardAreaDetection::~CardAreaDetection()
{
delete(results);
}
void IDAP::CardAreaDetection::isCardChanged(uint16_t& errorCode, cv::Mat currentFrame, std::vector<std::pair<int, cv::Mat>>& cardDataReference, std::vector<std::pair<int, cv::Mat>>& cardDataGradientReference, cv::Mat meanCardGrad, uint16_t& cardType) const
{
// cut roi from frame, settle up card in it, set the right direction and perform template matching
const cv::Mat area = currentFrame(roi);
// grayscale
cv::Mat gray;
cv::cvtColor(area, gray, cv::COLOR_RGB2GRAY);
// resize area
cv::Mat areaTM;
cv::resize(gray, areaTM, sizeTM);
// turn area if needed
if(turned)
{
cv::rotate(areaTM, areaTM, ROTATE_90_COUNTERCLOCKWISE);
}
// create gradient version
const int scale = 1;
const int delta = 0;
const int ddepth = CV_16S;
cv::Mat grad_x, grad_y;
cv::Mat abs_grad_x, abs_grad_y;
cv::Mat grad;
// Gradient X
Sobel(areaTM, grad_x, ddepth, 1, 0, 3, scale, delta, cv::BORDER_DEFAULT);
convertScaleAbs(grad_x, abs_grad_x);
// Gradient Y
Sobel(areaTM, grad_y, ddepth, 0, 1, 3, scale, delta, cv::BORDER_DEFAULT);
convertScaleAbs(grad_y, abs_grad_y);
// approximate total gradient calculation
cv::addWeighted(abs_grad_x, 0.5, abs_grad_y, 0.5, 0, grad);
cv::Mat img_display, result;
area.copyTo(img_display);
const int result_cols = areaTM.cols - meanCardGrad.cols + 1;
const int result_rows = areaTM.rows - meanCardGrad.rows + 1;
//cv::imshow("img", grad);
//cv::imshow("templ", meanCardGrad);
result.create(result_rows, result_cols, CV_32FC1);
cv::matchTemplate(grad, meanCardGrad, result, CV_TM_CCORR_NORMED);
double minVal; double maxVal;
cv::Point minLoc;
cv::Point maxLoc;
minMaxLoc(result, &minVal, &maxVal, &minLoc, &maxLoc, cv::Mat());
const float meanValue = cv::mean(grad)[0];
if(meanValue >= MIN_MEAN_VALUE && maxVal >= TEMPLATE_MATCH_SCORE_MIN)
{
// perform SURF on imput image
// Detect and describe interest points using SURF Detector and Descriptor.
const int minHessian = 500; // min Hessian was experimentaly set, to obtain at least 8 matches on correct card class
Ptr<cv::xfeatures2d::SURF> detector = cv::xfeatures2d::SURF::create();
detector->setHessianThreshold(minHessian);
std::vector<KeyPoint> interestPointsArea;
Mat interestPointsAreaDesc;
detector->detectAndCompute(area, Mat(), interestPointsArea, interestPointsAreaDesc);
// classify using SURF and FLANN
results->SetMin(true);
for (std::vector<std::pair<int, cv::Mat>>::iterator it = cardDataReference.begin(); it != cardDataReference.end(); ++it)
{
// ----------------------------------- FLANN -------------------------------------
const uint16_t templCardType = static_cast<uint16_t>(it->first);
std::vector<KeyPoint> interestPointTempl;
Mat interestPointTemplDesc;
detector->detectAndCompute(it->second, Mat(), interestPointTempl, interestPointTemplDesc);
// Matching descriptor vectors using FLANN matcher - searching for nearest neighbors
FlannBasedMatcher matcher;
std::vector< DMatch > matches;
matcher.match(interestPointsAreaDesc, interestPointTemplDesc, matches);
double maxDist = 0; double minDist = 100;
//-- Quick calculation of max and min distances between keypoints
for (int i = 0; i < interestPointsAreaDesc.rows; i++)
{
const double dist = matches[i].distance;
if (dist < minDist) minDist = dist;
if (dist > maxDist) maxDist = dist;
}
std::map<float, int> goodMatchesDistance;
// filter only good matches - the ones which are at worst two times minimal distance
std::vector< DMatch > good_matches;
for (int i = 0; i < interestPointsAreaDesc.rows; i++)
{
if (matches[i].distance <= max(2 * minDist, 0.02))
{
good_matches.push_back(matches[i]);
goodMatchesDistance.insert(std::make_pair(matches[i].distance, i));
}
}
// if at least 8 good matches were found, compare the sum of distance of these good matches with the previously classes
// if it is better, put this class to TopThree result
// the TopThree classes are then sorted by the best match -> this was experimentaly tested and lead to better result than using all 8 best matches
if (goodMatchesDistance.size() >= 8)
{
float bestEightSum = 0.f;
int count = 0;
for (std::map<float, int>::iterator it = goodMatchesDistance.begin(); it != goodMatchesDistance.end(); ++it)
{
if (++count > 8)
break;
bestEightSum += it->first;
}
if (results->isBetter(bestEightSum))
{
results->TryAddNew(templCardType, bestEightSum);
}
}
}
// return the class the card fit the best
cardType = results->GetFirst();
results->Init();
}
else
{
// return no card, if no card is detected
cardType = IDAP::BangCardTypes::NONE;
}
}
void IDAP::CardAreaDetection::CardDetectionTester(std::vector<std::pair<int, cv::Mat>> cardDataReference)
{
std::map<int, int> classifications;
for(int i = 1; i < 32; ++i)
{
classifications.insert(std::make_pair(i, 0));
}
const bool templateMethod = false;
const std::string path = "CardDetectionData/BANG_A";
const auto match_method = CV_TM_CCORR_NORMED;
if (templateMethod)
results->SetMin(false);
else
results->SetMin(true);
// variable settings for gradient
const int scale = 1;
const int delta = 0;
const int ddepth = CV_16S;
// list all files in given folder and load them to memory and provide them to card area detection for template matching
for (auto &file : std::experimental::filesystem::directory_iterator(path))
{
cv::Mat img = cv::imread(file.path().string().c_str(), CV_LOAD_IMAGE_COLOR);
std::cout << file.path().string().c_str() << std::endl;
if (file.path().string().find("Bang_06.png") == std::string::npos)
continue;
// variables
cv::Mat rotImg, templ, imgGray, templGray, imgGrayDenoise;
cv::Mat gradTempl, gradImage;
cv::Mat imgGradFinal;
// perform classification
if(templateMethod)
{
//----------------------------- TEMPLATE MATCHING -------------------------------
// hought transform to turn right -------------------------------------------------
cv::Mat edges, gray, dil, ero, dst, cdst;
cv::cvtColor(img, gray, CV_BGR2GRAY);
cv::Canny(gray, edges, 85, 255);
cv::cvtColor(edges, cdst, COLOR_GRAY2BGR);
cv::Mat cdstP = cdst.clone();
std::vector<Vec2f> lines; // will hold the results of the detection
// Probabilistic Line Transform
std::vector<Vec4i> linesP; // will hold the results of the detection
HoughLinesP(edges, linesP, 1, CV_PI / 180, 50, 50, 10); // runs the actual detection
// Draw the lines
float angleFin = 0.f;
float linesUsed = 0;
for (size_t i = 0; i < linesP.size(); i++)
{
Vec4i l = linesP[i];
line(cdstP, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0, 0, 255), 3, LINE_AA);
Point p1, p2;
p1 = Point(l[0], l[1]);
p2 = Point(l[2], l[3]);
// calculate angle in radian, to degrees: angle * 180 / PI
float angle = atan2(p1.y - p2.y, p1.x - p2.x) * 180 / CV_PI;
if (angle > 0)
angle -= 90;
else
angle += 90;
// limit the lines which will be used, to limit errors
if ((angle < MAX_LINE_ANGLE_FOR_HOUGH && angle > 0) ||
(angle > -MAX_LINE_ANGLE_FOR_HOUGH && angle < 0))
{
angleFin += angle;
++linesUsed;
}
}
if(linesUsed > 0)
angleFin /= linesUsed;
// rotate img
const cv::Mat rot = getRotationMatrix2D(Point2f(img.cols / 2, img.rows / 2), angleFin, 1);
cv::warpAffine(img, rotImg, rot, Size(img.cols, img.rows));
cv::cvtColor(rotImg, imgGray, CV_BGR2GRAY);
// gradient of input image
cv::Mat imgGradX, imgGradY;
cv::Mat absGradX, absGradY;
/// Gradient X
Sobel(imgGray, imgGradX, ddepth, 1, 0, 3, scale, delta, cv::BORDER_DEFAULT);
convertScaleAbs(imgGradX, absGradX);
/// Gradient Y
//Scharr( src_gray, grad_y, ddepth, 0, 1, scale, delta, BORDER_DEFAULT );
Sobel(imgGray, imgGradY, ddepth, 0, 1, 3, scale, delta, cv::BORDER_DEFAULT);
convertScaleAbs(imgGradY, absGradY);
// combine gradient
cv::addWeighted(absGradX, 0.5, absGradY, 0.5, 0, imgGradFinal);
}
for (std::vector<std::pair<int, cv::Mat>>::iterator it = cardDataReference.begin(); it != cardDataReference.end(); ++it)
{
uint16_t templCardType = static_cast<uint16_t>(it->first);
cv::Mat rawtempl = it->second;
cv::Mat mask;
// ----------------------------------- FLANN -------------------------------------
if (!templateMethod)
{
cv::Mat img_1, img_2;
img.copyTo(img_1);
rawtempl.copyTo(img_2);
const int minHessian = 500;
Ptr<cv::xfeatures2d::SURF> detector = cv::xfeatures2d::SURF::create();
detector->setHessianThreshold(minHessian);
std::vector<KeyPoint> keypoints_1, keypoints_2;
Mat descriptors_1, descriptors_2;
detector->detectAndCompute(img_1, Mat(), keypoints_1, descriptors_1);
detector->detectAndCompute(img_2, Mat(), keypoints_2, descriptors_2);
FlannBasedMatcher matcher;
std::vector< DMatch > matches;
matcher.match(descriptors_1, descriptors_2, matches);
double max_dist = 0; double min_dist = 100;
for (int i = 0; i < descriptors_1.rows; i++)
{
const double dist = matches[i].distance;
if (dist < min_dist) min_dist = dist;
if (dist > max_dist) max_dist = dist;
}
//printf("-- Max dist : %f \n", max_dist);
//printf("-- Min dist : %f \n", min_dist);
std::map<float, int> goodMatchesDistance;
std::vector< DMatch > good_matches;
for (int i = 0; i < descriptors_1.rows; i++)
{
if (matches[i].distance <= max(2 * min_dist, 0.02))
{
good_matches.push_back(matches[i]);
goodMatchesDistance.insert(std::make_pair(matches[i].distance, i));
}
}
double evalNew = static_cast<double>(good_matches.size()) / static_cast<double>(matches.size());
//printf("EVAL: %d | %d : %f\n", static_cast<int>(good_matches.size()), static_cast<int>(matches.size()), eval);
if (goodMatchesDistance.size() >= 8)
{
float bestFive = 0.f;
int count = 0;
for (std::map<float, int>::iterator it2 = goodMatchesDistance.begin(); it2 != goodMatchesDistance.end(); ++it2)
{
if (++count > 8)
break;
bestFive += it2->first;
}
//std::cout << "Chesking add: " << templCardType << ", " << bestFive << std::endl;
if (results->isBetter(bestFive))
{
results->TryAddNew(templCardType, bestFive);
}
}
//-- Draw only "good" matches
Mat img_matches;
drawMatches(img_1, keypoints_1, img_2, keypoints_2,
good_matches, img_matches, Scalar::all(-1), Scalar::all(-1),
std::vector<char>(), DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS);
//-- Show detected matches
//imshow("Good Matches", img_matches);
//imwrite("goodMatches.png", img_matches);
for (int i = 0; i < (int)good_matches.size(); i++)
{
//printf("-- Good Match [%d] Keypoint 1: %d -- Keypoint 2: %d \n", i, good_matches[i].queryIdx, good_matches[i].trainIdx);
}
//cv::waitKey(0);
}
else
{
cv::cvtColor(rawtempl, templGray, CV_BGR2GRAY);
// gradient of input image
cv::Mat templGradX, templGradY;
cv::Mat absGradXTempl, absGradYTempl;
cv::Mat templGradFinal;
/// Gradient X
Sobel(templGray, templGradX, ddepth, 1, 0, 3, scale, delta, cv::BORDER_DEFAULT);
convertScaleAbs(templGradX, absGradXTempl);
/// Gradient Y
//Scharr( src_gray, grad_y, ddepth, 0, 1, scale, delta, BORDER_DEFAULT );
Sobel(templGray, templGradY, ddepth, 0, 1, 3, scale, delta, cv::BORDER_DEFAULT);
convertScaleAbs(templGradY, absGradYTempl);
// combine gradient
cv::addWeighted(absGradXTempl, 0.5, absGradYTempl, 0.5, 0, templGradFinal);
cv::Point matchLoc;
/*for (float i = 1; i > 0.5; i -= 0.1)
{
// scale template
cv::Size newSize(rawtempl.cols*i, rawtempl.rows*i);
cv::resize(templGradFinal, templGradFinal, newSize);*/
cv::Mat img_display, result;
gradImage.copyTo(img_display);
int result_cols = imgGradFinal.cols - templGradFinal.cols + 1;
int result_rows = imgGradFinal.rows - templGradFinal.rows + 1;
result.create(result_rows, result_cols, CV_32FC1);
matchTemplate(imgGradFinal, templGradFinal, result, match_method);
double minVal; double maxVal; cv::Point minLoc; cv::Point maxLoc;
cv::minMaxLoc(result, &minVal, &maxVal, &minLoc, &maxLoc);
matchLoc = maxLoc;
results->TryAddNew(templCardType, maxVal);
cv::Mat locationMatch;
imgGradFinal.copyTo(locationMatch);
const cv::Rect rect(matchLoc.x, matchLoc.y, templGradFinal.size().width, templGradFinal.size().height);
cv::rectangle(locationMatch, rect, Scalar(255,0,0));
//}
}
}
//std::cout << "result for " << file.path().string() << ": " << results->GetFirst() << ", " << results->GetSecond() << ", " << results->GetThird() << std::endl;
//printf("eval: %f, %f, %f\n", results->firstEval, results->secondEval, results->thirdEval);
classifications.at(results->GetFirst()) += 1;
results->Init();
//cv::waitKey(0);
}
for(int i = 1; i < 32; ++i)
{
if(classifications.at(i) > 0)
std::cout << "template ID:" << i << " -> " << classifications.at(i) << std::endl;
}
//cv::waitKey(0);
}
void IDAP::TopThree::Init()
{
first = 0;
second = 0;
third = 0;
bestPoints = std::numeric_limits<double>::max();
if (min)
{
firstEval = std::numeric_limits<double>::max();
secondEval = std::numeric_limits<double>::max();
thirdEval = std::numeric_limits<double>::max();
}
else
{
firstEval = std::numeric_limits<double>::min();
secondEval = std::numeric_limits<double>::min();
thirdEval = std::numeric_limits<double>::min();
}
}
void IDAP::TopThree::TryAddNew(uint16_t cardType, float eval)
{
if (min)
{
if (eval < thirdEval)
{
// new top three
third = cardType;
thirdEval = eval;
SortTopThree();
}
}
else
{
if (eval > thirdEval)
{
// new top three
third = cardType;
thirdEval = eval;
SortTopThree();
}
}
}
bool IDAP::TopThree::isBetter(float val)
{
double curVal = static_cast<double>(val);
if (curVal < bestPoints)
{
bestPoints = curVal;
return true;
}
return false;
}
void IDAP::TopThree::SortTopThree()
{
if (min)
{
if (thirdEval < secondEval)
{
std::swap(third, second);
std::swap(thirdEval, secondEval);
}
if(secondEval < firstEval)
{
std::swap(first, second);
std::swap(firstEval, secondEval);
}
}
else
{
if (thirdEval > secondEval)
{
std::swap(third, second);
std::swap(thirdEval, secondEval);
}
if (secondEval > firstEval)
{
std::swap(first, second);
std::swap(firstEval, secondEval);
}
}
}
| 39.075248 | 257 | 0.539654 | rWarder4 |
ed2674d20a72a0a493fa68eb592abcf456cb9c53 | 28,956 | cpp | C++ | Source/CLI/Global.cpp | JeromeMartinez/RAWcooked | 41379cc9ebb9511eb7445dce7a4a9064125a92f0 | [
"BSD-2-Clause"
] | null | null | null | Source/CLI/Global.cpp | JeromeMartinez/RAWcooked | 41379cc9ebb9511eb7445dce7a4a9064125a92f0 | [
"BSD-2-Clause"
] | null | null | null | Source/CLI/Global.cpp | JeromeMartinez/RAWcooked | 41379cc9ebb9511eb7445dce7a4a9064125a92f0 | [
"BSD-2-Clause"
] | null | null | null | /* Copyright (c) MediaArea.net SARL & AV Preservation by reto.ch.
*
* Use of this source code is governed by a BSD-style license that can
* be found in the License.html file in the root of the source tree.
*/
//---------------------------------------------------------------------------
#include "CLI/Global.h"
#include "CLI/Help.h"
#include <iostream>
#include <cstring>
#include <iomanip>
#include <thread>
#if defined(_WIN32) || defined(_WINDOWS)
#include <direct.h>
#define getcwd _getcwd
#else
#include <unistd.h>
#endif
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
// Glue
void global_ProgressIndicator_Show(global* G)
{
G->ProgressIndicator_Show();
}
//---------------------------------------------------------------------------
int global::SetOutputFileName(const char* FileName)
{
OutputFileName = FileName;
OutputFileName_IsProvided = true;
return 0;
}
//---------------------------------------------------------------------------
int global::SetBinName(const char* FileName)
{
BinName = FileName;
return 0;
}
//---------------------------------------------------------------------------
int global::SetLicenseKey(const char* Key, bool StoreIt)
{
LicenseKey = Key;
StoreLicenseKey = StoreIt;
return 0;
}
//---------------------------------------------------------------------------
int global::SetSubLicenseId(uint64_t Id)
{
if (!Id || Id >= 127)
{
cerr << "Error: sub-licensee ID must be between 1 and 126.\n";
return 1;
}
SubLicenseId = Id;
return 0;
}
//---------------------------------------------------------------------------
int global::SetSubLicenseDur(uint64_t Dur)
{
if (Dur > 12)
{
cerr << "Error: sub-licensee duration must be between 0 and 12.\n";
return 1;
}
SubLicenseDur = Dur;
return 0;
}
//---------------------------------------------------------------------------
int global::SetDisplayCommand()
{
DisplayCommand = true;
return 0;
}
//---------------------------------------------------------------------------
int global::SetAcceptFiles()
{
AcceptFiles = true;
return 0;
}
//---------------------------------------------------------------------------
int global::SetCheck(bool Value)
{
Actions.set(Action_Check, Value);
Actions.set(Action_CheckOptionIsSet);
if (Value)
return SetDecode(false);
return 0;
}
//---------------------------------------------------------------------------
int global::SetQuickCheck()
{
Actions.set(Action_Check, false);
Actions.set(Action_CheckOptionIsSet, false);
return 0;
}
//---------------------------------------------------------------------------
int global::SetCheck(const char* Value, int& i)
{
if (Value && (strcmp(Value, "0") == 0 || strcmp(Value, "partial") == 0))
{
SetCheckPadding(false);
++i; // Next argument is used
cerr << "Warning: \" --check " << Value << "\" is deprecated, use \" --no-check-padding\" instead.\n" << endl;
return 0;
}
if (Value && (strcmp(Value, "1") == 0 || strcmp(Value, "full") == 0))
{
SetCheckPadding(true);
++i; // Next argument is used
cerr << "Warning: \" --check " << Value << "\" is deprecated, use \" --check-padding\" instead.\n" << endl;
return 0;
}
SetCheck(true);
return 0;
}
//---------------------------------------------------------------------------
int global::SetCheckPadding(bool Value)
{
Actions.set(Action_CheckPadding, Value);
Actions.set(Action_CheckPaddingOptionIsSet);
return 0;
}
//---------------------------------------------------------------------------
int global::SetQuickCheckPadding()
{
Actions.set(Action_CheckPadding, false);
Actions.set(Action_CheckPaddingOptionIsSet, false);
return 0;
}
//---------------------------------------------------------------------------
int global::SetAcceptGaps(bool Value)
{
Actions.set(Action_AcceptGaps, Value);
return 0;
}
//---------------------------------------------------------------------------
int global::SetCoherency(bool Value)
{
Actions.set(Action_Coherency, Value);
return 0;
}
//---------------------------------------------------------------------------
int global::SetConch(bool Value)
{
Actions.set(Action_Conch, Value);
if (Value)
{
SetDecode(false);
SetEncode(false);
}
return 0;
}
//---------------------------------------------------------------------------
int global::SetDecode(bool Value)
{
Actions.set(Action_Decode, Value);
return 0;
}
//---------------------------------------------------------------------------
int global::SetEncode(bool Value)
{
Actions.set(Action_Encode, Value);
return 0;
}
//---------------------------------------------------------------------------
int global::SetInfo(bool Value)
{
Actions.set(Action_Info, Value);
if (Value)
{
SetDecode(false);
SetEncode(false);
}
return 0;
}
//---------------------------------------------------------------------------
int global::SetFrameMd5(bool Value)
{
Actions.set(Action_FrameMd5, Value);
return 0;
}
//---------------------------------------------------------------------------
int global::SetFrameMd5FileName(const char* FileName)
{
FrameMd5FileName = FileName;
return 0;
}
//---------------------------------------------------------------------------
int global::SetHash(bool Value)
{
Actions.set(Action_Hash, Value);
return 0;
}
//---------------------------------------------------------------------------
int global::SetAll(bool Value)
{
if (int ReturnValue = SetInfo(Value))
return ReturnValue;
if (int ReturnValue = SetConch(Value))
return ReturnValue;
if (int ReturnValue = (Value?SetCheck(true):SetQuickCheck())) // Never implicitely set no check
return ReturnValue;
if (int ReturnValue = (Value && SetCheckPadding(Value))) // Never implicitely set no check padding
return ReturnValue;
if (int ReturnValue = SetAcceptGaps(Value))
return ReturnValue;
if (int ReturnValue = SetCoherency(Value))
return ReturnValue;
if (int ReturnValue = SetDecode(Value))
return ReturnValue;
if (int ReturnValue = SetEncode(Value))
return ReturnValue;
if (int ReturnValue = SetHash(Value))
return ReturnValue;
return 0;
}
//---------------------------------------------------------------------------
int Error_NotTested(const char* Option1, const char* Option2 = NULL)
{
cerr << "Error: option " << Option1;
if (Option2)
cerr << ' ' << Option2;
cerr << " not yet tested.\nPlease contact info@mediaarea.net if you want support of such option." << endl;
return 1;
}
//---------------------------------------------------------------------------
int Error_Missing(const char* Option1)
{
cerr << "Error: missing argument for option '" << Option1 << "'." << endl;
return 1;
}
//---------------------------------------------------------------------------
int global::SetOption(const char* argv[], int& i, int argc)
{
if (strcmp(argv[i], "-c:a") == 0)
{
if (++i >= argc)
return Error_NotTested(argv[i - 1]);
if (strcmp(argv[i], "copy") == 0)
{
OutputOptions["c:a"] = argv[i];
License.Encoder(encoder::PCM);
return 0;
}
if (strcmp(argv[i], "flac") == 0)
{
OutputOptions["c:a"] = argv[i];
License.Encoder(encoder::FLAC);
return 0;
}
return Error_NotTested(argv[i - 1], argv[i]);
}
if (!strcmp(argv[i], "-c:v"))
{
if (++i >= argc)
return Error_NotTested(argv[i - 1]);
if (!strcmp(argv[i], "ffv1"))
{
OutputOptions["c:v"] = argv[i];
License.Encoder(encoder::FFV1);
return 0;
}
return Error_NotTested(argv[i - 1], argv[i]);
}
if (!strcmp(argv[i], "-coder"))
{
if (++i >= argc)
return Error_NotTested(argv[i - 1]);
if (!strcmp(argv[i], "0")
|| !strcmp(argv[i], "1")
|| !strcmp(argv[i], "2"))
{
OutputOptions["coder"] = argv[i];
License.Feature(feature::EncodingOptions);
return 0;
}
return Error_NotTested(argv[i - 1], argv[i]);
}
if (!strcmp(argv[i], "-context"))
{
if (++i >= argc)
return Error_NotTested(argv[i - 1]);
if (!strcmp(argv[i], "0")
|| !strcmp(argv[i], "1"))
{
OutputOptions["context"] = argv[i];
License.Feature(feature::EncodingOptions);
return 0;
}
return Error_NotTested(argv[i - 1], argv[i]);
}
if (!strcmp(argv[i], "-f"))
{
if (++i >= argc)
return Error_NotTested(argv[i - 1]);
if (!strcmp(argv[i], "matroska"))
{
OutputOptions["f"] = argv[i];
return 0;
}
return 0;
}
if (!strcmp(argv[i], "-framerate"))
{
if (++i >= argc)
return Error_NotTested(argv[i - 1]);
if (atof(argv[i]))
{
VideoInputOptions["framerate"] = argv[i];
License.Feature(feature::InputOptions);
return 0;
}
return 0;
}
if (!strcmp(argv[i], "-g"))
{
if (++i >= argc)
return Error_NotTested(argv[i - 1]);
if (atoi(argv[i]))
{
OutputOptions["g"] = argv[i];
License.Feature(feature::EncodingOptions);
return 0;
}
cerr << "Invalid \"" << argv[i - 1] << " " << argv[i] << "\" value, it must be a number\n";
return 1;
}
if (!strcmp(argv[i], "-level"))
{
if (++i >= argc)
return Error_NotTested(argv[i - 1]);
if (!strcmp(argv[i], "0")
|| !strcmp(argv[i], "1")
|| !strcmp(argv[i], "3"))
{
OutputOptions["level"] = argv[i];
License.Feature(feature::EncodingOptions);
return 0;
}
return Error_NotTested(argv[i - 1], argv[i]);
}
if (!strcmp(argv[i], "-loglevel"))
{
if (++i >= argc)
return Error_NotTested(argv[i - 1]);
if (!strcmp(argv[i], "error")
|| !strcmp(argv[i], "warning"))
{
OutputOptions["loglevel"] = argv[i];
License.Feature(feature::GeneralOptions);
return 0;
}
return Error_NotTested(argv[i - 1], argv[i]);
}
if (strcmp(argv[i], "-n") == 0)
{
OutputOptions["n"] = string();
OutputOptions.erase("y");
Mode = AlwaysNo; // Also RAWcooked itself
License.Feature(feature::GeneralOptions);
return 0;
}
if (!strcmp(argv[i], "-slicecrc"))
{
if (++i >= argc)
return Error_NotTested(argv[i - 1]);
if (!strcmp(argv[i], "0")
|| !strcmp(argv[i], "1"))
{
OutputOptions["slicecrc"] = argv[i];
License.Feature(feature::EncodingOptions);
return 0;
}
return Error_NotTested(argv[i - 1], argv[i]);
}
if (!strcmp(argv[i], "-slices"))
{
if (++i >= argc)
return Error_NotTested(argv[i - 1]);
int SliceCount = atoi(argv[i]);
if (SliceCount) //TODO: not all slice counts are accepted by FFmpeg, we should filter
{
OutputOptions["slices"] = argv[i];
License.Feature(feature::EncodingOptions);
return 0;
}
return Error_NotTested(argv[i - 1], argv[i]);
}
if (!strcmp(argv[i], "-threads"))
{
if (++i >= argc)
return Error_NotTested(argv[i - 1]);
OutputOptions["threads"] = argv[i];
License.Feature(feature::GeneralOptions);
return 0;
}
if (strcmp(argv[i], "-y") == 0)
{
OutputOptions["y"] = string();
OutputOptions.erase("n");
Mode = AlwaysYes; // Also RAWcooked itself
License.Feature(feature::GeneralOptions);
return 0;
}
return Error_NotTested(argv[i]);
}
//---------------------------------------------------------------------------
int global::ManageCommandLine(const char* argv[], int argc)
{
if (argc < 2)
return Usage(argv[0]);
AttachmentMaxSize = (size_t)-1;
IgnoreLicenseKey = !License.IsSupported_License();
SubLicenseId = 0;
SubLicenseDur = 1;
ShowLicenseKey = false;
StoreLicenseKey = false;
DisplayCommand = false;
AcceptFiles = false;
OutputFileName_IsProvided = false;
Quiet = false;
Actions.set(Action_Encode);
Actions.set(Action_Decode);
Actions.set(Action_Coherency);
Hashes = hashes(&Errors);
ProgressIndicator_Thread = NULL;
for (int i = 1; i < argc; i++)
{
if ((argv[i][0] == '.' && argv[i][1] == '\0')
|| (argv[i][0] == '.' && (argv[i][1] == '/' || argv[i][1] == '\\') && argv[i][2] == '\0'))
{
//translate to "../xxx" in order to get the top level directory name
char buff[FILENAME_MAX];
if (getcwd(buff, FILENAME_MAX))
{
string Arg = buff;
size_t Path_Pos = Arg.find_last_of("/\\");
Arg = ".." + Arg.substr(Path_Pos);
Inputs.push_back(Arg);
}
else
{
cerr << "Error: " << argv[i] << " can not be transformed to a directory name." << endl;
return 1;
}
}
else if (strcmp(argv[i], "--all") == 0)
{
int Value = SetAll(true);
if (Value)
return Value;
}
else if ((strcmp(argv[i], "--attachment-max-size") == 0 || strcmp(argv[i], "-s") == 0))
{
if (i + 1 == argc)
return Error_Missing(argv[i]);
AttachmentMaxSize = atoi(argv[++i]);
License.Feature(feature::GeneralOptions);
}
else if ((strcmp(argv[i], "--bin-name") == 0 || strcmp(argv[i], "-b") == 0))
{
if (i + 1 == argc)
return Error_Missing(argv[i]);
int Value = SetBinName(argv[++i]);
if (Value)
return Value;
}
else if (strcmp(argv[i], "--check") == 0)
{
if (i + 1 < argc)
{
// Deprecated version handling
int Value = SetCheck(argv[i + 1], i);
if (Value)
return Value;
}
else
{
int Value = SetCheck(true);
License.Feature(feature::GeneralOptions);
if (Value)
return Value;
}
}
else if (strcmp(argv[i], "--check-padding") == 0)
{
int Value = SetCheckPadding(true);
if (Value)
return Value;
}
else if (strcmp(argv[i], "--accept-gaps") == 0)
{
int Value = SetAcceptGaps(true);
if (Value)
return Value;
}
else if (strcmp(argv[i], "--coherency") == 0)
{
int Value = SetCoherency(true);
if (Value)
return Value;
}
else if (strcmp(argv[i], "--conch") == 0)
{
int Value = SetConch(true);
if (Value)
return Value;
}
else if ((strcmp(argv[i], "--display-command") == 0 || strcmp(argv[i], "-d") == 0))
{
int Value = SetDisplayCommand();
if (Value)
return Value;
License.Feature(feature::GeneralOptions);
}
else if (strcmp(argv[i], "--decode") == 0)
{
int Value = SetDecode(true);
if (Value)
return Value;
}
else if (strcmp(argv[i], "--encode") == 0)
{
int Value = SetEncode(true);
if (Value)
return Value;
}
else if (strcmp(argv[i], "--framemd5") == 0)
{
int Value = SetFrameMd5(true);
if (Value)
return Value;
}
else if (strcmp(argv[i], "--framemd5-name") == 0)
{
if (i + 1 == argc)
return Error_Missing(argv[i]);
int Value = SetFrameMd5FileName(argv[++i]);
if (Value)
return Value;
}
else if (strcmp(argv[i], "--hash") == 0)
{
int Value = SetHash(true);
if (Value)
return Value;
}
else if (strcmp(argv[i], "--file") == 0)
{
int Value = SetAcceptFiles();
if (Value)
return Value;
}
else if (strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-h") == 0)
{
int Value = Help(argv[0]);
if (Value)
return Value;
}
else if (strcmp(argv[i], "--info") == 0)
{
int Value = SetInfo(true);
if (Value)
return Value;
}
else if ((strcmp(argv[i], "--license") == 0 || strcmp(argv[i], "--licence") == 0))
{
if (i + 1 == argc)
return Error_Missing(argv[i]);
int Value = SetLicenseKey(argv[++i], false);
if (Value)
return Value;
}
else if (strcmp(argv[i], "--no-check") == 0)
{
int Value = SetCheck(false);
if (Value)
return Value;
}
else if (strcmp(argv[i], "--no-check-padding") == 0)
{
int Value = SetCheckPadding(false);
if (Value)
return Value;
}
else if (strcmp(argv[i], "--no-coherency") == 0)
{
int Value = SetCoherency(false);
if (Value)
return Value;
}
else if (strcmp(argv[i], "--no-conch") == 0)
{
int Value = SetConch(false);
if (Value)
return Value;
}
else if (strcmp(argv[i], "--no-decode") == 0)
{
int Value = SetDecode(false);
if (Value)
return Value;
}
else if (strcmp(argv[i], "--no-encode") == 0)
{
int Value = SetEncode(false);
if (Value)
return Value;
}
else if (strcmp(argv[i], "--no-hash") == 0)
{
int Value = SetHash(false);
if (Value)
return Value;
}
else if (strcmp(argv[i], "--no-info") == 0)
{
int Value = SetInfo(false);
if (Value)
return Value;
}
else if (strcmp(argv[i], "--none") == 0)
{
int Value = SetAll(false);
if (Value)
return Value;
}
else if (strcmp(argv[i], "--quick-check") == 0)
{
int Value = SetQuickCheck();
if (Value)
return Value;
}
else if (strcmp(argv[i], "--quick-check-padding") == 0)
{
int Value = SetQuickCheckPadding();
if (Value)
return Value;
}
else if (strcmp(argv[i], "--version") == 0)
{
int Value = Version();
if (Value)
return Value;
}
else if ((strcmp(argv[i], "--output-name") == 0 || strcmp(argv[i], "-o") == 0))
{
if (i + 1 == argc)
return Error_Missing(argv[i]);
int Value = SetOutputFileName(argv[++i]);
if (Value)
return Value;
}
else if (strcmp(argv[i], "--quiet") == 0)
{
Quiet = true;
License.Feature(feature::GeneralOptions);
}
else if ((strcmp(argv[i], "--rawcooked-file-name") == 0 || strcmp(argv[i], "-r") == 0))
{
if (i + 1 == argc)
return Error_Missing(argv[i]);
rawcooked_reversibility_FileName = argv[++i];
}
else if (strcmp(argv[i], "--show-license") == 0 || strcmp(argv[i], "--show-licence") == 0)
{
ShowLicenseKey = true;
}
else if (strcmp(argv[i], "--sublicense") == 0 || strcmp(argv[i], "--sublicence") == 0)
{
if (i + 1 == argc)
return Error_Missing(argv[i]);
License.Feature(feature::SubLicense);
if (auto Value = SetSubLicenseId(atoi(argv[++i])))
return Value;
}
else if (strcmp(argv[i], "--sublicense-dur") == 0 || strcmp(argv[i], "--sublicence-dur") == 0)
{
if (i + 1 == argc)
return Error_Missing(argv[i]);
License.Feature(feature::SubLicense);
if (auto Value = SetSubLicenseDur(atoi(argv[++i])))
return Value;
}
else if ((strcmp(argv[i], "--store-license") == 0 || strcmp(argv[i], "--store-licence") == 0))
{
if (i + 1 == argc)
return Error_Missing(argv[i]);
int Value = SetLicenseKey(argv[++i], true);
if (Value)
return Value;
}
else if (argv[i][0] == '-' && argv[i][1] != '\0')
{
int Value = SetOption(argv, i, argc);
if (Value)
return Value;
}
else
Inputs.push_back(argv[i]);
}
// License
if (License.LoadLicense(LicenseKey, StoreLicenseKey))
return true;
if (!License.IsSupported())
{
cerr << "\nOne or more requested features are not supported with the current license key.\n";
cerr << "****** Please contact info@mediaarea.net for a quote or a temporary key." << endl;
if (!IgnoreLicenseKey)
return 1;
cerr << " Ignoring the license for the moment.\n" << endl;
}
if (License.ShowLicense(ShowLicenseKey, SubLicenseId, SubLicenseDur))
return 1;
if (Inputs.empty() && (ShowLicenseKey || SubLicenseId))
return 0;
return 0;
}
//---------------------------------------------------------------------------
int global::SetDefaults()
{
// Container format
if (OutputOptions.find("f") == OutputOptions.end())
OutputOptions["f"] = "matroska"; // Container format is Matroska
// Video format
if (OutputOptions.find("c:v") == OutputOptions.end())
OutputOptions["c:v"] = "ffv1"; // Video format is FFV1
// Audio format
if (OutputOptions.find("c:a") == OutputOptions.end())
OutputOptions["c:a"] = "flac"; // Audio format is FLAC
// FFV1 specific
if (OutputOptions["c:v"] == "ffv1")
{
if (OutputOptions.find("coder") == OutputOptions.end())
OutputOptions["coder"] = "1"; // Range Coder
if (OutputOptions.find("context") == OutputOptions.end())
OutputOptions["context"] = "1"; // Small context
if (OutputOptions.find("g") == OutputOptions.end())
OutputOptions["g"] = "1"; // Intra
if (OutputOptions.find("level") == OutputOptions.end())
OutputOptions["level"] = "3"; // FFV1 v3
if (OutputOptions.find("slicecrc") == OutputOptions.end())
OutputOptions["slicecrc"] = "1"; // Slice CRC on
// Check incompatible options
if (OutputOptions["level"] == "0" || OutputOptions["level"] == "1")
{
map<string, string>::iterator slices = OutputOptions.find("slices");
if (slices == OutputOptions.end() || slices->second != "1")
{
cerr << "\" -level " << OutputOptions["level"] << "\" does not permit slices, is it intended ? if so, add \" -slices 1\" to the command." << endl;
return 1;
}
}
}
return 0;
}
//---------------------------------------------------------------------------
void global::ProgressIndicator_Start(size_t Total)
{
if (ProgressIndicator_Thread)
return;
ProgressIndicator_Current = 0;
ProgressIndicator_Total = Total;
ProgressIndicator_Thread = new thread(global_ProgressIndicator_Show, this);
}
//---------------------------------------------------------------------------
void global::ProgressIndicator_Stop()
{
if (!ProgressIndicator_Thread)
return;
ProgressIndicator_Current = ProgressIndicator_Total;
ProgressIndicator_IsEnd.notify_one();
ProgressIndicator_Thread->join();
delete ProgressIndicator_Thread;
ProgressIndicator_Thread = NULL;
}
//---------------------------------------------------------------------------
// Progress indicator show
void global::ProgressIndicator_Show()
{
// Configure progress indicator precision
size_t ProgressIndicator_Value = (size_t)-1;
size_t ProgressIndicator_Frequency = 100;
streamsize Precision = 0;
cerr.setf(ios::fixed, ios::floatfield);
// Configure benches
using namespace chrono;
steady_clock::time_point Clock_Init = steady_clock::now();
steady_clock::time_point Clock_Previous = Clock_Init;
uint64_t FileCount_Previous = 0;
// Show progress indicator at a specific frequency
const chrono::seconds Frequency = chrono::seconds(1);
size_t StallDetection = 0;
mutex Mutex;
unique_lock<mutex> Lock(Mutex);
do
{
if (ProgressIndicator_IsPaused)
continue;
size_t ProgressIndicator_New = (size_t)(((float)ProgressIndicator_Current) * ProgressIndicator_Frequency / ProgressIndicator_Total);
if (ProgressIndicator_New == ProgressIndicator_Value)
{
StallDetection++;
if (StallDetection >= 4)
{
while (ProgressIndicator_New == ProgressIndicator_Value && ProgressIndicator_Frequency < 10000)
{
ProgressIndicator_Frequency *= 10;
ProgressIndicator_Value *= 10;
Precision++;
ProgressIndicator_New = (size_t)(((float)ProgressIndicator_Current) * ProgressIndicator_Frequency / ProgressIndicator_Total);
}
}
}
else
StallDetection = 0;
if (ProgressIndicator_New != ProgressIndicator_Value)
{
float FileRate = 0;
if (ProgressIndicator_Value != (size_t)-1)
{
steady_clock::time_point Clock_Current = steady_clock::now();
steady_clock::duration Duration = Clock_Current - Clock_Previous;
FileRate = (float)(ProgressIndicator_Current - FileCount_Previous) * 1000 / duration_cast<milliseconds>(Duration).count();
Clock_Previous = Clock_Current;
FileCount_Previous = ProgressIndicator_Current;
}
cerr << '\r';
cerr << "Analyzing files (" << setprecision(Precision) << ((float)ProgressIndicator_New) * 100 / ProgressIndicator_Frequency << "%)";
if (FileRate)
{
cerr << ", ";
cerr << setprecision(0) << FileRate;
cerr << " files/s";
}
cerr << " "; // Clean up in case there is less content outputed than the previous time
ProgressIndicator_Value = ProgressIndicator_New;
}
} while (ProgressIndicator_IsEnd.wait_for(Lock, Frequency) == cv_status::timeout && ProgressIndicator_Current != ProgressIndicator_Total);
// Show summary
cerr << '\r';
cerr << " \r"; // Clean up in case there is less content outputed than the previous time
}
| 32.461883 | 163 | 0.45355 | JeromeMartinez |
ed269c093362b25f78b5fabec7c061fa4b97f7b7 | 3,904 | cpp | C++ | src/perception/filters/object_filter.cpp | HSRobot/hiropV3 | 3f094035229708302aec976cfb252f7bcdb7cd3f | [
"BSD-3-Clause"
] | null | null | null | src/perception/filters/object_filter.cpp | HSRobot/hiropV3 | 3f094035229708302aec976cfb252f7bcdb7cd3f | [
"BSD-3-Clause"
] | null | null | null | src/perception/filters/object_filter.cpp | HSRobot/hiropV3 | 3f094035229708302aec976cfb252f7bcdb7cd3f | [
"BSD-3-Clause"
] | null | null | null | #include "object_filter.h"
#include <tf/transform_listener.h>
using namespace hirop_perception;
float ObjectFilter::minX = 0;
float ObjectFilter::maxX = 0;
float ObjectFilter::minZ = 0;
float ObjectFilter::maxZ = 0;
float ObjectFilter::minY = 0;
float ObjectFilter::maxY = 0;
ObjectFilter::ObjectFilter(){
_n = ros::NodeHandle();
}
ObjectFilter::~ObjectFilter(){
}
void ObjectFilter::declare_params(ecto::tendrils ¶ms){
params.declare<float>("hight", "object hight", 0.1);
params.declare<float>("width", "object width", 0.1);
params.declare<float>("length", "object length", 0.1);
params.declare<std::string>("frame_id", "The world frame id", "base_link");
}
void ObjectFilter::declare_io(const ecto::tendrils ¶ms, ecto::tendrils &in, ecto::tendrils &out){
in.declare<ecto::pcl::PointCloud>("input", "The colud to filter");
out.declare<ecto::pcl::PointCloud>("output", "The colud to out");
}
void ObjectFilter::configure(const ecto::tendrils ¶ms, const ecto::tendrils &inputs, const ecto::tendrils &outputs){
hight = params.get<float>("hight");
width = params.get<float>("width");
length = params.get<float>("length");
_worldFrameId = params.get<std::string>("frame_id");
_objectSub = _n.subscribe("/object_array", 1, &ObjectFilter::objectDetectionCallback, this);
}
int ObjectFilter::process(const ecto::tendrils &in, const ecto::tendrils &out){
_pointCloud = in.get<ecto::pcl::PointCloud>("input");
ecto::pcl::xyz_cloud_variant_t variant = _pointCloud.make_variant();
ecto::pcl::PointCloud outCloud;
FiltersDispatch dispatch(&outCloud);
boost::apply_visitor(dispatch, variant);
out.get<ecto::pcl::PointCloud>("output") = outCloud;
return ecto::OK;
}
void ObjectFilter::objectDetectionCallback(const hirop_msgs::ObjectArray::ConstPtr &msg){
geometry_msgs::PoseStamped _objectCamPose = msg->objects[0].pose;
/**
* @brief _worldPose save the world pose
*/
geometry_msgs::PoseStamped worldPose;
tf::TransformListener listener;
std::cout << "in objectDetectionCallback" << std::endl;
for(int i = 0; i < 5; i++){
try{
listener.waitForTransform(_worldFrameId, _objectCamPose.header.frame_id, ros::Time(0), ros::Duration(1.0));
listener.transformPose(_worldFrameId, _objectCamPose, worldPose);
break;
}catch (tf::TransformException &ex) {
/**
* @brief 获取变换关系失败,等待1秒后继续获取坐标变换
*/
ROS_ERROR("%s",ex.what());
ros::Duration(1.0).sleep();
continue;
}
}
minX = worldPose.pose.position.x - width/2;
minY = worldPose.pose.position.y - length/2;
minZ = worldPose.pose.position.z - hight/2;
maxX = worldPose.pose.position.x + width/2;
maxY = worldPose.pose.position.y + length/2;
maxZ = worldPose.pose.position.z + hight/2;
}
template<typename Point>
void ObjectFilter::FiltersDispatch::operator()(boost::shared_ptr<const pcl::PointCloud<Point> >& cloud) const{
typename pcl::PointCloud<Point>::Ptr outPointCloud(new pcl::PointCloud<Point>);
int size = cloud->points.size();
for(int i = 0; i < size; i++){
if(cloud->points[i].z > minZ && cloud->points[i].z < maxZ \
&& cloud->points[i].x > minX && cloud->points[i].x < maxX \
&& cloud->points[i].y > minY && cloud->points[i].y < maxY)
continue;
outPointCloud->points.push_back(cloud->points[i]);
}
outPointCloud->width = 1;
outPointCloud->height = outPointCloud->points.size();
*_outPointCloud = ecto::pcl::PointCloud(outPointCloud);
}
ObjectFilter::FiltersDispatch::FiltersDispatch(ecto::pcl::PointCloud *outCloud){
_outPointCloud = outCloud;
}
ECTO_CELL(hirop_perception, hirop_perception::ObjectFilter, "ObjectFilter", \
"A point cloud object filters")
| 31.483871 | 120 | 0.661629 | HSRobot |
ed26a2ae385692577b463e0542740bdc0391e734 | 4,156 | cpp | C++ | framework/PVRVk/DescriptorSetVk.cpp | jjYBdx4IL/Native_SDK | 5e1cdf579fd0a98c26935ebef098dd3f41829c86 | [
"MIT"
] | 559 | 2015-01-10T21:22:11.000Z | 2022-03-31T02:32:14.000Z | framework/PVRVk/DescriptorSetVk.cpp | jjYBdx4IL/Native_SDK | 5e1cdf579fd0a98c26935ebef098dd3f41829c86 | [
"MIT"
] | 69 | 2015-06-27T11:08:37.000Z | 2022-03-26T02:14:36.000Z | framework/PVRVk/DescriptorSetVk.cpp | jjYBdx4IL/Native_SDK | 5e1cdf579fd0a98c26935ebef098dd3f41829c86 | [
"MIT"
] | 213 | 2015-01-25T01:20:52.000Z | 2022-03-24T00:57:05.000Z | /*!
\brief Function definitions for the DescriptorSet class.
\file PVRVk/DescriptorSetVk.cpp
\author PowerVR by Imagination, Developer Technology Team
\copyright Copyright (c) Imagination Technologies Limited.
*/
#include "PVRVk/DescriptorSetVk.h"
#include "PVRVk/ImageVk.h"
#include "PVRVk/SamplerVk.h"
#include "PVRVk/BufferVk.h"
#ifdef DEBUG
#include <algorithm>
#endif
namespace pvrvk {
namespace impl {
pvrvk::DescriptorSet DescriptorPool_::allocateDescriptorSet(const DescriptorSetLayout& layout)
{
DescriptorPool descriptorPool = shared_from_this();
return DescriptorSet_::constructShared(layout, descriptorPool);
}
//!\cond NO_DOXYGEN
DescriptorPool_::DescriptorPool_(make_shared_enabler, const DeviceWeakPtr& device, const DescriptorPoolCreateInfo& createInfo)
: PVRVkDeviceObjectBase(device), DeviceObjectDebugUtils()
{
_createInfo = createInfo;
VkDescriptorPoolCreateInfo descPoolInfo;
descPoolInfo.sType = static_cast<VkStructureType>(StructureType::e_DESCRIPTOR_POOL_CREATE_INFO);
descPoolInfo.pNext = NULL;
descPoolInfo.maxSets = _createInfo.getMaxDescriptorSets();
descPoolInfo.flags = static_cast<VkDescriptorPoolCreateFlags>(DescriptorPoolCreateFlags::e_FREE_DESCRIPTOR_SET_BIT);
VkDescriptorPoolSize poolSizes[descriptorTypeSize];
uint32_t poolIndex = 0;
for (uint32_t i = 0; i < descriptorTypeSize; ++i)
{
uint32_t count = _createInfo.getNumDescriptorTypes(DescriptorType(i));
if (count)
{
poolSizes[poolIndex].type = static_cast<VkDescriptorType>(i);
poolSizes[poolIndex].descriptorCount = count;
++poolIndex;
}
} // next type
descPoolInfo.poolSizeCount = poolIndex;
descPoolInfo.pPoolSizes = poolSizes;
vkThrowIfFailed(getDevice()->getVkBindings().vkCreateDescriptorPool(getDevice()->getVkHandle(), &descPoolInfo, nullptr, &_vkHandle), "Create Descriptor Pool failed");
}
DescriptorPool_::~DescriptorPool_()
{
if (getVkHandle() != VK_NULL_HANDLE)
{
if (!_device.expired())
{
getDevice()->getVkBindings().vkDestroyDescriptorPool(getDevice()->getVkHandle(), getVkHandle(), nullptr);
_vkHandle = VK_NULL_HANDLE;
}
else
{
reportDestroyedAfterDevice();
}
}
}
#ifdef DEBUG
static inline bool bindingIdPairComparison(const std::pair<uint32_t, uint32_t>& a, const std::pair<uint32_t, uint32_t>& b) { return a.first < b.first; }
#endif
DescriptorSetLayout_::~DescriptorSetLayout_()
{
if (getVkHandle() != VK_NULL_HANDLE)
{
if (!_device.expired())
{
getDevice()->getVkBindings().vkDestroyDescriptorSetLayout(getDevice()->getVkHandle(), getVkHandle(), nullptr);
_vkHandle = VK_NULL_HANDLE;
}
else
{
reportDestroyedAfterDevice();
}
}
clearCreateInfo();
}
DescriptorSetLayout_::DescriptorSetLayout_(make_shared_enabler, const DeviceWeakPtr& device, const DescriptorSetLayoutCreateInfo& createInfo)
: PVRVkDeviceObjectBase(device), DeviceObjectDebugUtils()
{
_createInfo = createInfo;
VkDescriptorSetLayoutCreateInfo vkLayoutCreateInfo = {};
ArrayOrVector<VkDescriptorSetLayoutBinding, 4> vkBindings(getCreateInfo().getNumBindings());
const DescriptorSetLayoutCreateInfo::DescriptorSetLayoutBinding* bindings = createInfo.getAllBindings();
for (uint32_t i = 0; i < createInfo.getNumBindings(); ++i)
{
vkBindings[i].descriptorType = static_cast<VkDescriptorType>(bindings[i].descriptorType);
vkBindings[i].binding = bindings[i].binding;
vkBindings[i].descriptorCount = bindings[i].descriptorCount;
vkBindings[i].stageFlags = static_cast<VkShaderStageFlags>(bindings[i].stageFlags);
vkBindings[i].pImmutableSamplers = nullptr;
if (bindings[i].immutableSampler) { vkBindings[i].pImmutableSamplers = &bindings[i].immutableSampler->getVkHandle(); }
}
vkLayoutCreateInfo.sType = static_cast<VkStructureType>(StructureType::e_DESCRIPTOR_SET_LAYOUT_CREATE_INFO);
vkLayoutCreateInfo.bindingCount = static_cast<uint32_t>(getCreateInfo().getNumBindings());
vkLayoutCreateInfo.pBindings = vkBindings.get();
vkThrowIfFailed(getDevice()->getVkBindings().vkCreateDescriptorSetLayout(getDevice()->getVkHandle(), &vkLayoutCreateInfo, nullptr, &_vkHandle), "Create Descriptor Set Layout failed");
}
//!\endcond
} // namespace impl
} // namespace pvrvk
| 36.778761 | 184 | 0.782964 | jjYBdx4IL |
ed275cc17cde49f52def9dcc9f0c0470d9af7c14 | 1,617 | cpp | C++ | core/fxge/dib/fx_dib.cpp | yanxijian/pdfium | aba53245bf116a1d908f851a93236b500988a1ee | [
"Apache-2.0"
] | 16 | 2018-09-14T12:07:14.000Z | 2021-04-22T11:18:25.000Z | core/fxge/dib/fx_dib.cpp | yanxijian/pdfium | aba53245bf116a1d908f851a93236b500988a1ee | [
"Apache-2.0"
] | 1 | 2020-12-26T16:18:40.000Z | 2020-12-26T16:18:40.000Z | core/fxge/dib/fx_dib.cpp | yanxijian/pdfium | aba53245bf116a1d908f851a93236b500988a1ee | [
"Apache-2.0"
] | 6 | 2017-09-12T14:09:32.000Z | 2021-11-20T03:32:27.000Z | // Copyright 2014 PDFium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
#include "core/fxge/dib/fx_dib.h"
#include <tuple>
#include <utility>
#include "build/build_config.h"
#if defined(OS_WIN)
#include <windows.h>
#endif
#if defined(OS_WIN)
static_assert(sizeof(FX_COLORREF) == sizeof(COLORREF),
"FX_COLORREF vs. COLORREF mismatch");
#endif
FXDIB_Format MakeRGBFormat(int bpp) {
switch (bpp) {
case 1:
return FXDIB_Format::k1bppRgb;
case 8:
return FXDIB_Format::k8bppRgb;
case 24:
return FXDIB_Format::kRgb;
case 32:
return FXDIB_Format::kRgb32;
default:
return FXDIB_Format::kInvalid;
}
}
FXDIB_ResampleOptions::FXDIB_ResampleOptions() = default;
bool FXDIB_ResampleOptions::HasAnyOptions() const {
return bInterpolateBilinear || bHalftone || bNoSmoothing || bLossy;
}
std::tuple<int, int, int, int> ArgbDecode(FX_ARGB argb) {
return std::make_tuple(FXARGB_A(argb), FXARGB_R(argb), FXARGB_G(argb),
FXARGB_B(argb));
}
std::pair<int, FX_COLORREF> ArgbToAlphaAndColorRef(FX_ARGB argb) {
return {FXARGB_A(argb), ArgbToColorRef(argb)};
}
FX_COLORREF ArgbToColorRef(FX_ARGB argb) {
return FXSYS_BGR(FXARGB_B(argb), FXARGB_G(argb), FXARGB_R(argb));
}
FX_ARGB AlphaAndColorRefToArgb(int a, FX_COLORREF colorref) {
return ArgbEncode(a, FXSYS_GetRValue(colorref), FXSYS_GetGValue(colorref),
FXSYS_GetBValue(colorref));
}
| 26.508197 | 80 | 0.710575 | yanxijian |
ed298aa3d1170c7bde66bdd8ca2dc1ff29daf5d5 | 3,969 | cpp | C++ | src/3rdparty/khtml/src/rendering/media_controls.cpp | afarcat/QtHtmlView | fff12b6f5c08c2c6db15dd73e4f0b55421827b39 | [
"Apache-2.0"
] | null | null | null | src/3rdparty/khtml/src/rendering/media_controls.cpp | afarcat/QtHtmlView | fff12b6f5c08c2c6db15dd73e4f0b55421827b39 | [
"Apache-2.0"
] | null | null | null | src/3rdparty/khtml/src/rendering/media_controls.cpp | afarcat/QtHtmlView | fff12b6f5c08c2c6db15dd73e4f0b55421827b39 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2009 Michael Howell <mhowell123@gmail.com>.
* Copyright (C) 2009 Germain Garand <germain@ebooksfrance.org>
* Parts copyright (C) 2007, 2008 Apple Inc. All rights reserved.
* Copyright (C) 2018 afarcat <kabak@sina.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 APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "media_controls.h"
#ifdef QT_WIDGETS_LIB
#include <QHBoxLayout>
#endif
//AFA #include <phonon/seekslider.h>
//AFA #include <phonon/mediaobject.h>
#include <rendering/render_media.h>
//AFA #include <phonon/videowidget.h>
//AFA #include <ktogglefullscreenaction.h>
//AFA #include <kglobalaccel.h>
//AFA #include <klocalizedstring.h>
namespace khtml
{
MediaControls::MediaControls(MediaPlayer *mediaPlayer, QWidget *parent) : QWidget(parent)
{
m_mediaPlayer = mediaPlayer;
#ifdef QT_WIDGETS_LIB
//AFA Phonon::MediaObject *mediaObject = m_mediaPlayer->mediaObject();
setLayout(new QHBoxLayout(this));
m_play = new QPushButton(QIcon::fromTheme("media-playback-start"), i18n("Play"), this);
//AFA connect(m_play, SIGNAL(clicked()), mediaObject, SLOT(play()));
layout()->addWidget(m_play);
m_pause = new QPushButton(QIcon::fromTheme("media-playback-pause"), i18n("Pause"), this);
//AFA connect(m_pause, SIGNAL(clicked()), mediaObject, SLOT(pause()));
layout()->addWidget(m_pause);
//AFA layout()->addWidget(new Phonon::SeekSlider(mediaObject, this));
//AFA QAction *fsac = new KToggleFullScreenAction(this);
//AFA fsac->setObjectName("KHTMLMediaPlayerFullScreenAction"); // needed for global shortcut activation.
m_fullscreen = new QToolButton(this);
//AFA m_fullscreen->setDefaultAction(fsac);
m_fullscreen->setCheckable(true);
//AFA connect(fsac, SIGNAL(toggled(bool)), this, SLOT(slotToggled(bool)));
layout()->addWidget(m_fullscreen);
#else
m_play = nullptr;
m_pause = nullptr;
m_fullscreen = nullptr;
#endif
//AFA slotStateChanged(mediaObject->state());
//AFA connect(mediaObject, SIGNAL(stateChanged(Phonon::State,Phonon::State)), SLOT(slotStateChanged(Phonon::State)));
}
void MediaControls::slotToggled(bool t)
{
if (t) {
//AFA m_mediaPlayer->videoWidget()->enterFullScreen();
//AFA KGlobalAccel::self()->setShortcut(m_fullscreen->defaultAction(), QList<QKeySequence>() << Qt::Key_Escape);
} else {
//AFA m_mediaPlayer->videoWidget()->exitFullScreen();
//AFA KGlobalAccel::self()->removeAllShortcuts(m_fullscreen->defaultAction());
}
}
//AFA
//void MediaControls::slotStateChanged(Phonon::State state)
//{
// if (state == Phonon::PlayingState) {
// m_play->hide();
// m_pause->show();
// } else {
// m_pause->hide();
// m_play->show();
// }
//}
}
| 40.090909 | 121 | 0.715545 | afarcat |
ed2ded170e1a993c92d6fede74637559925a1719 | 1,229 | cpp | C++ | Software Engineering Algorithmic Techniques/Exam/3.cpp | danielgarm/Algorithms | 8acb3e913527cb158ea414bce2a99408f3a2bf84 | [
"MIT"
] | null | null | null | Software Engineering Algorithmic Techniques/Exam/3.cpp | danielgarm/Algorithms | 8acb3e913527cb158ea414bce2a99408f3a2bf84 | [
"MIT"
] | null | null | null | Software Engineering Algorithmic Techniques/Exam/3.cpp | danielgarm/Algorithms | 8acb3e913527cb158ea414bce2a99408f3a2bf84 | [
"MIT"
] | null | null | null | //Daniel Garcia Molero
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
//Esta solucion tiene un coste en tiempo y espacio de O(x*y), donde x e y son la
//longitud de las palabras 1 y 2 respectivamente
int getLongestSequence(const string &p1, const string &p2) {
//p1 = rows, p2 = cols
vector<vector<int>> matrix = vector<vector<int>>(p1.length() + 1, vector<int>(p2.length() + 1, 0));
int last;
for (size_t i = 1; i <= p1.length(); i++) {
last = -1;
for (size_t j = 1; j <= p2.length(); j++) {
if (p1[i - 1] == p2[j - 1]) {
if ((i == 0 || matrix[i - 1][j] == 0)) {
matrix[i][j]++;
} else {
if (last != -1 && matrix[i - 1][j] != matrix[i - 1][last]) {
matrix[i][j] = matrix[i - 1][j] + 1;
} else {
matrix[i][j] = max(matrix[i - 1][j] + 1, matrix[i][j - 1]);
}
}
last = j;
} else {
matrix[i][j] = max(matrix[i - 1][j], matrix[i][j - 1]);
}
}
}
return matrix[p1.length()][p2.length()];
}
bool solve() {
string palabra1, palabra2;
cin >> palabra1 >> palabra2;
if (!cin) return false;
cout << getLongestSequence(palabra1, palabra2) << endl;
return true;
}
int main() {
while (solve()) {}
return 0;
} | 25.604167 | 100 | 0.561432 | danielgarm |
ed2e6db9ffc4c595fffa607ced9ac223b80a909a | 5,746 | cpp | C++ | publibs/libzq/libzq/utils/ZQStringUtils.cpp | tianxiawuzhei/cocos-quick-cpp | 3bf7a05846e407c8b875cfe2c86f6499f8345bb7 | [
"MIT"
] | 1 | 2017-06-21T10:06:26.000Z | 2017-06-21T10:06:26.000Z | publibs/libzq/libzq/utils/ZQStringUtils.cpp | tianxiawuzhei/cocos-quick-cpp | 3bf7a05846e407c8b875cfe2c86f6499f8345bb7 | [
"MIT"
] | null | null | null | publibs/libzq/libzq/utils/ZQStringUtils.cpp | tianxiawuzhei/cocos-quick-cpp | 3bf7a05846e407c8b875cfe2c86f6499f8345bb7 | [
"MIT"
] | null | null | null | //
// ZQStringUtils.cpp
// libzq
//
// Created by staff on 16/11/18.
// Copyright © 2016年 zyqiosexercise. All rights reserved.
//
#include "ZQStringUtils.h"
#include <functional>
using namespace zq;
bool StringUtils::startsWith(const std::string &text, const std::string &start)
{
//if start is bigger than the string than it fails
if (start.length() > text.length()) {
return false;
}
else if (start.length() == text.length()) {
return start == text;
}
//loop through start and check if all char matches
for (int i = 0; i< start.length(); i++) {
if (start[i] != text[i]) {
return false;
}
}
return true;
}
bool StringUtils::endsWith(const std::string &text, const std::string &end)
{
//if end is bigger than the string than it fails
if (end.length() > text.length()) {
return false;
}
else if (end.length() == text.length()) {
return end == text;
}
std::size_t diff = text.length() - end.length();
for (std::size_t i = text.length()-1; i > diff-1; i--) {
if (end[i-diff] != text[i]) {
return false;
}
}
return true;
}
bool StringUtils::contains(const std::string &text, const std::string &str)
{
return text.find(str) != std::string::npos;
}
std::size_t StringUtils::count(const std::string &text, const std::string str, std::size_t start, std::size_t end)
{
if (start == 0) {
start = 0;
}
if (end == 0) {
end = text.length()-1;
}
std::size_t nb = 0;
while (start <= end) {
start = text.find(str, start);
if (start != std::string::npos) {
nb++;
start += str.length();
}
else {
break;
}
}
return nb;
}
std::vector<std::string> StringUtils::split(std::string &text, std::string &separator)
{
std::vector<std::string> elems;
std::size_t last_pos = 0;
std::size_t pos = text.find(separator);
while (pos != std::string::npos && last_pos != std::string::npos)
{
if (pos - last_pos > 0)
{
elems.push_back(text.substr(last_pos, pos - last_pos));
}
last_pos = text.find_first_not_of(separator, pos+separator.length()-1);
pos = text.find(separator, last_pos);
}
if (last_pos != std::string::npos)
{
elems.push_back(text.substr(last_pos));
}
return elems;
}
std::string StringUtils::join(std::vector<std::string> &vect, std::string &delimiter)
{
std::string retval;
std::vector<std::string>::const_iterator began = vect.begin();
std::vector<std::string>::const_iterator end = vect.end();
for (; began != end; ++began)
{
retval.append(*began);
retval.append(delimiter);
}
retval.erase(retval.length() - delimiter.length());
return retval;
}
bool StringUtils::iequals(const std::string a, const std::string b, bool ignore_case)
{
std::size_t sz = a.length();
if (b.length() != sz)
return false;
for (std::size_t i = 0; i < sz; ++i)
{
if (ignore_case)
{
if (::tolower(a[i]) != ::tolower(b[i]))
{
return false;
}
}
else
{
if (a[i] != b[i])
{
return false;
}
}
}
return true;
}
std::string StringUtils::replace(std::string &text, std::string &from, std::string &to)
{
std::string temp(text);
std::size_t start_pos = 0;
start_pos = temp.find(from, start_pos);
if (start_pos != std::string::npos) {
temp.replace(start_pos, from.length(), to);
}
return temp;
}
std::string StringUtils::replace_all(std::string &text, std::string &from, std::string &to)
{
std::string temp(text);
if(!from.empty()) {
size_t start_pos = 0;
while ((start_pos = temp.find(from, start_pos)) != std::string::npos) {
temp.replace(start_pos, from.length(), to);
// In case 'to' contains 'from', like replacing 'x' with 'yx'
start_pos += to.length();
}
}
return temp;
}
std::string StringUtils::tolower(const std::string &text)
{
std::string temp(text);
std::transform(text.begin(),text.end(), temp.begin(), ::tolower);
return temp;
}
std::string StringUtils::toupper(const std::string &text)
{
std::string temp(text);
std::transform(text.begin(),text.end(), temp.begin(), ::toupper);
return temp;
}
std::string StringUtils::capitalize(const std::string &text)
{
std::string temp(text);
std::string::iterator it = temp.begin();
*it = std::toupper(*it);
return temp;
}
std::string &StringUtils::ltrim(std::string &s) {
s.erase(s.begin(), std::find_if(s.begin(), s.end(),
std::not1(std::ptr_fun<int, int>(std::isspace))));
return s;
}
// trim from end
std::string &StringUtils::rtrim(std::string &s) {
s.erase(std::find_if(s.rbegin(), s.rend(),
std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
return s;
}
// trim from both ends
std::string &StringUtils::trim(std::string &s) {
return ltrim(rtrim(s));
}
std::string StringUtils::ltrim(const std::string &s) {
std::string temp(s);
StringUtils::ltrim(temp);
return temp;
}
// trim from end
std::string StringUtils::rtrim(const std::string &s) {
std::string temp(s);
StringUtils::rtrim(temp);
return temp;
}
// trim from both ends
std::string StringUtils::trim(const std::string &s) {
std::string temp(s);
StringUtils::trim(temp);
return temp;
}
| 24.347458 | 114 | 0.560042 | tianxiawuzhei |
ed2fe22e3bebe19526b10a68bcb9cb728a082742 | 1,118 | cpp | C++ | codeforces/2020/round#630/C.cpp | plusplus7/solutions | 31233c13ee2bd0da6a907a24adbaf5b49ebf843c | [
"CC0-1.0"
] | 5 | 2016-04-29T07:14:23.000Z | 2020-01-07T04:56:11.000Z | codeforces/2020/round#630/C.cpp | plusplus7/solutions | 31233c13ee2bd0da6a907a24adbaf5b49ebf843c | [
"CC0-1.0"
] | null | null | null | codeforces/2020/round#630/C.cpp | plusplus7/solutions | 31233c13ee2bd0da6a907a24adbaf5b49ebf843c | [
"CC0-1.0"
] | 1 | 2016-04-29T07:14:32.000Z | 2016-04-29T07:14:32.000Z | #include <bits/stdc++.h >
using namespace std;
int cnt[200005][26];
char s[200005];
int main()
{
int T;
scanf("%d", &T);
while (T--) {
int n, k;
scanf("%d%d", &n, &k);
scanf("%s", s);
for (int i=0; i<n; i++) {
for (int j=0; j<26; j++) {
cnt [i][j] = 0;
}
}
for (int i=0; i<n; i++) {
int x = i%k;
cnt[x][s[i]-'a'] ++;
}
int ans = 0;
for (int i=0; i<k/2; i++) {
int v = k-i-1;
int all = 0;
int m = 0;
for (int j=0; j<26; j++) {
cnt[i][j] += cnt[v][j];
all += cnt[i][j];
m = max(cnt[i][j], m);
}
ans += all-m;
}
if (k&1) {
int all = 0;
int m = 0;
int xx= k/2;
for (int j=0; j<26; j++) {
all += cnt[xx][j];
m = max(cnt[xx][j], m);
}
ans += all-m;
}
cout << ans << endl;
}
return 0;
}
| 20.703704 | 42 | 0.28712 | plusplus7 |
ed3090bc9abd62ac484ff5872db4b1682db29842 | 11,744 | cpp | C++ | src/system.cpp | marangisto/HAL | fa56b539f64b277fa122a010e4ee643463f58498 | [
"MIT"
] | 2 | 2019-09-12T04:12:16.000Z | 2020-09-23T19:13:06.000Z | src/system.cpp | marangisto/HAL | fa56b539f64b277fa122a010e4ee643463f58498 | [
"MIT"
] | 2 | 2019-09-10T13:47:50.000Z | 2020-02-24T03:27:47.000Z | src/system.cpp | marangisto/HAL | fa56b539f64b277fa122a010e4ee643463f58498 | [
"MIT"
] | 3 | 2019-08-31T12:58:28.000Z | 2020-03-26T22:56:34.000Z | #include <hal.h>
#include <algorithm>
namespace hal
{
using namespace device;
namespace internal
{
template<uint32_t x, uint32_t b, uint8_t nbits>
static constexpr uint32_t encode()
{
static_assert(x < (1 << nbits), "bit field overflow");
return ((x & (1 << 0)) ? (b << 0) : 0)
| ((x & (1 << 1)) ? (b << 1) : 0)
| ((x & (1 << 2)) ? (b << 2) : 0)
| ((x & (1 << 3)) ? (b << 3) : 0)
| ((x & (1 << 4)) ? (b << 4) : 0)
| ((x & (1 << 5)) ? (b << 5) : 0)
| ((x & (1 << 6)) ? (b << 6) : 0)
| ((x & (1 << 7)) ? (b << 7) : 0)
| ((x & (1 << 8)) ? (b << 8) : 0)
;
}
} // namespace internal
void sys_tick::delay_ms(uint32_t ms)
{
uint32_t now = ms_counter, then = now + ms;
while (ms_counter >= now && ms_counter < then)
; // busy wait
}
void sys_tick::delay_us(uint32_t us)
{
#if defined(STM32F051) || defined(STM32F072) || defined (STM32F767) || defined(STM32H743) || defined(STM32G070)
volatile uint32_t& c = STK.CVR;
const uint32_t c_max = STK.RVR;
#elif defined(STM32F103) || defined(STM32F411) || defined(STM32G431)
volatile uint32_t& c = STK.VAL;
const uint32_t c_max = STK.LOAD;
#else
static_assert(false, "no featured sys-tick micro-second delay");
#endif
const uint32_t fuzz = ticks_per_us - (ticks_per_us >> 2); // approx 3/4
const uint32_t n = us * ticks_per_us - fuzz;
const uint32_t now = c;
const uint32_t then = now >= n ? now - n : (c_max - n + now);
if (now > then)
while (c > then && c < now);
else
while (!(c > now && c < then));
}
void sys_tick::init(uint32_t n)
{
using namespace hal;
typedef stk_t _;
ms_counter = 0; // start new epoq
ticks_per_us = n / 1000; // for us in delay_us
#if defined(STM32F051) || defined(STM32F072) || defined (STM32F767) || defined(STM32H743) || defined(STM32G070)
STK.CSR = _::CSR_RESET_VALUE; // reset controls
STK.RVR = n - 1; // reload value
STK.CVR = _::CVR_RESET_VALUE; // current counter value
STK.CSR |= _::CSR_CLKSOURCE; // systick clock source
STK.CSR |= _::CSR_ENABLE | _::CSR_TICKINT; // enable counter & interrupts
#elif defined(STM32F103) || defined(STM32F411) || defined(STM32G431)
STK.CTRL = _::CTRL_RESET_VALUE; // reset controls
STK.LOAD = n - 1; // reload value
STK.VAL = _::VAL_RESET_VALUE; // current counter value
STK.CTRL |= _::CTRL_CLKSOURCE; // systick clock source
STK.CTRL |= _::CTRL_ENABLE | _::CTRL_TICKINT; // enable counter & interrupts
#else
static_assert(false, "no featured sys-tick initialzation");
#endif
}
volatile uint32_t sys_tick::ms_counter = 0;
uint32_t sys_tick::ticks_per_us = 0;
inline void sys_tick_init(uint32_t n) { sys_tick::init(n); }
inline void sys_tick_update() { ++sys_tick::ms_counter; } // N.B. wraps in 49 days!
uint32_t sys_clock::m_freq;
void sys_clock::init()
{
using namespace hal;
typedef rcc_t _;
// reset clock control registers (common for all families)
RCC.CR = _::CR_RESET_VALUE;
RCC.CFGR = _::CFGR_RESET_VALUE;
#if defined(STM32F051) || defined(STM32F072)
m_freq = 48000000;
// reset clock control registers
RCC.CFGR2 = _::CFGR2_RESET_VALUE;
RCC.CFGR3 = _::CFGR3_RESET_VALUE;
RCC.CR2 = _::CR2_RESET_VALUE;
RCC.CIR = _::CIR_RESET_VALUE;
// set system clock to HSI-PLL 48MHz
FLASH.ACR |= flash_t::ACR_PRFTBE | flash_t::ACR_LATENCY<0x1>;
RCC.CFGR |= _::CFGR_PLLMUL<0xa>; // PLL multiplier 12
RCC.CR |= _::CR_PLLON; // enable PLL
while (!(RCC.CR & _::CR_PLLRDY)); // wait for PLL to be ready
RCC.CFGR |= _::CFGR_SW<0x2>; // select PLL as system clock
// wait for PLL as system clock
while ((RCC.CFGR & _::CFGR_SWS<0x3>) != _::CFGR_SWS<0x2>);
#elif defined(STM32F103)
m_freq = 72000000;
// set system clock to HSE-PLL 72MHz
FLASH.ACR |= flash_t::ACR_PRFTBE | flash_t::template ACR_LATENCY<0x2>;
RCC.CR |= _::CR_HSEON; // enable external clock
while (!(RCC.CR & _::CR_HSERDY)); // wait for HSE ready
RCC.CFGR |= _::CFGR_PLLSRC // clock from PREDIV1
| _::CFGR_PLLMUL<0x7> // pll multiplier = 9
| _::CFGR_PPRE1<0x4> // APB low-speed prescale = 2
;
RCC.CR |= _::CR_PLLON; // enable external clock
while (!(RCC.CR & _::CR_PLLRDY)); // wait for pll ready
RCC.CFGR |= _::CFGR_SW<0x2>; // use pll as clock source
// wait for clock switch completion
while ((RCC.CFGR & _::CFGR_SWS<0x3>) != _::CFGR_SWS<0x2>);
#elif defined(STM32F411)
m_freq = 100000000;
// reset clock control registers
RCC.CIR = _::CIR_RESET_VALUE;
// set system clock to HSI-PLL 100MHz
constexpr uint8_t wait_states = 0x3; // 3 wait-states for 100MHz at 2.7-3.3V
FLASH.ACR |= flash_t::ACR_PRFTEN | flash_t::ACR_LATENCY<wait_states>;
while ((FLASH.ACR & flash_t::ACR_LATENCY<0x7>) != flash_t::ACR_LATENCY<wait_states>); // wait to take effect
enum pllP_t { pllP_2 = 0x0, pllP_4 = 0x1, pllP_6 = 0x2, pllP_8 = 0x3 };
// fVCO = hs[ei] * pllN / pllM // must be 100MHz - 400MHz
// fSYS = fVCO / pllP // <= 100MHz
// fUSB = fVCO / pllQ // <= 48MHz
// pllN = 200, pllM = 8, pllP = 4, pllQ = 9, fSYS = 1.0e8, fUSB = 4.4445e7
constexpr uint16_t pllN = 200; // 9 bits, valid range [50..432]
constexpr uint8_t pllM = 8; // 6 bits, valid range [2..63]
constexpr pllP_t pllP = pllP_4; // 2 bits, enum range [2, 4, 6, 8]
constexpr uint8_t pllQ = 9; // 4 bits, valid range [2..15]
constexpr uint8_t pllSRC = 0; // 1 bit, 0 = HSI, 1 = HSE
using internal::encode;
RCC.PLLCFGR = encode<pllSRC, _::PLLCFGR_PLLSRC, 1>()
| encode<pllN, _::PLLCFGR_PLLN0, 9>()
| encode<pllM, _::PLLCFGR_PLLM0, 6>()
| encode<pllP, _::PLLCFGR_PLLP0, 2>()
| encode<pllQ, _::PLLCFGR_PLLQ0, 4>()
;
RCC.CR |= _::CR_PLLON; // enable PLL
while (!(RCC.CR & _::CR_PLLRDY)); // wait for PLL to be ready
RCC.CFGR |= encode<0x2, _::CFGR_SW0, 2>(); // select PLL as system clock
// wait for PLL as system clock
while ((RCC.CFGR & encode<0x3, _::CFGR_SWS0, 2>()) != encode<0x2, _::CFGR_SWS0, 2>());
#elif defined(STM32F767)
m_freq = 16000000;
#elif defined(STM32H743)
m_freq = 8000000;
#elif defined(STM32G070)
m_freq = 64000000;
// set system clock to HSI-PLL 64MHz and p-clock = 64MHz
constexpr uint8_t wait_states = 0x2; // 2 wait-states for 64Hz at Vcore range 1
FLASH.ACR |= flash_t::ACR_PRFTEN | flash_t::ACR_LATENCY<wait_states>;
while ((FLASH.ACR & flash_t::ACR_LATENCY<0x7>) != flash_t::ACR_LATENCY<wait_states>); // wait to take effect
// fR (fSYS) = fVCO / pllR // <= 64MHz
// fP = fVCO / pllP // <= 122MHz
// pllN = 8.0, pllM = 1.0, pllP = 2.0, pllR = 2.0, fSYS = 6.4e7, fPllP = 6.4e7, fVCO = 1.28e8
constexpr uint16_t pllN = 8; // 7 bits, valid range [8..86]
constexpr uint8_t pllM = 1 - 1; // 3 bits, valid range [1..8]-1
constexpr uint8_t pllP = 2 - 1; // 5 bits, valid range [2..32]-1
constexpr uint8_t pllR = 2 - 1; // 3 bits, valid range [2..8]-1
constexpr uint8_t pllSRC = 2; // 2 bits, 2 = HSI16, 3 = HSE
RCC.PLLSYSCFGR = _::PLLSYSCFGR_PLLSRC<pllSRC>
| _::PLLSYSCFGR_PLLN<pllN>
| _::PLLSYSCFGR_PLLM<pllM>
| _::PLLSYSCFGR_PLLP<pllP>
| _::PLLSYSCFGR_PLLR<pllR>
| _::PLLSYSCFGR_PLLREN
| _::PLLSYSCFGR_PLLPEN
;
RCC.CR |= _::CR_PLLON; // enable PLL
while (!(RCC.CR & _::CR_PLLRDY)); // wait for PLL to be ready
RCC.CFGR |= _::CFGR_SW<0x2>; // select PLL as system clock
// wait for PLL as system clock
while ((RCC.CFGR & _::CFGR_SWS<0x3>) != _::CFGR_SWS<0x2>);
#elif defined(STM32G431)
m_freq = 170000000;
// set system clock to HSI-PLL 170MHz (R) and same for P and Q clocks
constexpr uint8_t wait_states = 0x8; // 8 wait-states for 170MHz at Vcore range 1
FLASH.ACR = flash_t::ACR_RESET_VALUE;
FLASH.ACR |= flash_t::ACR_PRFTEN | flash_t::ACR_LATENCY<wait_states>;
while ((FLASH.ACR & flash_t::ACR_LATENCY<0xf>) != flash_t::ACR_LATENCY<wait_states>); // wait to take effect
#if defined(HSE)
RCC.CR |= _::CR_HSEON; // enable external clock
while (!(RCC.CR & _::CR_HSERDY)); // wait for HSE ready
#if HSE == 24000000
constexpr uint8_t pllM = 6 - 1; // 3 bits, valid range [1..15]-1
#elif HSE == 8000000
constexpr uint8_t pllM = 2 - 1; // 3 bits, valid range [1..15]-1
#else
static_assert(false, "unsupported HSE frequency");
#endif
constexpr uint8_t pllSRC = 3; // 2 bits, 2 = HSI16, 3 = HSE
#else
// pllN = 85.0, pllM = 4.0, pllP = 7.0, pllPDIV = 2.0, pllQ = 2.0, pllR = 2.0, fSYS = 1.7e8, fPllP = 1.7e8, fPllQ = 1.7e8, fVCO = 3.4e8
constexpr uint8_t pllM = 4 - 1; // 3 bits, valid range [1..15]-1
constexpr uint8_t pllSRC = 2; // 2 bits, 2 = HSI16, 3 = HSE
#endif
constexpr uint16_t pllN = 85; // 7 bits, valid range [8..127]
constexpr uint8_t pllPDIV = 2; // 5 bits, valid range [2..31]
constexpr uint8_t pllR = 0; // 2 bits, 0 = 2, 1 = 4, 2 = 6, 3 = 8
constexpr uint8_t pllQ = 0; // 2 bits, 0 = 2, 1 = 4, 2 = 6, 3 = 8
RCC.PLLSYSCFGR = _::PLLSYSCFGR_PLLSRC<pllSRC>
| _::PLLSYSCFGR_PLLSYSN<pllN>
| _::PLLSYSCFGR_PLLSYSM<pllM>
| _::PLLSYSCFGR_PLLSYSPDIV<pllPDIV>
| _::PLLSYSCFGR_PLLSYSQ<pllQ>
| _::PLLSYSCFGR_PLLSYSR<pllR>
| _::PLLSYSCFGR_PLLPEN
| _::PLLSYSCFGR_PLLSYSQEN
| _::PLLSYSCFGR_PLLSYSREN
;
RCC.CR |= _::CR_PLLSYSON; // enable PLL
while (!(RCC.CR & _::CR_PLLSYSRDY)); // wait for PLL to be ready
RCC.CFGR |= _::CFGR_SW<0x3>; // select PLL as system clock
// wait for PLL as system clock
while ((RCC.CFGR & _::CFGR_SWS<0x3>) != _::CFGR_SWS<0x3>);
// enable FPU
FPU_CPACR.CPACR |= fpu_cpacr_t::CPACR_CP<0xf>; // enable co-processors
__asm volatile ("dsb"); // data pipe-line reset
__asm volatile ("isb"); // instruction pipe-line reset
#else
static_assert(false, "no featured clock initialzation");
#endif
// initialize sys-tick for milli-second counts
hal::sys_tick_init(m_freq / 1000);
}
} // namespace hal
template<> void handler<interrupt::SYSTICK>()
{
hal::sys_tick_update();
}
extern void system_init(void)
{
hal::sys_clock::init();
}
| 38.006472 | 139 | 0.538658 | marangisto |
ed310c573883603a89722dd85d846cac70c032fc | 1,857 | cpp | C++ | platform/platform_std.cpp | LaGrunge/geocore | b599eda29a32a14e5c02f51c66848959b50732f2 | [
"Apache-2.0"
] | 1 | 2019-10-02T16:17:31.000Z | 2019-10-02T16:17:31.000Z | platform/platform_std.cpp | LaGrunge/omim | 8ce6d970f8f0eb613531b16edd22ea8ab923e72a | [
"Apache-2.0"
] | 6 | 2019-09-09T10:11:41.000Z | 2019-10-02T15:04:21.000Z | platform/platform_std.cpp | LaGrunge/geocore | b599eda29a32a14e5c02f51c66848959b50732f2 | [
"Apache-2.0"
] | null | null | null | #include "platform/constants.hpp"
#include "platform/measurement_utils.hpp"
#include "platform/platform.hpp"
#include "platform/settings.hpp"
#include "coding/file_reader.hpp"
#include "base/logging.hpp"
#include "platform/target_os.hpp"
#include <algorithm>
#include <future>
#include <memory>
#include <regex>
#include <string>
#include <boost/filesystem.hpp>
#include <boost/range/iterator_range.hpp>
namespace fs = boost::filesystem;
using namespace std;
unique_ptr<ModelReader> Platform::GetReader(string const & file, string const & searchScope) const
{
return make_unique<FileReader>(ReadPathForFile(file, searchScope), READER_CHUNK_LOG_SIZE,
READER_CHUNK_LOG_COUNT);
}
bool Platform::GetFileSizeByName(string const & fileName, uint64_t & size) const
{
try
{
return GetFileSizeByFullPath(ReadPathForFile(fileName), size);
}
catch (RootException const &)
{
return false;
}
}
void Platform::GetFilesByRegExp(string const & directory, string const & regexp,
FilesList & outFiles)
{
boost::system::error_code ec{};
regex exp(regexp);
for (auto const & entry : boost::make_iterator_range(fs::directory_iterator(directory, ec), {}))
{
string const name = entry.path().filename().string();
if (regex_search(name.begin(), name.end(), exp))
outFiles.push_back(name);
}
}
// static
Platform::EError Platform::MkDir(string const & dirName)
{
boost::system::error_code ec{};
fs::path dirPath{dirName};
if (fs::exists(dirPath, ec))
return Platform::ERR_FILE_ALREADY_EXISTS;
if (!fs::create_directory(dirPath, ec))
{
LOG(LWARNING, ("Can't create directory: ", dirName));
return Platform::ERR_UNKNOWN;
}
return Platform::ERR_OK;
}
extern Platform & GetPlatform()
{
static Platform platform;
return platform;
}
| 23.807692 | 98 | 0.699515 | LaGrunge |
ed3307a3e2baf12abd506d5a0cd8c85d862afac7 | 878 | cpp | C++ | src/servers/server.cpp | thepieterdc/mailbridge | b64e42ee976c60cbef663840fb19377e6624dae3 | [
"MIT"
] | null | null | null | src/servers/server.cpp | thepieterdc/mailbridge | b64e42ee976c60cbef663840fb19377e6624dae3 | [
"MIT"
] | 6 | 2019-03-30T14:12:56.000Z | 2021-04-06T20:24:01.000Z | src/servers/server.cpp | thepieterdc/mailbridge | b64e42ee976c60cbef663840fb19377e6624dae3 | [
"MIT"
] | 1 | 2020-10-08T04:47:32.000Z | 2020-10-08T04:47:32.000Z | /**
* Copyright (c) 2019 - Pieter De Clercq. All rights reserved.
*
* https://github.com/thepieterdc/mailbridge/
*/
#include <sys/socket.h>
#include <unistd.h>
#include <iostream>
#include "server.h"
#include "../configurations/slack_configuration.h"
#include "../handlers/slack_handler.h"
#include "../handlers/stdout_handler.h"
bool Server::authenticate(Authentication *authentication) {
for (auto &handler : this->configuration()->get_handlers()) {
auto auth = handler.first;
if (*auth == *authentication) {
return true;
}
}
return false;
}
void Server::handle(Authentication *authentication, SmtpMessage *message) {
for (auto &handler : this->configuration()->get_handlers()) {
auto auth = handler.first;
if (*auth == *authentication) {
handler.second->handle(message);
}
}
} | 27.4375 | 75 | 0.643508 | thepieterdc |
ed341d5d54054a4f7820114ffb37bbcdb7a88045 | 2,113 | cpp | C++ | luogu/5105.cpp | swwind/code | 25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0 | [
"WTFPL"
] | 3 | 2017-09-17T09:12:50.000Z | 2018-04-06T01:18:17.000Z | luogu/5105.cpp | swwind/code | 25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0 | [
"WTFPL"
] | null | null | null | luogu/5105.cpp | swwind/code | 25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0 | [
"WTFPL"
] | null | null | null | #include <bits/stdc++.h>
#define N 100020
#define ll long long
using namespace std;
inline ll read(){
ll x=0,f=1;char ch=getchar();
while(ch>'9'||ch<'0')ch=='-'&&(f=0)||(ch=getchar());
while(ch<='9'&&ch>='0')x=(x<<3)+(x<<1)+ch-'0',ch=getchar();
return f?x:-x;
}
typedef pair<ll, ll> pairs;
inline ll calc(ll x) {
switch (x % 4) {
case 0: return 0;
case 1: return x + x - 1;
case 2: return 2;
case 3: return x + x + 1;
}
return 19260817;
}
inline ll calc(ll l, ll r) {
return calc(l) ^ calc(r);
}
multiset<pairs> st;
deque<multiset<pairs>::iterator> rub;
ll now;
void update_left(multiset<pairs>::iterator x) {
if (x != st.begin()) {
ll u = (ll)x->first * x->first;
--x;
now ^= u - ((ll)x->second * x->second);
}
}
void update_right(multiset<pairs>::iterator x) {
if (x != --st.end()) {
ll u = (ll)x->second * x->second;
++x;
now ^= ((ll)x->first * x->first) - u;
}
}
void insert(ll l, ll r) {
pairs x = make_pair(l, r);
auto t = st.lower_bound(x), u = t;
while (true) {
if (u == st.begin())
break;
--u;
if (x.first - 1 <= u->second)
rub.push_front(u);
else
break;
}
u = t;
while (true) {
if (u == st.end())
break;
if (x.second + 1 >= u->first)
rub.push_back(u);
else
break;
++u;
}
for (auto u : rub) {
if (u->first < x.first)
x.first = u->first;
if (u->second > x.second)
x.second = u->second;
update_left(u);
now ^= calc(u -> first, u -> second);
}
if (rub.size())
update_right(*--rub.end());
else {
auto t = st.lower_bound(x);
if (t != st.end())
update_left(t);
}
for (auto u : rub)
st.erase(u);
rub.clear();
st.insert(x);
update_left(st.find(x));
update_right(st.find(x));
now ^= calc(x.second) ^ calc(x.first);
}
int main(int argc, char const *argv[]) {
// freopen("../tmp/.in", "r", stdin);
ll n = read();
while (n --) {
ll op = read();
if (op == 1) {
ll l = read(), r = read();
insert(l, r);
} else {
printf("%d\n", now);
}
}
return 0;
} | 19.747664 | 61 | 0.508755 | swwind |
ed34b0ffb3a8702b93b2797a10e2f2ebb0ba8ad3 | 1,939 | cpp | C++ | src/CDirFTW.cpp | colinw7/CFile | 1ac42b52303585fe9a49b043c293afe118551c50 | [
"MIT"
] | 1 | 2021-12-23T02:21:05.000Z | 2021-12-23T02:21:05.000Z | src/CDirFTW.cpp | colinw7/CFile | 1ac42b52303585fe9a49b043c293afe118551c50 | [
"MIT"
] | null | null | null | src/CDirFTW.cpp | colinw7/CFile | 1ac42b52303585fe9a49b043c293afe118551c50 | [
"MIT"
] | null | null | null | #include <CDirFTW.h>
#include <ftw.h>
#include <iostream>
typedef int (*FtwProc)(const char *file, const struct stat *sb, int flag, struct FTW *ftw);
CDirFTW *CDirFTW::walk_ = NULL;
CDirFTW::
CDirFTW(const std::string &dirname) :
dirname_(dirname), follow_links_(false), change_dir_(false), debug_(false)
{
}
bool
CDirFTW::
walk()
{
walk_ = this;
#if defined(sun) || defined(__linux__)
int flags = 0;
if (! getFollowLinks()) flags |= FTW_PHYS;
if (! getChangeDir ()) flags |= FTW_CHDIR;
nftw(dirname_.c_str(), (FtwProc) CDirFTW::processCB, 10, flags);
#else
ftw (dirname_.c_str(), (FtwProc) CDirFTW::processCB, 10);
#endif
return true;
}
int
CDirFTW::
#if defined(sun) || defined(__linux__)
processCB(const char *filename, struct stat *stat, int type)
#else
processCB(const char *filename, struct stat *stat, int type, struct FTW *)
#endif
{
if (walk_->getDebug()) {
switch (type) {
case FTW_D : std::cerr << "Dir : " << filename << std::endl; break;
case FTW_DNR: std::cerr << "DirE: " << filename << std::endl; break;
case FTW_DP : std::cerr << "DirP: " << filename << std::endl; break;
case FTW_F : std::cerr << "File: " << filename << std::endl; break;
case FTW_NS : std::cerr << "LnkE: " << filename << std::endl; break;
case FTW_SL : std::cerr << "Lnk : " << filename << std::endl; break;
case FTW_SLN: std::cerr << "LnkN: " << filename << std::endl; break;
default : std::cerr << "?? : " << filename << std::endl; break;
}
}
if (type == FTW_NS)
return 0;
CFileType file_type = CFILE_TYPE_INODE_REG;
if (type == FTW_D || type == FTW_DNR || type == FTW_DP)
file_type = CFILE_TYPE_INODE_DIR;
walk_->callProcess(filename, stat, file_type);
return 0;
}
void
CDirFTW::
callProcess(const char *filename, struct stat *stat, CFileType type)
{
filename_ = filename;
stat_ = stat;
type_ = type;
process();
}
| 23.938272 | 91 | 0.626096 | colinw7 |
ed3723efd8501d72d40c6428e25d6fe8bf1f9734 | 113 | hpp | C++ | src/afk/io/Time.hpp | christocs/ICT398 | 9fd7c17a72985ac2eb59a13c1d3761598e544771 | [
"ISC"
] | null | null | null | src/afk/io/Time.hpp | christocs/ICT398 | 9fd7c17a72985ac2eb59a13c1d3761598e544771 | [
"ISC"
] | null | null | null | src/afk/io/Time.hpp | christocs/ICT398 | 9fd7c17a72985ac2eb59a13c1d3761598e544771 | [
"ISC"
] | null | null | null | #pragma once
#include <string>
namespace afk {
namespace io {
auto get_date_time() -> std::string;
}
}
| 11.3 | 40 | 0.637168 | christocs |
ed37816ab920205a9631d33a5a5ec9ad7362cd8e | 413 | cpp | C++ | CPP.Part_2/week_4/01.Error_Handling/static_assert.cpp | DGolgovsky/Courses | 01e2dedc06f677bcdb1cbfd02ccc08a89cc932a0 | [
"Unlicense"
] | 4 | 2017-11-17T12:02:21.000Z | 2021-02-08T11:24:16.000Z | CPP.Part_2/week_4/01.Error_Handling/static_assert.cpp | DGolgovsky/Courses | 01e2dedc06f677bcdb1cbfd02ccc08a89cc932a0 | [
"Unlicense"
] | null | null | null | CPP.Part_2/week_4/01.Error_Handling/static_assert.cpp | DGolgovsky/Courses | 01e2dedc06f677bcdb1cbfd02ccc08a89cc932a0 | [
"Unlicense"
] | null | null | null | #include <type_traits>
#include <iostream>
//#define NDEBUG
#include <cassert> // assert
template<class T>
void countdown(T start) {
// Compile time
static_assert(std::is_integral<T>::value
&& std::is_signed<T>::value,
"Requires signed integral type");
assert(start >= 0); // Runtime error
while (start >= 0) {
std::cout << start-- << std::endl;
}
}
| 22.944444 | 51 | 0.581114 | DGolgovsky |
ed3796b61b2e82dd4989bf22aa03ee38e46c92fc | 381 | cpp | C++ | Array/zhangjunwei/6.28-7.4/reverseList.cpp | JessonYue/LeetCodeLearning | 3c22a4fcdfe8b47f9f64b939c8b27742c4e30b79 | [
"MIT"
] | 39 | 2020-05-31T06:14:39.000Z | 2021-01-09T11:06:39.000Z | Array/zhangjunwei/6.28-7.4/reverseList.cpp | JessonYue/LeetCodeLearning | 3c22a4fcdfe8b47f9f64b939c8b27742c4e30b79 | [
"MIT"
] | 7 | 2020-06-02T11:04:14.000Z | 2020-06-11T14:11:58.000Z | Array/zhangjunwei/6.28-7.4/reverseList.cpp | JessonYue/LeetCodeLearning | 3c22a4fcdfe8b47f9f64b939c8b27742c4e30b79 | [
"MIT"
] | 20 | 2020-05-31T06:21:57.000Z | 2020-10-01T04:48:38.000Z | //
// Created by 张俊伟 on 2020/7/1.
//
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode *reverseList(struct ListNode *head) {
struct ListNode *pre = nullptr;
struct ListNode *cur = head;
while (cur!= nullptr){
struct ListNode *temp = cur->next;
cur->next = pre;
pre = cur;
cur = temp;
}
return pre;
} | 18.142857 | 53 | 0.572178 | JessonYue |
ed3955cdc3fd6a96e8232f765fdf5de4d43dc086 | 5,862 | hxx | C++ | main/svx/inc/svx/fmview.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/svx/inc/svx/fmview.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/svx/inc/svx/fmview.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
#ifndef _SVX_FMVIEW_HXX
#define _SVX_FMVIEW_HXX
#include <svx/view3d.hxx>
#include <comphelper/uno3.hxx>
#include "svx/svxdllapi.h"
FORWARD_DECLARE_INTERFACE(util,XNumberFormats)
FORWARD_DECLARE_INTERFACE(beans,XPropertySet)
class OutputDevice;
class FmFormModel;
class FmPageViewWinRec;
class FmFormObj;
class FmFormPage;
class FmFormShell;
class FmXFormView;
namespace svx {
class ODataAccessDescriptor;
struct OXFormsDescriptor;
}
class SdrUnoObj;
namespace com { namespace sun { namespace star { namespace form {
class XForm;
namespace runtime {
class XFormController;
}
} } } }
class SVX_DLLPUBLIC FmFormView : public E3dView
{
FmXFormView* pImpl;
FmFormShell* pFormShell;
void Init();
public:
TYPEINFO();
FmFormView(FmFormModel* pModel, OutputDevice* pOut = 0L);
virtual ~FmFormView();
/** create a control pair (label/bound control) for the database field description given.
@param rFieldDesc
description of the field. see clipboard format SBA-FIELDFORMAT
@deprecated
This method is deprecated. Use the version with a ODataAccessDescriptor instead.
*/
SdrObject* CreateFieldControl(const UniString& rFieldDesc) const;
/** create a control pair (label/bound control) for the database field description given.
*/
SdrObject* CreateFieldControl( const ::svx::ODataAccessDescriptor& _rColumnDescriptor );
/** create a control pair (label/bound control) for the xforms description given.
*/
SdrObject* CreateXFormsControl( const ::svx::OXFormsDescriptor &_rDesc );
virtual void MarkListHasChanged();
virtual void AddWindowToPaintView(OutputDevice* pNewWin);
virtual void DeleteWindowFromPaintView(OutputDevice* pOldWin);
static void createControlLabelPair(
OutputDevice* _pOutDev,
sal_Int32 _nXOffsetMM,
sal_Int32 _nYOffsetMM,
const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxField,
const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormats >& _rxNumberFormats,
sal_uInt16 _nControlObjectID,
const ::rtl::OUString& _rFieldPostfix,
sal_uInt32 _nInventor,
sal_uInt16 _nLabelObjectID,
SdrPage* _pLabelPage,
SdrPage* _pControlPage,
SdrModel* _pModel,
SdrUnoObj*& _rpLabel,
SdrUnoObj*& _rpControl
);
virtual SdrPageView* ShowSdrPage(SdrPage* pPage);
virtual void HideSdrPage();
// for copying complete form structures, not only control models
virtual SdrModel* GetMarkedObjModel() const;
using E3dView::Paste;
virtual sal_Bool Paste(const SdrModel& rMod, const Point& rPos, SdrObjList* pLst=NULL, sal_uInt32 nOptions=0);
virtual sal_Bool MouseButtonDown( const MouseEvent& _rMEvt, Window* _pWin );
/** grab the focus to the first form control on the view
@param _bForceSync
<TRUE/> if the handling should be done synchronously.
*/
SVX_DLLPRIVATE void GrabFirstControlFocus( sal_Bool _bForceSync = sal_False );
/** returns the form controller for a given form and a given device
*/
SVX_DLLPRIVATE ::com::sun::star::uno::Reference< ::com::sun::star::form::runtime::XFormController >
GetFormController( const ::com::sun::star::uno::Reference< ::com::sun::star::form::XForm >& _rxForm, const OutputDevice& _rDevice ) const;
// SdrView
sal_Bool KeyInput(const KeyEvent& rKEvt, Window* pWin);
/// shortcut to "GetSdrPageView() ? PTR_CAST( FmFormPage, GetSdrPageView() ) : NULL"
FmFormPage* GetCurPage();
SVX_DLLPRIVATE void ActivateControls(SdrPageView*);
SVX_DLLPRIVATE void DeactivateControls(SdrPageView*);
SVX_DLLPRIVATE void ChangeDesignMode(sal_Bool bDesign);
SVX_DLLPRIVATE FmXFormView* GetImpl() const { return pImpl; }
SVX_DLLPRIVATE FmFormShell* GetFormShell() const { return pFormShell; }
struct FormShellAccess { friend class FmFormShell; private: FormShellAccess() { } };
void SetFormShell( FmFormShell* pShell, FormShellAccess ) { pFormShell = pShell; }
struct ImplAccess { friend class FmXFormView; private: ImplAccess() { } };
void SetMoveOutside( bool _bMoveOutside, ImplAccess ) { E3dView::SetMoveOutside( _bMoveOutside ); }
virtual void InsertControlContainer(const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlContainer >& xCC);
virtual void RemoveControlContainer(const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlContainer >& xCC);
virtual SdrPaintWindow* BeginCompleteRedraw(OutputDevice* pOut);
virtual void EndCompleteRedraw(SdrPaintWindow& rPaintWindow, bool bPaintFormLayer);
SVX_DLLPRIVATE const OutputDevice* GetActualOutDev() const {return pActualOutDev;}
SVX_DLLPRIVATE sal_Bool checkUnMarkAll(const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _xSource);
private:
SVX_DLLPRIVATE void AdjustMarks(const SdrMarkList& rMarkList);
SVX_DLLPRIVATE FmFormObj* getMarkedGrid() const;
protected:
using E3dView::SetMoveOutside;
};
#endif // _FML_FMVIEW_HXX
| 35.96319 | 150 | 0.73695 | Grosskopf |
ed397e564c1f568a424b6ed732a044d20946b591 | 25,953 | cc | C++ | src/canoe/filter_models.cc | nrc-cnrc/Portage-SMT-TAS | 73f5a65de4adfa13008ea9a01758385c97526059 | [
"MIT"
] | null | null | null | src/canoe/filter_models.cc | nrc-cnrc/Portage-SMT-TAS | 73f5a65de4adfa13008ea9a01758385c97526059 | [
"MIT"
] | null | null | null | src/canoe/filter_models.cc | nrc-cnrc/Portage-SMT-TAS | 73f5a65de4adfa13008ea9a01758385c97526059 | [
"MIT"
] | null | null | null | /**
* @author Samuel Larkin
* @file filter_models.cc
* @brief Program that filters TMs and LMs.
*
* LMs & TMs filtering
*
* Technologies langagieres interactives / Interactive Language Technologies
* Inst. de technologie de l'information / Institute for Information Technology
* Conseil national de recherches Canada / National Research Council Canada
* Copyright 2004, Sa Majeste la Reine du Chef du Canada /
* Copyright 2004, Her Majesty in Right of Canada
*/
#include "filter_models.h"
#include "exception_dump.h"
#include "printCopyright.h"
#include "config_io.h"
#include "phrasetable_filter_grep.h"
#include "phrasetable_filter_joint.h"
#include "phrasetable_filter_lm.h"
#include "inputparser.h"
#include "basicmodel.h"
#include "lm.h"
#include "lmtext.h" // LMText::isA
#include <sstream>
using namespace std;
using namespace Portage;
using namespace Portage::filter_models;
/******************************************************************************
Here's a graph of all possible LM/TM filtering
,-LM-+-filter_LM
|
-+ ,-filter_grep
| |
| +-online--+-tm_hard_limit-+-complete
| | | `-src-grep
`-TM-+ `-tm_soft_limit-+-complete
| `-src-grep
|
`-general-+-tm_hard_limit-+-complete
| `-src-grep
`-tm_soft_limit-+-complete
`-src-grep
online => not in memory, processing on the fly TMs must be sorted
general => loaded in memory before processing
tm_hard_limit => tm_hard_limit_weights -> exactly L or less entries are kept
tm_soft_limit => LimitTM in Badr et al, 2007
complete => all TM entries are processed no filtering based on source sentences is done
src-grep => source are required and are used to prefilter the phrase table entries
******************************************************************************/
/// Logger for filter_models
Logging::logger filter_models_Logger(Logging::getLogger("verbose.canoe.filter_models"));
/**
*
* @return Returns true if a filtered CPT was created.
*/
bool processOnline(const CanoeConfig& c, const ARG& arg,
VocabFilter& tgt_vocab, const VectorPSrcSent& src_sents)
{
LOG_VERBOSE1(filter_models_Logger, "Processing online/streaming");
// In online mode there can only be one multiTM and we must be
// in either hard or soft mode
if (!(arg.limit() && c.multiProbTMFiles.size() == 1))
error(ETFatal, "When using the tm-online mode there can only be one multi-prob TM!");
const string filename = c.multiProbTMFiles.front();
// What's the final cpt filename.
const string filtered_cpt_filename = arg.prepareFilename(arg.limit_file);
// If the filtered TM exists there is nothing to do.
if (arg.isReadOnly(filtered_cpt_filename)) {
error(ETWarn, "Translation Model %s has already been filtered. Skipping...", filename.c_str());
return false;
}
else if (arg.isReadOnlyOnDisk(filtered_cpt_filename)) {
error(ETWarn,
"Cannot filter %s since %s is read-only.",
filename.c_str(),
filtered_cpt_filename.c_str());
return false;
}
error_unless_exists(filename, true, "translation model");
// Instanciate the proper pruning style.
const pruningStyle* pruning_style = pruningStyle::create(arg.pruning_strategy_switch, c.phraseTableSizeLimit);
assert(pruning_style);
PhraseTableFilterJoint phraseTable(
arg.limitPhrases(),
tgt_vocab,
pruning_style,
arg.phraseTablePruneType,
c.forwardWeights,
c.transWeights,
arg.tm_hard_limit,
c.appendJointCounts);
// Parses the input source sentences
phraseTable.addSourceSentences(src_sents);
// Do the actual online filtering.
phraseTable.filter(filename, filtered_cpt_filename);
delete pruning_style; pruning_style = NULL;
return true;
}
/**
* Program filter_models's entry point.
* @return Returns 0 if successful.
*/
int MAIN(argc, argv)
{
typedef vector<string> FileList;
typedef FileList::iterator FL_iterator;
printCopyright(2006, "filter_models");
ARG arg(argc, argv);
CanoeConfig c;
c.read(arg.config.c_str());
c.check(); // Check that the canoe.ini file is coherent
if (arg.phraseTablePruneType.empty())
arg.phraseTablePruneType = c.phraseTablePruneType;
const Uint ttable_limit_from_config = c.phraseTableSizeLimit; // save for write-back
if (arg.ttable_limit >= 0) // use ttable_limit for pruning, instead of config file value
c.phraseTableSizeLimit = Uint(arg.ttable_limit);
if (arg.limit() && arg.phraseTablePruneType == "full") {
error(ETWarn, "filter_models -tm-soft-limit or -tm-hard-limit implements \"-ttable-prune-type full\" approximately.\n");
if (arg.ttable_limit < 0 && arg.pruning_strategy_switch.empty()) {
c.phraseTableSizeLimit = (1.0 + arg.full_prune_extra/100.0) * c.phraseTableSizeLimit;
error(ETWarn, "Increasing -ttable-limit by %u%% -- to %u -- to compensate for approximated \"full\" implementation.",
arg.full_prune_extra, c.phraseTableSizeLimit);
}
}
if (arg.filterLDMs and c.LDMFiles.empty()) {
error(ETWarn, "You asked to filter lexicalized DMs but your config file doesn't contain any.");
// Disable filtering LDMs since there are no LDMs in the canoe.ini file.
arg.filterLDMs = false;
}
// Print the requested running mode from user
if (arg.verbose) {
if (arg.tm_online) cerr << " Running in online / streaming mode" << endl;
else cerr << " Running in load all in memory" << endl;
if (arg.no_src_grep) cerr << " Running without source sentences => processing all table entries" << endl;
else cerr << " Running with source sentences => filtering phrase table base on source phrases" << endl;
if (arg.tm_soft_limit) cerr << " Running in SOFT mode using limit(" << c.phraseTableSizeLimit << ")" << endl;
if (arg.tm_hard_limit) cerr << " Running in HARD mode using limit(" << c.phraseTableSizeLimit << ")" << endl;
}
if (arg.tm_online) error(ETWarn, "Be sure that your phrasetable is sorted before calling filter_models (LC_ALL=C)");
// Setting the value of log_almost_zero
PhraseTable::log_almost_0 = c.phraseTableLogZero;
// Prepares the source sentences
VectorPSrcSent src_sents;
if (arg.limitPhrases()) {
LOG_VERBOSE1(filter_models_Logger, "Loading source sentences");
string line;
iSafeMagicStream is(arg.input);
InputParser reader(is);
PSrcSent ss;
while (ss = reader.getMarkedSent())
src_sents.push_back(ss);
if (src_sents.empty())
error(ETFatal, "No source sentences, nothing to do! (or did you forget to say -no-src-grep?");
else
cerr << "Using " << src_sents.size() << " source sentences" << endl;
}
// CHECKING consistency in user's request.
LOG_VERBOSE1(filter_models_Logger, "Consistency check of user's request");
// Logic checking
if (arg.limit() and !c.allNonMultiProbPTs.empty())
error(ETFatal, "You can't use limit aka filter30 with ttables other than multi-prob ones");
if (arg.limit() and !(c.phraseTableSizeLimit > NO_SIZE_LIMIT))
error(ETFatal, "You're using filter TM, please set a value greater than 0 to [ttable-limit]");
// When using tm hard limit, user must provide the tms-weights
if (arg.tm_hard_limit and c.transWeights.empty())
error(ETFatal, "You must provide the TMs weights when doing a tm_hard_limit");
if (src_sents.empty() and arg.limitPhrases())
error(ETFatal, "You must provide source sentences when doing grep");
if (arg.filterLMs and !c.allNonMultiProbPTs.empty())
error(ETFatal, "Filtering Language Models (-L) only works for multi-prob phrase tables");
if (arg.filterLDMs and (!(arg.limit() or c.multiProbTMFiles.size() == 1))) {
if (arg.limitPhrases())
error(ETWarn, "Filtering LDMs with multiple CPTs and no hard/soft filtering; taking only source phrases into account for LDM filtering, not target phrases.");
else
error(ETFatal, "To filter LDMs, we must either have one cpt or use hard/soft filtering to produce one cpt before filtering LDMs. Alternatively, use filter-grep mode, in which case LDM filtering takes into account source phrases, but not target phrases, as it would normally.");
}
if (arg.filterLDMs and !c.allNonMultiProbPTs.empty()) {
if (arg.limitPhrases())
error(ETWarn, "Filtering LDMs when using phrase tables other than multi-prob takes only source phrases into account for LDM filtering, not target phrases.");
else
error(ETFatal, "Filtering LDMs when using phrase tables other than multi-prob and not limiting phrases is not supported.");
}
// online mode only applies to tm_hard_limit or tm_soft_limit.
if (!arg.limit()) arg.tm_online = false;
// hack - rely on a side effect of maxSourceSentence4filtering to disable
// per-sentence filtering
if ( arg.nopersent ) VocabFilter::maxSourceSentence4filtering = 1;
////////////////////////////////////////
// Changing what to do based on what the user asked for and what has already been done.
if (arg.limit()) {
// What's the final cpt filename.
const string filtered_cpt_filename = arg.prepareFilename(arg.limit_file);
if (check_if_exists(filtered_cpt_filename)) {
if (arg.readonly) {
error(ETWarn, "Translation Model %s has already been filtered. Skipping...", filtered_cpt_filename.c_str());
// The filtered TM already exists thus we don't want to redo the
// work. We will disable soft/hard filtering and also disable grep
// filtering. If the user requested LM filtering, the TM's
// vocabulary will be loaded.
arg.tm_soft_limit = false;
arg.tm_hard_limit = false;
arg.tm_online = false;
arg.no_src_grep = true;
// Change the config file to reflect the new filtered TM.
c.readStatus("ttable-multi-prob") = true;
c.multiProbTMFiles.clear(); // We should end up with only one multi-prob
c.multiProbTMFiles.push_back(filtered_cpt_filename);
}
// The filtered model exists but it's read-only and we are supposed to overwrite it.
// We can't proceed since we should be filtering a new model and thus
// loading the vocabulary for potentially filtering LMs & LDMs.
else if (arg.isReadOnlyOnDisk(filtered_cpt_filename)) {
error(ETFatal,
"Incoherent scenario, a filtered TM exists (%s), is read-only but user want to overwrite. Cannot proceed....",
filtered_cpt_filename.c_str());
}
// The filtered model exists and it's not readonly in any shape or form thus we will generate a new one.
else {
error(ETWarn,
"A filtered TM exists (%s) but we have no indication from the user that we shouldn't overwrite it. Overwriting...",
filtered_cpt_filename.c_str());
}
}
}
else if (arg.limitPhrases()) {
if (c.multiProbTMFiles.size() == 1) {
string& file = c.multiProbTMFiles.front();
const string translationModelFilename = file;
const string filteredTranslationModelFilename = arg.prepareFilename(translationModelFilename);
error_unless_exists(translationModelFilename, true, "translation model");
if (arg.readonly && check_if_exists(filteredTranslationModelFilename)) {
// The filtered version exists let's use the much faster tm vocab loading mechanism with PhraseTable_filter_lm.
if (arg.filterLMs) arg.no_src_grep = true;
file = filteredTranslationModelFilename;
error(ETWarn, "Translation Model %s has already been filtered. Skipping...",
filteredTranslationModelFilename.c_str());
}
else if (arg.isReadOnlyOnDisk(filteredTranslationModelFilename)) {
error(ETFatal, "Cannot filter %s since %s is read-only.",
translationModelFilename.c_str(),
filteredTranslationModelFilename.c_str());
}
}
/*
else
if (arg.filterLDMs)
error(ETFatal, "It is impossible to either filter LDMs in source grep mode unless you only have one TM.");
*/
}
VocabFilter tgt_vocab(src_sents.size());
GlobalVoc::set(&tgt_vocab);
////////////////////////////////////////
// Filter Conditional Phrase Tables.
bool weve_created_a_cpt = false;
// We are doing either soft or hard filtering.
if (arg.limit()) {
// What's the final cpt filename.
const string filtered_cpt_filename = arg.prepareFilename(arg.limit_file);
if (arg.tm_online) {
weve_created_a_cpt = processOnline(c, arg, tgt_vocab, src_sents);
}
else {
// Creating what will be needed for filtering
LOG_VERBOSE1(filter_models_Logger, "Creating the models");
// Get the proper pruning specifier.
const pruningStyle* pruning_style = pruningStyle::create(arg.pruning_strategy_switch, c.phraseTableSizeLimit);
assert(pruning_style != NULL);
PhraseTableFilterJoint phraseTable(
arg.limitPhrases(),
tgt_vocab,
pruning_style,
arg.phraseTablePruneType,
c.forwardWeights,
c.transWeights,
arg.tm_hard_limit,
c.appendJointCounts);
// Parses the input source sentences
phraseTable.addSourceSentences(src_sents);
// Read in memory all Translation Models.
// Side effect: load vocabulary into tgt_vocab.
LOG_VERBOSE1(filter_models_Logger, "Processing multi-probs");
for (FL_iterator file(c.multiProbTMFiles.begin()); file!=c.multiProbTMFiles.end(); ++file) {
LOG_VERBOSE2(filter_models_Logger,
"Translation Model filename: %s", file->c_str());
error_unless_exists(*file, true, "translation model");
// If there exists a filtered version of *file, use it instead.
phraseTable.readMultiProb(*file);
}
LOG_VERBOSE1(filter_models_Logger, "Filtering with filter_joint with: %d", c.phraseTableSizeLimit);
const time_t start_time = time(NULL);
// Perform hard or soft filtering on the in-memory trie strucutre and writes it to disk.
phraseTable.filter(filtered_cpt_filename);
weve_created_a_cpt = true;
delete pruning_style; pruning_style = NULL;
if (arg.verbose) {
cerr << " ... done in " << (time(NULL) - start_time) << "s" << endl;
}
}
// Change the config file to reflect the new filtered TM.
c.readStatus("ttable-multi-prob") = true;
c.multiProbTMFiles.clear(); // We should end up with only one multi-prob
c.multiProbTMFiles.push_back(filtered_cpt_filename);
}
// This is grep filtering.
else if (arg.limitPhrases()) {
// Creating what will be needed for filtering
LOG_VERBOSE1(filter_models_Logger, "Creating the models");
PhraseTableFilterGrep phraseTable(arg.limitPhrases(), tgt_vocab,
arg.phraseTablePruneType, c.appendJointCounts);
// Parses the input source sentences
phraseTable.addSourceSentences(src_sents);
// Add multi-prob TMs to vocab and filter them
LOG_VERBOSE1(filter_models_Logger, "Processing multi-probs");
for (FL_iterator file(c.multiProbTMFiles.begin()); file!=c.multiProbTMFiles.end(); ++file) {
const string translationModelFilename = *file;
const string filteredTranslationModelFilename = arg.prepareFilename(translationModelFilename);
LOG_VERBOSE2(filter_models_Logger,
"Translation Model filename: %s filtered Translation Model filename: %s",
translationModelFilename.c_str(),
filteredTranslationModelFilename.c_str());
error_unless_exists(translationModelFilename, true, "translation model");
if (arg.readonly && check_if_exists(filteredTranslationModelFilename)) {
error(ETWarn, "Translation Model %s has already been filtered. Skipping...",
filteredTranslationModelFilename.c_str());
}
else if (arg.isReadOnlyOnDisk(filteredTranslationModelFilename)) {
error(ETWarn, "Cannot filter %s since %s is read-only.",
translationModelFilename.c_str(),
filteredTranslationModelFilename.c_str());
}
else {
phraseTable.filter(translationModelFilename, filteredTranslationModelFilename);
weve_created_a_cpt = true;
}
*file = filteredTranslationModelFilename;
}
}
// Reading the vocabulary in the TMs in order to filter LMs.
// Here, we don't create a new TM.
else if (arg.filterLMs) {
// PhraseTableFilterLM will not load the phrase table in memory but it will simply populate tgt_vocab.
PhraseTableFilterLM phraseTable(arg.limitPhrases(),
tgt_vocab, arg.phraseTablePruneType, c.appendJointCounts);
// Parses the input source sentences
phraseTable.addSourceSentences(src_sents);
// Add multi-prob TMs to vocab and filter them
if (!c.multiProbTMFiles.empty()) LOG_VERBOSE1(filter_models_Logger, "Processing multi-probs");
for (FL_iterator file(c.multiProbTMFiles.begin()); file!=c.multiProbTMFiles.end(); ++file) {
LOG_VERBOSE2(filter_models_Logger,
"Reading in %s's vocab to filter the LMs.",
file->c_str());
error_unless_exists(*file, true, "translation model");
string filename, dummy;
arg.getFilenames(*file, filename, dummy);
// This function call doesn't actually load the LM in memory but
// rather populates the tgt_vocab for us.
phraseTable.readMultiProb(filename);
}
}
else {
LOG_VERBOSE2(filter_models_Logger, "No filtering of TM was performed.");
}
////////////////////////////////////////
// Filter Language Models.
// In order to filter LMs, we need tgt_vocab to be populated at this point.
if (arg.filterLMs and !c.lmFiles.empty()) {
// We must get the vocab from the TPPTs first
if ( !c.allNonMultiProbPTs.empty() && arg.limitPhrases() && c.lmFiles.size() > 0 ) {
LOG_VERBOSE1(filter_models_Logger, "Extracting vocabulary from TPPTs");
const time_t start_time = time(NULL);
if (arg.verbose)
cerr << "Extracting target vocabulary from TPPTs";
PhraseTable phraseTable(tgt_vocab, NULL, c.appendJointCounts);
phraseTable.extractVocabFromTPPTs(0); // Will extract the TPPT voc into tgt_vocab.
if (arg.verbose) {
cerr << " ... done in " << (time(NULL) - start_time) << "s" << endl;
}
}
// At this point, we must have a populated voc or else filtering will remove everything.
assert(!tgt_vocab.empty());
LOG_VERBOSE1(filter_models_Logger, "Processing Language Models");
for (FL_iterator file(c.lmFiles.begin()); file!=c.lmFiles.end(); ++file) {
// Extract the physical file name.
const size_t hash_pos = file->rfind(PLM::lm_order_separator);
const string lm = file->substr(0, hash_pos);
const string option = (hash_pos != string::npos ? file->substr(hash_pos+1) : "");
const string flm = arg.prepareFilename(lm);
// Let's skip Language Model types that we cannot filter.
if (!LMText::isA(lm)) {
error(ETWarn, "Cannot filter Language Models of types other than ARPA LM! Skipping %s...", lm.c_str());
continue;
}
error_unless_exists(lm, true, "language model");
if (arg.readonly && check_if_exists(flm)) {
error(ETWarn, "Language Model %s has already been filtered. Skipping...", lm.c_str());
}
else if (arg.isReadOnlyOnDisk(flm)) {
error(ETWarn, "Cannot filter %s since %s is read-only.", lm.c_str(), flm.c_str());
}
else {
if (arg.verbose) {
cerr << "loading Language Model from " << lm << " to " << flm << endl;
}
const time_t start_time = time(NULL);
oSafeMagicStream os_filtered(flm);
const PLM *lm_model = PLM::Create(lm, &tgt_vocab, PLM::ClosedVoc,
LOG_ALMOST_0, arg.limitPhrases(), c.lmOrder, &os_filtered);
if (arg.verbose) {
cerr << " ... done in " << (time(NULL) - start_time) << "s" << endl;
}
if (lm_model) { delete lm_model; lm_model = NULL; }
*file = flm + option;
}
}
}
////////////////////////////////////////
// Filter Lexicalized Distortion Models.
if (arg.filterLDMs && !c.LDMFiles.empty()) {
LOG_VERBOSE1(filter_models_Logger, "Processing Lexicalized Distortion Models");
// There can only be one cpt to filter ldms.
if (c.multiProbTMFiles.size() != 1 or !c.allNonMultiProbPTs.empty()) {
if (arg.limitPhrases())
error(ETWarn, "There is more than one CPT or there are other types of phrase tables, so LDM filtering can't look at target phrases; doing filter-grep only on the LDM(s).");
else
error(ETFatal, "In order to filter LDMs, we must have only one CPT and no TPPTs, or do filter-grep.");
}
const string cpt_filename = c.multiProbTMFiles.front();
for (FL_iterator file(c.LDMFiles.begin()); file!=c.LDMFiles.end(); ++file) {
// We don't know how to filter TPLDMs, let's skip it.
if (isSuffix(".tpldm", *file)) {
error(ETWarn, "Cannot filter Lexicalized Distortion Models of TPLDM type (%s)! Skipping...", file->c_str());
continue;
}
error_unless_exists(*file, true, "Lexicalized Distortion Model");
// Don't redo work if there exists a filtered ldm.
const string filtered_ldm = arg.prepareFilename(*file, arg.preserve_ldm_paths);
if (arg.readonly && check_if_exists(filtered_ldm)) {
if (weve_created_a_cpt)
error(ETFatal, "%s hasn't been filtered even though a new cpt was created (%s) since you asked not to overwrite models.",
file->c_str(),
cpt_filename.c_str());
else
error(ETWarn, "Lexicalized Distortion Model %s has already been filtered. Skipping...", file->c_str());
}
else if (arg.isReadOnlyOnDisk(filtered_ldm)) {
error(ETWarn, "Cannot filter %s since %s is read-only.", file->c_str(), filtered_ldm.c_str());
}
else {
if (c.multiProbTMFiles.size() != 1 || !c.allNonMultiProbPTs.empty()) {
assert(arg.limitPhrases());
PhraseTableFilterGrep phraseTable(arg.limitPhrases(),
tgt_vocab, arg.phraseTablePruneType,
c.appendJointCounts);
phraseTable.addSourceSentences(src_sents);
error_unless_exists(*file, true, "LDM");
phraseTable.filter(*file, filtered_ldm);
const string bkoff_file = (isZipFile(*file) ? removeExtension(*file) : *file) + ".bkoff";
const string filt_bkoff_file = (isZipFile(filtered_ldm) ? removeExtension(filtered_ldm) : filtered_ldm) + ".bkoff";
iSafeMagicStream bk_in(bkoff_file.c_str());
oSafeMagicStream bk_out(filt_bkoff_file.c_str());
string line;
while (getline(bk_in, line))
bk_out << line;
} else {
// filter-distortion-model.pl -v ${CPT} ${LDM} ${FLDM}
const string cmd = "filter-distortion-model.pl -v " + cpt_filename
+ " " + *file
+ " " + filtered_ldm;
if (arg.verbose)
cerr << "Filtering LDM using: " << cmd << endl; // SAM DEBUGGING
const int rc = system(cmd.c_str());
if (rc != 0)
error(ETFatal, "Error filtering Lexicalized Distortion Model with filter-distortion-model.pl! (rc=%d)", rc);
// NOTE: the associated .bkoff for the newly filtered LDM will be created by filter-distortion-model.pl.
}
}
// Replace unfiltered ldm in config file with the filtered one.
*file = filtered_ldm;
}
}
// Print out the vocab if necessary
if (arg.vocab_file.size() > 0) {
if (arg.verbose) {
cerr << "Dumping Vocab" << endl;
}
if (tgt_vocab.per_sentence_vocab) {
fprintf(stderr, "Average vocabulary size per source sentences: %f\n",
tgt_vocab.per_sentence_vocab->averageVocabSizePerSentence());
}
oSafeMagicStream os_vocab(arg.vocab_file);
tgt_vocab.write(os_vocab);
}
// Builds a new canoe.ini with the modified models
LOG_VERBOSE1(filter_models_Logger, "Creating new canoe.ini");
const string configFile(addExtension(arg.config, arg.suffix));
if (arg.ttable_limit >= 0) // restore original configfile limit
c.phraseTableSizeLimit = ttable_limit_from_config;
if (arg.output_config) {
if (arg.verbose) {
cerr << "New config file is: " << configFile << endl;
}
c.write(configFile.c_str(), 1, true);
}
} END_MAIN
| 42.826733 | 287 | 0.629908 | nrc-cnrc |
ed407add37f5d554e19b171cfe8f4cbb407845c7 | 4,566 | cpp | C++ | src/vulkan/vulkan-commandlist.cpp | Zwingling/nvrhi | 12f3e12eb29b681e99a53af7347c60c0733a6ef9 | [
"MIT"
] | 325 | 2021-07-19T13:55:23.000Z | 2022-03-31T20:38:58.000Z | src/vulkan/vulkan-commandlist.cpp | Zwingling/nvrhi | 12f3e12eb29b681e99a53af7347c60c0733a6ef9 | [
"MIT"
] | 11 | 2021-07-20T00:15:59.000Z | 2022-03-12T08:50:33.000Z | src/vulkan/vulkan-commandlist.cpp | Zwingling/nvrhi | 12f3e12eb29b681e99a53af7347c60c0733a6ef9 | [
"MIT"
] | 38 | 2021-07-19T15:04:17.000Z | 2022-03-28T09:09:09.000Z | /*
* Copyright (c) 2014-2021, NVIDIA CORPORATION. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include "vulkan-backend.h"
namespace nvrhi::vulkan
{
CommandList::CommandList(Device* device, const VulkanContext& context, const CommandListParameters& parameters)
: m_Device(device)
, m_Context(context)
, m_CommandListParameters(parameters)
, m_StateTracker(context.messageCallback)
, m_UploadManager(std::make_unique<UploadManager>(device, parameters.uploadChunkSize, 0, false))
, m_ScratchManager(std::make_unique<UploadManager>(device, parameters.scratchChunkSize, parameters.scratchMaxMemory, true))
{
}
nvrhi::Object CommandList::getNativeObject(ObjectType objectType)
{
switch (objectType)
{
case ObjectTypes::VK_CommandBuffer:
return Object(m_CurrentCmdBuf->cmdBuf);
default:
return nullptr;
}
}
void CommandList::open()
{
m_CurrentCmdBuf = m_Device->getQueue(m_CommandListParameters.queueType)->getOrCreateCommandBuffer();
auto beginInfo = vk::CommandBufferBeginInfo()
.setFlags(vk::CommandBufferUsageFlagBits::eOneTimeSubmit);
(void)m_CurrentCmdBuf->cmdBuf.begin(&beginInfo);
m_CurrentCmdBuf->referencedResources.push_back(this); // prevent deletion of e.g. UploadManager
clearState();
}
void CommandList::close()
{
endRenderPass();
m_StateTracker.keepBufferInitialStates();
m_StateTracker.keepTextureInitialStates();
commitBarriers();
#ifdef NVRHI_WITH_RTXMU
if (!m_CurrentCmdBuf->rtxmuBuildIds.empty())
{
m_Context.rtxMemUtil->PopulateCompactionSizeCopiesCommandList(m_CurrentCmdBuf->cmdBuf, m_CurrentCmdBuf->rtxmuBuildIds);
}
#endif
m_CurrentCmdBuf->cmdBuf.end();
clearState();
flushVolatileBufferWrites();
}
void CommandList::clearState()
{
endRenderPass();
m_CurrentPipelineLayout = vk::PipelineLayout();
m_CurrentPipelineShaderStages = vk::ShaderStageFlagBits();
m_CurrentGraphicsState = GraphicsState();
m_CurrentComputeState = ComputeState();
m_CurrentMeshletState = MeshletState();
m_CurrentRayTracingState = rt::State();
m_CurrentShaderTablePointers = ShaderTableState();
m_AnyVolatileBufferWrites = false;
// TODO: add real context clearing code here
}
void CommandList::setPushConstants(const void* data, size_t byteSize)
{
assert(m_CurrentCmdBuf);
m_CurrentCmdBuf->cmdBuf.pushConstants(m_CurrentPipelineLayout, m_CurrentPipelineShaderStages, 0, uint32_t(byteSize), data);
}
void CommandList::executed(Queue& queue, const uint64_t submissionID)
{
assert(m_CurrentCmdBuf);
m_CurrentCmdBuf->submissionID = submissionID;
const CommandQueue queueID = queue.getQueueID();
const uint64_t recordingID = m_CurrentCmdBuf->recordingID;
m_CurrentCmdBuf = nullptr;
submitVolatileBuffers(recordingID, submissionID);
m_StateTracker.commandListSubmitted();
m_UploadManager->submitChunks(
MakeVersion(recordingID, queueID, false),
MakeVersion(submissionID, queueID, true));
m_ScratchManager->submitChunks(
MakeVersion(recordingID, queueID, false),
MakeVersion(submissionID, queueID, true));
m_VolatileBufferStates.clear();
}
} | 33.822222 | 131 | 0.70127 | Zwingling |
ed45890d5c7aa5f43dd8b1a6cf0b617a7507517f | 507 | cpp | C++ | Gems/LyShine/Code/Editor/UndoStackExecutionScope.cpp | aaarsene/o3de | 37e3b0226958974defd14dd6d808e8557dcd7345 | [
"Apache-2.0",
"MIT"
] | 1 | 2021-09-13T00:01:12.000Z | 2021-09-13T00:01:12.000Z | Gems/LyShine/Code/Editor/UndoStackExecutionScope.cpp | aaarsene/o3de | 37e3b0226958974defd14dd6d808e8557dcd7345 | [
"Apache-2.0",
"MIT"
] | null | null | null | Gems/LyShine/Code/Editor/UndoStackExecutionScope.cpp | aaarsene/o3de | 37e3b0226958974defd14dd6d808e8557dcd7345 | [
"Apache-2.0",
"MIT"
] | 1 | 2021-07-20T11:07:25.000Z | 2021-07-20T11:07:25.000Z | /*
* Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include "UiCanvasEditor_precompiled.h"
#include "EditorCommon.h"
UndoStackExecutionScope::UndoStackExecutionScope(UndoStack* stack)
: m_stack(stack)
{
m_stack->SetIsExecuting(true);
}
UndoStackExecutionScope::~UndoStackExecutionScope()
{
m_stack->SetIsExecuting(false);
}
| 24.142857 | 158 | 0.757396 | aaarsene |
ed458e377aa8dc1d93a06d53c26c7680ac9fcdb0 | 4,296 | cpp | C++ | listen/tcp_listen_service.cpp | zhangdongai/libnetxcq | 59007e9cfa78a6ff2a8f2cf9c652a4e0cfc5c65d | [
"Apache-2.0"
] | null | null | null | listen/tcp_listen_service.cpp | zhangdongai/libnetxcq | 59007e9cfa78a6ff2a8f2cf9c652a4e0cfc5c65d | [
"Apache-2.0"
] | null | null | null | listen/tcp_listen_service.cpp | zhangdongai/libnetxcq | 59007e9cfa78a6ff2a8f2cf9c652a4e0cfc5c65d | [
"Apache-2.0"
] | null | null | null | #include "listen/tcp_listen_service.h"
#include <string.h>
#include "log/log.h"
#include "common/config/listen_flags.h"
#include "connector/connector_manager.h"
TCPListenService::TCPListenService() {
stop_ = false;
}
TCPListenService::~TCPListenService() {
stop();
close(listen_fd_);
}
void TCPListenService::stop() {
ListenService::stop();
}
void TCPListenService::init_config() {
}
bool TCPListenService::init_socket() {
DEBUG_LOG("listen port = %d", FLAGS_port);
DEBUG_LOG("communication type = %s", FLAGS_communication_type.c_str());
struct sockaddr_in listen_addr;
listen_fd_ = socket(AF_INET, SOCK_STREAM, 0);
bzero(&listen_addr, sizeof(listen_addr));
listen_addr.sin_family = AF_INET;
listen_addr.sin_port = htons(FLAGS_port);
listen_addr.sin_addr.s_addr = htonl(INADDR_ANY);
int ret = bind(listen_fd_, (struct sockaddr*)&listen_addr, sizeof(listen_addr));
if (ret == invalid_id) {
const char* error = "error occured while bind";
switch (errno) {
case EADDRINUSE:
error = "The given address is already in use";
break;
case EINVAL:
error = "The socket is already bound to an address.";
break;
default:
break;
}
ERROR_LOG(error);
close(listen_fd_);
return false;
}
listen(listen_fd_, 256);
epoll_fd_ = epoll_create(MAX_EVENT);
if (epoll_fd_ == invalid_id) {
ERROR_LOG("create epoll error!");
close(listen_fd_);
return false;
}
struct epoll_event event;
event.data.fd = listen_fd_;
event.events = EPOLLIN | EPOLLHUP |EPOLLERR;
ret = epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, listen_fd_, &event);
if (ret == invalid_id) {
ERROR_LOG("add epoll error!");
close(listen_fd_);
return false;
}
DEBUG_LOG("create socket success!");
return true;
}
void TCPListenService::run_logic() {
ListenService::run_logic();
// init ConnectorManager
ConnectorManager::instance();
}
void TCPListenService::main_loop() {
struct epoll_event events[MAX_EVENT];
while(!stop_) {
int fds = epoll_wait(epoll_fd_, events, MAX_EVENT, 100);
for (int i = 0; i < fds; ++i) {
struct epoll_event& tmp_ev = events[i];
if (tmp_ev.data.fd == listen_fd_) {
accept_connection();
}
else if (tmp_ev.events & EPOLLIN) {
}
else if (tmp_ev.events & EPOLLOUT) {
}
}
}
}
bool TCPListenService::accept_connection() {
struct sockaddr_in socket_in;
socklen_t socket_len = sizeof(struct sockaddr_in);
int new_socket_fd = accept(listen_fd_, (struct sockaddr*)&socket_in, &socket_len);
if (new_socket_fd == -1) {
const char* err_con = nullptr;
switch(errno) {
case EAGAIN:
err_con = "The socket is marked nonblocking and no connections are "
"present to be accepted";
break;
case EBADF:
err_con = "sockfd is not an open file descriptor";
break;
case EFAULT:
err_con = "The addr argument is not in a writable part of the user "
"address space";
break;
case EINTR:
err_con = "The system call was interrupted by a signal";
break;
case EINVAL:
err_con = "Socket is not listening for connections, or addrlen is invalid";
break;
case ENOMEM:
err_con = "Not enough free memory";
break;
case EPERM:
err_con = "Firewall rules forbid connection";
break;
default:
err_con = "unknown error";
break;
}
ERROR_LOG(err_con);
return false;
}
const char* addr_in = inet_ntoa(socket_in.sin_addr);
DEBUG_LOG("establish connection from %s", addr_in);
int flag = fcntl(new_socket_fd, F_GETFL, 0);
int ret = fcntl(new_socket_fd, F_SETFL, flag | O_NONBLOCK);
if (ret == invalid_id) {
ERROR_LOG("set non block for socket %d failed, errno = %d", new_socket_fd, ret);
return false;
}
ConnectorManager::instance()->accept_connector(new_socket_fd);
return true;
}
| 28.832215 | 88 | 0.606378 | zhangdongai |
ed45e39629ea753cba0b162fae5f90771da878a1 | 2,189 | cc | C++ | src/libc/wchar/wmemmem_test.cc | NuxiNL/CloudLibc | d361c06c3fab3a7814d05b4630abe6da0cc7d757 | [
"BSD-2-Clause"
] | 298 | 2015-03-04T13:36:51.000Z | 2021-12-19T05:11:58.000Z | src/libc/wchar/wmemmem_test.cc | NuxiNL/CloudLibc | d361c06c3fab3a7814d05b4630abe6da0cc7d757 | [
"BSD-2-Clause"
] | 31 | 2015-07-27T14:51:55.000Z | 2020-09-14T15:59:57.000Z | src/libc/wchar/wmemmem_test.cc | NuxiNL/CloudLibc | d361c06c3fab3a7814d05b4630abe6da0cc7d757 | [
"BSD-2-Clause"
] | 18 | 2016-03-27T13:49:22.000Z | 2021-09-21T19:02:04.000Z | // Copyright (c) 2016 Nuxi, https://nuxi.nl/
//
// SPDX-License-Identifier: BSD-2-Clause
#include <stdbool.h>
#include <stdlib.h>
#include <wchar.h>
#include <iterator>
#include "gtest/gtest.h"
TEST(wmemmem, null) {
// wmemmem() should not attempt to access any buffers if the needle
// has length 0 or is larger than the haystack.
ASSERT_EQ(NULL, wmemmem(NULL, 0, NULL, 123));
ASSERT_EQ(NULL, wmemmem(NULL, 123, NULL, 0));
ASSERT_EQ(NULL, wmemmem(NULL, 123, NULL, 456));
}
TEST(wmemmem, examples) {
const wchar_t *str = L"Hello world";
ASSERT_EQ(str + 4, wmemmem(str, 11, L"o worl", 6));
ASSERT_EQ(NULL, wmemmem(str, 11, L"o worl", 7));
ASSERT_EQ(str + 6, wmemmem(str, 11, L"world", 5));
ASSERT_EQ(NULL, wmemmem(str, 11, L"world", 6));
ASSERT_EQ(str + 6, wmemmem(str, 12, L"world", 6));
ASSERT_EQ(NULL, wmemmem(str, 11, L"word", 4));
ASSERT_EQ(NULL, wmemmem(str, 11, L"world!", 6));
}
// Fills a buffer with random letters between A and D.
static void fill_random(wchar_t *buf, size_t len) {
arc4random_buf(buf, len * sizeof(wchar_t));
for (size_t i = 0; i < len; ++i)
buf[i] = (buf[i] & 0x3) + L'A';
}
// Performs a naïve wmemmem() operation.
static wchar_t *naive_memmem(const wchar_t *haystack, size_t haystacklen,
const wchar_t *needle, size_t needlelen) {
if (needlelen > haystacklen)
return NULL;
for (size_t i = 0; i + needlelen <= haystacklen; ++i) {
bool match = true;
for (size_t j = 0; j < needlelen; ++j) {
if (haystack[i + j] != needle[j]) {
match = false;
break;
}
}
if (match)
return (wchar_t *)haystack + i;
}
return NULL;
}
// Compares the output of wmemmem() against a naïve implementation.
TEST(wmemmem, random) {
for (size_t i = 0; i < 1000; ++i) {
wchar_t haystack[40000];
wchar_t needle[8];
size_t needlelen = arc4random_uniform(std::size(needle));
SCOPED_TRACE(needlelen);
fill_random(haystack, std::size(haystack));
fill_random(needle, needlelen);
ASSERT_EQ(naive_memmem(haystack, std::size(haystack), needle, needlelen),
wmemmem(haystack, std::size(haystack), needle, needlelen));
}
}
| 31.271429 | 77 | 0.637734 | NuxiNL |
ed464ebdac73f3e0f61523fed818c13bac3326f4 | 35 | cpp | C++ | Reference/BITs Manipulation/Is Odd.cpp | searleser97/Algorithms | af791541d416c29867213d705375cbb3361f486c | [
"Apache-2.0"
] | 7 | 2019-06-06T17:54:20.000Z | 2021-03-24T02:31:55.000Z | Reference/BITs Manipulation/Is Odd.cpp | searleser97/Algorithms | af791541d416c29867213d705375cbb3361f486c | [
"Apache-2.0"
] | null | null | null | Reference/BITs Manipulation/Is Odd.cpp | searleser97/Algorithms | af791541d416c29867213d705375cbb3361f486c | [
"Apache-2.0"
] | 1 | 2021-03-24T02:31:57.000Z | 2021-03-24T02:31:57.000Z | bool isOdd(int n) { return n & 1; } | 35 | 35 | 0.6 | searleser97 |
ed484f059f358a65e49a0ae7051b35f682d81bbc | 27,224 | hpp | C++ | src/3rd/Simd/Simd/SimdDetection.hpp | inger147/AntiDupl | fb331c6312783bb74a62aa2efffcb7f5a5a54d3d | [
"MIT"
] | 674 | 2018-01-09T19:13:40.000Z | 2022-03-29T19:54:35.000Z | src/3rd/Simd/Simd/SimdDetection.hpp | inger147/AntiDupl | fb331c6312783bb74a62aa2efffcb7f5a5a54d3d | [
"MIT"
] | 124 | 2018-01-09T08:12:45.000Z | 2022-03-28T14:19:49.000Z | src/3rd/Simd/Simd/SimdDetection.hpp | inger147/AntiDupl | fb331c6312783bb74a62aa2efffcb7f5a5a54d3d | [
"MIT"
] | 78 | 2018-01-11T03:09:43.000Z | 2022-03-20T17:43:39.000Z | /*
* Simd Library (http://ermig1979.github.io/Simd).
*
* Copyright (c) 2011-2020 Yermalayeu Ihar,
* 2019-2019 Facundo Galan.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef __SimdDetection_hpp__
#define __SimdDetection_hpp__
#include "Simd/SimdLib.hpp"
#include "Simd/SimdParallel.hpp"
#include <vector>
#include <map>
#include <memory>
#include <limits.h>
#ifndef SIMD_CHECK_PERFORMANCE
#define SIMD_CHECK_PERFORMANCE()
#endif
namespace Simd
{
/*! @ingroup cpp_detection
\short The Detection structure provides object detection with using of HAAR and LBP cascade classifiers.
Using example (face detection in the image):
\code
#include "Simd/SimdDetection.hpp"
#include "Simd/SimdDrawing.hpp"
int main()
{
typedef Simd::Detection<Simd::Allocator> Detection;
Detection::View image;
image.Load("../../data/image/face/lena.pgm");
Detection detection;
detection.Load("../../data/cascade/haar_face_0.xml");
detection.Init(image.Size());
Detection::Objects objects;
detection.Detect(image, objects);
for (size_t i = 0; i < objects.size(); ++i)
Simd::DrawRectangle(image, objects[i].rect, uint8_t(255));
image.Save("result.pgm");
return 0;
}
\endcode
Using example (face detection in the video captured by OpenCV):
\code
#include <iostream>
#include <string>
#include "opencv2/opencv.hpp"
#ifndef SIMD_OPENCV_ENABLE
#define SIMD_OPENCV_ENABLE
#endif
#include "Simd/SimdDetection.hpp"
#include "Simd/SimdDrawing.hpp"
int main(int argc, char * argv[])
{
if (argc < 2)
{
std::cout << "You have to set video source! It can be 0 for camera or video file name." << std::endl;
return 1;
}
std::string source = argv[1];
cv::VideoCapture capture;
if (source == "0")
capture.open(0);
else
capture.open(source);
if (!capture.isOpened())
{
std::cout << "Can't capture '" << source << "' !" << std::endl;
return 1;
}
typedef Simd::Detection<Simd::Allocator> Detection;
Detection detection;
detection.Load("../../data/cascade/haar_face_0.xml");
bool inited = false;
const char * WINDOW_NAME = "FaceDetection";
cv::namedWindow(WINDOW_NAME, 1);
for (;;)
{
cv::Mat frame;
capture >> frame;
Detection::View image = frame;
if (!inited)
{
detection.Init(image.Size(), 1.2, image.Size() / 20);
inited = true;
}
Detection::Objects objects;
detection.Detect(image, objects);
for (size_t i = 0; i < objects.size(); ++i)
Simd::DrawRectangle(image, objects[i].rect, Simd::Pixel::Bgr24(0, 255, 255));
cv::imshow(WINDOW_NAME, frame);
if (cvWaitKey(1) == 27)// "press 'Esc' to break video";
break;
}
return 0;
}
\endcode
\note This is wrapper around low-level \ref object_detection API.
*/
template <template<class> class A>
struct Detection
{
typedef A<uint8_t> Allocator; /*!< Allocator type definition. */
typedef Simd::View<A> View; /*!< An image type definition. */
typedef Simd::Point<ptrdiff_t> Size; /*!< An image size type definition. */
typedef std::vector<Size> Sizes; /*!< A vector of image sizes type definition. */
typedef Simd::Rectangle<ptrdiff_t> Rect; /*!< A rectangle type definition. */
typedef std::vector<Rect> Rects; /*!< A vector of rectangles type definition. */
typedef int Tag; /*!< A tag type definition. */
static const Tag UNDEFINED_OBJECT_TAG = -1; /*!< The undefined object tag. */
/*!
\short The Object structure describes detected object.
*/
struct Object
{
Rect rect; /*!< \brief A bounding box around of detected object. */
int weight; /*!< \brief An object weight (number of elementary detections). */
Tag tag; /*!< \brief An object tag. It's useful if more than one detector works. */
/*!
Creates a new Object structure.
\param [in] r - initial bounding box.
\param [in] w - initial weight.
\param [in] t - initial tag.
*/
Object(const Rect & r = Rect(), int w = 0, Tag t = UNDEFINED_OBJECT_TAG)
: rect(r)
, weight(w)
, tag(t)
{
}
/*!
Creates a new Object structure on the base of another object.
\param [in] o - another object.
*/
Object(const Object & o)
: rect(o.rect)
, weight(o.weight)
, tag(o.tag)
{
}
};
typedef std::vector<Object> Objects; /*!< A vector of objects type defenition. */
/*!
Creates a new empty Detection structure.
*/
Detection()
{
}
/*!
A Detection destructor.
*/
~Detection()
{
for (size_t i = 0; i < _data.size(); ++i)
::SimdRelease(_data[i].handle);
}
/*!
Loads from file classifier cascade. Supports OpenCV HAAR and LBP cascades type.
You can call this function more than once if you want to use several object detectors at the same time.
\note Tree based cascades and old cascade formats are not supported!
\param [in] xml - a string containing XML with cascade.
\param [in] tag - an user defined tag. This tag will be inserted in output Object structure.
\return a result of this operation.
*/
bool LoadStringXml(const std::string & xml, Tag tag = UNDEFINED_OBJECT_TAG)
{
// Copy the received string to a non const char pointer.
char * xmlTmp = new char[xml.size() + 1];
std::copy(xml.begin(), xml.end(), xmlTmp);
xmlTmp[xml.size()] = '\0';
Handle handle = ::SimdDetectionLoadStringXml(xmlTmp);
if (handle)
{
Data data;
data.handle = handle;
data.tag = tag;
::SimdDetectionInfo(handle, (size_t*)&data.size.x, (size_t*)&data.size.y, &data.flags);
_data.push_back(data);
}
return handle != NULL;
}
/*!
Loads from file classifier cascade. Supports OpenCV HAAR and LBP cascades type.
You can call this function more than once if you want to use several object detectors at the same time.
\note Tree based cascades and old cascade formats are not supported!
\param [in] path - a path to cascade.
\param [in] tag - an user defined tag. This tag will be inserted in output Object structure.
\return a result of this operation.
*/
bool Load(const std::string & path, Tag tag = UNDEFINED_OBJECT_TAG)
{
Handle handle = ::SimdDetectionLoadA(path.c_str());
if (handle)
{
Data data;
data.handle = handle;
data.tag = tag;
::SimdDetectionInfo(handle, (size_t*)&data.size.x, (size_t*)&data.size.y, &data.flags);
_data.push_back(data);
}
return handle != NULL;
}
/*!
Prepares Detection structure to work with image of given size.
\param [in] imageSize - a size of input image.
\param [in] scaleFactor - a scale factor. To detect objects of different sizes the algorithm uses many scaled image.
This parameter defines size difference between neighboring images. This parameter strongly affects to performance.
\param [in] sizeMin - a minimal size of detected objects. This parameter strongly affects to performance.
\param [in] sizeMax - a maximal size of detected objects.
\param [in] roi - a 8-bit image mask which defines Region Of Interest. User can restricts detection region with using this mask.
The mask affects to the center of detected object.
\param [in] threadNumber - a number of work threads. It useful for multi core CPU. Use value -1 to auto choose of thread number.
\return a result of this operation.
*/
bool Init(const Size & imageSize, double scaleFactor = 1.1, const Size & sizeMin = Size(0, 0),
const Size & sizeMax = Size(INT_MAX, INT_MAX), const View & roi = View(), ptrdiff_t threadNumber = -1)
{
if (_data.empty())
return false;
_imageSize = imageSize;
ptrdiff_t threadNumberMax = std::thread::hardware_concurrency();
_threadNumber = (threadNumber <= 0 || threadNumber > threadNumberMax) ? threadNumberMax : threadNumber;
return InitLevels(scaleFactor, sizeMin, sizeMax, roi);
}
/*!
Detects objects at given image.
\param [in] src - a input image.
\param [out] objects - detected objects.
\param [in] groupSizeMin - a minimal weight (number of elementary detections) of detected image.
\param [in] sizeDifferenceMax - a parameter to group elementary detections.
\param [in] motionMask - an using of motion detection flag. Useful for dynamical restriction of detection region to addition to ROI.
\param [in] motionRegions - a set of rectangles (motion regions) to restrict detection region to addition to ROI.
The regions affect to the center of detected object.
\return a result of this operation.
*/
bool Detect(const View & src, Objects & objects, int groupSizeMin = 3, double sizeDifferenceMax = 0.2,
bool motionMask = false, const Rects & motionRegions = Rects())
{
SIMD_CHECK_PERFORMANCE();
if (_levels.empty() || src.Size() != _imageSize)
return false;
FillLevels(src);
typedef std::map<Tag, Objects> Candidates;
Candidates candidates;
for (size_t i = 0; i < _levels.size(); ++i)
{
Level & level = *_levels[i];
View mask = level.roi;
Rect rect = level.rect;
if (motionMask)
{
FillMotionMask(motionRegions, level, rect);
mask = level.mask;
}
if (rect.Empty())
continue;
for (size_t j = 0; j < level.hids.size(); ++j)
{
Hid & hid = level.hids[j];
hid.Detect(mask, rect, level.dst, _threadNumber, level.throughColumn);
AddObjects(candidates[hid.data->tag], level.dst, rect, hid.data->size, level.scale,
level.throughColumn ? 2 : 1, hid.data->tag);
}
}
objects.clear();
for (typename Candidates::iterator it = candidates.begin(); it != candidates.end(); ++it)
GroupObjects(objects, it->second, groupSizeMin, sizeDifferenceMax);
return true;
}
private:
typedef void * Handle;
struct Data
{
Handle handle;
Tag tag;
Size size;
::SimdDetectionInfoFlags flags;
bool Haar() const { return (flags&::SimdDetectionInfoFeatureMask) == ::SimdDetectionInfoFeatureHaar; }
bool Tilted() const { return (flags&::SimdDetectionInfoHasTilted) != 0; }
bool Int16() const { return (flags&::SimdDetectionInfoCanInt16) != 0; }
};
typedef void(*DetectPtr)(const void * hid, const uint8_t * mask, size_t maskStride,
ptrdiff_t left, ptrdiff_t top, ptrdiff_t right, ptrdiff_t bottom, uint8_t * dst, size_t dstStride);
struct Worker;
typedef std::shared_ptr<Worker> WorkerPtr;
typedef std::vector<WorkerPtr> WorkerPtrs;
struct Hid
{
Handle handle;
Data * data;
DetectPtr detect;
void Detect(const View & mask, const Rect & rect, View & dst, size_t threadNumber, bool throughColumn)
{
SIMD_CHECK_PERFORMANCE();
Size s = dst.Size() - data->size;
View m = mask.Region(s, View::MiddleCenter);
Rect r = rect.Shifted(-data->size / 2).Intersection(Rect(s));
Simd::Fill(dst, 0);
::SimdDetectionPrepare(handle);
Parallel(r.top, r.bottom, [&](size_t thread, size_t begin, size_t end)
{
detect(handle, m.data, m.stride, r.left, begin, r.right, end, dst.data, dst.stride);
}, rect.Area() >= (data->Haar() ? 10000 : 30000) ? threadNumber : 1, throughColumn ? 2 : 1);
}
};
typedef std::vector<Hid> Hids;
struct Level
{
Hids hids;
double scale;
View src;
View roi;
View mask;
Rect rect;
View sum;
View sqsum;
View tilted;
View dst;
bool throughColumn;
bool needSqsum;
bool needTilted;
~Level()
{
for (size_t i = 0; i < hids.size(); ++i)
::SimdRelease(hids[i].handle);
}
};
typedef std::unique_ptr<Level> LevelPtr;
typedef std::vector<LevelPtr> LevelPtrs;
std::vector<Data> _data;
Size _imageSize;
bool _needNormalization;
ptrdiff_t _threadNumber;
LevelPtrs _levels;
bool InitLevels(double scaleFactor, const Size & sizeMin, const Size & sizeMax, const View & roi)
{
_needNormalization = false;
_levels.clear();
_levels.reserve(100);
double scale = 1.0;
do
{
std::vector<bool> inserts(_data.size(), false);
bool exit = true, insert = false;
for (size_t i = 0; i < _data.size(); ++i)
{
Size windowSize = _data[i].size * scale;
if (windowSize.x <= sizeMax.x && windowSize.y <= sizeMax.y &&
windowSize.x <= _imageSize.x && windowSize.y <= _imageSize.y)
{
if (windowSize.x >= sizeMin.x && windowSize.y >= sizeMin.y)
insert = inserts[i] = true;
exit = false;
}
}
if (exit)
break;
if (insert)
{
_levels.push_back(LevelPtr(new Level()));
Level & level = *_levels.back();
level.scale = scale;
level.throughColumn = scale <= 2.0;
Size scaledSize(_imageSize / scale);
level.src.Recreate(scaledSize, View::Gray8);
level.roi.Recreate(scaledSize, View::Gray8);
level.mask.Recreate(scaledSize, View::Gray8);
level.sum.Recreate(scaledSize + Size(1, 1), View::Int32);
level.sqsum.Recreate(scaledSize + Size(1, 1), View::Int32);
level.tilted.Recreate(scaledSize + Size(1, 1), View::Int32);
level.dst.Recreate(scaledSize, View::Gray8);
level.needSqsum = false, level.needTilted = false;
for (size_t i = 0; i < _data.size(); ++i)
{
if (!inserts[i])
continue;
Handle handle = ::SimdDetectionInit(_data[i].handle, level.sum.data, level.sum.stride, level.sum.width, level.sum.height,
level.sqsum.data, level.sqsum.stride, level.tilted.data, level.tilted.stride, level.throughColumn, _data[i].Int16());
if (handle)
{
Hid hid;
hid.handle = handle;
hid.data = &_data[i];
if (_data[i].Haar())
hid.detect = level.throughColumn ? ::SimdDetectionHaarDetect32fi : ::SimdDetectionHaarDetect32fp;
else
{
if (_data[i].Int16())
hid.detect = level.throughColumn ? ::SimdDetectionLbpDetect16ii : ::SimdDetectionLbpDetect16ip;
else
hid.detect = level.throughColumn ? ::SimdDetectionLbpDetect32fi : ::SimdDetectionLbpDetect32fp;
}
level.hids.push_back(hid);
}
else
return false;
level.needSqsum = level.needSqsum | _data[i].Haar();
level.needTilted = level.needTilted | _data[i].Tilted();
_needNormalization = _needNormalization | _data[i].Haar();
}
level.rect = Rect(level.roi.Size());
if (roi.format == View::None)
Simd::Fill(level.roi, 255);
else
{
Simd::ResizeBilinear(roi, level.roi);
Simd::Binarization(level.roi, 0, 255, 0, level.roi, SimdCompareGreater);
Simd::SegmentationShrinkRegion(level.roi, 255, level.rect);
}
}
scale *= scaleFactor;
} while (true);
return !_levels.empty();
}
void FillLevels(View src)
{
View gray;
if (src.format != View::Gray8)
{
gray.Recreate(src.Size(), View::Gray8);
Convert(src, gray);
src = gray;
}
Simd::ResizeBilinear(src, _levels[0]->src);
if (_needNormalization)
Simd::NormalizeHistogram(_levels[0]->src, _levels[0]->src);
EstimateIntegral(*_levels[0]);
for (size_t i = 1; i < _levels.size(); ++i)
{
Simd::ResizeBilinear(_levels[0]->src, _levels[i]->src);
EstimateIntegral(*_levels[i]);
}
}
void EstimateIntegral(Level & level)
{
if (level.needSqsum)
{
if (level.needTilted)
Simd::Integral(level.src, level.sum, level.sqsum, level.tilted);
else
Simd::Integral(level.src, level.sum, level.sqsum);
}
else
Simd::Integral(level.src, level.sum);
}
void FillMotionMask(const Rects & rects, Level & level, Rect & rect) const
{
Simd::Fill(level.mask, 0);
rect = Rect();
for (size_t i = 0; i < rects.size(); i++)
{
Rect r = rects[i] / level.scale;
rect |= r;
Simd::Fill(level.mask.Region(r).Ref(), 0xFF);
}
rect &= level.rect;
Simd::OperationBinary8u(level.mask, level.roi, level.mask, SimdOperationBinary8uAnd);
}
void AddObjects(Objects & objects, const View & dst, const Rect & rect, const Size & size, double scale, size_t step, Tag tag)
{
Size s = dst.Size() - size;
Rect r = rect.Shifted(-size / 2).Intersection(Rect(s));
for (ptrdiff_t row = r.top; row < r.bottom; row += step)
{
const uint8_t * mask = dst.data + row*dst.stride;
for (ptrdiff_t col = r.left; col < r.right; col += step)
{
if (mask[col] != 0)
objects.push_back(Object(Rect(col, row, col + size.x, row + size.y)*scale, 1, tag));
}
}
}
struct Similar
{
Similar(double sizeDifferenceMax)
: _sizeDifferenceMax(sizeDifferenceMax)
{}
SIMD_INLINE bool operator() (const Object & o1, const Object & o2) const
{
const Rect & r1 = o1.rect;
const Rect & r2 = o2.rect;
double delta = _sizeDifferenceMax*(std::min(r1.Width(), r2.Width()) + std::min(r1.Height(), r2.Height()))*0.5;
return
std::abs(r1.left - r2.left) <= delta && std::abs(r1.top - r2.top) <= delta &&
std::abs(r1.right - r2.right) <= delta && std::abs(r1.bottom - r2.bottom) <= delta;
}
private:
double _sizeDifferenceMax;
};
template<typename T> int Partition(const std::vector<T> & vec, std::vector<int> & labels, double sizeDifferenceMax)
{
Similar similar(sizeDifferenceMax);
int i, j, N = (int)vec.size();
const int PARENT = 0;
const int RANK = 1;
std::vector<int> _nodes(N * 2);
int(*nodes)[2] = (int(*)[2])&_nodes[0];
for (i = 0; i < N; i++)
{
nodes[i][PARENT] = -1;
nodes[i][RANK] = 0;
}
for (i = 0; i < N; i++)
{
int root = i;
while (nodes[root][PARENT] >= 0)
root = nodes[root][PARENT];
for (j = 0; j < N; j++)
{
if (i == j || !similar(vec[i], vec[j]))
continue;
int root2 = j;
while (nodes[root2][PARENT] >= 0)
root2 = nodes[root2][PARENT];
if (root2 != root)
{
int rank = nodes[root][RANK], rank2 = nodes[root2][RANK];
if (rank > rank2)
nodes[root2][PARENT] = root;
else
{
nodes[root][PARENT] = root2;
nodes[root2][RANK] += rank == rank2;
root = root2;
}
assert(nodes[root][PARENT] < 0);
int k = j, parent;
while ((parent = nodes[k][PARENT]) >= 0)
{
nodes[k][PARENT] = root;
k = parent;
}
k = i;
while ((parent = nodes[k][PARENT]) >= 0)
{
nodes[k][PARENT] = root;
k = parent;
}
}
}
}
labels.resize(N);
int nclasses = 0;
for (i = 0; i < N; i++)
{
int root = i;
while (nodes[root][PARENT] >= 0)
root = nodes[root][PARENT];
if (nodes[root][RANK] >= 0)
nodes[root][RANK] = ~nclasses++;
labels[i] = ~nodes[root][RANK];
}
return nclasses;
}
void GroupObjects(Objects & dst, const Objects & src, size_t groupSizeMin, double sizeDifferenceMax)
{
if (groupSizeMin == 0 || src.size() < groupSizeMin)
return;
std::vector<int> labels;
int nclasses = Partition(src, labels, sizeDifferenceMax);
Objects buffer;
buffer.resize(nclasses);
for (size_t i = 0; i < labels.size(); ++i)
{
int cls = labels[i];
buffer[cls].rect += src[i].rect;
buffer[cls].weight++;
buffer[cls].tag = src[i].tag;
}
for (size_t i = 0; i < buffer.size(); i++)
buffer[i].rect = buffer[i].rect / double(buffer[i].weight);
for (size_t i = 0; i < buffer.size(); i++)
{
Rect r1 = buffer[i].rect;
int n1 = buffer[i].weight;
if (n1 < (int)groupSizeMin)
continue;
size_t j;
for (j = 0; j < buffer.size(); j++)
{
int n2 = buffer[j].weight;
if (j == i || n2 < (int)groupSizeMin)
continue;
Rect r2 = buffer[j].rect;
int dx = Simd::Round(r2.Width() * sizeDifferenceMax);
int dy = Simd::Round(r2.Height() * sizeDifferenceMax);
if (i != j && (n2 > std::max(3, n1) || n1 < 3) &&
r1.left >= r2.left - dx && r1.top >= r2.top - dy &&
r1.right <= r2.right + dx && r1.bottom <= r2.bottom + dy)
break;
}
if (j == buffer.size())
dst.push_back(buffer[i]);
}
}
};
}
#endif//__SimdDetection_hpp__
| 37.242134 | 152 | 0.490192 | inger147 |
ed484f41521a3f09c7769954d090ee8c697f7ff4 | 5,499 | hpp | C++ | KFPlugin/KFTcpClient/KFTcpClientModule.hpp | 282951387/KFrame | 5d6e953f7cc312321c36632715259394ca67144c | [
"Apache-2.0"
] | 1 | 2021-04-26T09:31:32.000Z | 2021-04-26T09:31:32.000Z | KFPlugin/KFTcpClient/KFTcpClientModule.hpp | 282951387/KFrame | 5d6e953f7cc312321c36632715259394ca67144c | [
"Apache-2.0"
] | null | null | null | KFPlugin/KFTcpClient/KFTcpClientModule.hpp | 282951387/KFrame | 5d6e953f7cc312321c36632715259394ca67144c | [
"Apache-2.0"
] | null | null | null | #ifndef __KF_CLIENT_MODULE_H__
#define __KF_CLIENT_MODULE_H__
/************************************************************************
// @Module : tcp客户端
// @Author : __凌_痕__
// @QQ : 7969936
// @Mail : lori227@qq.com
// @Date : 2017-1-8
************************************************************************/
#include "KFrame.h"
#include "KFTcpClientInterface.h"
#include "KFMessage/KFMessageInterface.h"
#include "KFNetwork/KFNetClientEngine.hpp"
namespace KFrame
{
class KFTcpClientModule : public KFTcpClientInterface
{
public:
KFTcpClientModule() = default;
~KFTcpClientModule() = default;
// 初始化
virtual void InitModule();
// 逻辑
virtual void BeforeRun();
virtual void Run();
// 关闭
virtual void BeforeShut();
virtual void ShutDown();
/////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////
// 添加客户端连接
virtual void StartClient( const KFNetData* netdata );
virtual void StartClient( const std::string& name, const std::string& type, uint64 id, const std::string& ip, uint32 port );
// 断开连接
virtual void CloseClient( uint64 serverid, const char* function, uint32 line );
/////////////////////////////////////////////////////////////////////////
// 发送消息
virtual void SendNetMessage( uint32 msgid, google::protobuf::Message* message, uint32 delay = 0 );
virtual bool SendNetMessage( uint64 serverid, uint32 msgid, google::protobuf::Message* message, uint32 delay = 0 );
virtual bool SendNetMessage( uint64 serverid, uint64 recvid, uint32 msgid, google::protobuf::Message* message, uint32 delay = 0 );
virtual void SendNetMessage( uint32 msgid, const char* data, uint32 length );
virtual bool SendNetMessage( uint64 serverid, uint32 msgid, const char* data, uint32 length );
virtual bool SendNetMessage( uint64 serverid, uint64 recvid, uint32 msgid, const char* data, uint32 length );
virtual void SendMessageToName( const std::string& servername, uint32 msgid, google::protobuf::Message* message );
virtual void SendMessageToName( const std::string& servername, uint32 msgid, const char* data, uint32 length );;
virtual void SendMessageToType( const std::string& servertype, uint32 msgid, google::protobuf::Message* message );
virtual void SendMessageToType( const std::string& servertype, uint32 msgid, const char* data, uint32 length );
virtual void SendMessageToServer( const std::string& servername, const std::string& servertype, uint32 msgid, google::protobuf::Message* message );
virtual void SendMessageToServer( const std::string& servername, const std::string& servertype, uint32 msgid, const char* data, uint32 length );
////////////////////////////////////////////////////////////////////////////////////////////////////////
protected:
// 客户端连接
__KF_NET_EVENT_FUNCTION__( OnClientConnected );
// 客户端断开
__KF_NET_EVENT_FUNCTION__( OnClientDisconnect );
// 客户端关闭
__KF_NET_EVENT_FUNCTION__( OnClientShutdown );
// 客户端连接失败
__KF_NET_EVENT_FUNCTION__( OnClientFailed );
// 注册回馈
__KF_MESSAGE_FUNCTION__( HandleRegisterAck );
private:
// 连接回调
void AddConnectionFunction( KFModule* module, KFNetEventFunction& function );
void RemoveConnectionFunction( KFModule* module );
void CallClientConnectionFunction( const KFNetData* netdata );
// 断线函数
virtual void AddLostFunction( KFModule* module, KFNetEventFunction& function );
void RemoveLostFunction( KFModule* module );
void CallClientLostFunction( const KFNetData* netdata );
// 添加关闭函数
virtual void AddShutdownFunction( KFModule* module, KFNetEventFunction& function );
virtual void RemoveShutdownFunction( KFModule* module );
void CallClientShutdownFunction( const KFNetData* netdata );
// 添加失败函数
virtual void AddFailedFunction( KFModule* module, KFNetEventFunction& function );
virtual void RemoveFailedFunction( KFModule* module );
void CallClientFailedFunction( const KFNetData* netdata );
// 转发函数
virtual void AddTranspondFunction( KFModule* module, KFTranspondFunction& function );
virtual void RemoveTranspondFunction( KFModule* module );
////////////////////////////////////////////////////////////////
// 处理客户端消息
void HandleNetMessage( const Route& route, uint32 msgid, const char* data, uint32 length );
// 是否连接自己
bool IsSelfConnection( const std::string& name, const std::string& type, uint64 id );
public:
// 客户端引擎
KFNetClientEngine* _client_engine = nullptr;
// 转发函数
KFTranspondFunction _kf_transpond_function = nullptr;
// 注册成功回调函数
KFFunctionMap< KFModule*, KFModule*, KFNetEventFunction > _kf_connection_function;
// 客户端掉线
KFFunctionMap< KFModule*, KFModule*, KFNetEventFunction > _kf_lost_function;
// 客户端关闭
KFFunctionMap< KFModule*, KFModule*, KFNetEventFunction > _kf_shutdown_function;
// 客户端失败
KFFunctionMap< KFModule*, KFModule*, KFNetEventFunction > _kf_failed_function;
};
}
#endif | 41.345865 | 155 | 0.603019 | 282951387 |
ed48c1714f07f74f3c94bde2dbf575d44ac8ba62 | 7,084 | cpp | C++ | Gems/GraphCanvas/Code/Source/Components/Slots/Execution/ExecutionSlotLayoutComponent.cpp | whywhywhyw/o3de | 8e09f66799d4c8f188d45861d821e8656a554cb1 | [
"Apache-2.0",
"MIT"
] | 11 | 2021-07-08T09:58:26.000Z | 2022-03-17T17:59:26.000Z | Gems/GraphCanvas/Code/Source/Components/Slots/Execution/ExecutionSlotLayoutComponent.cpp | RoddieKieley/o3de | e804fd2a4241b039a42d9fa54eaae17dc94a7a92 | [
"Apache-2.0",
"MIT"
] | 29 | 2021-07-06T19:33:52.000Z | 2022-03-22T10:27:49.000Z | Gems/GraphCanvas/Code/Source/Components/Slots/Execution/ExecutionSlotLayoutComponent.cpp | RoddieKieley/o3de | e804fd2a4241b039a42d9fa54eaae17dc94a7a92 | [
"Apache-2.0",
"MIT"
] | 4 | 2021-07-06T19:24:43.000Z | 2022-03-31T12:42:27.000Z | /*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include <QCoreApplication>
#include <Components/Slots/Execution/ExecutionSlotLayoutComponent.h>
#include <Components/Slots/Execution/ExecutionSlotConnectionPin.h>
namespace GraphCanvas
{
////////////////////////
// ExecutionSlotLayout
////////////////////////
ExecutionSlotLayout::ExecutionSlotLayout(ExecutionSlotLayoutComponent& owner)
: m_connectionType(ConnectionType::CT_Invalid)
, m_owner(owner)
, m_textDecoration(nullptr)
{
setInstantInvalidatePropagation(true);
setOrientation(Qt::Horizontal);
m_slotConnectionPin = aznew ExecutionSlotConnectionPin(owner.GetEntityId());
m_slotText = aznew GraphCanvasLabel();
}
ExecutionSlotLayout::~ExecutionSlotLayout()
{
}
void ExecutionSlotLayout::Activate()
{
SceneMemberNotificationBus::Handler::BusConnect(m_owner.GetEntityId());
SlotNotificationBus::Handler::BusConnect(m_owner.GetEntityId());
StyleNotificationBus::Handler::BusConnect(m_owner.GetEntityId());
m_slotConnectionPin->Activate();
}
void ExecutionSlotLayout::Deactivate()
{
m_slotConnectionPin->Deactivate();
SceneMemberNotificationBus::Handler::BusDisconnect();
SlotNotificationBus::Handler::BusDisconnect();
StyleNotificationBus::Handler::BusDisconnect();
}
void ExecutionSlotLayout::OnSceneSet(const AZ::EntityId&)
{
SlotRequests* slotRequests = SlotRequestBus::FindFirstHandler(m_owner.GetEntityId());
if (slotRequests)
{
m_connectionType = slotRequests->GetConnectionType();
m_slotText->SetLabel(slotRequests->GetName());
OnTooltipChanged(slotRequests->GetTooltip());
const SlotConfiguration& configuration = slotRequests->GetSlotConfiguration();
if (!configuration.m_textDecoration.empty())
{
SetTextDecoration(configuration.m_textDecoration, configuration.m_textDecorationToolTip);
}
}
UpdateLayout();
OnStyleChanged();
}
void ExecutionSlotLayout::OnSceneReady()
{
OnStyleChanged();
}
void ExecutionSlotLayout::OnRegisteredToNode(const AZ::EntityId& /*nodeId*/)
{
OnStyleChanged();
}
void ExecutionSlotLayout::OnNameChanged(const AZStd::string& name)
{
m_slotText->SetLabel(name);
}
void ExecutionSlotLayout::OnTooltipChanged(const AZStd::string& tooltip)
{
m_slotConnectionPin->setToolTip(tooltip.c_str());
m_slotText->setToolTip(tooltip.c_str());
}
void ExecutionSlotLayout::OnStyleChanged()
{
m_style.SetStyle(m_owner.GetEntityId());
ApplyTextStyle(m_slotText);
if (m_textDecoration)
{
ApplyTextStyle(m_textDecoration);
}
m_slotConnectionPin->RefreshStyle();
qreal padding = m_style.GetAttribute(Styling::Attribute::Padding, 2.);
setContentsMargins(padding, padding, padding, padding);
setSpacing(m_style.GetAttribute(Styling::Attribute::Spacing, 2.));
UpdateGeometry();
}
void ExecutionSlotLayout::SetTextDecoration(const AZStd::string& textDecoration, const AZStd::string& toolTip)
{
if (m_textDecoration)
{
delete m_textDecoration;
m_textDecoration = nullptr;
}
if (!textDecoration.empty())
{
m_textDecoration = new GraphCanvasLabel();
m_textDecoration->SetLabel(textDecoration);
m_textDecoration->setToolTip(toolTip.c_str());
ApplyTextStyle(m_textDecoration);
}
}
void ExecutionSlotLayout::ClearTextDecoration()
{
delete m_textDecoration;
m_textDecoration = nullptr;
}
void ExecutionSlotLayout::ApplyTextStyle(GraphCanvasLabel* graphCanvasLabel)
{
switch (m_connectionType)
{
case ConnectionType::CT_Input:
graphCanvasLabel->SetStyle(m_owner.GetEntityId(), ".inputSlotName");
break;
case ConnectionType::CT_Output:
graphCanvasLabel->SetStyle(m_owner.GetEntityId(), ".outputSlotName");
break;
default:
graphCanvasLabel->SetStyle(m_owner.GetEntityId(), ".slotName");
break;
};
}
void ExecutionSlotLayout::UpdateLayout()
{
for (int i = count() - 1; i >= 0; --i)
{
removeAt(i);
}
switch (m_connectionType)
{
case ConnectionType::CT_Input:
addItem(m_slotConnectionPin);
setAlignment(m_slotConnectionPin, Qt::AlignLeft);
addItem(m_slotText);
setAlignment(m_slotText, Qt::AlignLeft);
if (m_textDecoration)
{
addItem(m_textDecoration);
setAlignment(m_textDecoration, Qt::AlignLeft);
}
break;
case ConnectionType::CT_Output:
if (m_textDecoration)
{
addItem(m_textDecoration);
setAlignment(m_textDecoration, Qt::AlignRight);
}
addItem(m_slotText);
setAlignment(m_slotText, Qt::AlignRight);
addItem(m_slotConnectionPin);
setAlignment(m_slotConnectionPin, Qt::AlignRight);
break;
default:
if (m_textDecoration)
{
addItem(m_textDecoration);
}
addItem(m_slotConnectionPin);
addItem(m_slotText);
break;
}
}
void ExecutionSlotLayout::UpdateGeometry()
{
m_slotConnectionPin->updateGeometry();
m_slotText->update();
invalidate();
updateGeometry();
}
/////////////////////////////////
// ExecutionSlotLayoutComponent
/////////////////////////////////
void ExecutionSlotLayoutComponent::Reflect(AZ::ReflectContext* reflectContext)
{
AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(reflectContext);
if (serializeContext)
{
serializeContext->Class<ExecutionSlotLayoutComponent, AZ::Component>()
->Version(1)
;
}
}
ExecutionSlotLayoutComponent::ExecutionSlotLayoutComponent()
: m_layout(nullptr)
{
}
void ExecutionSlotLayoutComponent::Init()
{
SlotLayoutComponent::Init();
m_layout = aznew ExecutionSlotLayout((*this));
SetLayout(m_layout);
}
void ExecutionSlotLayoutComponent::Activate()
{
SlotLayoutComponent::Activate();
m_layout->Activate();
}
void ExecutionSlotLayoutComponent::Deactivate()
{
SlotLayoutComponent::Deactivate();
m_layout->Deactivate();
}
}
| 27.671875 | 114 | 0.612507 | whywhywhyw |
ed4a152a3507efe10e81219d3d348a7b6865d933 | 12,684 | cc | C++ | HeavyFlavorAnalysis/RecoDecay/src/BPHKinematicFit.cc | pasmuss/cmssw | 566f40c323beef46134485a45ea53349f59ae534 | [
"Apache-2.0"
] | null | null | null | HeavyFlavorAnalysis/RecoDecay/src/BPHKinematicFit.cc | pasmuss/cmssw | 566f40c323beef46134485a45ea53349f59ae534 | [
"Apache-2.0"
] | null | null | null | HeavyFlavorAnalysis/RecoDecay/src/BPHKinematicFit.cc | pasmuss/cmssw | 566f40c323beef46134485a45ea53349f59ae534 | [
"Apache-2.0"
] | null | null | null | /*
* See header file for a description of this class.
*
* \author Paolo Ronchese INFN Padova
*
*/
//-----------------------
// This Class' Header --
//-----------------------
#include "HeavyFlavorAnalysis/RecoDecay/interface/BPHKinematicFit.h"
//-------------------------------
// Collaborating Class Headers --
//-------------------------------
#include "HeavyFlavorAnalysis/RecoDecay/interface/BPHRecoCandidate.h"
#include "RecoVertex/KinematicFitPrimitives/interface/KinematicParticleFactoryFromTransientTrack.h"
#include "RecoVertex/KinematicFitPrimitives/interface/RefCountedKinematicParticle.h"
#include "RecoVertex/KinematicFit/interface/KinematicParticleVertexFitter.h"
#include "RecoVertex/KinematicFit/interface/KinematicConstrainedVertexFitter.h"
#include "RecoVertex/KinematicFit/interface/KinematicParticleFitter.h"
#include "RecoVertex/KinematicFit/interface/MassKinematicConstraint.h"
#include "RecoVertex/KinematicFit/interface/TwoTrackMassKinematicConstraint.h"
#include "RecoVertex/KinematicFit/interface/MultiTrackMassKinematicConstraint.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
//---------------
// C++ Headers --
//---------------
#include <iostream>
using namespace std;
//-------------------
// Initializations --
//-------------------
//----------------
// Constructors --
//----------------
BPHKinematicFit::BPHKinematicFit():
BPHDecayVertex( 0 ),
massConst( -1.0 ),
massSigma( -1.0 ),
oldKPs( true ),
oldFit( true ),
oldMom( true ),
kinTree( 0 ) {
}
BPHKinematicFit::BPHKinematicFit( const BPHKinematicFit* ptr ):
BPHDecayVertex( ptr, 0 ),
massConst( -1.0 ),
massSigma( -1.0 ),
oldKPs( true ),
oldFit( true ),
oldMom( true ),
kinTree( 0 ) {
map<const reco::Candidate*,const reco::Candidate*> iMap;
const vector<const reco::Candidate*>& daug = daughters();
const vector<Component>& list = ptr->componentList();
int i;
int n = daug.size();
for ( i = 0; i < n; ++i ) {
const reco::Candidate* cand = daug[i];
iMap[originalReco( cand )] = cand;
}
for ( i = 0; i < n; ++i ) {
const Component& c = list[i];
dMSig[iMap[c.cand]] = c.msig;
}
const vector<BPHRecoConstCandPtr>& dComp = daughComp();
int j;
int m = dComp.size();
for ( j = 0; j < m; ++j ) {
const map<const reco::Candidate*,double>& dMap = dComp[j]->dMSig;
dMSig.insert( dMap.begin(), dMap.end() );
}
}
//--------------
// Destructor --
//--------------
BPHKinematicFit::~BPHKinematicFit() {
}
//--------------
// Operations --
//--------------
void BPHKinematicFit::setConstraint( double mass, double sigma ) {
oldFit = oldMom = true;
massConst = mass;
massSigma = sigma;
return;
}
double BPHKinematicFit::constrMass() const {
return massConst;
}
double BPHKinematicFit::constrSigma() const {
return massSigma;
}
const vector<RefCountedKinematicParticle>& BPHKinematicFit::kinParticles()
const {
if ( oldKPs ) buildParticles();
return allParticles;
}
vector<RefCountedKinematicParticle> BPHKinematicFit::kinParticles(
const vector<string>& names ) const {
if ( oldKPs ) buildParticles();
const vector<const reco::Candidate*>& daugs = daughFull();
vector<RefCountedKinematicParticle> plist;
if ( allParticles.size() != daugs.size() ) return plist;
set<RefCountedKinematicParticle> pset;
int i;
int n = names.size();
int m = daugs.size();
plist.reserve( m );
for ( i = 0; i < n; ++i ) {
const string& pname = names[i];
if ( pname == "*" ) {
int j = m;
while ( j-- ) {
RefCountedKinematicParticle& kp = allParticles[j];
if ( pset.find( kp ) != pset.end() ) continue;
plist.push_back( kp );
pset .insert ( kp );
}
break;
}
map<const reco::Candidate*,
RefCountedKinematicParticle>::const_iterator iter = kinMap.find(
getDaug( pname ) );
map<const reco::Candidate*,
RefCountedKinematicParticle>::const_iterator iend = kinMap.end();
if ( iter != iend ) {
const RefCountedKinematicParticle& kp = iter->second;
if ( pset.find( kp ) != pset.end() ) continue;
plist.push_back( kp );
pset .insert ( kp );
}
else {
edm::LogPrint( "ParticleNotFound" )
<< "BPHKinematicFit::kinParticles: "
<< pname << " not found";
}
}
return plist;
}
const RefCountedKinematicTree& BPHKinematicFit::kinematicTree() const {
if ( oldFit ) return kinematicTree( "", massConst, massSigma );
return kinTree;
}
const RefCountedKinematicTree& BPHKinematicFit::kinematicTree(
const string& name,
double mass, double sigma ) const {
if ( sigma < 0 ) return kinematicTree( name, mass );
ParticleMass mc = mass;
MassKinematicConstraint kinConst( mc, sigma );
return kinematicTree( name, &kinConst );
}
const RefCountedKinematicTree& BPHKinematicFit::kinematicTree(
const string& name,
double mass ) const {
if ( mass < 0 ) {
kinTree = RefCountedKinematicTree( 0 );
oldFit = false;
return kinTree;
}
int nn = daughFull().size();
ParticleMass mc = mass;
if ( nn == 2 ) {
TwoTrackMassKinematicConstraint kinConst( mc );
return kinematicTree( name, &kinConst );
}
else {
MultiTrackMassKinematicConstraint kinConst( mc, nn );
return kinematicTree( name, &kinConst );
}
}
const RefCountedKinematicTree& BPHKinematicFit::kinematicTree(
const string& name,
KinematicConstraint* kc ) const {
kinTree = RefCountedKinematicTree( 0 );
oldFit = false;
kinParticles();
if ( allParticles.size() != daughFull().size() ) return kinTree;
vector<RefCountedKinematicParticle> kComp;
vector<RefCountedKinematicParticle> kTail;
if ( name != "" ) {
const BPHRecoCandidate* comp = getComp( name ).get();
if ( comp == 0 ) {
edm::LogPrint( "ParticleNotFound" )
<< "BPHKinematicFit::kinematicTree: "
<< name << " daughter not found";
return kinTree;
}
const vector<string>& names = comp->daugNames();
int ns;
int nn = ns = names.size();
vector<string> nfull( nn + 1 );
nfull[nn] = "*";
while ( nn-- ) nfull[nn] = name + "/" + names[nn];
vector<RefCountedKinematicParticle> kPart = kinParticles( nfull );
vector<RefCountedKinematicParticle>::const_iterator iter = kPart.begin();
vector<RefCountedKinematicParticle>::const_iterator imid = iter + ns;
vector<RefCountedKinematicParticle>::const_iterator iend = kPart.end();
kComp.insert( kComp.end(), iter, imid );
kTail.insert( kTail.end(), imid, iend );
}
else {
kComp = allParticles;
}
try {
KinematicParticleVertexFitter vtxFitter;
RefCountedKinematicTree compTree = vtxFitter.fit( kComp );
if ( compTree->isEmpty() ) return kinTree;
KinematicParticleFitter kinFitter;
compTree = kinFitter.fit( kc, compTree );
if ( compTree->isEmpty() ) return kinTree;
compTree->movePointerToTheTop();
if ( kTail.size() ) {
RefCountedKinematicParticle compPart = compTree->currentParticle();
if ( !compPart->currentState().isValid() ) return kinTree;
kTail.push_back( compPart );
kinTree = vtxFitter.fit( kTail );
}
else {
kinTree = compTree;
}
}
catch ( std::exception e ) {
edm::LogPrint( "FitFailed" )
<< "BPHKinematicFit::kinematicTree: "
<< "kin fit reset";
kinTree = RefCountedKinematicTree( 0 );
}
return kinTree;
}
const RefCountedKinematicTree& BPHKinematicFit::kinematicTree(
const string& name,
MultiTrackKinematicConstraint* kc ) const {
kinTree = RefCountedKinematicTree( 0 );
oldFit = false;
kinParticles();
if ( allParticles.size() != daughFull().size() ) return kinTree;
vector<string> nfull;
if ( name != "" ) {
const BPHRecoCandidate* comp = getComp( name ).get();
if ( comp == 0 ) {
edm::LogPrint( "ParticleNotFound" )
<< "BPHKinematicFit::kinematicTree: "
<< name << " daughter not found";
return kinTree;
}
const vector<string>& names = comp->daugNames();
int nn = names.size();
nfull.resize( nn + 1 );
nfull[nn] = "*";
while ( nn-- ) nfull[nn] = name + "/" + names[nn];
}
else {
nfull.push_back( "*" );
}
try {
KinematicConstrainedVertexFitter cvf;
kinTree = cvf.fit( kinParticles( nfull ), kc );
}
catch ( std::exception e ) {
edm::LogPrint( "FitFailed" )
<< "BPHKinematicFit::kinematicTree: "
<< "kin fit reset";
kinTree = RefCountedKinematicTree( 0 );
}
return kinTree;
}
void BPHKinematicFit::resetKinematicFit() const {
oldKPs = oldFit = oldMom = true;
return;
}
bool BPHKinematicFit::isEmpty() const {
kinematicTree();
if ( kinTree.get() == 0 ) return true;
return kinTree->isEmpty();
}
bool BPHKinematicFit::isValidFit() const {
const RefCountedKinematicParticle kPart = currentParticle();
if ( kPart.get() == 0 ) return false;
return kPart->currentState().isValid();
}
const RefCountedKinematicParticle BPHKinematicFit::currentParticle() const {
if ( isEmpty() ) return RefCountedKinematicParticle( 0 );
return kinTree->currentParticle();
}
const RefCountedKinematicVertex BPHKinematicFit::currentDecayVertex() const {
if ( isEmpty() ) return RefCountedKinematicVertex( 0 );
return kinTree->currentDecayVertex();
}
ParticleMass BPHKinematicFit::mass() const {
const RefCountedKinematicParticle kPart = currentParticle();
if ( kPart.get() == 0 ) return -1.0;
const KinematicState kStat = kPart->currentState();
if ( kStat.isValid() ) return kStat.mass();
return -1.0;
}
const math::XYZTLorentzVector& BPHKinematicFit::p4() const {
if ( oldMom ) fitMomentum();
return totalMomentum;
}
void BPHKinematicFit::addK( const string& name,
const reco::Candidate* daug,
double mass, double sigma ) {
addK( name, daug, "cfhpmig", mass, sigma );
return;
}
void BPHKinematicFit::addK( const string& name,
const reco::Candidate* daug,
const string& searchList,
double mass, double sigma ) {
addV( name, daug, searchList, mass );
dMSig[daughters().back()] = sigma;
return;
}
void BPHKinematicFit::addK( const string& name,
const BPHRecoConstCandPtr& comp ) {
addV( name, comp );
const map<const reco::Candidate*,double>& dMap = comp->dMSig;
dMSig.insert( dMap.begin(), dMap.end() );
return;
}
void BPHKinematicFit::setNotUpdated() const {
BPHDecayVertex::setNotUpdated();
resetKinematicFit();
return;
}
void BPHKinematicFit::buildParticles() const {
kinMap.clear();
allParticles.clear();
const vector<const reco::Candidate*>& daug = daughFull();
KinematicParticleFactoryFromTransientTrack pFactory;
int n = daug.size();
allParticles.reserve( n );
float chi = 0.0;
float ndf = 0.0;
while ( n-- ) {
const reco::Candidate* cand = daug[n];
ParticleMass mass = cand->mass();
float sigma = dMSig.find( cand )->second;
if ( sigma < 0 ) sigma = 1.0e-7;
reco::TransientTrack* tt = getTransientTrack( cand );
if ( tt != 0 ) allParticles.push_back( kinMap[cand] =
pFactory.particle( *tt,
mass, chi, ndf, sigma ) );
}
oldKPs = false;
return;
}
void BPHKinematicFit::fitMomentum() const {
if ( isValidFit() ) {
const KinematicState& ks = currentParticle()->currentState();
GlobalVector tm = ks.globalMomentum();
double x = tm.x();
double y = tm.y();
double z = tm.z();
double m = ks.mass();
double e = sqrt( ( x * x ) + ( y * y ) + ( z * z ) + ( m * m ) );
totalMomentum.SetPxPyPzE( x, y, z, e );
}
else {
edm::LogPrint( "FitNotFound" )
<< "BPHKinematicFit::fitMomentum: "
<< "simple momentum sum computed";
math::XYZTLorentzVector tm;
const vector<const reco::Candidate*>& daug = daughters();
int n = daug.size();
while ( n-- ) tm += daug[n]->p4();
const vector<BPHRecoConstCandPtr>& comp = daughComp();
int m = comp.size();
while ( m-- ) tm += comp[m]->p4();
totalMomentum = tm;
}
oldMom = false;
return;
}
| 29.361111 | 99 | 0.607537 | pasmuss |
ed4c3299ec2b60452ac666a9903ce85105463a48 | 1,906 | hpp | C++ | include/pcg/Random.hpp | TerensTare/tnt | 916067a9bf697101afb1d0785112aa34014e8126 | [
"MIT"
] | 29 | 2020-04-22T01:31:30.000Z | 2022-02-03T12:21:29.000Z | include/pcg/Random.hpp | TerensTare/tnt | 916067a9bf697101afb1d0785112aa34014e8126 | [
"MIT"
] | 6 | 2020-04-17T10:31:56.000Z | 2021-09-10T12:07:22.000Z | include/pcg/Random.hpp | TerensTare/tnt | 916067a9bf697101afb1d0785112aa34014e8126 | [
"MIT"
] | 7 | 2020-03-13T01:50:41.000Z | 2022-03-06T23:44:29.000Z | #ifndef TNT_PCG_RANDOM_HPP
#define TNT_PCG_RANDOM_HPP
#include <concepts>
#include "core/Config.hpp"
#include "math/Vector.hpp"
// TODO:
// randomColor, etc.
// constexpr halton*
namespace tnt
{
/// @brief Get a random float on range @c [min_,max_].
/// @param min_ The minimum value of the float.
/// @param max_ The maximum value of the float.
/// @return float
TNT_API float randomFloat(float min_, float max_);
/// @brief Get a random int on range @c [min_,max_].
/// @param min_ The minimum value of the int.
/// @param max_ The maximum value of the int.
/// @return int
TNT_API int randomInt(int min_, int max_);
/// @brief Get a tnt::Vector with randomly generated coordinates.
/// @param minX The minimum value of the x coordinate.
/// @param maxX The maximum value of the x coordinate.
/// @param minY The minimum value of the y coordinate.
/// @param maxY The maximum value of the y coordinate.
/// @return @ref tnt::Vector
TNT_API Vector randomVector(float minX, float maxX, float minY, float maxY);
/// @brief Create a randomly generated Vector with magnitude 1.
/// @return @ref tnt::Vector
TNT_API Vector randomUnitVector();
/// @brief Generate a random number using a Halton sequence.
template <std::integral I>
inline auto halton1(I const base, I index) noexcept
{
I result{0};
for (I denom{1}; index > 0; index = floor(index / base))
{
denom *= base;
result += (index % base) / denom;
}
return result;
}
/// @brief Generate a random Vector using Halton sequences.
template <std::integral I>
inline Vector halton2(I const baseX, I const baseY, I index) noexcept
{
return {(float)halton1<I>(baseX, index), (float)halton1<I>(baseY, index)};
}
} // namespace tnt
#endif //!TNT_PCG_RANDOM_HPP | 31.766667 | 82 | 0.644281 | TerensTare |
ed4d5bfd8b95769f8040728c1ade7d26d0a1c67c | 13,010 | cc | C++ | tunnel_localizer/src/range_based_tunnel_localizer.cc | ozaslan/estimators | ad78f2d395d4a6155f0b6d61541167a99959a1c9 | [
"MIT"
] | null | null | null | tunnel_localizer/src/range_based_tunnel_localizer.cc | ozaslan/estimators | ad78f2d395d4a6155f0b6d61541167a99959a1c9 | [
"MIT"
] | null | null | null | tunnel_localizer/src/range_based_tunnel_localizer.cc | ozaslan/estimators | ad78f2d395d4a6155f0b6d61541167a99959a1c9 | [
"MIT"
] | null | null | null | /*
See the header file for detailed explanations
of the below functions.
*/
#include "range_based_tunnel_localizer.hh"
RangeBasedTunnelLocalizer::RangeBasedTunnelLocalizer(int max_iter, double yz_tol, double yaw_tol){
_cloud = pcl::PointCloud<pcl::PointXYZ>().makeShared();
_cloud_aligned = pcl::PointCloud<pcl::PointXYZ>().makeShared();
_max_iters = max_iter;
_yz_tol = yz_tol;
_yaw_tol = yaw_tol;
}
bool RangeBasedTunnelLocalizer::_reset(){
_cloud->points.clear();
_cloud_aligned->points.clear();
_num_laser_pushes = 0;
_num_rgbd_pushes = 0;
_fim = Eigen::Matrix6d::Zero();
return true;
}
bool RangeBasedTunnelLocalizer::set_map(const pcl::PointCloud<pcl::PointXYZ>::Ptr &map){
// ### This will cause memory leak!!!
_octree = new pcl::octree::OctreePointCloudSearch<pcl::PointXYZ>(0.05);
_octree->setInputCloud(map);
_octree->addPointsFromInputCloud();
return true;
}
bool RangeBasedTunnelLocalizer::push_laser_data(const LaserProc &laser_proc, bool clean_start){
const vector<int> &mask = laser_proc.get_mask();
const vector<Eigen::Vector3d> &_3d_pts = laser_proc.get_3d_points();
if(clean_start == true)
_reset();
// Reserve required space to prevent repetitive memory allocation
_cloud->points.reserve(_cloud->points.size() + mask.size());
for(int i = 0 ; i < (int)mask.size() ; i++){
if(mask[i] <= 0)
continue;
_cloud->points.push_back(pcl::PointXYZ(_3d_pts[i](0), _3d_pts[i](1), _3d_pts[i](2)));
}
// Accumulate information due to the laser scanner onto the _fim matrix.
// Each additional information is in the body frame. In the 'get_covariance(...)'
// function (if points have to been registered) this is projected onto the world
// frame.
Eigen::Matrix3d fim_xyz = Eigen::Matrix3d::Zero(); // Fisher information for x, y, z coords.
Eigen::Matrix3d dcm = laser_proc.get_calib_params().relative_pose.topLeftCorner<3, 3>(); // Rotation matrix
Eigen::Matrix3d fim_xyp; // Fisher information for x, y, yaw
double fi_p = 0; // Fisher information for yaw only (neglecting correlative information)
fim_xyp = laser_proc.get_fim();
//cout << "fim_xyp = " << fim_xyp << endl;
fim_xyz.topLeftCorner<2, 2>() = fim_xyp.topLeftCorner<2, 2>();
fim_xyz = dcm * fim_xyz * dcm.transpose();
fi_p = fabs(fim_xyp(2, 2)) * fabs(dcm(2, 2));
//cout << "dcm = [" << dcm << "];" << endl;
// Here we use the ypr convention for compatibility with the 'quadrotor_ukf_lite' node.
_fim.block<3, 3>(0, 0) += fim_xyz;
_fim(3, 3) += fi_p;
//cout << "_fim = [" << _fim << "];" << endl;
return true;
}
bool RangeBasedTunnelLocalizer::push_laser_data(const Eigen::Matrix4d &rel_pose, const sensor_msgs::LaserScan &data, const vector<char> &mask, char cluster_id, bool clean_start){
// ### This still does not incorporate the color information
ASSERT(mask.size() == 0 || data.ranges.size() == mask.size(), "mask and data size should be the same.");
ASSERT(cluster_id != 0, "Cluster \"0\" is reserved.");
if(clean_start == true)
_reset();
// Reserve required space to prevent repetitive memory allocation
_cloud->points.reserve(_cloud->points.size() + data.ranges.size());
Eigen::Vector4d pt;
double th = data.angle_min;
for(int i = 0 ; i < (int)data.ranges.size() ; i++, th += data.angle_increment){
if(mask.size() != 0 && mask[i] != cluster_id)
continue;
utils::laser::polar2euclidean(data.ranges[i], th, pt(0), pt(1));
pt(2) = pt(3) = 0;
pt = rel_pose * pt;
_cloud->points.push_back(pcl::PointXYZ(pt(0), pt(1), pt(2)));
}
// Accumulate information due to the laser scanner onto the _fim matrix.
// Each additional information is in the body frame. In the 'get_covariance(...)'
// function (if points have to been registered) this is projected onto the world
// frame.
Eigen::Matrix3d fim_xyz = Eigen::Matrix3d::Zero(); // Fisher information for x, y, z coords.
Eigen::Matrix3d dcm = rel_pose.topLeftCorner<3, 3>(); // Rotation matrix
Eigen::Matrix3d fim_xyp; // Fisher information for x, y, yaw
double fi_p = 0; // Fisher information for yaw only (neglecting correlative information)
utils::laser::get_fim(data, mask, fim_xyp, cluster_id);
fim_xyz.topLeftCorner<2, 2>() = fim_xyp.topLeftCorner<2, 2>();
fim_xyz = dcm.transpose() * fim_xyz * dcm;
fi_p = fim_xyp(2, 2) * dcm(2, 2);
// Here we use the ypr convention for compatibility with the 'quadrotor_ukf_lite' node.
_fim.block<3, 3>(0, 0) += fim_xyz;
_fim(3, 3) += fi_p;
_num_laser_pushes++;
return true;
}
bool RangeBasedTunnelLocalizer::push_rgbd_data(const Eigen::Matrix4d &rel_pose, const sensor_msgs::PointCloud2 &data, const vector<char> &mask, char cluster_id, bool clean_start){
// ### This still does not incorporate the color information
ASSERT(mask.size() == 0 || data.data.size() == mask.size(), "mask and data size should be the same.");
ASSERT(cluster_id != 0, "Cluster \"0\" is reserved.");
if(clean_start == true)
_reset();
// Reserve required space to prevent repetitive memory allocation
_cloud->points.reserve(_cloud->points.size() + data.data.size());
Eigen::Vector4d pt;
ROS_WARN("\"push_rgbd_data(...)\" is not implemented yet!");
for(int i = 0 ; i < (int)data.data.size() ; i++){
if(mask.size() != 0 || mask[i] == false)
continue;
// ### To be implemented!
}
_num_rgbd_pushes++;
return true;
}
int RangeBasedTunnelLocalizer::estimate_pose(const Eigen::Matrix4d &init_pose, double heading){
// ### This will cause memory leak!!!
_cloud_aligned = pcl::PointCloud<pcl::PointXYZ>().makeShared();
// Initialize '_cloud_aligned' by transforming the collective point cloud
// with the initial pose.
pcl::transformPointCloud(*_cloud, *_cloud_aligned, init_pose);
// Steps :
// (1) - For each ray, find the point of intersection. Use ray-casting of PCL-Octree
// (2) - Prepare the matrix A and vector b s.t. A*x = b
// (3) - Solve for A*x = b where x = [cos(th) sin(th), dy, dz]'.
// (4) - Repeat for _max_iter's or tolerance conditions are met
// (*) - Use weighing to eliminate outliers.
int num_pts = _cloud_aligned->points.size();
int num_valid_pts = 0; // # of data points intersecting with the map.
double dTz = 0; // update along the z-coordinate.
Eigen::MatrixXd A(num_pts, 3);
Eigen::VectorXd b(num_pts);
Eigen::Vector3d x, rpy; // solution to Ax=b,
// roll-pitch-yaw
Eigen::Vector3f pos; // initial position of the robot.
// This is given as argument to ray-caster.
Eigen::Vector3f ray;
Eigen::Vector3d res_vec;
Eigen::Matrix4d curr_pose = init_pose; // 'current' pose after each iteration.
// container for ray-casting results :
pcl::octree::OctreePointCloudSearch<pcl::PointXYZ>::AlignedPointTVector voxel_centers;
pos = curr_pose.topRightCorner<3, 1>().cast<float>();
_matched_map_pts.resize(num_pts);
int iter;
for(iter = 0 ; iter < _max_iters ; iter++){
//cout << "projection pos = " << pos << endl;
num_valid_pts = 0;
_fitness_scores[0] = _fitness_scores[1] = _fitness_scores[2] = 0;
for(int i = 0 ; i < num_pts ; i++){
// Get the ray in the body frame ()
ray(0) = _cloud_aligned->points[i].x - pos(0);
ray(1) = _cloud_aligned->points[i].y - pos(1);
ray(2) = _cloud_aligned->points[i].z - pos(2);
A(i, 0) = ray(1);
A(i, 1) = -ray(0);
A(i, 2) = 1;
// Fetch only the first intersection point
_octree->getIntersectedVoxelCenters(pos, ray, voxel_centers , 1);
// If there is no intersection, nullify the effect by zero'ing the corresponding equation
if(voxel_centers.size() == 0){
A.block<1, 3>(i, 0) *= 0;
b(i) = 0;
_matched_map_pts[i].x =
_matched_map_pts[i].y =
_matched_map_pts[i].z = std::numeric_limits<float>::infinity();
} else {
// Save the matched point
_matched_map_pts[i] = voxel_centers[0];
// Use only the y-comp of the residual vector. Because
// this is going to contribute to y and yaw updates only.
b(i) = voxel_centers[0].y - pos(1);
// Get the residual vector
res_vec(0) = _cloud_aligned->points[i].x - voxel_centers[0].x;
res_vec(1) = _cloud_aligned->points[i].y - voxel_centers[0].y;
res_vec(2) = _cloud_aligned->points[i].z - voxel_centers[0].z;
// Update the delta-z-estimate according to the direction of the
// corresponding ray's z component. The update factor is weighed using
// ML outlier elimination.
dTz += -res_vec(2) * (exp(fabs(ray(2) / ray.norm())) - 1);
// Calculate a weighing coefficent for ML outlier elimination
// regarding y-yaw DOFs
double weight = exp(-pow(res_vec.squaredNorm(), 1.5));
b(i) *= weight;
A.block<1, 3>(i, 0) *= weight;
num_valid_pts++;
_fitness_scores[0] += res_vec[1] * res_vec[1];
_fitness_scores[1] += res_vec[2] * res_vec[2];
_fitness_scores[2] += res_vec[1] * res_vec[1] * ray(0) * ray(0);
}
}
// ####
/*
if(num_valid_pts < 100){
continue;
}
*/
/*
cout << "heading = " << heading << endl;
cout << "A = " << A << endl;
cout << "b = " << b << endl;
*/
// Solve for the least squares solution.
x = (A.transpose() * A).inverse() * A.transpose() * b;
// Get the mean of dTz since it has been accumulated
dTz /= num_valid_pts;
_fitness_scores[0] /= num_valid_pts;
_fitness_scores[1] /= num_valid_pts;
_fitness_scores[2] /= num_valid_pts;
// x = [cos(yaw) sin(yaw) dY]
x(0) = fabs(x(0)) > 1 ? x(0) / fabs(x(0)) : x(0);
double dyaw = -1.2 * atan2(x(1), x(0));
// Update the position
pos(1) += x(2); // y-update
pos(2) += dTz; // z-update
// Convert the orientation to 'rpy', update yaw and
// convert back to dcm.
Eigen::Matrix3d dcm = curr_pose.topLeftCorner<3, 3>();
rpy = utils::trans::dcm2rpy(dcm);
rpy(2) += dyaw;
//rpy(2) = heading; //####
dcm = utils::trans::rpy2dcm(rpy);
// Update the global pose matrix.
curr_pose.topLeftCorner(3, 3) = dcm;
curr_pose(1, 3) = pos(1);
curr_pose(2, 3) = pos(2);
// Transform points for next iteration.
pcl::transformPointCloud(*_cloud, *_cloud_aligned, curr_pose);
if(fabs(x(2)) < _yz_tol && fabs(dTz) < _yz_tol && fabs(dyaw) < _yaw_tol)
break;
}
_pose = curr_pose;
return iter;
}
bool RangeBasedTunnelLocalizer::get_pose(Eigen::Matrix4d &pose){
pose = _pose.cast<double>();
return true;
}
bool RangeBasedTunnelLocalizer::get_registered_pointcloud(pcl::PointCloud<pcl::PointXYZ>::Ptr &pc){
pc = _cloud_aligned;
return true;
}
bool RangeBasedTunnelLocalizer::get_covariance(Eigen::Matrix6d &cov, bool apply_fitness_result){
// ### I have to find a way to project uncertainties in orientation
// to other frame sets.
// ### I might have to fix some elements before inverting
Eigen::EigenSolver<Eigen::Matrix6d> es;
es.compute(_fim, true);
Eigen::MatrixXd D = es.eigenvalues().real().asDiagonal();
Eigen::MatrixXd V = es.eigenvectors().real();
bool reconstruct = false;
for(int i = 0 ; i < 6 ; i++)
if(D(i, i) < 0.00001){
D(i, i) = 0.00001;
reconstruct = true;
}
if(reconstruct)
_fim = (V.transpose() * D * V).real();
//cout << "FIM = [" << _fim << "];" << endl;
// ### This assumes uniform covariance for each rays, and superficially
// handles the uncertainties. I should first run ICP and then
// find '_fim' and so on. This will require a lot of bookkeeping etc.
// Thus leaving to a later version :)
if(apply_fitness_result){
// ### Is the rotation ypr/rpy ???
// We assume that 0.001 m^2 variance is perfect fit, or unit information.
D(0, 0) /= exp(_fitness_scores[0] / 0.001);
D(1, 1) /= exp(_fitness_scores[1] / 0.001);
D(2, 2) /= exp(_fitness_scores[2] / 0.001);
}
for(int i = 0 ; i < 6 ; i++)
D(i, i) = 1 / D(i, i) + 0.00001;
cov = (V * D * V.transpose());
//cout << "V = [" << V << "];" << endl;
//cout << "D = [" << D << "];" << endl;
//cout << "cov = [ " << cov << "];" << endl;
cov.topLeftCorner<3, 3> () = _pose.topLeftCorner<3, 3>().transpose() *
cov.topLeftCorner<3, 3>() *
_pose.topLeftCorner<3, 3>();
// Exclude the pose estimate along the x direction.
es.compute(cov, true);
D = es.eigenvalues().real().asDiagonal();
V = es.eigenvectors().real();
D(0, 0) = 0.00001;
D(4, 4) = 0.00009;
D(5, 5) = 0.00009;
cov = (V * D * V.transpose());
return true;
}
bool RangeBasedTunnelLocalizer::get_fitness_scores(double &y, double &z, double &yaw){
y = _fitness_scores[0];
z = _fitness_scores[1];
yaw = _fitness_scores[2];
return true;
}
bool RangeBasedTunnelLocalizer::get_correspondences(vector<pcl::PointXYZ> &sensor_pts, vector<pcl::PointXYZ> &map_pts){
int num_valid_pts = 0;
for(int i = 0 ; i < (int)_matched_map_pts.size() ; i++)
if(isfinite(_matched_map_pts[i].y))
num_valid_pts++;
map_pts.resize(num_valid_pts);
sensor_pts.resize(num_valid_pts);
for(int i = 0, j = 0 ; i < (int)_cloud_aligned->points.size() ; i++){
if(isfinite(_matched_map_pts[i].y)){
sensor_pts[j] = _cloud_aligned->points[i];
map_pts[j] = _matched_map_pts[i];
j++;
}
}
return true;
}
| 33.704663 | 179 | 0.657264 | ozaslan |
ed51646e6816d35c30fa86f285429110d89a924c | 5,493 | cpp | C++ | SofaKernel/modules/SofaComponentBase/SofaComponentBase_test/MessageHandlerComponent_test.cpp | sofa-framework/issofa | 94855f488465bc3ed41223cbde987581dfca5389 | [
"OML"
] | null | null | null | SofaKernel/modules/SofaComponentBase/SofaComponentBase_test/MessageHandlerComponent_test.cpp | sofa-framework/issofa | 94855f488465bc3ed41223cbde987581dfca5389 | [
"OML"
] | null | null | null | SofaKernel/modules/SofaComponentBase/SofaComponentBase_test/MessageHandlerComponent_test.cpp | sofa-framework/issofa | 94855f488465bc3ed41223cbde987581dfca5389 | [
"OML"
] | null | null | null | /******************************************************************************
* SOFA, Simulation Open-Framework Architecture, development version *
* (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH *
* *
* This program is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as published by *
* the Free Software Foundation; either version 2.1 of the License, or (at *
* your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*******************************************************************************
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
#include <gtest/gtest.h>
#include <string>
using std::string ;
#include <SofaSimulationGraph/DAGSimulation.h>
using sofa::simulation::graph::DAGSimulation ;
#include <sofa/simulation/Simulation.h>
using sofa::simulation::Simulation ;
#include <sofa/simulation/Node.h>
using sofa::simulation::Node ;
#include <SofaSimulationCommon/SceneLoaderXML.h>
using sofa::simulation::SceneLoaderXML ;
#include <SofaComponentBase/messageHandlerComponent.h>
using sofa::component::logging::MessageHandlerComponent ;
#include <SofaComponentBase/initComponentBase.h>
TEST(MessageHandlerComponent, simpleInit)
{
sofa::component::initComponentBase();
string scene =
"<?xml version='1.0'?> "
"<Node name='Root' gravity='0 0 0' time='0' animate='0' > "
" <Node> "
" <MessageHandlerComponent handler='silent'/> "
" </Node> "
"</Node> " ;
sofa::simulation::setSimulation(new DAGSimulation());
Node::SPtr root = SceneLoaderXML::loadFromMemory ( "test1",
scene.c_str(),
scene.size() ) ;
EXPECT_TRUE(root!=NULL) ;
MessageHandlerComponent* component = NULL;
root->getTreeObject(component) ;
EXPECT_TRUE(component!=NULL) ;
}
TEST(MessageHandlerComponent, missingHandler)
{
sofa::component::initComponentBase();
string scene =
"<?xml version='1.0'?> "
"<Node name='Root' gravity='0 0 0' time='0' animate='0' > "
" <MessageHandlerComponent/> "
"</Node> " ;
Node::SPtr root = SceneLoaderXML::loadFromMemory ( "test1",
scene.c_str(),
scene.size() ) ;
MessageHandlerComponent* component = NULL;
root->getTreeObject(component) ;
EXPECT_TRUE(component!=NULL) ;
EXPECT_FALSE(component->isValid()) ;
}
TEST(MessageHandlerComponent, invalidHandler)
{
sofa::component::initComponentBase();
string scene =
"<?xml version='1.0'?> "
"<Node name='Root' gravity='0 0 0' time='0' animate='0' > "
" <MessageHandlerComponent handler='thisisinvalid'/> "
"</Node> " ;
Node::SPtr root = SceneLoaderXML::loadFromMemory ( "test1",
scene.c_str(),
scene.size() ) ;
MessageHandlerComponent* component = NULL;
root->getTreeObject(component) ;
EXPECT_TRUE(component!=NULL) ;
EXPECT_FALSE(component->isValid()) ;
}
TEST(MessageHandlerComponent, clangHandler)
{
sofa::component::initComponentBase();
string scene =
"<?xml version='1.0'?> "
"<Node name='Root' gravity='0 0 0' time='0' animate='0' > "
" <MessageHandlerComponent handler='clang'/> "
"</Node> " ;
Node::SPtr root = SceneLoaderXML::loadFromMemory ( "test1",
scene.c_str(),
scene.size() ) ;
MessageHandlerComponent* component = NULL;
root->getTreeObject(component) ;
EXPECT_TRUE(component!=NULL) ;
EXPECT_TRUE(component->isValid()) ;
}
| 42.581395 | 80 | 0.463499 | sofa-framework |
ed518a28c3b906413f7b0f6ec058afadb4bbea1b | 4,617 | inl | C++ | include/fileos/path.inl | napina/fileos | 44443d126d9c4faf1192196bfe88b556c4a7411f | [
"MIT"
] | 2 | 2017-05-10T06:05:54.000Z | 2021-03-31T13:14:49.000Z | include/fileos/path.inl | napina/fileos | 44443d126d9c4faf1192196bfe88b556c4a7411f | [
"MIT"
] | null | null | null | include/fileos/path.inl | napina/fileos | 44443d126d9c4faf1192196bfe88b556c4a7411f | [
"MIT"
] | null | null | null | /*=============================================================================
Copyright (c) 2013 Ville Ruusutie
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
=============================================================================*/
#pragma once
#ifndef fileos_path_inl
#define fileos_path_inl
namespace fileos {
__forceinline Path::Path()
: m_buffer()
{
}
__forceinline Path::Path(size_t capasity)
: m_buffer(capasity)
{
}
__forceinline Path::Path(Path const& other)
: m_buffer(other.m_buffer)
{
}
/*template<typename T>
__forceinline Path::Path(T const* path)
: m_buffer(path)
{
fixSlashes();
}*/
template<typename T>
__forceinline Path::Path(T const* path, size_t count)
: m_buffer(path, count)
{
fixSlashes();
}
template<size_t Count>
__forceinline Path::Path(char const (&str)[Count])
: m_buffer(str)
{
fixSlashes();
}
template<size_t Count>
__forceinline Path::Path(wchar_t const (&str)[Count])
: m_buffer(str)
{
fixSlashes();
}
__forceinline void Path::reserve(size_t capasity)
{
m_buffer.reserve(capasity);
}
__forceinline void Path::clear()
{
m_buffer.clear();
}
__forceinline void Path::set(Path const& other)
{
m_buffer = other.m_buffer;
}
__forceinline void Path::set(containos::Utf8Slice const& slice)
{
m_buffer.set(slice);
fixSlashes();
}
template<>
__forceinline void Path::set(Path const* other)
{
m_buffer = other->m_buffer;
}
template<>
__forceinline void Path::set(containos::Utf8Slice const* slice)
{
m_buffer.set(*slice);
fixSlashes();
}
template<typename T>
__forceinline void Path::set(T const* path)
{
m_buffer.set(path);
fixSlashes();
}
template<typename T>
__forceinline void Path::set(T const* path, size_t count)
{
m_buffer.set(path, count);
fixSlashes();
}
__forceinline void Path::append(Path const& other)
{
if(m_buffer.length() > 0) m_buffer.append('/');
m_buffer.append(other.m_buffer);
fixSlashes();
}
__forceinline void Path::append(Utf8Slice const& slice)
{
if(m_buffer.length() > 0) m_buffer.append('/');
m_buffer.append(slice);
fixSlashes();
}
template<>
__forceinline void Path::append(Path const* other)
{
if(m_buffer.length() > 0) m_buffer.append('/');
m_buffer.append(other->m_buffer);
fixSlashes();
}
template<>
__forceinline void Path::append(Utf8Slice const* slice)
{
if(m_buffer.length() > 0) m_buffer.append('/');
m_buffer.append(*slice);
fixSlashes();
}
template<typename T>
__forceinline void Path::append(T const* str)
{
if(m_buffer.length() > 0) m_buffer.append('/');
m_buffer.append(str);
fixSlashes();
}
template<typename T>
__forceinline void Path::append(T const* str, size_t count)
{
if(m_buffer.length() > 0) m_buffer.append('/');
m_buffer.append(str, count);
fixSlashes();
}
__forceinline void Path::clone(Path const& from)
{
m_buffer.clone(from.m_buffer);
}
template<typename T>
__forceinline void Path::convertTo(T* buffer, size_t count) const
{
m_buffer.convertTo(buffer, count);
}
__forceinline uint8_t const* Path::data() const
{
return m_buffer.data();
}
__forceinline size_t Path::length() const
{
return m_buffer.length();
}
__forceinline bool Path::operator==(Path const& other) const
{
return m_buffer == other.m_buffer;
}
__forceinline bool Path::operator==(containos::Utf8Slice const& slice) const
{
return m_buffer == slice;
}
__forceinline bool Path::operator==(char const* str) const
{
return m_buffer == str;
}
__forceinline bool Path::operator==(wchar_t const* str) const
{
return m_buffer == str;
}
} // end of fileos
#endif
| 21.881517 | 79 | 0.690925 | napina |
ed51a54892790ba25f520c34ffed15509fb4b9e7 | 453 | cpp | C++ | S03/Enum.cpp | stevekeol/-Thinking-in-Cpp-PracticeCode | 5b147e704015bbda364ab069f1de58dcef7ab14a | [
"MIT"
] | 2 | 2017-06-20T12:16:30.000Z | 2021-11-12T12:06:57.000Z | S03/Enum.cpp | stevekeol/-Thinking-in-Cpp-PracticeCode | 5b147e704015bbda364ab069f1de58dcef7ab14a | [
"MIT"
] | null | null | null | S03/Enum.cpp | stevekeol/-Thinking-in-Cpp-PracticeCode | 5b147e704015bbda364ab069f1de58dcef7ab14a | [
"MIT"
] | null | null | null | //: S03:Enum.cpp
// From "Thinking in C++, 2nd Edition, Volume 1, Annotated Solutions Guide"
// by Chuck Allison, (c) 2001 MindView, Inc. all rights reserved
// Available at www.BruceEckel.com.
#include <iostream>
enum color {
BLACK,
RED,
GREEN,
BLUE,
WHITE
};
int main() {
using namespace std;
for (int hue = BLACK; hue <= WHITE; ++hue)
cout << hue << ' ';
}
/* Output:
0 1 2 3 4
*/
///:~
| 18.12 | 76 | 0.556291 | stevekeol |
ed52e6ef57926d2f3d71c2ce4bbb6fe608271ed7 | 7,472 | cpp | C++ | resources/Wireshark/WiresharkDissectorFoo/ui/qt/moc_interface_toolbar.cpp | joshis1/C_Programming | 4a8003321251448a167bfca0b595c5eeab88608d | [
"MIT"
] | 2 | 2020-09-11T05:51:42.000Z | 2020-12-31T11:42:02.000Z | resources/Wireshark/WiresharkDissectorFoo/ui/qt/moc_interface_toolbar.cpp | joshis1/C_Programming | 4a8003321251448a167bfca0b595c5eeab88608d | [
"MIT"
] | null | null | null | resources/Wireshark/WiresharkDissectorFoo/ui/qt/moc_interface_toolbar.cpp | joshis1/C_Programming | 4a8003321251448a167bfca0b595c5eeab88608d | [
"MIT"
] | null | null | null | /****************************************************************************
** Meta object code from reading C++ file 'interface_toolbar.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.6.1)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "interface_toolbar.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'interface_toolbar.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.6.1. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
struct qt_meta_stringdata_InterfaceToolbar_t {
QByteArrayData data[23];
char stringdata0[337];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_InterfaceToolbar_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_InterfaceToolbar_t qt_meta_stringdata_InterfaceToolbar = {
{
QT_MOC_LITERAL(0, 0, 16), // "InterfaceToolbar"
QT_MOC_LITERAL(1, 17, 11), // "closeReader"
QT_MOC_LITERAL(2, 29, 0), // ""
QT_MOC_LITERAL(3, 30, 20), // "interfaceListChanged"
QT_MOC_LITERAL(4, 51, 15), // "controlReceived"
QT_MOC_LITERAL(5, 67, 6), // "ifname"
QT_MOC_LITERAL(6, 74, 3), // "num"
QT_MOC_LITERAL(7, 78, 7), // "command"
QT_MOC_LITERAL(8, 86, 7), // "message"
QT_MOC_LITERAL(9, 94, 17), // "startReaderThread"
QT_MOC_LITERAL(10, 112, 10), // "control_in"
QT_MOC_LITERAL(11, 123, 13), // "updateWidgets"
QT_MOC_LITERAL(12, 137, 22), // "onControlButtonClicked"
QT_MOC_LITERAL(13, 160, 18), // "onLogButtonClicked"
QT_MOC_LITERAL(14, 179, 19), // "onHelpButtonClicked"
QT_MOC_LITERAL(15, 199, 22), // "onRestoreButtonClicked"
QT_MOC_LITERAL(16, 222, 17), // "onCheckBoxChanged"
QT_MOC_LITERAL(17, 240, 5), // "state"
QT_MOC_LITERAL(18, 246, 17), // "onComboBoxChanged"
QT_MOC_LITERAL(19, 264, 3), // "idx"
QT_MOC_LITERAL(20, 268, 17), // "onLineEditChanged"
QT_MOC_LITERAL(21, 286, 8), // "closeLog"
QT_MOC_LITERAL(22, 295, 41) // "on_interfacesComboBox_current..."
},
"InterfaceToolbar\0closeReader\0\0"
"interfaceListChanged\0controlReceived\0"
"ifname\0num\0command\0message\0startReaderThread\0"
"control_in\0updateWidgets\0"
"onControlButtonClicked\0onLogButtonClicked\0"
"onHelpButtonClicked\0onRestoreButtonClicked\0"
"onCheckBoxChanged\0state\0onComboBoxChanged\0"
"idx\0onLineEditChanged\0closeLog\0"
"on_interfacesComboBox_currentIndexChanged"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_InterfaceToolbar[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
14, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
1, // signalCount
// signals: name, argc, parameters, tag, flags
1, 0, 84, 2, 0x06 /* Public */,
// slots: name, argc, parameters, tag, flags
3, 0, 85, 2, 0x0a /* Public */,
4, 4, 86, 2, 0x0a /* Public */,
9, 2, 95, 2, 0x08 /* Private */,
11, 0, 100, 2, 0x08 /* Private */,
12, 0, 101, 2, 0x08 /* Private */,
13, 0, 102, 2, 0x08 /* Private */,
14, 0, 103, 2, 0x08 /* Private */,
15, 0, 104, 2, 0x08 /* Private */,
16, 1, 105, 2, 0x08 /* Private */,
18, 1, 108, 2, 0x08 /* Private */,
20, 0, 111, 2, 0x08 /* Private */,
21, 0, 112, 2, 0x08 /* Private */,
22, 1, 113, 2, 0x08 /* Private */,
// signals: parameters
QMetaType::Void,
// slots: parameters
QMetaType::Void,
QMetaType::Void, QMetaType::QString, QMetaType::Int, QMetaType::Int, QMetaType::QByteArray, 5, 6, 7, 8,
QMetaType::Void, QMetaType::QString, QMetaType::VoidStar, 5, 10,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void, QMetaType::Int, 17,
QMetaType::Void, QMetaType::Int, 19,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void, QMetaType::QString, 5,
0 // eod
};
void InterfaceToolbar::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
InterfaceToolbar *_t = static_cast<InterfaceToolbar *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->closeReader(); break;
case 1: _t->interfaceListChanged(); break;
case 2: _t->controlReceived((*reinterpret_cast< QString(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2])),(*reinterpret_cast< int(*)>(_a[3])),(*reinterpret_cast< QByteArray(*)>(_a[4]))); break;
case 3: _t->startReaderThread((*reinterpret_cast< QString(*)>(_a[1])),(*reinterpret_cast< void*(*)>(_a[2]))); break;
case 4: _t->updateWidgets(); break;
case 5: _t->onControlButtonClicked(); break;
case 6: _t->onLogButtonClicked(); break;
case 7: _t->onHelpButtonClicked(); break;
case 8: _t->onRestoreButtonClicked(); break;
case 9: _t->onCheckBoxChanged((*reinterpret_cast< int(*)>(_a[1]))); break;
case 10: _t->onComboBoxChanged((*reinterpret_cast< int(*)>(_a[1]))); break;
case 11: _t->onLineEditChanged(); break;
case 12: _t->closeLog(); break;
case 13: _t->on_interfacesComboBox_currentIndexChanged((*reinterpret_cast< const QString(*)>(_a[1]))); break;
default: ;
}
} else if (_c == QMetaObject::IndexOfMethod) {
int *result = reinterpret_cast<int *>(_a[0]);
void **func = reinterpret_cast<void **>(_a[1]);
{
typedef void (InterfaceToolbar::*_t)();
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&InterfaceToolbar::closeReader)) {
*result = 0;
return;
}
}
}
}
const QMetaObject InterfaceToolbar::staticMetaObject = {
{ &QFrame::staticMetaObject, qt_meta_stringdata_InterfaceToolbar.data,
qt_meta_data_InterfaceToolbar, qt_static_metacall, Q_NULLPTR, Q_NULLPTR}
};
const QMetaObject *InterfaceToolbar::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *InterfaceToolbar::qt_metacast(const char *_clname)
{
if (!_clname) return Q_NULLPTR;
if (!strcmp(_clname, qt_meta_stringdata_InterfaceToolbar.stringdata0))
return static_cast<void*>(const_cast< InterfaceToolbar*>(this));
return QFrame::qt_metacast(_clname);
}
int InterfaceToolbar::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QFrame::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 14)
qt_static_metacall(this, _c, _id, _a);
_id -= 14;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 14)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 14;
}
return _id;
}
// SIGNAL 0
void InterfaceToolbar::closeReader()
{
QMetaObject::activate(this, &staticMetaObject, 0, Q_NULLPTR);
}
QT_END_MOC_NAMESPACE
| 37.737374 | 199 | 0.622725 | joshis1 |
ed544679088b86bdbec210bf4443dbe01fe57a0d | 3,869 | cpp | C++ | ThorEngine/Source Code/R_Mesh.cpp | markitus18/Game-Engine | ea9546a16f2e40d13002340b4cb6b42a33a41344 | [
"Unlicense"
] | null | null | null | ThorEngine/Source Code/R_Mesh.cpp | markitus18/Game-Engine | ea9546a16f2e40d13002340b4cb6b42a33a41344 | [
"Unlicense"
] | null | null | null | ThorEngine/Source Code/R_Mesh.cpp | markitus18/Game-Engine | ea9546a16f2e40d13002340b4cb6b42a33a41344 | [
"Unlicense"
] | null | null | null | #include "R_Mesh.h"
#include "OpenGL.h"
R_Mesh::R_Mesh() : Resource(ResourceType::MESH)
{
isExternal = true;
for (uint i = 0; i < max_buffer_type; i++)
{
buffers[i] = 0;
buffersSize[i] = 0;
}
}
R_Mesh::~R_Mesh()
{
}
void R_Mesh::CreateAABB()
{
aabb.SetNegativeInfinity();
aabb.Enclose((math::vec*)vertices, buffersSize[b_vertices]);
}
void R_Mesh::LoadOnMemory()
{
// Create a vertex array object which will hold all buffer objects
glGenVertexArrays(1, &VAO);
glBindVertexArray(VAO);
// Create a vertex buffer object to hold vertex positions
glGenBuffers(1, &buffers[b_vertices]);
glBindBuffer(GL_ARRAY_BUFFER, buffers[b_vertices]);
glBufferData(GL_ARRAY_BUFFER, sizeof(float) * buffersSize[b_vertices] * 3, vertices, GL_STATIC_DRAW);
// Create an element buffer object to hold indices
glGenBuffers(1, &buffers[b_indices]);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffers[b_indices]);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(uint) * buffersSize[b_indices], indices, GL_STATIC_DRAW);
// Set the vertex attrib pointer
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
// Create the array buffer for tex coords and enable attrib pointer
if (buffersSize[b_tex_coords] > 0)
{
glGenBuffers(1, &buffers[b_tex_coords]);
glBindBuffer(GL_ARRAY_BUFFER, buffers[b_tex_coords]);
glBufferData(GL_ARRAY_BUFFER, sizeof(float) * buffersSize[b_tex_coords] * 2, tex_coords, GL_STATIC_DRAW);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), (void*)0);
glEnableVertexAttribArray(1);
}
// Create the array buffer for normals and enable attrib pointer
if (buffersSize[b_normals] > 0)
{
glGenBuffers(1, &buffers[b_normals]);
glBindBuffer(GL_ARRAY_BUFFER, buffers[b_normals]);
glBufferData(GL_ARRAY_BUFFER, sizeof(float) * buffersSize[b_normals] * 3, normals, GL_STATIC_DRAW);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), (void*)0);
glEnableVertexAttribArray(2);
}
glBindVertexArray(0);
}
void R_Mesh::LoadSkinnedBuffers(bool init)
{
if (init)
{
// Create a vertex array object which will hold all buffer objects
glGenVertexArrays(1, &VAO);
glBindVertexArray(VAO);
// Create a vertex buffer object to hold vertex positions
glGenBuffers(1, &buffers[b_vertices]);
// Create an element buffer object to hold indices
glGenBuffers(1, &buffers[b_indices]);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffers[b_indices]);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(uint) * buffersSize[b_indices], indices, GL_STATIC_DRAW);
// Set the vertex attrib pointer
glEnableVertexAttribArray(0);
//Create the array buffer for tex coords and enable attrib pointer
if (buffersSize[b_tex_coords] > 0)
{
glGenBuffers(1, &buffers[b_tex_coords]);
glBindBuffer(GL_ARRAY_BUFFER, buffers[b_tex_coords]);
glBufferData(GL_ARRAY_BUFFER, sizeof(float) * buffersSize[b_tex_coords] * 2, tex_coords, GL_STATIC_DRAW);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), (void*)0);
glEnableVertexAttribArray(1);
}
glGenBuffers(1, &buffers[b_normals]);
}
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, buffers[b_vertices]);
glBufferData(GL_ARRAY_BUFFER, sizeof(float) * buffersSize[b_vertices] * 3, vertices, GL_STREAM_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
// Create the array buffer for normals and enable attrib pointer
if (buffersSize[b_normals] > 0)
{
glBindBuffer(GL_ARRAY_BUFFER, buffers[b_normals]);
glBufferData(GL_ARRAY_BUFFER, sizeof(float) * buffersSize[b_normals] * 3, normals, GL_STREAM_DRAW);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glEnableVertexAttribArray(2);
}
glBindVertexArray(0);
}
void R_Mesh::FreeMemory()
{
//glDeleteBuffers(max_buffer_type, buffers);
} | 30.952 | 108 | 0.747738 | markitus18 |
ed551ff087fb4dbe31bc3c97adc3d16b4a20568f | 4,249 | cpp | C++ | gm/yuvtorgbeffect.cpp | zhaodm/skia_sdl | 8724ae26584df523eb7bb814ffe7aec5f597d187 | [
"BSD-3-Clause"
] | null | null | null | gm/yuvtorgbeffect.cpp | zhaodm/skia_sdl | 8724ae26584df523eb7bb814ffe7aec5f597d187 | [
"BSD-3-Clause"
] | null | null | null | gm/yuvtorgbeffect.cpp | zhaodm/skia_sdl | 8724ae26584df523eb7bb814ffe7aec5f597d187 | [
"BSD-3-Clause"
] | null | null | null |
/*
* Copyright 2014 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
// This test only works with the GPU backend.
#include "gm.h"
#if SK_SUPPORT_GPU
#include "GrContext.h"
#include "GrTest.h"
#include "effects/GrYUVtoRGBEffect.h"
#include "SkBitmap.h"
#include "SkGr.h"
#include "SkGradientShader.h"
namespace skiagm {
/**
* This GM directly exercises GrYUVtoRGBEffect.
*/
class YUVtoRGBEffect : public GM {
public:
YUVtoRGBEffect() {
this->setBGColor(0xFFFFFFFF);
}
protected:
virtual SkString onShortName() SK_OVERRIDE {
return SkString("yuv_to_rgb_effect");
}
virtual SkISize onISize() SK_OVERRIDE {
return SkISize::Make(334, 128);
}
virtual uint32_t onGetFlags() const SK_OVERRIDE {
// This is a GPU-specific GM.
return kGPUOnly_Flag;
}
virtual void onOnceBeforeDraw() SK_OVERRIDE {
SkImageInfo info = SkImageInfo::MakeA8(24, 24);
fBmp[0].allocPixels(info);
fBmp[1].allocPixels(info);
fBmp[2].allocPixels(info);
unsigned char* pixels[3];
for (int i = 0; i < 3; ++i) {
pixels[i] = (unsigned char*)fBmp[i].getPixels();
}
int color[] = {0, 85, 170};
const int limit[] = {255, 0, 255};
const int invl[] = {0, 255, 0};
const int inc[] = {1, -1, 1};
for (int j = 0; j < 576; ++j) {
for (int i = 0; i < 3; ++i) {
pixels[i][j] = (unsigned char)color[i];
color[i] = (color[i] == limit[i]) ? invl[i] : color[i] + inc[i];
}
}
}
virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE {
GrRenderTarget* rt = canvas->internal_private_accessTopLayerRenderTarget();
if (NULL == rt) {
return;
}
GrContext* context = rt->getContext();
if (NULL == context) {
return;
}
GrTestTarget tt;
context->getTestTarget(&tt);
if (NULL == tt.target()) {
SkDEBUGFAIL("Couldn't get Gr test target.");
return;
}
SkAutoTUnref<GrTexture> texture[3];
texture[0].reset(GrRefCachedBitmapTexture(context, fBmp[0], NULL));
texture[1].reset(GrRefCachedBitmapTexture(context, fBmp[1], NULL));
texture[2].reset(GrRefCachedBitmapTexture(context, fBmp[2], NULL));
if (!texture[0] || !texture[1] || !texture[2]) {
return;
}
static const SkScalar kDrawPad = 10.f;
static const SkScalar kTestPad = 10.f;
static const SkScalar kColorSpaceOffset = 64.f;
for (int space = kJPEG_SkYUVColorSpace; space <= kLastEnum_SkYUVColorSpace;
++space) {
SkRect renderRect = SkRect::MakeWH(SkIntToScalar(fBmp[0].width()),
SkIntToScalar(fBmp[0].height()));
renderRect.outset(kDrawPad, kDrawPad);
SkScalar y = kDrawPad + kTestPad + space * kColorSpaceOffset;
SkScalar x = kDrawPad + kTestPad;
const int indices[6][3] = {{0, 1, 2}, {0, 2, 1}, {1, 0, 2},
{1, 2, 0}, {2, 0, 1}, {2, 1, 0}};
for (int i = 0; i < 6; ++i) {
SkAutoTUnref<GrFragmentProcessor> fp(
GrYUVtoRGBEffect::Create(texture[indices[i][0]],
texture[indices[i][1]],
texture[indices[i][2]],
static_cast<SkYUVColorSpace>(space)));
if (fp) {
SkMatrix viewMatrix;
viewMatrix.setTranslate(x, y);
GrDrawState drawState;
drawState.setRenderTarget(rt);
drawState.addColorProcessor(fp);
tt.target()->drawSimpleRect(&drawState, GrColor_WHITE, viewMatrix, renderRect);
}
x += renderRect.width() + kTestPad;
}
}
}
private:
SkBitmap fBmp[3];
typedef GM INHERITED;
};
DEF_GM( return SkNEW(YUVtoRGBEffect); )
}
#endif
| 30.789855 | 99 | 0.526948 | zhaodm |
ed562103ef94506123254714804254094079389c | 15,054 | cpp | C++ | plugins/gui/src/grouping/grouping_manager_widget.cpp | e7p/hal | 2a88a8abefe5e2f79a74ec646e5fb3d8e6eb7cc8 | [
"MIT"
] | null | null | null | plugins/gui/src/grouping/grouping_manager_widget.cpp | e7p/hal | 2a88a8abefe5e2f79a74ec646e5fb3d8e6eb7cc8 | [
"MIT"
] | null | null | null | plugins/gui/src/grouping/grouping_manager_widget.cpp | e7p/hal | 2a88a8abefe5e2f79a74ec646e5fb3d8e6eb7cc8 | [
"MIT"
] | null | null | null | #include "gui/grouping/grouping_manager_widget.h"
#include "gui/gui_globals.h"
#include "gui/graph_tab_widget/graph_tab_widget.h"
#include "gui/grouping/grouping_color_delegate.h"
#include "gui/grouping/grouping_proxy_model.h"
#include "gui/input_dialog/input_dialog.h"
#include "gui/searchbar/searchbar.h"
#include "gui/gui_utils/graphics.h"
#include "gui/toolbar/toolbar.h"
#include "hal_core/utilities/log.h"
#include <QAction>
#include <QMenu>
#include <QResizeEvent>
#include <QSize>
#include <QVBoxLayout>
#include <QHeaderView>
#include <QColorDialog>
#include <QStringList>
namespace hal
{
GroupingManagerWidget::GroupingManagerWidget(GraphTabWidget* tab_view, QWidget* parent)
: ContentWidget("Groupings", parent),
mProxyModel(new GroupingProxyModel(this)),
mSearchbar(new Searchbar(this)),
mNewGroupingAction(new QAction(this)),
mRenameAction(new QAction(this)),
mColorSelectAction(new QAction(this)),
mDeleteAction(new QAction(this)),
mToSelectionAction(new QAction(this))
{
//needed to load the properties
ensurePolished();
mTabView = tab_view;
mNewGroupingAction->setIcon(gui_utility::getStyledSvgIcon(mNewGroupingIconStyle, mNewGroupingIconPath));
mRenameAction->setIcon(gui_utility::getStyledSvgIcon(mRenameGroupingIconStyle, mRenameGroupingIconPath));
mDeleteAction->setIcon(gui_utility::getStyledSvgIcon(mDeleteIconStyle, mDeleteIconPath));
mColorSelectAction->setIcon(gui_utility::getStyledSvgIcon(mColorSelectIconStyle, mColorSelectIconPath));
mToSelectionAction->setIcon(gui_utility::getStyledSvgIcon(mToSelectionIconStyle, mToSelectionIconPath));
mNewGroupingAction->setToolTip("New");
mRenameAction->setToolTip("Rename");
mColorSelectAction->setToolTip("Color");
mDeleteAction->setToolTip("Delete");
mToSelectionAction->setToolTip("To selection");
mNewGroupingAction->setText("Create new grouping");
mRenameAction->setText("Rename grouping");
mColorSelectAction->setText("Select color for grouping");
mDeleteAction->setText("Delete grouping");
mToSelectionAction->setText("Add grouping to selection");
//mOpenAction->setEnabled(false);
//mRenameAction->setEnabled(false);
//mDeleteAction->setEnabled(false);
mGroupingTableModel = new GroupingTableModel;
mProxyModel->setSourceModel(mGroupingTableModel);
mProxyModel->setSortRole(Qt::UserRole);
mGroupingTableView = new QTableView(this);
mGroupingTableView->setModel(mProxyModel);
mGroupingTableView->setSelectionBehavior(QAbstractItemView::SelectRows);
mGroupingTableView->setSelectionMode(QAbstractItemView::SingleSelection); // ERROR ???
mGroupingTableView->setContextMenuPolicy(Qt::ContextMenuPolicy::CustomContextMenu);
mGroupingTableView->verticalHeader()->hide();
mGroupingTableView->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
mGroupingTableView->setItemDelegateForColumn(2,new GroupingColorDelegate(mGroupingTableView));
mGroupingTableView->setSortingEnabled(true);
mGroupingTableView->sortByColumn(0, Qt::SortOrder::AscendingOrder);
mGroupingTableView->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch);
mGroupingTableView->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents);
mGroupingTableView->horizontalHeader()->setSectionResizeMode(2, QHeaderView::ResizeToContents);
mGroupingTableView->horizontalHeader()->setDefaultAlignment(Qt::AlignHCenter | Qt::AlignCenter);
QFont font = mGroupingTableView->horizontalHeader()->font();
font.setBold(true);
mGroupingTableView->horizontalHeader()->setFont(font);
mContentLayout->addWidget(mGroupingTableView);
mContentLayout->addWidget(mSearchbar);
mSearchbar->hide();
connect(mSearchbar, &Searchbar::textEdited, this, &GroupingManagerWidget::filter);
connect(mNewGroupingAction, &QAction::triggered, this, &GroupingManagerWidget::handleCreateGroupingClicked);
connect(mRenameAction, &QAction::triggered, this, &GroupingManagerWidget::handleRenameGroupingClicked);
connect(mColorSelectAction, &QAction::triggered, this, &GroupingManagerWidget::handleColorSelectClicked);
connect(mToSelectionAction, &QAction::triggered, this, &GroupingManagerWidget::handleToSelectionClicked);
connect(mDeleteAction, &QAction::triggered, this, &GroupingManagerWidget::handleDeleteGroupingClicked);
connect(mGroupingTableView, &QTableView::customContextMenuRequested, this, &GroupingManagerWidget::handleContextMenuRequest);
connect(mGroupingTableView->selectionModel(), &QItemSelectionModel::currentChanged, this, &GroupingManagerWidget::handleCurrentChanged);
connect(mGroupingTableModel, &GroupingTableModel::lastEntryDeleted, this, &GroupingManagerWidget::handleLastEntryDeleted);
connect(mGroupingTableModel, &GroupingTableModel::newEntryAdded, this, &GroupingManagerWidget::handleNewEntryAdded);
handleCurrentChanged();
}
QList<QShortcut*> GroupingManagerWidget::createShortcuts()
{
QShortcut* search_shortcut = gKeybindManager->makeShortcut(this, "keybinds/searchbar_toggle");
connect(search_shortcut, &QShortcut::activated, this, &GroupingManagerWidget::toggleSearchbar);
QList<QShortcut*> list;
list.append(search_shortcut);
return list;
}
void GroupingManagerWidget::handleCreateGroupingClicked()
{
mGroupingTableModel->addDefaultEntry();
}
void GroupingManagerWidget::handleColorSelectClicked()
{
QModelIndex currentIndex = mProxyModel->mapToSource(mGroupingTableView->currentIndex());
if (!currentIndex.isValid()) return;
QModelIndex nameIndex = mGroupingTableModel->index(currentIndex.row(),0);
QString name = mGroupingTableModel->data(nameIndex,Qt::DisplayRole).toString();
QModelIndex modelIndex = mGroupingTableModel->index(currentIndex.row(),2);
QColor color = mGroupingTableModel->data(modelIndex,Qt::BackgroundRole).value<QColor>();
color = QColorDialog::getColor(color,this,"Select color for grouping " + name);
if (color.isValid())
mGroupingTableModel->setData(modelIndex,color,Qt::EditRole);
}
void GroupingManagerWidget::handleToSelectionClicked()
{
QModelIndex currentIndex = mProxyModel->mapToSource(mGroupingTableView->currentIndex());
if (!currentIndex.isValid()) return;
Grouping* grp = getCurrentGrouping().grouping();
if (!grp) return;
for (Module* m : grp->get_modules())
gSelectionRelay->mSelectedModules.insert(m->get_id());
for (Gate* g : grp->get_gates())
gSelectionRelay->mSelectedGates.insert(g->get_id());
for (Net* n : grp->get_nets())
gSelectionRelay->mSelectedNets.insert(n->get_id());
gSelectionRelay->relaySelectionChanged(this);
}
void GroupingManagerWidget::handleRenameGroupingClicked()
{
QModelIndex currentIndex = mProxyModel->mapToSource(mGroupingTableView->currentIndex());
if (!currentIndex.isValid()) return;
QModelIndex modelIndex = mGroupingTableModel->index(currentIndex.row(),0);
InputDialog ipd;
ipd.setWindowTitle("Rename Grouping");
ipd.setInfoText("Please select a new unique name for the grouping.");
QString oldName = mGroupingTableModel->data(modelIndex,Qt::DisplayRole).toString();
mGroupingTableModel->setAboutToRename(oldName);
ipd.setInputText(oldName);
ipd.addValidator(mGroupingTableModel);
if (ipd.exec() == QDialog::Accepted)
mGroupingTableModel->renameGrouping(modelIndex.row(),ipd.textValue());
mGroupingTableModel->setAboutToRename(QString());
}
void GroupingManagerWidget::handleDeleteGroupingClicked()
{
mGroupingTableModel->removeRows(mProxyModel->mapToSource(mGroupingTableView->currentIndex()).row());
}
void GroupingManagerWidget::handleSelectionChanged(const QItemSelection &selected, const QItemSelection &deselected)
{
Q_UNUSED(deselected);
if(selected.indexes().isEmpty())
setToolbarButtonsEnabled(false);
else
setToolbarButtonsEnabled(true);
}
void GroupingManagerWidget::handleContextMenuRequest(const QPoint& point)
{
const QModelIndex clicked_index = mGroupingTableView->indexAt(point);
QMenu context_menu;
context_menu.addAction(mNewGroupingAction);
if (clicked_index.isValid())
{
context_menu.addAction(mRenameAction);
context_menu.addAction(mColorSelectAction);
context_menu.addAction(mToSelectionAction);
context_menu.addAction(mDeleteAction);
}
context_menu.exec(mGroupingTableView->viewport()->mapToGlobal(point));
}
GroupingTableEntry GroupingManagerWidget::getCurrentGrouping()
{
QModelIndex modelIndex = mProxyModel->mapToSource(mGroupingTableView->currentIndex());
return mGroupingTableModel->groupingAt(modelIndex.row());
}
void GroupingManagerWidget::setupToolbar(Toolbar* toolbar)
{
toolbar->addAction(mNewGroupingAction);
toolbar->addAction(mRenameAction);
toolbar->addAction(mColorSelectAction);
toolbar->addAction(mToSelectionAction);
toolbar->addAction(mDeleteAction);
}
void GroupingManagerWidget::setToolbarButtonsEnabled(bool enabled)
{
mRenameAction->setEnabled(enabled);
mColorSelectAction->setEnabled(enabled);
mToSelectionAction->setEnabled(enabled);
mDeleteAction->setEnabled(enabled);
}
void GroupingManagerWidget::handleNewEntryAdded(const QModelIndex& modelIndex)
{
if (!modelIndex.isValid()) return;
QModelIndex proxyIndex = mProxyModel->mapFromSource(modelIndex);
if (!proxyIndex.isValid()) return;
mGroupingTableView->setCurrentIndex(proxyIndex);
handleCurrentChanged(proxyIndex);
}
void GroupingManagerWidget::handleLastEntryDeleted()
{
if (mProxyModel->rowCount())
{
QModelIndex inx = mProxyModel->index(0,0);
mGroupingTableView->setCurrentIndex(inx);
handleCurrentChanged(inx);
}
else
handleCurrentChanged();
}
void GroupingManagerWidget::handleCurrentChanged(const QModelIndex& current, const QModelIndex& previous)
{
Q_UNUSED(previous);
bool enable = mGroupingTableModel->rowCount() > 0 && current.isValid();
QAction* entryBasedAction[] = { mRenameAction, mColorSelectAction,
mDeleteAction, mToSelectionAction, nullptr};
QStringList iconPath, iconStyle;
iconPath << mRenameGroupingIconPath << mColorSelectIconPath
<< mDeleteIconPath << mToSelectionIconPath;
iconStyle << mRenameGroupingIconStyle << mColorSelectIconStyle
<< mDeleteIconStyle << mToSelectionIconStyle;
for (int iacc = 0; entryBasedAction[iacc]; iacc++)
{
entryBasedAction[iacc]->setEnabled(enable);
entryBasedAction[iacc]->setIcon(
gui_utility::getStyledSvgIcon(enable
? iconStyle.at(iacc)
: disabledIconStyle(),
iconPath.at(iacc)));
}
}
void GroupingManagerWidget::toggleSearchbar()
{
if (mSearchbar->isHidden())
{
mSearchbar->show();
mSearchbar->setFocus();
}
else
mSearchbar->hide();
}
void GroupingManagerWidget::filter(const QString& text)
{
QRegExp* regex = new QRegExp(text);
if (regex->isValid())
{
mProxyModel->setFilterRegExp(*regex);
QString output = "Groupings widget regular expression '" + text + "' entered.";
log_info("user", output.toStdString());
}
}
QString GroupingManagerWidget::disabledIconStyle() const
{
return mDisabledIconStyle;
}
QString GroupingManagerWidget::newGroupingIconPath() const
{
return mNewGroupingIconPath;
}
QString GroupingManagerWidget::newGroupingIconStyle() const
{
return mNewGroupingIconStyle;
}
QString GroupingManagerWidget::renameGroupingIconPath() const
{
return mRenameGroupingIconPath;
}
QString GroupingManagerWidget::renameGroupingIconStyle() const
{
return mRenameGroupingIconStyle;
}
QString GroupingManagerWidget::deleteIconPath() const
{
return mDeleteIconPath;
}
QString GroupingManagerWidget::deleteIconStyle() const
{
return mDeleteIconStyle;
}
QString GroupingManagerWidget::colorSelectIconPath() const
{
return mColorSelectIconPath;
}
QString GroupingManagerWidget::colorSelectIconStyle() const
{
return mColorSelectIconStyle;
}
QString GroupingManagerWidget::toSelectionIconPath() const
{
return mToSelectionIconPath;
}
QString GroupingManagerWidget::toSelectionIconStyle() const
{
return mToSelectionIconStyle;
}
void GroupingManagerWidget::setDisabledIconStyle(const QString& style)
{
mDisabledIconStyle = style;
}
void GroupingManagerWidget::setNewGroupingIconPath(const QString& path)
{
mNewGroupingIconPath = path;
}
void GroupingManagerWidget::setNewGroupingIconStyle(const QString& style)
{
mNewGroupingIconStyle = style;
}
void GroupingManagerWidget::setRenameGroupingIconPath(const QString& path)
{
mRenameGroupingIconPath = path;
}
void GroupingManagerWidget::setRenameGroupingIconStyle(const QString& style)
{
mRenameGroupingIconStyle = style;
}
void GroupingManagerWidget::setDeleteIconPath(const QString& path)
{
mDeleteIconPath = path;
}
void GroupingManagerWidget::setDeleteIconStyle(const QString& style)
{
mDeleteIconStyle = style;
}
void GroupingManagerWidget::setColorSelectIconPath(const QString& path)
{
mColorSelectIconPath = path;
}
void GroupingManagerWidget::setColorSelectIconStyle(const QString& style)
{
mColorSelectIconStyle = style;
}
void GroupingManagerWidget::setToSelectionIconPath(const QString& path)
{
mToSelectionIconPath = path;
}
void GroupingManagerWidget::setToSelectionIconStyle(const QString& style)
{
mToSelectionIconStyle = style;
}
}
| 37.354839 | 144 | 0.687724 | e7p |
ed56342a68c738c824389e349e942e22dc9c813c | 1,880 | cpp | C++ | src/model/seasonlistmodel.cpp | sailfish-os-apps/harbour-sailseries | df8fb67b720e4ba9f8c4644ebc03cf90bb745e3c | [
"MIT"
] | null | null | null | src/model/seasonlistmodel.cpp | sailfish-os-apps/harbour-sailseries | df8fb67b720e4ba9f8c4644ebc03cf90bb745e3c | [
"MIT"
] | null | null | null | src/model/seasonlistmodel.cpp | sailfish-os-apps/harbour-sailseries | df8fb67b720e4ba9f8c4644ebc03cf90bb745e3c | [
"MIT"
] | null | null | null | #include "seasonlistmodel.h"
SeasonListModel::SeasonListModel(QObject *parent, DatabaseManager* dbmanager) :
QObject(parent)
{
m_dbmanager = dbmanager;
}
SeasonListModel::~SeasonListModel()
{
for (auto season : m_seasonListModel) {
delete season;
season = 0;
}
}
QQmlListProperty<SeasonData> SeasonListModel::getSeasonList()
{
return QQmlListProperty<SeasonData>(this, &m_seasonListModel, &SeasonListModel::seasonListCount, &SeasonListModel::seasonListAt);
}
// list handling methods
void SeasonListModel::seasonListAppend(QQmlListProperty<SeasonData>* prop, SeasonData* val)
{
SeasonListModel* seasonListModel = qobject_cast<SeasonListModel*>(prop->object);
seasonListModel->m_seasonListModel.append(val);
}
SeasonData* SeasonListModel::seasonListAt(QQmlListProperty<SeasonData>* prop, int index)
{
return (qobject_cast<SeasonListModel*>(prop->object))->m_seasonListModel.at(index);
}
int SeasonListModel::seasonListCount(QQmlListProperty<SeasonData>* prop)
{
return qobject_cast<SeasonListModel*>(prop->object)->m_seasonListModel.size();
}
void SeasonListModel::seasonListClear(QQmlListProperty<SeasonData>* prop)
{
qobject_cast<SeasonListModel*>(prop->object)->m_seasonListModel.clear();
}
void SeasonListModel::populateSeasonList(QString seriesID)
{
m_seasonListModel.clear();
int seasonsCount = m_dbmanager->seasonCount(seriesID.toInt());
for (int i = 1; i <= seasonsCount; ++i) {
QString banner = m_dbmanager->getSeasonBanner(seriesID.toInt(),i);
int watchedCount = m_dbmanager->watchedCountBySeason(seriesID.toInt(),i);
int totalCount = m_dbmanager->totalCountBySeason(seriesID.toInt(),i);
SeasonData* seasonData = new SeasonData(this, i, banner, watchedCount, totalCount);
m_seasonListModel.append(seasonData);
}
emit seasonListChanged();
}
| 29.84127 | 133 | 0.743617 | sailfish-os-apps |
ed5a55a0d431d28bd8c2e93e9da44b446141e59e | 20,129 | cc | C++ | code/machine/mips_sim.cc | barufa/nachos | c61004eb45144835180be12eefc250d470842d04 | [
"MIT"
] | 1 | 2019-10-21T02:22:16.000Z | 2019-10-21T02:22:16.000Z | code/machine/mips_sim.cc | barufa/Nachos | c61004eb45144835180be12eefc250d470842d04 | [
"MIT"
] | null | null | null | code/machine/mips_sim.cc | barufa/Nachos | c61004eb45144835180be12eefc250d470842d04 | [
"MIT"
] | null | null | null | /// Simulate a MIPS R2/3000 processor.
///
/// This code has been adapted from Ousterhout's MIPSSIM package. Byte
/// ordering is little-endian, so we can be compatible with DEC RISC systems.
///
/// DO NOT CHANGE -- part of the machine emulation
///
/// Copyright (c) 1992-1993 The Regents of the University of California.
/// 2016-2017 Docentes de la Universidad Nacional de Rosario.
/// All rights reserved. See `copyright.h` for copyright notice and
/// limitation of liability and disclaimer of warranty provisions.
#include "instruction.hh"
#include "machine.hh"
#include "threads/system.hh"
/// Simulate the execution of a user-level program on Nachos.
///
/// Called by the kernel when the program starts up; never returns.
///
/// This routine is re-entrant, in that it can be called multiple times
/// concurrently -- one for each thread executing user code.
void
Machine::Run()
{
Instruction * instr = new Instruction;
// Storage for decoded instruction.
if (debug.IsEnabled('m'))
printf("Starting to run at time %u\n", stats->totalTicks);
interrupt->SetStatus(USER_MODE);
for (;;) {
if (FetchInstruction(instr))
ExecInstruction(instr);
interrupt->OneTick();
if (singleStepper != nullptr && !singleStepper->Step())
singleStepper = nullptr;
}
}
/// Simulate effects of a delayed load.
///
/// NOTE -- `RaiseException`/`CheckInterrupts` must also call `DelayedLoad`,
/// since any delayed load must get applied before we trap to the kernel.
void
Machine::DelayedLoad(unsigned nextReg, int nextValue)
{
registers[registers[LOAD_REG]] = registers[LOAD_VALUE_REG];
registers[LOAD_REG] = nextReg;
registers[LOAD_VALUE_REG] = nextValue;
registers[0] = 0; // And always make sure R0 stays zero.
}
bool
Machine::FetchInstruction(Instruction * instr)
{
ASSERT(instr != nullptr);
int raw;
if (!ReadMem(registers[PC_REG], 4, &raw))
return false; // Exception occurred.
instr->value = raw;
instr->Decode();
if (debug.IsEnabled('m')) {
const struct OpString * str = &OP_STRINGS[instr->opCode];
ASSERT(instr->opCode <= MAX_OPCODE);
DEBUG('P', "At PC = 0x%X: ", registers[PC_REG]);
DEBUG_CONT('P', str->string, instr->RegFromType(str->args[0]),
instr->RegFromType(str->args[1]),
instr->RegFromType(str->args[2]));
DEBUG_CONT('P', "\n");
}
return true;
}
/// Simulate R2000 multiplication.
///
/// The words at `*hiPtr` and `*loPtr` are overwritten with the double-length
/// result of the multiplication.
static void
Mult(int a, int b, bool signedArith, int * hiPtr, int * loPtr)
{
ASSERT(hiPtr != nullptr);
ASSERT(loPtr != nullptr);
if (a == 0 || b == 0) {
*hiPtr = *loPtr = 0;
return;
}
// Compute the sign of the result, then make everything positive so
// unsigned computation can be done in the main loop.
bool negative = false;
if (signedArith) {
if (a < 0) {
negative = !negative;
a = -a;
}
if (b < 0) {
negative = !negative;
b = -b;
}
}
// Compute the result in unsigned arithmetic (check `a`'s bits one at a
// time, and add in a shifted value of `b`).
unsigned bLo = b;
unsigned bHi = 0;
unsigned lo = 0;
unsigned hi = 0;
for (unsigned i = 0; i < 32; i++) {
if (a & 1) {
lo += bLo;
if (lo < bLo) // Carry out of the low bits?
hi += 1;
hi += bHi;
if ((a & 0xFFFFFFFE) == 0)
break;
}
bHi <<= 1;
if (bLo & 0x80000000)
bHi |= 1;
bLo <<= 1;
a >>= 1;
}
// If the result is supposed to be negative, compute the two's complement
// of the double-word result.
if (negative) {
hi = ~hi;
lo = ~lo;
lo++;
if (lo == 0)
hi++;
}
*hiPtr = (int) hi;
*loPtr = (int) lo;
} // Mult
/// Execute one instruction from a user-level program.
///
/// If there is any kind of exception or interrupt, we invoke the exception
/// handler, and when it returns, we return to `Run`, which will re-invoke us
/// in a loop. This allows us to re-start the instruction execution from the
/// beginning, in case any of our state has changed. On a syscall, the OS
/// software must increment the PC so execution begins at the instruction
/// immediately after the syscall.
///
/// This routine is re-entrant, in that it can be called multiple times
/// concurrently -- one for each thread executing user code. We get
/// re-entrancy by never caching any data -- we always re-start the
/// simulation from scratch each time we are called (or after trapping back
/// to the Nachos kernel on an exception or interrupt), and we always store
/// all data back to the machine registers and memory before leaving. This
/// allows the Nachos kernel to control our behavior by controlling the
/// contents of memory, the translation table, and the register set.
void
Machine::ExecInstruction(const Instruction * instr)
{
int nextLoadReg = 0;
int nextLoadValue = 0; // Record delayed load operation, to apply in the
// future.
// Compute next pc, but do not install in case there is an error or
// branch.
int pcAfter = registers[NEXT_PC_REG] + 4;
int sum, diff, tmp, value;
unsigned rs, rt, imm;
// Execute the instruction (cf. Kane's book).
switch (instr->opCode) {
case OP_ADD:
sum = registers[instr->rs] + registers[instr->rt];
if (!((registers[instr->rs] ^ registers[instr->rt]) & SIGN_BIT) &&
(registers[instr->rs] ^ sum) & SIGN_BIT)
{
RaiseException(OVERFLOW_EXCEPTION, 0);
return;
}
registers[instr->rd] = sum;
break;
case OP_ADDI:
sum = registers[instr->rs] + instr->extra;
if (!((registers[instr->rs] ^ instr->extra) & SIGN_BIT) &&
(instr->extra ^ sum) & SIGN_BIT)
{
RaiseException(OVERFLOW_EXCEPTION, 0);
return;
}
registers[instr->rt] = sum;
break;
case OP_ADDIU:
registers[instr->rt] = registers[instr->rs] + instr->extra;
break;
case OP_ADDU:
registers[instr->rd] = registers[instr->rs]
+ registers[instr->rt];
break;
case OP_AND:
registers[instr->rd] = registers[instr->rs]
& registers[instr->rt];
break;
case OP_ANDI:
registers[instr->rt] = registers[instr->rs]
& (instr->extra & 0xFFFF);
break;
case OP_BEQ:
if (registers[instr->rs] == registers[instr->rt])
pcAfter = registers[NEXT_PC_REG] + IndexToAddr(instr->extra);
break;
case OP_BGEZAL:
registers[RET_ADDR_REG] = registers[NEXT_PC_REG] + 4;
case OP_BGEZ:
if (!(registers[instr->rs] & SIGN_BIT))
pcAfter = registers[NEXT_PC_REG] + IndexToAddr(instr->extra);
break;
case OP_BGTZ:
if (registers[instr->rs] > 0)
pcAfter = registers[NEXT_PC_REG] + IndexToAddr(instr->extra);
break;
case OP_BLEZ:
if (registers[instr->rs] <= 0)
pcAfter = registers[NEXT_PC_REG] + IndexToAddr(instr->extra);
break;
case OP_BLTZAL:
registers[RET_ADDR_REG] = registers[NEXT_PC_REG] + 4;
case OP_BLTZ:
if (registers[instr->rs] & SIGN_BIT)
pcAfter = registers[NEXT_PC_REG] + IndexToAddr(instr->extra);
break;
case OP_BNE:
if (registers[instr->rs] != registers[instr->rt])
pcAfter = registers[NEXT_PC_REG] + IndexToAddr(instr->extra);
break;
case OP_DIV:
if (registers[instr->rt] == 0) {
registers[LO_REG] = 0;
registers[HI_REG] = 0;
} else {
registers[LO_REG] = registers[instr->rs]
/ registers[instr->rt];
registers[HI_REG] = registers[instr->rs]
% registers[instr->rt];
}
break;
case OP_DIVU:
rs = (unsigned) registers[instr->rs];
rt = (unsigned) registers[instr->rt];
if (rt == 0) {
registers[LO_REG] = 0;
registers[HI_REG] = 0;
} else {
tmp = rs / rt;
registers[LO_REG] = (int) tmp;
tmp = rs % rt;
registers[HI_REG] = (int) tmp;
}
break;
case OP_JAL:
registers[RET_ADDR_REG] = registers[NEXT_PC_REG] + 4;
case OP_J:
pcAfter = (pcAfter & 0xF0000000) | IndexToAddr(instr->extra);
break;
case OP_JALR:
registers[instr->rd] = registers[NEXT_PC_REG] + 4;
case OP_JR:
pcAfter = registers[instr->rs];
break;
case OP_LB:
case OP_LBU:
tmp = registers[instr->rs] + instr->extra;
if (!ReadMem(tmp, 1, &value))
return;
if (value & 0x80 && instr->opCode == OP_LB)
value |= 0xFFFFFF00;
else
value &= 0xFF;
nextLoadReg = instr->rt;
nextLoadValue = value;
break;
case OP_LH:
case OP_LHU:
tmp = registers[instr->rs] + instr->extra;
if (tmp & 0x1) {
RaiseException(ADDRESS_ERROR_EXCEPTION, tmp);
return;
}
if (!ReadMem(tmp, 2, &value))
return;
if (value & 0x8000 && instr->opCode == OP_LH)
value |= 0xFFFF0000;
else
value &= 0xFFFF;
nextLoadReg = instr->rt;
nextLoadValue = value;
break;
case OP_LUI:
DEBUG('P', "Executing: LUI r%d,%d\n", instr->rt, instr->extra);
registers[instr->rt] = instr->extra << 16;
break;
case OP_LW:
tmp = registers[instr->rs] + instr->extra;
if (tmp & 0x3) {
RaiseException(ADDRESS_ERROR_EXCEPTION, tmp);
return;
}
if (!ReadMem(tmp, 4, &value))
return;
nextLoadReg = instr->rt;
nextLoadValue = value;
break;
case OP_LWL:
tmp = registers[instr->rs] + instr->extra;
// `ReadMem` assumes all 4 byte requests are aligned on an even
// word boundary. Also, the little endian/big endian swap code
// would fail (I think) if the other cases are ever exercised.
ASSERT((tmp & 0x3) == 0);
if (!ReadMem(tmp, 4, &value))
return;
if (registers[LOAD_REG] == instr->rt)
nextLoadValue = registers[LOAD_VALUE_REG];
else
nextLoadValue = registers[instr->rt];
switch (tmp & 0x3) {
case 0:
nextLoadValue = value;
break;
case 1:
nextLoadValue = (nextLoadValue & 0xFF) | value << 8;
break;
case 2:
nextLoadValue = (nextLoadValue & 0xFFFF) | value << 16;
break;
case 3:
nextLoadValue = (nextLoadValue & 0xFFFFFF) | value << 24;
break;
}
nextLoadReg = instr->rt;
break;
case OP_LWR:
tmp = registers[instr->rs] + instr->extra;
// `ReadMem` assumes all 4 byte requests are aligned on an even
// word boundary. Also, the little endian/big endian swap code
// would fail (I think) if the other cases are ever exercised.
ASSERT((tmp & 0x3) == 0);
if (!ReadMem(tmp, 4, &value))
return;
if (registers[LOAD_REG] == instr->rt)
nextLoadValue = registers[LOAD_VALUE_REG];
else
nextLoadValue = registers[instr->rt];
switch (tmp & 0x3) {
case 0:
nextLoadValue = (nextLoadValue & 0xFFFFFF00)
| (value >> 24 & 0xFF);
break;
case 1:
nextLoadValue = (nextLoadValue & 0xFFFF0000)
| (value >> 16 & 0xFFFF);
break;
case 2:
nextLoadValue = (nextLoadValue & 0xFF000000)
| (value >> 8 & 0xFFFFFF);
break;
case 3:
nextLoadValue = value;
break;
}
nextLoadReg = instr->rt;
break;
case OP_MFHI:
registers[instr->rd] = registers[HI_REG];
break;
case OP_MFLO:
registers[instr->rd] = registers[LO_REG];
break;
case OP_MTHI:
registers[HI_REG] = registers[instr->rs];
break;
case OP_MTLO:
registers[LO_REG] = registers[instr->rs];
break;
case OP_MULT:
Mult(registers[instr->rs], registers[instr->rt],
true, ®isters[HI_REG], ®isters[LO_REG]);
break;
case OP_MULTU:
Mult(registers[instr->rs], registers[instr->rt],
false, ®isters[HI_REG], ®isters[LO_REG]);
break;
case OP_NOR:
registers[instr->rd] = ~(registers[instr->rs]
| registers[instr->rt]);
break;
case OP_OR:
registers[instr->rd] = registers[instr->rs]
| registers[instr->rt];
break;
case OP_ORI:
registers[instr->rt] = registers[instr->rs]
| (instr->extra & 0xFFFF);
break;
case OP_SB:
if (!WriteMem((unsigned) (registers[instr->rs] + instr->extra),
1, registers[instr->rt]))
return;
break;
case OP_SH:
if (!WriteMem((unsigned) (registers[instr->rs] + instr->extra),
2, registers[instr->rt]))
return;
break;
case OP_SLL:
registers[instr->rd] = registers[instr->rt] << instr->extra;
break;
case OP_SLLV:
registers[instr->rd] = registers[instr->rt]
<< (registers[instr->rs] & 0x1F);
break;
case OP_SLT:
if (registers[instr->rs] < registers[instr->rt])
registers[instr->rd] = 1;
else
registers[instr->rd] = 0;
break;
case OP_SLTI:
if (registers[instr->rs] < instr->extra)
registers[instr->rt] = 1;
else
registers[instr->rt] = 0;
break;
case OP_SLTIU:
rs = registers[instr->rs];
imm = instr->extra;
if (rs < imm)
registers[instr->rt] = 1;
else
registers[instr->rt] = 0;
break;
case OP_SLTU:
rs = registers[instr->rs];
rt = registers[instr->rt];
if (rs < rt)
registers[instr->rd] = 1;
else
registers[instr->rd] = 0;
break;
case OP_SRA:
registers[instr->rd] = registers[instr->rt] >> instr->extra;
break;
case OP_SRAV:
registers[instr->rd] = registers[instr->rt]
>> (registers[instr->rs] & 0x1F);
break;
case OP_SRL:
tmp = registers[instr->rt];
tmp >>= instr->extra;
registers[instr->rd] = tmp;
break;
case OP_SRLV:
tmp = registers[instr->rt];
tmp >>= registers[instr->rs] & 0x1F;
registers[instr->rd] = tmp;
break;
case OP_SUB:
diff = registers[instr->rs] - registers[instr->rt];
if ((registers[instr->rs] ^ registers[instr->rt]) & SIGN_BIT &&
(registers[instr->rs] ^ diff) & SIGN_BIT)
{
RaiseException(OVERFLOW_EXCEPTION, 0);
return;
}
registers[instr->rd] = diff;
break;
case OP_SUBU:
registers[instr->rd] = registers[instr->rs]
- registers[instr->rt];
break;
case OP_SW:
if (!WriteMem((unsigned) (registers[instr->rs] + instr->extra),
4, registers[instr->rt]))
return;
break;
case OP_SWL:
tmp = registers[instr->rs] + instr->extra;
// The little endian/big endian swap code would fail (I think) if
// the other cases are ever exercised.
ASSERT((tmp & 0x3) == 0);
if (!ReadMem(tmp & ~0x3, 4, &value))
return;
switch (tmp & 0x3) {
case 0:
value = registers[instr->rt];
break;
case 1:
value = (value & 0xFF000000)
| (registers[instr->rt] >> 8 & 0xFFFFFF);
break;
case 2:
value = (value & 0xFFFF0000)
| (registers[instr->rt] >> 16 & 0xFFFF);
break;
case 3:
value = (value & 0xFFFFFF00)
| (registers[instr->rt] >> 24 & 0xFF);
break;
}
if (!WriteMem(tmp & ~0x3, 4, value))
return;
break;
case OP_SWR:
tmp = registers[instr->rs] + instr->extra;
// The little endian/big endian swap code would fail (I think) if
// the other cases are ever exercised.
ASSERT((tmp & 0x3) == 0);
if (!ReadMem(tmp & ~0x3, 4, &value))
return;
switch (tmp & 0x3) {
case 0:
value = (value & 0xFFFFFF)
| registers[instr->rt] << 24;
break;
case 1:
value = (value & 0xFFFF)
| registers[instr->rt] << 16;
break;
case 2:
value = (value & 0xFF) | registers[instr->rt] << 8;
break;
case 3:
value = registers[instr->rt];
break;
}
if (!WriteMem(tmp & ~0x3, 4, value))
return;
break;
case OP_SYSCALL:
RaiseException(SYSCALL_EXCEPTION, 0);
return;
case OP_XOR:
registers[instr->rd] = registers[instr->rs]
^ registers[instr->rt];
break;
case OP_XORI:
registers[instr->rt] = registers[instr->rs]
^ (instr->extra & 0xFFFF);
break;
case OP_RES:
case OP_UNIMP:
RaiseException(ILLEGAL_INSTR_EXCEPTION, 0);
return;
default:
ASSERT(false);
}
// Now we have successfully executed the instruction.
// Do any delayed load operation.
DelayedLoad(nextLoadReg, nextLoadValue);
// Advance program counters.
registers[PREV_PC_REG] = registers[PC_REG];
// For debugging, in case we are jumping into lala-land.
registers[PC_REG] = registers[NEXT_PC_REG];
registers[NEXT_PC_REG] = pcAfter;
} // Machine::ExecInstruction
| 31.063272 | 78 | 0.498038 | barufa |
ed5ccab1bbc5d5d87fd8ef351769529774b248b6 | 3,398 | cpp | C++ | src/prediction.cpp | zardosht/Path_Planning_SDCP7 | d7bad37e81e1345737e9c4e44d5d15386bbe10c3 | [
"MIT"
] | 1 | 2021-03-24T11:17:34.000Z | 2021-03-24T11:17:34.000Z | src/prediction.cpp | zardosht/Path_Planning_SDCP7 | d7bad37e81e1345737e9c4e44d5d15386bbe10c3 | [
"MIT"
] | null | null | null | src/prediction.cpp | zardosht/Path_Planning_SDCP7 | d7bad37e81e1345737e9c4e44d5d15386bbe10c3 | [
"MIT"
] | null | null | null | #include <math.h>
#include <iostream>
#include <math.h>
#include "prediction.h"
using std::cout;
using std::endl;
using std::min;
using std::max;
Prediction::Prediction()
{
init_lanes();
}
Prediction::~Prediction() { }
void Prediction::update(vector<vector<double>>& sensor_fusion, Vehicle& egocar, Trajectory& prev_path)
{
int prev_path_size = prev_path.size();
int ego_lane = egocar.get_lane();
double ego_s = egocar.s;
if (prev_path_size > 2) {
ego_s = prev_path.end_s;
}
reset_lanes();
for (int i = 0; i < sensor_fusion.size(); ++i)
{
if (sensor_fusion[i][6] < 0) continue;
Vehicle car((int)sensor_fusion[i][0], //id
sensor_fusion[i][1], //x
sensor_fusion[i][2], //y
sensor_fusion[i][3], //vx
sensor_fusion[i][4], //vy
sensor_fusion[i][5], //s
sensor_fusion[i][6]); //d
// projection of s value of the car in the future
// (i.e. when we would have passed through all the
// points in previous_path)
int car_lane = car.get_lane();
double car_speed = sqrt(car.vx*car.vx + car.vy*car.vy); // m/s
car.s += (double)prev_path_size * TIMESTEP * car_speed;
// distance from ego car to the car in front of us
double dist = car.s - ego_s;
Lane& lane = lanes[car_lane];
if (lane.id == ego_lane) {
if(dist >= 0 && dist < TOO_CLOSE_GAP) {
lane.blocked = true;
}
} else {
double delta_v = egocar.speed - car_speed;
double adapted_lcgap_f = LANE_CHANGE_GAP_FRONT + delta_v;
double adapted_lcgap_r = min(LANE_CHANGE_GAP_REAR + delta_v, -10.0);
if (adapted_lcgap_r < dist && dist < adapted_lcgap_f) {
lane.blocked = true;
}
}
if(dist >= 0) {
lane.front_dist = min(lane.front_dist, dist);
if (dist < TOO_CLOSE_GAP) {
lane.front_v = min(lane.front_v, car_speed);
} else {
lane.front_v = min(lane.front_v, MAX_SPEED);
}
}
}
bool all_bloked = true;
for (int i = 0; i < NUM_LANES; i++) {
all_bloked &= lanes[i].blocked;
}
all_lanes_blocked = all_bloked;
}
void Prediction::init_lanes()
{
for (int i = 0; i < NUM_LANES; i++)
{
Lane lane;
lane.id = i;
lane.blocked = false;
lane.front_dist = PREDICTION_HIROZON;
lane.front_v = MAX_SPEED;
lanes.push_back(lane);
}
}
void Prediction::reset_lanes()
{
all_lanes_blocked = false;
for (int i = 0; i < NUM_LANES; i++)
{
lanes[i].blocked = false;
lanes[i].front_dist = PREDICTION_HIROZON;
lanes[i].front_v = MAX_SPEED;
}
}
std::ostream& operator<<(std::ostream &strm, const Prediction &pred) {
for (int i = 0; i < NUM_LANES; i++)
{
const Lane& lane = pred.lanes[i];
strm << "Lane " << i
<< ": blocked=" << lane.blocked
<< ", front_dist=" << lane.front_dist
<< ", front_v=" << lane.front_v << endl;
}
strm << "---- ALL_BLOCKED=" << pred.all_lanes_blocked << endl;
return strm;
}
| 26.755906 | 102 | 0.524426 | zardosht |
ed5d40ec16569384379998e22dd30acdc9503ab0 | 8,022 | cpp | C++ | src/arch/ArchHooks/ArchHooks_Win32.cpp | caiohsr14/stepmania | 7d33efe587c75a683938aeabafc1ec2bec3007d6 | [
"MIT"
] | null | null | null | src/arch/ArchHooks/ArchHooks_Win32.cpp | caiohsr14/stepmania | 7d33efe587c75a683938aeabafc1ec2bec3007d6 | [
"MIT"
] | null | null | null | src/arch/ArchHooks/ArchHooks_Win32.cpp | caiohsr14/stepmania | 7d33efe587c75a683938aeabafc1ec2bec3007d6 | [
"MIT"
] | null | null | null | #include "global.h"
#include "ArchHooks_Win32.h"
#include "RageUtil.h"
#include "RageLog.h"
#include "RageThreads.h"
#include "ProductInfo.h"
#include "archutils/win32/AppInstance.h"
#include "archutils/win32/crash.h"
#include "archutils/win32/DebugInfoHunt.h"
#include "archutils/win32/ErrorStrings.h"
#include "archutils/win32/RestartProgram.h"
#include "archutils/win32/GotoURL.h"
#include "archutils/Win32/RegistryAccess.h"
static HANDLE g_hInstanceMutex;
static bool g_bIsMultipleInstance = false;
#if _MSC_VER >= 1400 // VC8
void InvalidParameterHandler( const wchar_t *szExpression, const wchar_t *szFunction, const wchar_t *szFile,
unsigned int iLine, uintptr_t pReserved )
{
FAIL_M( "Invalid parameter" ); //TODO: Make this more informative
}
#endif
ArchHooks_Win32::ArchHooks_Win32()
{
HOOKS = this;
/* Disable critical errors, and handle them internally. We never want the
* "drive not ready", etc. dialogs to pop up. */
SetErrorMode( SetErrorMode(0) | SEM_FAILCRITICALERRORS );
CrashHandler::CrashHandlerHandleArgs( g_argc, g_argv );
SetUnhandledExceptionFilter( CrashHandler::ExceptionHandler );
#if _MSC_VER >= 1400 // VC8
_set_invalid_parameter_handler( InvalidParameterHandler );
#endif
/* Windows boosts priority on keyboard input, among other things. Disable that for
* the main thread. */
SetThreadPriorityBoost( GetCurrentThread(), TRUE );
g_hInstanceMutex = CreateMutex( NULL, TRUE, PRODUCT_ID );
g_bIsMultipleInstance = false;
if( GetLastError() == ERROR_ALREADY_EXISTS )
g_bIsMultipleInstance = true;
}
ArchHooks_Win32::~ArchHooks_Win32()
{
CloseHandle( g_hInstanceMutex );
}
void ArchHooks_Win32::DumpDebugInfo()
{
/* This is a good time to do the debug search: before we actually
* start OpenGL (in case something goes wrong). */
SearchForDebugInfo();
}
struct CallbackData
{
HWND hParent;
HWND hResult;
};
// Like GW_ENABLEDPOPUP:
static BOOL CALLBACK GetEnabledPopup( HWND hWnd, LPARAM lParam )
{
CallbackData *pData = (CallbackData *) lParam;
if( GetParent(hWnd) != pData->hParent )
return TRUE;
if( (GetWindowLong(hWnd, GWL_STYLE) & WS_POPUP) != WS_POPUP )
return TRUE;
if( !IsWindowEnabled(hWnd) )
return TRUE;
pData->hResult = hWnd;
return FALSE;
}
bool ArchHooks_Win32::CheckForMultipleInstances(int argc, char* argv[])
{
if( !g_bIsMultipleInstance )
return false;
/* Search for the existing window. Prefer to use the class name, which is less likely to
* have a false match, and will match the gameplay window. If that fails, try the window
* name, which should match the loading window. */
HWND hWnd = FindWindow( PRODUCT_ID, NULL );
if( hWnd == NULL )
hWnd = FindWindow( NULL, PRODUCT_ID );
if( hWnd != NULL )
{
/* If the application has a model dialog box open, we want to be sure to give focus to it,
* not the main window. */
CallbackData data;
data.hParent = hWnd;
data.hResult = NULL;
EnumWindows( GetEnabledPopup, (LPARAM) &data );
if( data.hResult != NULL )
SetForegroundWindow( data.hResult );
else
SetForegroundWindow( hWnd );
// Send the command line to the existing window.
vector<RString> vsArgs;
for( int i=0; i<argc; i++ )
vsArgs.push_back( argv[i] );
RString sAllArgs = join("|", vsArgs);
COPYDATASTRUCT cds;
cds.dwData = 0;
cds.cbData = sAllArgs.size();
cds.lpData = (void*)sAllArgs.data();
SendMessage(
(HWND)hWnd, // HWND hWnd = handle of destination window
WM_COPYDATA,
(WPARAM)NULL, // HANDLE OF SENDING WINDOW
(LPARAM)&cds ); // 2nd msg parameter = pointer to COPYDATASTRUCT
}
return true;
}
void ArchHooks_Win32::RestartProgram()
{
Win32RestartProgram();
}
void ArchHooks_Win32::SetTime( tm newtime )
{
SYSTEMTIME st;
ZERO( st );
st.wYear = (WORD)newtime.tm_year+1900;
st.wMonth = (WORD)newtime.tm_mon+1;
st.wDay = (WORD)newtime.tm_mday;
st.wHour = (WORD)newtime.tm_hour;
st.wMinute = (WORD)newtime.tm_min;
st.wSecond = (WORD)newtime.tm_sec;
st.wMilliseconds = 0;
SetLocalTime( &st );
}
void ArchHooks_Win32::BoostPriority()
{
/* We just want a slight boost, so we don't skip needlessly if something happens
* in the background. We don't really want to be high-priority--above normal should
* be enough. However, ABOVE_NORMAL_PRIORITY_CLASS is only supported in Win2000
* and later. */
OSVERSIONINFO version;
version.dwOSVersionInfoSize=sizeof(version);
if( !GetVersionEx(&version) )
{
LOG->Warn( werr_ssprintf(GetLastError(), "GetVersionEx failed") );
return;
}
#ifndef ABOVE_NORMAL_PRIORITY_CLASS
#define ABOVE_NORMAL_PRIORITY_CLASS 0x00008000
#endif
DWORD pri = HIGH_PRIORITY_CLASS;
if( version.dwMajorVersion >= 5 )
pri = ABOVE_NORMAL_PRIORITY_CLASS;
/* Be sure to boost the app, not the thread, to make sure the
* sound thread stays higher priority than the main thread. */
SetPriorityClass( GetCurrentProcess(), pri );
}
void ArchHooks_Win32::UnBoostPriority()
{
SetPriorityClass( GetCurrentProcess(), NORMAL_PRIORITY_CLASS );
}
void ArchHooks_Win32::SetupConcurrentRenderingThread()
{
SetThreadPriority( GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL );
}
bool ArchHooks_Win32::GoToURL( const RString &sUrl )
{
return ::GotoURL( sUrl );
}
float ArchHooks_Win32::GetDisplayAspectRatio()
{
DEVMODE dm;
ZERO( dm );
dm.dmSize = sizeof(dm);
BOOL bResult = EnumDisplaySettings( NULL, ENUM_REGISTRY_SETTINGS, &dm );
ASSERT( bResult != 0 );
return dm.dmPelsWidth / (float)dm.dmPelsHeight;
}
RString ArchHooks_Win32::GetClipboard()
{
HGLOBAL hgl;
LPTSTR lpstr;
RString ret;
// First make sure that the clipboard actually contains a string
// (or something stringifiable)
if(unlikely( !IsClipboardFormatAvailable( CF_TEXT ) )) return "";
// Yes. All this mess just to gain access to the string stored by the clipboard.
// I'm having flashbacks to Berkeley sockets.
if(unlikely( !OpenClipboard( NULL ) ))
{ LOG->Warn(werr_ssprintf( GetLastError(), "InputHandler_DirectInput: OpenClipboard() failed" )); return ""; }
hgl = GetClipboardData( CF_TEXT );
if(unlikely( hgl == NULL ))
{ LOG->Warn(werr_ssprintf( GetLastError(), "InputHandler_DirectInput: GetClipboardData() failed" )); CloseClipboard(); return ""; }
lpstr = (LPTSTR) GlobalLock( hgl );
if(unlikely( lpstr == NULL ))
{ LOG->Warn(werr_ssprintf( GetLastError(), "InputHandler_DirectInput: GlobalLock() failed" )); CloseClipboard(); return ""; }
// And finally, we have a char (or wchar_t) array of the clipboard contents,
// pointed to by sToPaste.
// (Hopefully.)
#ifdef UNICODE
ret = WStringToRString( wstring()+*lpstr );
#else
ret = RString( lpstr );
#endif
// And now we clean up.
GlobalUnlock( hgl );
CloseClipboard();
return ret;
}
/*
* (c) 2003-2004 Glenn Maynard, Chris Danford
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, and/or sell copies of the Software, and to permit persons to
* whom the Software is furnished to do so, provided that the above
* copyright notice(s) and this permission notice appear in all copies of
* the Software and that both the above copyright notice(s) and this
* permission notice appear in supporting documentation.
*
* 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 OF
* THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS
* INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT
* OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
* OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
* OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
| 30.271698 | 133 | 0.733732 | caiohsr14 |
ed5ed317aacfd450f282d0974ada1bb154a12e85 | 709 | cc | C++ | Question/全排列.cc | lkimprove/Study_C | ee1153536f28e160d5daad4ddebaa547c3941ee7 | [
"MIT"
] | null | null | null | Question/全排列.cc | lkimprove/Study_C | ee1153536f28e160d5daad4ddebaa547c3941ee7 | [
"MIT"
] | null | null | null | Question/全排列.cc | lkimprove/Study_C | ee1153536f28e160d5daad4ddebaa547c3941ee7 | [
"MIT"
] | null | null | null | class Solution {
public:
void Perm(vector<vector<int>>& ret, vector<int>& nums, int index, int size){
//结束条件
if(index == size){
vector<int> tmp = nums;
ret.push_back(tmp);
return;
}
for(int i = index; i < size; i++){
//在0位置依次固定nums中的每一个数
//之后再固定1,2,3位置
swap(nums[i], nums[index]);
//向下递归(分治思想)
Perm(ret, nums, index + 1, size);
//还原原数组,避免重复
swap(nums[i], nums[index]);
}
}
vector<vector<int>> permute(vector<int>& nums) {
vector<vector<int>> ret;
Perm(ret, nums, 0, nums.size());
return ret;
}
};
| 23.633333 | 80 | 0.461213 | lkimprove |
ed5ff105e5090fa080564478bbcb3e570a821284 | 399 | cpp | C++ | warm-up-contest/data/star/gen.cpp | yuchong-pan/my-oi-lectures | 721ff870b5cc388ef81961bf1a96361a74e2d896 | [
"MIT"
] | 3 | 2019-07-30T10:43:58.000Z | 2019-07-30T10:46:05.000Z | warm-up-contest/data/star/gen.cpp | yuchong-pan/my-oi-lectures | 721ff870b5cc388ef81961bf1a96361a74e2d896 | [
"MIT"
] | null | null | null | warm-up-contest/data/star/gen.cpp | yuchong-pan/my-oi-lectures | 721ff870b5cc388ef81961bf1a96361a74e2d896 | [
"MIT"
] | null | null | null | #include <cstdio>
#include <cstdlib>
using namespace std;
char cmd[100];
int main() {
for (int i = 1; i <= 10; i++) {
sprintf(cmd, "cp star%d.in star.in", i);
system(cmd);
sprintf(cmd, "./star");
system(cmd);
sprintf(cmd, "mv star.out star%d.out", i);
system(cmd);
sprintf(cmd, "rm star.in");
system(cmd);
}
return 0;
}
| 19 | 50 | 0.506266 | yuchong-pan |
ed64f4379ab6d94dbefb2750a80656e68312ed4c | 1,307 | hpp | C++ | chapter03/InputComponent.hpp | AconCavy/gpcpp | 70d06e00f9ffc4dea580890a8b95027b32f5a9f6 | [
"MIT"
] | null | null | null | chapter03/InputComponent.hpp | AconCavy/gpcpp | 70d06e00f9ffc4dea580890a8b95027b32f5a9f6 | [
"MIT"
] | null | null | null | chapter03/InputComponent.hpp | AconCavy/gpcpp | 70d06e00f9ffc4dea580890a8b95027b32f5a9f6 | [
"MIT"
] | null | null | null | #ifndef GPCPP_CHAPTER03_INPUTCOMPONENT_HPP
#define GPCPP_CHAPTER03_INPUTCOMPONENT_HPP
#include "MoveComponent.hpp"
namespace gpcpp::c03 {
class InputComponent : public MoveComponent {
public:
explicit InputComponent(class Actor *Owner);
void processInput(const uint8_t *KeyState) override;
[[nodiscard]] float getMaxAngularSpeed() const { return MaxAngularSpeed; }
[[nodiscard]] float getMaxForward() const { return MaxForwardSpeed; }
[[nodiscard]] int getForwardKey() const { return ForwardKey; }
[[nodiscard]] int getBackKey() const { return BackKey; }
[[nodiscard]] int getClockwiseKey() const { return ClockwiseKey; }
[[nodiscard]] int getCounterClockwiseKey() const {
return CounterClockwiseKey;
}
void setMaxAngularSpeed(float Speed) { MaxAngularSpeed = Speed; }
void setMaxForwardSpeed(float Speed) { MaxForwardSpeed = Speed; }
void setForwardKey(int Key) { ForwardKey = Key; }
void setBackKey(int Key) { BackKey = Key; }
void setClockwiseKey(int Key) { ClockwiseKey = Key; }
void setCounterClockwiseKey(int Key) { CounterClockwiseKey = Key; }
private:
float MaxAngularSpeed;
float MaxForwardSpeed;
int ForwardKey;
int BackKey;
int ClockwiseKey;
int CounterClockwiseKey;
};
} // namespace gpcpp::c03
#endif // GPCPP_CHAPTER03_INPUTCOMPONENT_HPP
| 31.119048 | 76 | 0.752104 | AconCavy |
ed6a08e905256517309d069a0b585d1fc66f6d7b | 348 | hpp | C++ | modules/math/source/blub/math/rectangle.hpp | qwertzui11/voxelTerrain | 05038fb261893dd044ae82fab96b7708ea5ed623 | [
"MIT"
] | 96 | 2015-02-02T20:01:24.000Z | 2021-11-14T20:33:29.000Z | modules/math/source/blub/math/rectangle.hpp | qwertzui11/voxelTerrain | 05038fb261893dd044ae82fab96b7708ea5ed623 | [
"MIT"
] | 12 | 2016-06-04T15:45:30.000Z | 2020-02-04T11:10:51.000Z | modules/math/source/blub/math/rectangle.hpp | qwertzui11/voxelTerrain | 05038fb261893dd044ae82fab96b7708ea5ed623 | [
"MIT"
] | 19 | 2015-09-22T01:21:45.000Z | 2020-09-30T09:52:27.000Z | #ifndef RECTANGLE_HPP
#define RECTANGLE_HPP
#include "vector2.hpp"
namespace blub
{
class rectangle
{
public:
vector2 topLeft, rightBottom;
rectangle(void);
rectangle(const vector2 &topLeft_, const vector2 &rightBottom_);
void merge(const rectangle &other);
void merge(const vector2 &other);
};
}
#endif // RECTANGLE_HPP
| 14.5 | 68 | 0.721264 | qwertzui11 |
ed6b514c805774c8fc3b1aa06b5d422900155cc2 | 2,999 | cc | C++ | src/poly/schedule_pass/init_schedule.cc | laekov/akg | 5316b8cb2340bbf71bdc724dc9d81513a67b3104 | [
"Apache-2.0"
] | 1 | 2020-08-31T02:43:43.000Z | 2020-08-31T02:43:43.000Z | src/poly/schedule_pass/init_schedule.cc | laekov/akg | 5316b8cb2340bbf71bdc724dc9d81513a67b3104 | [
"Apache-2.0"
] | null | null | null | src/poly/schedule_pass/init_schedule.cc | laekov/akg | 5316b8cb2340bbf71bdc724dc9d81513a67b3104 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2019 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "init_schedule.h"
namespace akg {
namespace ir {
namespace poly {
void InitSchedule::RemoveUninitializedCopyin(isl::union_map ©_in, const Binds &binds) {
isl::union_set copyin_range = copy_in.range();
auto ForeachSetFn = [©_in, &binds](const isl::set &set) {
std::string tensor_name = set.get_tuple_name();
bool defined = false;
for (auto bind : binds) {
if (bind.first->op->name == tensor_name) {
defined = true;
}
}
if (!defined) {
copy_in = copy_in.subtract_range(set);
LOG(WARNING) << "remove uninitialized copyin, tensor name=" << tensor_name << ", access=" << set;
}
};
copyin_range.foreach_set(ForeachSetFn);
}
void InitSchedule::ModDependencesBeforeGroup(const isl::schedule &schedule) {
if (!scop_info_.cube_info_.IsSpecGemm()) {
if (scop_info_.user_config_.GetRemoveSelfDependence()) {
pass_info_.dependences_ = RemoveReduceOpSelfDependence(scop_info_, pass_info_);
}
if (scop_info_.user_config_.GetForceRemoveSelfDependence()) {
pass_info_.dependences_ = RemoveSelfDependence(pass_info_);
}
}
if (scop_info_.user_config_.GetRemoveInvariantDependence()) {
pass_info_.dependences_ = RemoveInvariantDependence(schedule, pass_info_);
}
}
void InitSchedule::ComputeCopyIn(const isl::schedule &schedule) {
auto reads = scop_info_.analysis_result_.GetReads().domain_factor_domain();
auto writes = scop_info_.analysis_result_.GetWrites().domain_factor_domain();
auto uai = isl::union_access_info(reads);
uai = uai.set_kill(writes);
uai = uai.set_may_source(writes);
uai = uai.set_schedule(schedule);
auto flow = uai.compute_flow();
auto mayNoSource = flow.get_may_no_source();
scop_info_.analysis_result_.RecordCopyin(scop_info_.analysis_result_.GetReads().intersect_range(mayNoSource.range()));
}
isl::schedule InitSchedule::Run(isl::schedule sch) {
ComputeCopyIn(sch);
RemoveUninitializedCopyin(scop_info_.analysis_result_.GetCopyin(), scop_info_.user_config_.GetOriginBind());
pass_info_.dependences_ = ComputeAllDependences(sch, scop_info_.analysis_result_.GetReads(),
scop_info_.analysis_result_.GetWrites());
pass_info_.orig_dependences_ = pass_info_.dependences_;
ModDependencesBeforeGroup(sch);
return sch;
}
} // namespace poly
} // namespace ir
} // namespace akg
| 36.573171 | 120 | 0.726909 | laekov |
ed6ce8fb3e469fba323f9450e3f97fc44be7d8aa | 236 | cpp | C++ | cpp/new_features/cpp20/aggregate.cpp | KaiserLancelot/Cpp-Primer | a4791a6765f0b6c864e8881e6a5328e2a3d68974 | [
"MIT"
] | 2 | 2019-12-21T00:53:47.000Z | 2020-01-01T10:36:30.000Z | cpp/new_features/cpp20/aggregate.cpp | KaiserLancelot/Cpp-Primer | a4791a6765f0b6c864e8881e6a5328e2a3d68974 | [
"MIT"
] | null | null | null | cpp/new_features/cpp20/aggregate.cpp | KaiserLancelot/Cpp-Primer | a4791a6765f0b6c864e8881e6a5328e2a3d68974 | [
"MIT"
] | null | null | null | /**
* @ Author: KaiserLancelot
* @ Create Time: 2020-05-14 06:26:07
* @ Modified time: 2020-05-15 02:16:50
*/
#include <cstdint>
struct A {
std::int32_t x;
std::int32_t y;
std::int32_t z;
};
// TODO 编译器实现不完整
int main() {}
| 13.111111 | 39 | 0.605932 | KaiserLancelot |
ed6ea34c796889ff5aed0e4f2a185fe0c4836f90 | 1,374 | hpp | C++ | include/librandom/random.hpp | averrin/citygen-viewer | 6bf44a91c97d79bb9871f9571d3f8a7213b09505 | [
"MIT"
] | null | null | null | include/librandom/random.hpp | averrin/citygen-viewer | 6bf44a91c97d79bb9871f9571d3f8a7213b09505 | [
"MIT"
] | null | null | null | include/librandom/random.hpp | averrin/citygen-viewer | 6bf44a91c97d79bb9871f9571d3f8a7213b09505 | [
"MIT"
] | null | null | null | #ifndef __RANDOM_H_
#define __RANDOM_H_
#include <chrono>
#include <cmath>
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <random>
namespace R {
// float R(float min, float max) {
// return min + static_cast<float>(rand()) /
// (static_cast<float>(RAND_MAX / (max - min)));
// ;
// }
// float R() { return static_cast<float>(rand()) / static_cast<float>(RAND_MAX); }
// int Z(int min, int max) { return rand() % (max - min + 1) + min; }
// int Z() { return rand() % 100; }
// int N(int mean, int dev) {
// std::normal_distribution<> d{double(mean), double(dev)};
// return std::round(d(gen));
// }
class Generator {
private:
std::mt19937 *gen;
public:
int seed;
Generator() { updateSeed(); }
void updateSeed() {
setSeed(std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch())
.count());
}
void setSeed(int s) {
seed = s;
gen = new std::mt19937(seed);
}
int R() {
std::uniform_int_distribution<> dis(0, RAND_MAX);
return dis(*gen);
}
int R(float min, float max) {
std::uniform_real_distribution<> dis(min, max);
return dis(*gen);
}
int R(int min, int max) {
std::uniform_int_distribution<> dis(min, max);
return dis(*gen);
}
};
} // namespace R
#endif // __RANDOM_H_
| 20.507463 | 82 | 0.597525 | averrin |
ed74c682f9694601e7855a9d62431763a70407b6 | 2,840 | cpp | C++ | shadow/core/network.cpp | junluan/shadow | 067d1c51d7c38bc1c985008a2e2e1599bbf11a8c | [
"Apache-2.0"
] | 20 | 2017-07-04T11:22:47.000Z | 2022-01-16T03:58:32.000Z | shadow/core/network.cpp | junluan/shadow | 067d1c51d7c38bc1c985008a2e2e1599bbf11a8c | [
"Apache-2.0"
] | 2 | 2017-12-03T13:07:39.000Z | 2021-01-13T11:11:52.000Z | shadow/core/network.cpp | junluan/shadow | 067d1c51d7c38bc1c985008a2e2e1599bbf11a8c | [
"Apache-2.0"
] | 10 | 2017-09-30T05:06:30.000Z | 2020-11-13T05:43:44.000Z | #include "network.hpp"
#include "network_impl.hpp"
namespace Shadow {
Network::Network() { engine_ = std::make_shared<NetworkImpl>(); }
void Network::LoadXModel(const shadow::NetParam& net_param,
const ArgumentHelper& arguments) {
engine_->LoadXModel(net_param, arguments);
}
void Network::Forward(
const std::map<std::string, void*>& data_map,
const std::map<std::string, std::vector<int>>& shape_map) {
engine_->Forward(data_map, shape_map);
}
#define INSTANTIATE_GET_BLOB(T) \
template <> \
const T* Network::GetBlobDataByName<T>(const std::string& blob_name, \
const std::string& locate) { \
return engine_->GetBlobDataByName<T>(blob_name, locate); \
} \
template <> \
std::vector<int> Network::GetBlobShapeByName<T>( \
const std::string& blob_name) const { \
return engine_->GetBlobShapeByName(blob_name); \
}
INSTANTIATE_GET_BLOB(std::int64_t);
INSTANTIATE_GET_BLOB(std::int32_t);
INSTANTIATE_GET_BLOB(std::int16_t);
INSTANTIATE_GET_BLOB(std::int8_t);
INSTANTIATE_GET_BLOB(std::uint64_t);
INSTANTIATE_GET_BLOB(std::uint32_t);
INSTANTIATE_GET_BLOB(std::uint16_t);
INSTANTIATE_GET_BLOB(std::uint8_t);
INSTANTIATE_GET_BLOB(float);
INSTANTIATE_GET_BLOB(bool);
#undef INSTANTIATE_GET_BLOB
const std::vector<std::string>& Network::in_blob() const {
return engine_->in_blob();
}
const std::vector<std::string>& Network::out_blob() const {
return engine_->out_blob();
}
bool Network::has_argument(const std::string& name) const {
return engine_->has_argument(name);
}
#define INSTANTIATE_ARGUMENT(T) \
template <> \
T Network::get_single_argument<T>(const std::string& name, \
const T& default_value) const { \
return engine_->get_single_argument<T>(name, default_value); \
} \
template <> \
std::vector<T> Network::get_repeated_argument<T>( \
const std::string& name, const std::vector<T>& default_value) const { \
return engine_->get_repeated_argument<T>(name, default_value); \
}
INSTANTIATE_ARGUMENT(float);
INSTANTIATE_ARGUMENT(int);
INSTANTIATE_ARGUMENT(bool);
INSTANTIATE_ARGUMENT(std::string);
#undef INSTANTIATE_ARGUMENT
} // namespace Shadow
| 38.378378 | 77 | 0.551408 | junluan |
ed7bec52e1ce340fcc0d8beffff026e9836b89b5 | 422 | cpp | C++ | polygons/translationgraphwidget.cpp | humble-barnacle001/qt-raster-lines | 7c5d38d6d6dd802901702b97084df3db12151e2e | [
"MIT"
] | null | null | null | polygons/translationgraphwidget.cpp | humble-barnacle001/qt-raster-lines | 7c5d38d6d6dd802901702b97084df3db12151e2e | [
"MIT"
] | null | null | null | polygons/translationgraphwidget.cpp | humble-barnacle001/qt-raster-lines | 7c5d38d6d6dd802901702b97084df3db12151e2e | [
"MIT"
] | null | null | null | #include "translationgraphwidget.h"
TranslationGraphWidget::TranslationGraphWidget(QWidget *parent)
: PolygonGraphWidget(parent), p(QPoint(0, 0))
{
}
void TranslationGraphWidget::translateXYChanged(const QPoint &p)
{
this->p = p;
}
void TranslationGraphWidget::performOperation()
{
foreach (auto pp, polygon)
{
editPixMap(QPoint(pp.x() + p.x(), pp.y() + p.y()), qMakePair(true, false));
}
}
| 21.1 | 83 | 0.682464 | humble-barnacle001 |
ed7c595698362fe1ed4489098912b9d9e642e69e | 1,868 | cpp | C++ | plugins/single_plugins/rotator.cpp | SirCmpwn/wayfire | 007452f6ccc07ceca51879187bba142431832382 | [
"MIT"
] | 3 | 2019-01-16T14:43:24.000Z | 2019-10-09T10:07:33.000Z | plugins/single_plugins/rotator.cpp | SirCmpwn/wayfire | 007452f6ccc07ceca51879187bba142431832382 | [
"MIT"
] | null | null | null | plugins/single_plugins/rotator.cpp | SirCmpwn/wayfire | 007452f6ccc07ceca51879187bba142431832382 | [
"MIT"
] | 1 | 2019-05-07T09:46:58.000Z | 2019-05-07T09:46:58.000Z | #include <output.hpp>
#include <core.hpp>
#include "../../shared/config.hpp"
#include <linux/input-event-codes.h>
#include <compositor.h>
class wayfire_rotator : public wayfire_plugin_t {
key_callback up, down, left, right;
public:
void init(wayfire_config *config) {
grab_interface->name = "rotator";
grab_interface->abilities_mask = WF_ABILITY_NONE;
auto section = config->get_section("rotator");
wayfire_key up_key = section->get_key("rotate_up",
{MODIFIER_ALT|MODIFIER_CTRL, KEY_UP});
wayfire_key down_key = section->get_key("rotate_down",
{MODIFIER_ALT|MODIFIER_CTRL, KEY_DOWN});
wayfire_key left_key = section->get_key("rotate_left",
{MODIFIER_ALT|MODIFIER_CTRL, KEY_LEFT});
wayfire_key right_key = section->get_key("rotate_right",
{MODIFIER_ALT|MODIFIER_CTRL, KEY_RIGHT});
up = [=] (weston_keyboard*, uint32_t) {
output->set_transform(WL_OUTPUT_TRANSFORM_NORMAL);
};
down = [=] (weston_keyboard*, uint32_t) {
output->set_transform(WL_OUTPUT_TRANSFORM_180);
};
left = [=] (weston_keyboard*, uint32_t) {
output->set_transform(WL_OUTPUT_TRANSFORM_270);
};
right = [=] (weston_keyboard*, uint32_t) {
output->set_transform(WL_OUTPUT_TRANSFORM_90);
};
output->add_key((weston_keyboard_modifier)up_key.mod, up_key.keyval, &up);
output->add_key((weston_keyboard_modifier)down_key.mod, down_key.keyval, &down);
output->add_key((weston_keyboard_modifier)left_key.mod, left_key.keyval, &left);
output->add_key((weston_keyboard_modifier)right_key.mod, right_key.keyval, &right);
}
};
extern "C" {
wayfire_plugin_t *newInstance() {
return new wayfire_rotator();
}
}
| 36.627451 | 91 | 0.645075 | SirCmpwn |
ed7c74fbb3aa78d04cea01e249d67b10d386e9f7 | 3,328 | hpp | C++ | src/webots/nodes/WbContactProperties.hpp | victorhu3/webots | 60d173850f0b4714c500db004e69f2df8cfb9e8a | [
"Apache-2.0"
] | 1 | 2020-06-08T13:38:11.000Z | 2020-06-08T13:38:11.000Z | src/webots/nodes/WbContactProperties.hpp | victorhu3/webots | 60d173850f0b4714c500db004e69f2df8cfb9e8a | [
"Apache-2.0"
] | 2 | 2020-05-18T12:49:14.000Z | 2020-12-01T15:13:43.000Z | src/webots/nodes/WbContactProperties.hpp | victorhu3/webots | 60d173850f0b4714c500db004e69f2df8cfb9e8a | [
"Apache-2.0"
] | 1 | 2022-02-25T12:34:18.000Z | 2022-02-25T12:34:18.000Z | // Copyright 1996-2020 Cyberbotics Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef WB_CONTACT_PROPERTIES_HPP
#define WB_CONTACT_PROPERTIES_HPP
#include "WbBaseNode.hpp"
#include "WbMFDouble.hpp"
#include "WbSFDouble.hpp"
#include "WbSFString.hpp"
#include "WbSFVector2.hpp"
class WbSoundClip;
class WbContactProperties : public WbBaseNode {
Q_OBJECT
public:
// constructors and destructor
explicit WbContactProperties(WbTokenizer *tokenizer = NULL);
WbContactProperties(const WbContactProperties &other);
explicit WbContactProperties(const WbNode &other);
virtual ~WbContactProperties();
// reimplemented public functions
int nodeType() const override { return WB_NODE_CONTACT_PROPERTIES; }
void preFinalize() override;
void postFinalize() override;
// field accessors
const QString &material1() const { return mMaterial1->value(); }
const QString &material2() const { return mMaterial2->value(); }
int coulombFrictionSize() const { return mCoulombFriction->size(); }
double coulombFriction(int index) const { return mCoulombFriction->item(index); }
WbVector2 frictionRotation() const { return mFrictionRotation->value(); }
double bounce() const { return mBounce->value(); }
double bounceVelocity() const { return mBounceVelocity->value(); }
int forceDependentSlipSize() const { return mForceDependentSlip->size(); }
double forceDependentSlip(int index) const { return mForceDependentSlip->item(index); }
double softERP() const { return mSoftErp->value(); }
double softCFM() const { return mSoftCfm->value(); }
const WbSoundClip *bumpSoundClip() const { return mBumpSoundClip; }
const WbSoundClip *rollSoundClip() const { return mRollSoundClip; }
const WbSoundClip *slideSoundClip() const { return mSlideSoundClip; }
signals:
void valuesChanged();
void needToEnableBodies();
private:
// user accessible fields
WbSFString *mMaterial1;
WbSFString *mMaterial2;
WbMFDouble *mCoulombFriction;
WbSFVector2 *mFrictionRotation;
WbSFDouble *mBounce;
WbSFDouble *mBounceVelocity;
WbMFDouble *mForceDependentSlip;
WbSFDouble *mSoftCfm;
WbSFDouble *mSoftErp;
WbSFString *mBumpSound;
WbSFString *mRollSound;
WbSFString *mSlideSound;
WbSoundClip *mBumpSoundClip;
WbSoundClip *mRollSoundClip;
WbSoundClip *mSlideSoundClip;
WbContactProperties &operator=(const WbContactProperties &); // non copyable
WbNode *clone() const override { return new WbContactProperties(*this); }
void init();
private slots:
void updateCoulombFriction();
void updateFrictionRotation();
void updateBounce();
void updateBounceVelocity();
void updateSoftCfm();
void updateSoftErp();
void updateBumpSound();
void updateRollSound();
void updateSlideSound();
void updateForceDependentSlip();
void enableBodies();
};
#endif
| 34.309278 | 89 | 0.758113 | victorhu3 |
ed7e1d6eb52956cd07af23c0dfb875e027703b21 | 1,340 | cpp | C++ | test/TestMain.cpp | apache/incubator-retired-concerted | c51c9a21b390792252df191c82309c19d7dc8b8f | [
"Apache-2.0"
] | 9 | 2015-10-24T02:43:47.000Z | 2018-02-19T10:00:24.000Z | test/TestMain.cpp | apache/incubator-retired-concerted | c51c9a21b390792252df191c82309c19d7dc8b8f | [
"Apache-2.0"
] | 2 | 2015-10-26T15:14:43.000Z | 2015-11-05T11:51:01.000Z | test/TestMain.cpp | apache/incubator-concerted | c51c9a21b390792252df191c82309c19d7dc8b8f | [
"Apache-2.0"
] | 6 | 2015-10-25T12:35:04.000Z | 2016-05-12T00:25:55.000Z | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to you under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <iostream>
#include "../include/tests/ConcDCTTest.h"
#include "../include/tests/ConcMATTest.h"
#include "../include/tests/ConcSegHashTableTest.h"
#include "../include/tests/ConcInvertedIndexTest.h"
#include "../include/tests/QueueLockTest.h"
using namespace std;
int main()
{
int res1 = 0;
int res2 = 0;
int res3 = 0;
res1 = testDCT(0);
if (res1)
throw;
res2 = testMAT(0);
if (res2)
throw;
testSegHashTable(0);
res3 = testInvertedIndex(0);
if (res3)
throw;
cout <<"All tests passed"<<endl;
}
| 27.916667 | 75 | 0.719403 | apache |
142e85d012098a17186d271a138a6752d9ed7666 | 851 | cpp | C++ | Cpp14/autotype8.cpp | ernestyalumni/HrdwCCppCUDA | 17ed937dea06431a4d5ca103f993ea69a6918734 | [
"MIT"
] | 1 | 2018-02-09T19:44:51.000Z | 2018-02-09T19:44:51.000Z | Cpp14/autotype8.cpp | ernestyalumni/HrdwCCppCUDA | 17ed937dea06431a4d5ca103f993ea69a6918734 | [
"MIT"
] | null | null | null | Cpp14/autotype8.cpp | ernestyalumni/HrdwCCppCUDA | 17ed937dea06431a4d5ca103f993ea69a6918734 | [
"MIT"
] | null | null | null | /**
* @file autotype8.cpp
* @brief C++11/14/17 program to demonstrate auto type of 8
* @ref https://stackoverflow.com/questions/38060436/what-are-the-new-features-in-c17
* @details http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n3922.html
*
* COMPILATION TIP : -Wall warning all, -g debugger, gdb can step through
* g++ -Wall -g autotype8.cpp -o autotype8
* */
#include <iostream>
#include <typeinfo> // typeid
int main() {
auto x{8};
auto x1 = { 1, 2}; // decltype(x1) is std::initializer_list<int>
auto x4 = { 3 }; // decltype(x4) is std::initializer_list<int>
std::cout << typeid( decltype( x )).name() << std::endl; // i
std::cout << typeid( decltype( x1 )).name() << std::endl; // St16initializer_listIiE
std::cout << typeid( decltype( x4 )).name() << std::endl; // St16initializer_listIiE
}
| 29.344828 | 86 | 0.642773 | ernestyalumni |
142ec8b1666cace04a2efd094e0f325bb83173fc | 647 | cpp | C++ | UVa/1203 - Argus.cpp | geniustanley/problem-solving | 2b83c5c8197fa8fe2277367027b392a2911d4a28 | [
"Apache-2.0"
] | 1 | 2018-11-21T07:36:16.000Z | 2018-11-21T07:36:16.000Z | UVa/1203 - Argus.cpp | geniustanley/problem-solving | 2b83c5c8197fa8fe2277367027b392a2911d4a28 | [
"Apache-2.0"
] | null | null | null | UVa/1203 - Argus.cpp | geniustanley/problem-solving | 2b83c5c8197fa8fe2277367027b392a2911d4a28 | [
"Apache-2.0"
] | null | null | null | #include <stdio.h>
#include <string.h>
#include <iostream>
#include <queue>
#include <map>
using namespace std;
int main(void)
{
int qnum, r, n, f, s;
char c[10];
priority_queue<pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > > pq;
map<int, int> m;
while (EOF != scanf("%s", c) && strcmp(c, "#")) {
scanf("%d %d", &qnum, &r);
pq.push(pair<int, int> (r, qnum));
m[qnum] = r;
}
scanf("%d", &n);
for (int i = 0; i < n; i++) {
printf("%d\n", pq.top().second);
f = pq.top().first;
s = pq.top().second;
pq.push(pair<int, int> (((f/m[s])+1)*m[s], s));
pq.pop();
}
return 0;
}
| 19.029412 | 88 | 0.517774 | geniustanley |
143193c52e1cd4b1ba91759295778bea80d8b65d | 21 | cpp | C++ | core/src/BVH.cpp | lonelywm/cuda_path_tracer | d99f0b682ad7f64fa127ca3604d0eab26f61452c | [
"MIT"
] | 1 | 2021-06-12T11:33:12.000Z | 2021-06-12T11:33:12.000Z | core/src/BVH.cpp | lonelywm/cuda_path_tracer | d99f0b682ad7f64fa127ca3604d0eab26f61452c | [
"MIT"
] | null | null | null | core/src/BVH.cpp | lonelywm/cuda_path_tracer | d99f0b682ad7f64fa127ca3604d0eab26f61452c | [
"MIT"
] | null | null | null | #include "../BVH.h"
| 7 | 19 | 0.52381 | lonelywm |
143240ff53df66a0053bcf03d60dc905357f4adb | 6,107 | cc | C++ | granary/trace_log.cc | Granary/granary | f9ac2b6af0864f420b93917dc21a38041905b3aa | [
"BSD-3-Clause"
] | 37 | 2015-03-13T08:29:46.000Z | 2022-03-04T06:54:29.000Z | granary/trace_log.cc | Granary/granary | f9ac2b6af0864f420b93917dc21a38041905b3aa | [
"BSD-3-Clause"
] | null | null | null | granary/trace_log.cc | Granary/granary | f9ac2b6af0864f420b93917dc21a38041905b3aa | [
"BSD-3-Clause"
] | 3 | 2015-10-16T21:18:01.000Z | 2022-03-04T06:54:31.000Z | /* Copyright 2012-2013 Peter Goodman, all rights reserved. */
/*
* trace_log.cc
*
* Created on: 2013-05-06
* Author: Peter Goodman
*/
#include "granary/globals.h"
#include "granary/trace_log.h"
#if CONFIG_DEBUG_TRACE_EXECUTION
# include "granary/instruction.h"
# include "granary/emit_utils.h"
# include "granary/state.h"
#endif
namespace granary {
#if CONFIG_DEBUG_TRACE_EXECUTION
# if !CONFIG_DEBUG_TRACE_PRINT_LOG
/// An item in the trace log.
struct trace_log_item {
/// Previous log item in this thread.
trace_log_item *prev;
/// A code cache address into a basic block.
void *code_cache_addr;
# if CONFIG_DEBUG_TRACE_RECORD_REGS
/// State of the general purpose registers on entry to this basic block.
simple_machine_state state;
# endif /* CONFIG_DEBUG_TRACE_RECORD_REGS */
};
/// Head of the log.
static std::atomic<trace_log_item *> TRACE = ATOMIC_VAR_INIT(nullptr);
static std::atomic<uint64_t> NUM_TRACE_ENTRIES = ATOMIC_VAR_INIT(0);
/// A ring buffer representing the trace log.
static trace_log_item LOGS[CONFIG_DEBUG_NUM_TRACE_LOG_ENTRIES];
# endif /* CONFIG_DEBUG_TRACE_PRINT_LOG */
#endif /* CONFIG_DEBUG_TRACE_EXECUTION */
/// Log a lookup in the code cache.
void trace_log::add_entry(
app_pc IF_TRACE(code_cache_addr),
simple_machine_state *IF_TRACE(state)
) {
#if CONFIG_DEBUG_TRACE_EXECUTION
# if CONFIG_DEBUG_TRACE_PRINT_LOG
printf("app=%p cache=%p\n", app_addr, target_addr);
(void) kind;
# else
trace_log_item *prev(nullptr);
trace_log_item *item(&(LOGS[
NUM_TRACE_ENTRIES.fetch_add(1) % CONFIG_DEBUG_NUM_TRACE_LOG_ENTRIES]));
item->code_cache_addr = code_cache_addr;
# if CONFIG_DEBUG_TRACE_RECORD_REGS
// Have to use our internal `memcpy`, because even when telling the
// compiler not to use xmm registers, it will sometimes optimize an
// assignment of `item->state = *state` into a libc `memcpy`.
memcpy(&(item->state), state, sizeof *state);
item->state.rsp.value_64 += IF_USER_ELSE(REDZONE_SIZE + 8, 8);
# else
(void) state;
# endif /* CONFIG_DEBUG_TRACE_RECORD_REGS */
do {
prev = TRACE.load();
item->prev = prev;
} while(!TRACE.compare_exchange_weak(prev, item));
# endif /* CONFIG_DEBUG_TRACE_PRINT_LOG */
#endif
}
extern "C" void **kernel_get_cpu_state(void *ptr[]);
#if CONFIG_DEBUG_TRACE_EXECUTION
static app_pc trace_logger(void) {
static volatile app_pc routine(nullptr);
if(routine) {
return routine;
}
instruction_list ls;
instruction in;
instruction xmm_tail;
register_manager all_regs;
all_regs.kill_all();
ls.append(push_(reg::rsp));
in = save_and_restore_registers(all_regs, ls, ls.last());
in = ls.insert_after(in,
mov_ld_(reg::arg1, reg::rsp[sizeof(simple_machine_state)]));
# if CONFIG_DEBUG_TRACE_RECORD_REGS
in = ls.insert_after(in, mov_st_(reg::arg2, reg::rsp));
# endif /* CONFIG_DEBUG_TRACE_RECORD_REGS */
in = insert_save_flags_after(ls, in);
in = insert_align_stack_after(ls, in);
xmm_tail = ls.insert_after(in, label_());
# if 0 && !CONFIG_ENV_KERNEL
// In some user space programs (e.g. kcachegrind), we need to
// unconditionally save all XMM registers.
in = save_and_restore_xmm_registers(
all_regs, ls, in, XMM_SAVE_ALIGNED);
# endif /* CONFIG_ENV_KERNEL */
in = insert_cti_after(ls, in,
unsafe_cast<app_pc>(trace_log::add_entry),
CTI_STEAL_REGISTER, reg::ret,
CTI_CALL);
xmm_tail = insert_restore_old_stack_alignment_after(ls, xmm_tail);
xmm_tail = insert_restore_flags_after(ls, xmm_tail);
ls.append(lea_(reg::rsp, reg::rsp[8]));
ls.append(ret_());
// Encode.
const unsigned size(ls.encoded_size());
app_pc temp(global_state::FRAGMENT_ALLOCATOR-> \
allocate_array<uint8_t>(size));
ls.encode(temp, size);
BARRIER;
routine = temp;
return temp;
}
static void add_trace_log_call(
instruction_list &ls,
instruction in
) {
IF_USER( in = ls.insert_after(in,
lea_(reg::rsp, reg::rsp[-REDZONE_SIZE])); )
in = insert_cti_after(ls, in,
trace_logger(),
CTI_DONT_STEAL_REGISTER, operand(),
CTI_CALL);
in.set_mangled();
IF_USER( in = ls.insert_after(in,
lea_(reg::rsp, reg::rsp[REDZONE_SIZE])); )
}
#endif /* CONFIG_DEBUG_TRACE_EXECUTION */
/// Log the run of some code. This will add a lot of instructions to the
/// beginning of an instruction list, as well as replace RET instructions
/// with tail-calls to the trace logger so that we can observe ourselves
/// re-entering a given basic block after a CALL.
void trace_log::log_execution(instruction_list &IF_TRACE(ls)) {
#if CONFIG_DEBUG_TRACE_EXECUTION
// The first instruction will be a label.
instruction in(ls.first());
ASSERT(in.is_valid());
instruction in_next(in.next());
add_trace_log_call(ls, in);
UNUSED(in_next);
// TODO: It's a bit weird that this works in user space but not kernel
// space!!
# if 0 && !CONFIG_ENV_KERNEL
for(in = in_next; in.is_valid(); in = in_next) {
in_next = in.next();
if(in.is_return()) {
// We don't need to guard against the redzone for RETs
// because they're popping their return address off of the
// stack.
insert_cti_after(ls, in,
trace_logger(),
CTI_DONT_STEAL_REGISTER, operand(),
CTI_JMP).set_mangled();
ls.remove(in);
}
}
# endif
#endif
}
}
| 28.806604 | 83 | 0.619944 | Granary |
14365cef8d2e7da1381afc9eb47e07f73172b976 | 2,569 | hpp | C++ | gamebase/Player.hpp | GenBrg/MagicCastlevania | 76ed248d4f0362ea92d29a159a2027d5b16c8a7b | [
"CC-BY-4.0"
] | 2 | 2020-10-31T01:34:42.000Z | 2020-12-08T15:16:22.000Z | gamebase/Player.hpp | GenBrg/MagicCastlevania | 76ed248d4f0362ea92d29a159a2027d5b16c8a7b | [
"CC-BY-4.0"
] | 50 | 2020-10-31T01:31:56.000Z | 2020-12-11T15:13:43.000Z | gamebase/Player.hpp | GenBrg/MagicCastlevania | 76ed248d4f0362ea92d29a159a2027d5b16c8a7b | [
"CC-BY-4.0"
] | null | null | null | #pragma once
#include <engine/MovementComponent.hpp>
#include <engine/Transform2D.hpp>
#include <engine/InputSystem.hpp>
#include <engine/TimerGuard.hpp>
#include <engine/Animation.hpp>
#include <engine/Mob.hpp>
#include <engine/Attack.hpp>
#include <gamebase/Buff.hpp>
#include <gamebase/Inventory.hpp>
#include <Sprite.hpp>
#include <DrawSprites.hpp>
#include <glm/glm.hpp>
#include <chrono>
#include <string>
#include <unordered_map>
#include <string>
#include <vector>
class Room;
class Player : public Mob {
public:
virtual void UpdateImpl(float elapsed) override;
virtual void OnDie() override;
virtual Animation* GetAnimation(AnimationState state) override;
void UpdatePhysics(float elapsed, const std::vector<Collider*>& colliders_to_consider);
void StopMovement() { movement_component_.StopMovement(); }
void SetPosition(const glm::vec2& pos);
void Reset();
void AddBuff(const Buff& buff) { buff_ = buff; }
void ClearBuff();
void AddHp(int hp);
void AddMp(int mp);
void AddExp(int exp);
void AddCoin(int coin);
int GetLevel() {return cur_level_;}
int GetCurLevelExp() {return exp_;}
int GetCurLevelMaxExp() {
if (GetLevel() < (int)level_exps_.size()) {
return level_exps_[GetLevel()];
}
else {
return 10000;
}
}
int GetCoin() {return coin_;}
// Inventory
bool PickupItem(ItemPrototype* item);
void UseItem(size_t slot_num);
void UnequipItem(size_t slot_num);
void DropItem(size_t slot_num);
void DropEquipment(size_t slot_num);
ItemPrototype* GetItem(size_t slot_num);
EquipmentPrototype* GetEquipment(size_t slot_num);
bool IsInventoryFull() const { return inventory_.IsFull(); }
static Player* Create(Room** room, const std::string& player_config_file);
std::vector<Attack> GetAttackInfo() const;
virtual int GetAttackPoint() override;
virtual int GetDefense() override;
int GetMaxHP() { return max_hp_; }
virtual void OnTakeDamage() override;
protected:
virtual void DrawImpl(DrawSprites& draw) override;
private:
std::unordered_map<Mob::AnimationState, Animation*> animations_;
MovementComponent movement_component_;
Room** room_;
int max_hp_ { 100 };
int mp_ { 100 };
int max_mp_ { 100 };
int exp_ { 0 };
int cur_level_ {0};
int coin_ { 0 };
std::vector<int> level_exps_;
std::vector<Attack> skills_;
Buff buff_;
float shining_duration_ { 0.0f };
bool is_shining_ { false };
Inventory inventory_;
Player(const Player& player);
Player(Room** room, const glm::vec4 bounding_box);
void LevelUp();
void Shine(float duration) { shining_duration_ = duration; }
};
| 26.214286 | 88 | 0.734527 | GenBrg |
1436e44f34a66f681f3a04b47a858f83f4680ac2 | 1,006 | cpp | C++ | libnorth/src/Utils/FileSystem.cpp | lzmru/north | cc6c17d3049c514b5c754beed7be4170ef380864 | [
"MIT"
] | null | null | null | libnorth/src/Utils/FileSystem.cpp | lzmru/north | cc6c17d3049c514b5c754beed7be4170ef380864 | [
"MIT"
] | null | null | null | libnorth/src/Utils/FileSystem.cpp | lzmru/north | cc6c17d3049c514b5c754beed7be4170ef380864 | [
"MIT"
] | null | null | null | //===--- Utils/FileSystem.cpp - File system utilities -----------*- C++ -*-===//
//
// The North Compiler Infrastructure
//
// This file is distributed under the MIT License.
// See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "Utils/FileSystem.h"
namespace north::utils {
llvm::SourceMgr *openFile(llvm::StringRef Path) {
auto MemBuff = llvm::MemoryBuffer::getFile(Path);
if (auto Error = MemBuff.getError()) {
llvm::errs() << Path << ": " << Error.message() << '\n';
std::exit(0);
}
if (!MemBuff->get()->getBufferSize())
std::exit(0);
auto SourceManager = new llvm::SourceMgr();
SourceManager->AddNewSourceBuffer(std::move(*MemBuff), llvm::SMLoc());
SourceManager->setDiagHandler([](const llvm::SMDiagnostic &SMD, void *Context) {
SMD.print("", llvm::errs());
std::exit(0);
});
return SourceManager;
}
} // north::utils
| 27.189189 | 82 | 0.538767 | lzmru |
1437068186c50e9c3d35e3556234f470e4f2775c | 3,000 | hpp | C++ | include/ImgIcon.hpp | vinben/Rotopp | f0c25db5bd25074c55ff0f67539a2452d92aaf72 | [
"Unlicense"
] | 47 | 2016-07-27T07:22:06.000Z | 2021-08-17T13:08:19.000Z | include/ImgIcon.hpp | vinben/Rotopp | f0c25db5bd25074c55ff0f67539a2452d92aaf72 | [
"Unlicense"
] | 1 | 2016-09-24T06:04:39.000Z | 2016-09-25T10:34:19.000Z | include/ImgIcon.hpp | vinben/Rotopp | f0c25db5bd25074c55ff0f67539a2452d92aaf72 | [
"Unlicense"
] | 13 | 2016-07-27T10:44:35.000Z | 2020-07-01T21:08:33.000Z | /**************************************************************************
** This file is a part of our work (Siggraph'16 paper, binary, code and dataset):
**
** Roto++: Accelerating Professional Rotoscoping using Shape Manifolds
** Wenbin Li, Fabio Viola, Jonathan Starck, Gabriel J. Brostow and Neill D.F. Campbell
**
** w.li AT cs.ucl.ac.uk
** http://visual.cs.ucl.ac.uk/pubs/rotopp
**
** Copyright (c) 2016, Wenbin Li
** 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 and data 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.
**
** THIS WORK AND THE RELATED SOFTWARE, SOURCE CODE AND DATA 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.
***************************************************************************/
#ifndef IMGICON_H
#define IMGICON_H
#include <QLabel>
#include <QPainter>
#include <QWidget>
#include <QMouseEvent>
#include "include/designZone/SpCurve.hpp"
#include "include/utils.hpp"
class QLabel;
class ImgIcon: public QLabel
{
Q_OBJECT
private:
QImage *img;
qreal num;
QColor color;
QList<SpCurve*> curves;
public:
EditType status;
explicit ImgIcon(QImage *image,QWidget *parent = 0);
explicit ImgIcon(QImage *image, int i,QWidget *parent = 0);
~ImgIcon(){}
void setStatus(EditType);
void paintEvent(QPaintEvent *event);
void setImage(QImage* im){img=im;}
QImage* getImage(){return img;}
int getNum(){return num;}
void designActionClick();
signals:
void pushImgIconClicked(qreal);
// void pushRecheckDesignActions();
protected:
void mousePressEvent(QMouseEvent *event);
public slots:
void updateCurves(QList<SpCurve*>);
void setEditingStatus();
void setNoEditStatus();
void setSuggestStatus();
void setKeyFrameStatus();
};
typedef QList<ImgIcon*> ImgIconList;
typedef QList<EditType> StatusList;
#endif
| 33.707865 | 86 | 0.698333 | vinben |
14397ab880fbe31dfcb186562f0fbf691920d199 | 1,083 | cc | C++ | bin/ui/scenic/main.cc | PowerOlive/garnet | 16b5b38b765195699f41ccb6684cc58dd3512793 | [
"BSD-3-Clause"
] | null | null | null | bin/ui/scenic/main.cc | PowerOlive/garnet | 16b5b38b765195699f41ccb6684cc58dd3512793 | [
"BSD-3-Clause"
] | null | null | null | bin/ui/scenic/main.cc | PowerOlive/garnet | 16b5b38b765195699f41ccb6684cc58dd3512793 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2018 The Fuchsia 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 <memory>
#include <lib/async-loop/cpp/loop.h>
#include <trace-provider/provider.h>
#include "lib/component/cpp/startup_context.h"
#include "lib/fsl/syslogger/init.h"
#include "lib/fxl/command_line.h"
#include "lib/fxl/log_settings_command_line.h"
#include "lib/fxl/logging.h"
#include "garnet/bin/ui/scenic/app.h"
int main(int argc, const char** argv) {
auto command_line = fxl::CommandLineFromArgcArgv(argc, argv);
if (!fxl::SetLogSettingsFromCommandLine(command_line))
return 1;
if (fsl::InitLoggerFromCommandLine(command_line, {"scenic"}) != ZX_OK)
return 1;
async::Loop loop(&kAsyncLoopConfigAttachToThread);
trace::TraceProvider trace_provider(loop.dispatcher());
std::unique_ptr<component::StartupContext> app_context(
component::StartupContext::CreateFromStartupInfo());
scenic_impl::App app(app_context.get(), [&loop] { loop.Quit(); });
loop.Run();
return 0;
}
| 30.083333 | 73 | 0.737765 | PowerOlive |
143a45786418a329fcb81a6e1cb1b3283c8b33d9 | 14,668 | cpp | C++ | core/src/main/java/site/ycsb/data_gen/Graph_gen/Graph_gen/glib-adv/fa.cpp | qiuhere/Bench | 80f15facb81120b754547586cf3a7e5f46ca1551 | [
"Apache-2.0"
] | null | null | null | core/src/main/java/site/ycsb/data_gen/Graph_gen/Graph_gen/glib-adv/fa.cpp | qiuhere/Bench | 80f15facb81120b754547586cf3a7e5f46ca1551 | [
"Apache-2.0"
] | null | null | null | core/src/main/java/site/ycsb/data_gen/Graph_gen/Graph_gen/glib-adv/fa.cpp | qiuhere/Bench | 80f15facb81120b754547586cf3a7e5f46ca1551 | [
"Apache-2.0"
] | null | null | null | /////////////////////////////////////////////////
// Includes
#include "fa.h"
/////////////////////////////////////////////////
// Finite-Automata-Transition
PFaTrans TFaTrans::LoadCustomXml(const PXmlTok& XmlTok){
IAssert(XmlTok->IsTag("Trans"));
// collect transition values
TStr MsgNm=XmlTok->GetArgVal("Msg");
TStr DstStateNm=XmlTok->GetArgVal("DstState");
TStr ScriptStr;
if (XmlTok->IsSubTag("Script")){
ScriptStr=XmlTok->GetTagTok("Script")->GetTokStr(false);}
// create transition
PFaTrans Trans=TFaTrans::New(MsgNm, DstStateNm, ScriptStr);
// return result
return Trans;
}
void TFaTrans::_ChangeStateNm(const TStr& OldStateNm, const TStr& NewStateNm){
if (SrcStateNm==OldStateNm){SrcStateNm=NewStateNm;}
if (DstStateNm==OldStateNm){DstStateNm=NewStateNm;}
}
/////////////////////////////////////////////////
// Finite-Automata-State
PFaState TFaState::LoadCustomXml(const PXmlTok& XmlTok){
IAssert(XmlTok->IsTag("State"));
// collect state values
// name
TStr Nm=XmlTok->GetArgVal("Nm");
// script
TStr ScriptStr;
if (XmlTok->IsSubTag("Script")){
ScriptStr=XmlTok->GetTagTok("Script")->GetTokStr(false);}
// transitions
TXmlTokV TransTokV; XmlTok->GetTagTokV("Trans", TransTokV);
TFaTransV TransV;
for (int TransN=0; TransN<TransTokV.Len(); TransN++){
PFaTrans Trans=TFaTrans::LoadCustomXml(TransTokV[TransN]);
TransV.Add(Trans);
}
// create transition
PFaState State=TFaState::New(Nm, ScriptStr);
for (int TransN=0; TransN<TransV.Len(); TransN++){
State->AddTrans(TransV[TransN]);}
// return result
return State;
}
void TFaState::_ChangeStateNm(const TStr& OldStateNm, const TStr& NewStateNm){
if (Nm==OldStateNm){Nm=NewStateNm;}
for (int TransN=0; TransN<FaTransV.Len(); TransN++){
FaTransV[TransN]->_ChangeStateNm(OldStateNm, NewStateNm);}
}
bool TFaState::IsTransTo(const TStr& StateNm) const {
for (int TransN=0; TransN<FaTransV.Len(); TransN++){
if (FaTransV[TransN]->GetDstStateNm()==StateNm){return true;}
}
return false;
}
void TFaState::DelTrans(const PFaTrans& Trans){
for (int TransN=FaTransV.Len()-1; TransN>=0; TransN--){
if (FaTransV[TransN]()==Trans()){
FaTransV.Del(TransN);}
}
}
void TFaState::DelTransIfDstState(const TStr& DstStateNm){
for (int TransN=FaTransV.Len()-1; TransN>=0; TransN--){
if (FaTransV[TransN]->GetDstStateNm()==DstStateNm){
FaTransV.Del(TransN);}
}
}
/////////////////////////////////////////////////
// Finite-Automata
TStr TFaDef::GetNewStateNm() const {
int StateN=0;
while (IsState(TInt::GetStr(StateN, "State%d"))){StateN++;}
return TInt::GetStr(StateN, "State%d");
}
void TFaDef::ChangeStateNm(const TStr& OldStateNm, const TStr& NewStateNm){
// return if no change
if (OldStateNm==NewStateNm){return;}
// get state
PFaState State=GetState(OldStateNm);
// assert new name doesn't exist yet and is not start or end state
IAssert(!IsState(NewStateNm));
IAssert(State()!=GetStartState()());
IAssert(State()!=GetEndState()());
// change references to state in states and transitions
TFaStateV StateV; GetStateV(StateV);
for (int StateN=0; StateN<StateV.Len(); StateN++){
StateV[StateN]->_ChangeStateNm(OldStateNm, NewStateNm);}
for (int TransN=0; TransN<GlobalTransV.Len(); TransN++){
GlobalTransV[TransN]->_ChangeStateNm(OldStateNm, NewStateNm);}
// reinsert the state
NmToFaStateH.DelKey(OldStateNm);
NmToFaStateH.AddDat(State->GetNm(), State);
}
void TFaDef::DelState(const TStr& StateNm){
// cannot delete start & end state
IAssert(StateNm!=GetStartState()->GetNm());
IAssert(StateNm!=GetEndState()->GetNm());
// get state
PFaState State=GetState(StateNm);
// delete local state transitions
TFaStateV StateV; GetStateV(StateV);
for (int StateN=0; StateN<StateV.Len(); StateN++){
StateV[StateN]->DelTransIfDstState(StateNm);}
// delete global transitions
for (int TransN=GlobalTransV.Len()-1; TransN>=0; TransN--){
PFaTrans Trans=GlobalTransV[TransN];
if ((Trans->GetSrcStateNm()==StateNm)||(Trans->GetDstStateNm()==StateNm)){
GlobalTransV.Del(TransN);}
}
// delete state from hash table
NmToFaStateH.DelKey(StateNm);
}
TStr TFaDef::GetStateNmAtXY(const double& X, const double& Y) const {
TFaStateV StateV; GetStateV(StateV);
for (int StateN=StateV.Len()-1; StateN>=0; StateN--){
if (StateV[StateN]->GetRect().IsXYIn(X, Y)){
return StateV[StateN]->GetNm();}
}
return "";
}
void TFaDef::DelTrans(const PFaTrans& Trans){
// delete local state transition
TFaStateV StateV; GetStateV(StateV);
for (int StateN=0; StateN<StateV.Len(); StateN++){
StateV[StateN]->DelTrans(Trans);}
// delete global transitions
for (int TransN=GlobalTransV.Len()-1; TransN>=0; TransN--){
if (GlobalTransV[TransN]()==Trans()){
GlobalTransV.Del(TransN);}
}
}
PFaTrans TFaDef::GetTransAtXY(const double& X, const double& Y) const {
// get states
TFaStateV StateV; GetStateV(StateV);
// traverse states
for (int StateN=0; StateN<StateV.Len(); StateN++){
// get state data
PFaState SrcFaState=StateV[StateN];
// traverse transitions
for (int TransN=0; TransN<SrcFaState->GetTranss(); TransN++){
// get transition
PFaTrans FaTrans=SrcFaState->GetTrans(TransN);
// check point being in the transition rectangle
if (FaTrans->GetRect().IsXYIn(X, Y)){return FaTrans;}
}
}
// no transition found
return NULL;
}
const TStr TFaDef::FaDefVerStr="Automaton Definition / 09.03.2004";
const TStr TFaDef::DfFNm="Automaton.Xml";
const TStr TFaDef::FExt=".Xml";
PFaDef TFaDef::LoadBin(const TStr& FNm){
PSIn SIn=TFIn::New(FNm);
char* VerCStr;
SIn->Load(VerCStr, FaDefVerStr.Len(), FaDefVerStr.Len());
if (FaDefVerStr!=VerCStr){
TExcept::Throw("Invalid version of Faulation Definition file.");}
return TFaDef::Load(*SIn);
}
void TFaDef::SaveBin(const TStr& FNm) const {
PSOut SOut=TFOut::New(FNm);
SOut->Save(FaDefVerStr.CStr(), FaDefVerStr.Len());
Save(*SOut);
}
PFaDef TFaDef::LoadXml(const TStr& FNm){
PFaDef FaDef=TFaDef::New();
XLoadFromFile(FNm, "FaDef", *FaDef);
return FaDef;
}
void TFaDef::SaveXml(const TStr& FNm){
PSOut SOut=TFOut::New(FNm);
SaveXml(*SOut, "FaDef");
}
PFaDef TFaDef::LoadCustomXml(const TStr& FNm){
// create finite automaton
PFaDef FaDef=TFaDef::New();
// load xml file
PXmlDoc XmlDoc=TXmlDoc::LoadTxt(FNm);
// global transitions
TXmlTokV GlobalTransTokV;
XmlDoc->GetTagTokV("FinAut|Trans", GlobalTransTokV);
for (int TransN=0; TransN<GlobalTransTokV.Len(); TransN++){
PFaTrans Trans=TFaTrans::LoadCustomXml(GlobalTransTokV[TransN]);
FaDef->AddGlobalTrans(Trans);
}
// states
TXmlTokV StateTokV; XmlDoc->GetTagTokV("FinAut|State", StateTokV);
for (int StateN=0; StateN<StateTokV.Len(); StateN++){
PFaState State=TFaState::LoadCustomXml(StateTokV[StateN]);
FaDef->AddState(State);
}
// start & end state
TStr StartStateNm=XmlDoc->GetTagVal("StartState", false);
FaDef->PutStartState(FaDef->GetState(StartStateNm));
TStr EndStateNm=XmlDoc->GetTagVal("EndState", false);
FaDef->PutEndState(FaDef->GetState(EndStateNm));
// return finite automaton
return FaDef;
}
/////////////////////////////////////////////////
// Finite-Automata-Expression-Environment
void TFaExpEnv::PutVarVal(const TStr& VarNm, const PExpVal& ExpVal){
VarNmToValH.AddDat(VarNm.GetUc(), ExpVal);
}
PExpVal TFaExpEnv::GetVarVal(const TStr& VarNm, bool& IsVar){
int VarNmToValP;
if (VarNmToValH.IsKey(VarNm.GetUc(), VarNmToValP)){
IsVar=true; return VarNmToValH[VarNmToValP];
} else {
printf("Variable '%s' does not exist\n", VarNm.CStr());
IsVar=false; return TExpVal::GetUndefExpVal();
}
}
PExpVal TFaExpEnv::GetFuncVal(
const TStr& FuncNm, const TExpValV& ArgValV, bool& IsFunc){
IsFunc=true; PExpVal ExpVal=TExpVal::GetUndefExpVal();
//printf("Env. function call %s/%d\n", FuncNm.CStr(), ArgValV.Len());
if (TExpEnv::IsFuncOk("Assign", efatStrAny, FuncNm, ArgValV)){
// assign value to variable
TStr VarNm=ArgValV[0]->GetStrVal();
PutVarVal(VarNm, ArgValV[1]);
} else
if (TExpEnv::IsFuncOk("OnProb", efatFlt, FuncNm, ArgValV)){
// returns true if probability in (_Prb, _PrbUsed) fires
double RqPrb=ArgValV[0]->GetFltVal();
double Prb=GetVarVal("_Prb")->GetFltVal();
double PrbUsed=GetVarVal("_PrbUsed")->GetFltVal();
bool Ok=(PrbUsed<=Prb)&&(Prb<PrbUsed+RqPrb);
PutVarVal("_PrbUsed", TExpVal::New(PrbUsed+RqPrb));
ExpVal=TExpVal::New(double(Ok)); IsFunc=true;
} else
if (TExpEnv::IsFuncOk("AfterTime", efatFlt, FuncNm, ArgValV)){
// returns true if in state longer then arg. number of secons
double MxSecs=ArgValV[0]->GetFltVal();
TSecTm StartStateTm=FaExe->GetActStateStartTm();
bool Ok=TSecTm::GetDSecs(StartStateTm, TSecTm::GetCurTm())>MxSecs;
ExpVal=TExpVal::New(double(Ok)); IsFunc=true;
} else
if (TExpEnv::IsFuncOk("SendMsg", efatStr, FuncNm, ArgValV)){
// send message created from Arg0
TStr MsgNm=ArgValV[0]->GetStrVal();
PFaMsg Msg=TFaMsg::New(MsgNm);
FaExe->PushMsg(Msg);
} else
if (TExpEnv::IsFuncOk("SaveMsgArg", efatStrFlt, FuncNm, ArgValV)){
// saves message on the index Arg1 to the variable from Arg0
TStr VarNm=ArgValV[0]->GetStrVal();
int ArgN=ArgValV[1]->GetFltValAsInt()-1;
PFaMsg Msg=FaExe->GetLastMsg();
if ((!Msg.Empty())&&(0<=ArgN)&&(ArgN<Msg->GetArgs())){
TStr MsgArgValStr=Msg->GetArgVal(ArgN);
PExpVal ExpVal=TExpVal::New(MsgArgValStr);
PutVarVal(VarNm, ExpVal);
printf("Assign '%s'='%s'\n", VarNm.CStr(), MsgArgValStr.CStr());
}
} else
if (TExpEnv::IsFuncOk("SaveMsgArg", efatStr, FuncNm, ArgValV)){
// saves message on the index 1 to the variable from Arg0
TStr VarNm=ArgValV[0]->GetStrVal();
int ArgN=0;
PFaMsg Msg=FaExe->GetLastMsg();
if ((!Msg.Empty())&&(0<=ArgN)&&(ArgN<Msg->GetArgs())){
TStr MsgArgValStr=Msg->GetArgVal(ArgN);
PExpVal ExpVal=TExpVal::New(MsgArgValStr);
PutVarVal(VarNm, ExpVal);
printf("Assign '%s'='%s'\n", VarNm.CStr(), MsgArgValStr.CStr());
}
} else
if (TExpEnv::IsFuncOk("PlayIntro", efatStr, FuncNm, ArgValV)){
// play introduction for number in Arg0
TStr CallNumStr=ArgValV[0]->GetStrVal();
printf(".....Playing Intro for '%s'.....\n", CallNumStr.CStr());
} else
if (TExpEnv::IsFuncOk("PlayCm", efatStrStr, FuncNm, ArgValV)){
// play command
TStr CallNumStr=ArgValV[0]->GetStrVal();
TStr CmNm=ArgValV[1]->GetStrVal();
printf(".....Playing Command '%s' for '%s'.....\n",
CmNm.CStr(), CallNumStr.CStr());
} else {
printf("Bad env. function call %s/%d\n", FuncNm.CStr(), ArgValV.Len());
IsFunc=false;
}
return ExpVal;
}
/////////////////////////////////////////////////
// Finite-Automata-Execution
PExpVal TFaExe::EvalExpStr(const TStr& ExpStr){
bool Ok; TStr MsgStr; bool DbgP; TStr DbgStr; PExpVal ExpVal;
PExp Exp=TExp::LoadTxt(ExpStr, Ok, MsgStr);
if (Ok){
ExpVal=Exp->Eval(Ok, MsgStr, DbgP, DbgStr, ExpEnv);
if (!Ok){Notify->OnNotify(ntErr, MsgStr);}
} else {
Notify->OnNotify(ntErr, MsgStr);
ExpVal=TExpVal::GetUndefExpVal();
}
return ExpVal;
}
TFaExe::TFaExe(const PFaDef& _FaDef, const PNotify& _Notify):
FaDef(_FaDef), Notify(_Notify),
ActState(FaDef->GetStartState()), ActTrans(),
ActStateStartTm(TSecTm::GetCurTm()), MsgQ(),
ExpEnv(TFaExpEnv::New(this)),
LastMsg(){
Notify->OnNotify(ntInfo, TStr("Starting at state: ")+ActState->GetNm());
// execute start-state script
if (!ActState->GetScriptStr().Empty()){
EvalExpStr(ActState->GetScriptStr());
}
}
TFaExe::~TFaExe(){
Notify->OnNotify(ntInfo, TStr("Terminating at state: ")+ActState->GetNm());
}
void TFaExe::ExeStep(){
// get probability random
double Prb=ExpEnv->GetRnd().GetUniDev();
ExpEnv->PutVarVal("_Prb", TExpVal::New(Prb));
ExpEnv->PutVarVal("_PrbUsed", TExpVal::New(0));
// split transitions into conditions and empty
TFaTransV EmptyTransV; TFaTransV CondTransV;
for (int TransN=0; TransN<ActState->GetTranss(); TransN++){
PFaTrans Trans=ActState->GetTrans(TransN);
if (Trans->GetCondStr().GetTrunc().Empty()){EmptyTransV.Add(Trans);}
else {CondTransV.Add(Trans);}
}
// evaluate true conditions
PFaState NewActState; ActTrans=NULL;
for (int CondTransN=0; CondTransN<CondTransV.Len(); CondTransN++){
PFaTrans CondTrans=CondTransV[CondTransN];
PExpVal ExpVal=EvalExpStr(CondTrans->GetCondStr());
if (ExpVal->GetFltVal()!=0){
ActTrans=CondTrans;
TStr NewActStateNm=CondTransV[CondTransN]->GetDstStateNm();
if (FaDef->IsState(NewActStateNm)){
NewActState=FaDef->GetState(NewActStateNm);
} else {
Notify->OnNotify(ntErr, TStr("Invalid state name (")+NewActStateNm+")");
}
break;
}
}
// if no conditions applied
if (NewActState.Empty()){
if (EmptyTransV.Len()>0){
ActTrans=EmptyTransV[0];
TStr NewActStateNm=ActTrans->GetDstStateNm();
if (FaDef->IsState(NewActStateNm)){
NewActState=FaDef->GetState(NewActStateNm);
} else {
Notify->OnNotify(ntErr, TStr("Invalid state name (")+NewActStateNm+")");
}
}
}
// get new active state and execute its script
TStr OldStateNm=ActState->GetNm();
if (!NewActState.Empty()){
ActState=NewActState; ActStateStartTm=TSecTm::GetCurTm();
if (!ActState->GetScriptStr().Empty()){
EvalExpStr(ActState->GetScriptStr());
}
TStr NewStateNm=ActState->GetNm();
Notify->OnNotify(ntInfo, TStr("Transition: ")+OldStateNm+" -> "+NewStateNm);
}
}
void TFaExe::SendMsg(const PFaMsg& Msg){
if (!Msg.Empty()){
MsgQ.Push(Msg);}
while ((ActState()!=FaDef->GetEndState()())&&(!MsgQ.Empty())){
// process messages
if (!MsgQ.Empty()){
LastMsg=MsgQ.Top(); MsgQ.Pop();
printf("Msg: '%s'\n", LastMsg->GetNm()());
PFaTrans Trans;//**=FaDef->GetTrans(State, LastMsg);
if (!Trans.Empty()){
// execute transition script
if (!Trans->GetScriptStr().Empty()){
bool Ok; TStr MsgStr;
TExp::LoadAndEvalExpL(Trans->GetScriptStr(), Ok, MsgStr, ExpEnv);
}
// get new state
ActState=FaDef->GetState(Trans->GetDstStateNm());
// execute state script
if (!ActState->GetScriptStr().Empty()){
bool Ok; TStr MsgStr;
TExp::LoadAndEvalExpL(ActState->GetScriptStr(), Ok, MsgStr, ExpEnv);
}
} else {
printf("No transition for Msg: '%s'\n", LastMsg->GetNm()());
}
}
printf("State: '%s'\n", ActState->GetNm().CStr());
}
}
| 33.953704 | 80 | 0.660485 | qiuhere |
143ae0238189ff961b572bd0c38c8abfc1ef70cc | 1,735 | cpp | C++ | lib/lexer/token/Variable.cpp | federico-terzi/ninx | ff760a481fc6c16ab06fe106c0f2051125f1b9c6 | [
"MIT"
] | 2 | 2020-08-18T23:12:52.000Z | 2021-11-15T11:29:19.000Z | lib/lexer/token/Variable.cpp | federico-terzi/ninx | ff760a481fc6c16ab06fe106c0f2051125f1b9c6 | [
"MIT"
] | 15 | 2018-12-29T20:33:14.000Z | 2019-02-03T15:13:47.000Z | lib/lexer/token/Variable.cpp | federico-terzi/ninx | ff760a481fc6c16ab06fe106c0f2051125f1b9c6 | [
"MIT"
] | null | null | null | /*
MIT License
Copyright (c) 2018 Federico Terzi
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 "Variable.h"
ninx::lexer::token::Variable::Variable(int line_number, const std::string &name) : Token(line_number), name(name) {}
ninx::lexer::token::Type ninx::lexer::token::Variable::get_type() {
return Type::VARIABLE;
}
std::string ninx::lexer::token::Variable::dump() const {
return "VARIABLE: '" + this->name + "'";
}
const std::string &ninx::lexer::token::Variable::get_name() const {
return name;
}
int ninx::lexer::token::Variable::get_trailing_spaces() const {
return trailing_spaces;
}
void ninx::lexer::token::Variable::set_trailing_spaces(int trailing_spaces) {
Variable::trailing_spaces = trailing_spaces;
}
| 35.408163 | 116 | 0.762536 | federico-terzi |
143bf37fad4d73b1758cc1de7432eee5b3325901 | 4,148 | cpp | C++ | example/src/ofApp.cpp | bakercp/ofxJitterNetworkSender | e04ef62f490e0f86cb020cd04393b2a158cb8a82 | [
"MIT"
] | 8 | 2015-03-17T17:30:23.000Z | 2020-12-06T21:34:00.000Z | example/src/ofApp.cpp | bakercp/ofxJitterNetworkSender | e04ef62f490e0f86cb020cd04393b2a158cb8a82 | [
"MIT"
] | 3 | 2017-02-07T19:57:31.000Z | 2021-09-16T14:24:50.000Z | example/src/ofApp.cpp | bakercp/ofxJitterNetworkSender | e04ef62f490e0f86cb020cd04393b2a158cb8a82 | [
"MIT"
] | 1 | 2018-10-19T21:09:21.000Z | 2018-10-19T21:09:21.000Z | // =============================================================================
//
// Copyright (c) 2009-2013 Christopher Baker <http://christopherbaker.net>
//
// 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 "ofApp.h"
//------------------------------------------------------------------------------
void ofApp::setup()
{
ofSetVerticalSync(true);
useGrabber = false;
vidGrabber.setVerbose(false);
vidGrabber.initGrabber(160,120);
fingerMovie.loadMovie("movies/fingers_160x120x15fps.mov");
fingerMovie.play();
// are we connected to the server - if this fails we
// will check every few seconds to see if the server exists
sender.setVerbose(false);
if(sender.setup("127.0.0.1", 8888))
{
connectTime = ofGetElapsedTimeMillis();
}
// some counter text
counter = 0.0;
}
//------------------------------------------------------------------------------
void ofApp::update()
{
// prepare our video frames
fingerMovie.update();
vidGrabber.update();
if(sender.isConnected())
{
if(useGrabber)
{
if (vidGrabber.isFrameNew())
{
sender.sendFrame(vidGrabber.getPixelsRef());
}
}
else
{
if(fingerMovie.isFrameNew())
{
sender.sendFrame(fingerMovie.getPixelsRef());
}
}
}
else
{
//if we are not connected lets try and reconnect every 5 seconds
if((ofGetElapsedTimeMillis() - connectTime) > 5000)
{
sender.setup("127.0.0.1", 8888);
}
}
}
//------------------------------------------------------------------------------
void ofApp::draw()
{
ofBackground(0);
ofSetColor(127);
ofRect(190,20,ofGetWidth()-160-40,ofGetHeight()-40);
ofSetColor(255,255,0);
if(useGrabber)
{
ofRect(18,158,164,124);
} else {
ofRect(18,18,164,124);
}
ofSetColor(255);
fingerMovie.draw(20,20);
vidGrabber.draw(20,160);
// send some text
std::string txt = "sent from of => " + ofToString(counter++);
sender.sendText(txt);
std::stringstream ss;
ss << "This video is being sent over TCP to port 8888 can be" << endl;
ss << "received in Jitter by using [jit.net.recv @port 8888]." << endl;
ss << "See ofxJitterNetworkSender_Example.maxpat for example" << endl;
ss << "usage. This also works in Jitter 4.5, 5, 6, etc." << endl;
ss << endl;
ss << "This message is also being sent:" << endl;
ss << endl;
ss << "[" << txt << "]" << endl;
ss << endl;
ss << "More complex messages including bangs, lists, etc" << endl;
ss << "are not fully implemented yet." << endl;
ss << "" << endl;
ss << endl;
ss << "SPACEBAR toggles between video sources." << endl;
ofDrawBitmapString(ss.str(), 200, 60);
}
//------------------------------------------------------------------------------
void ofApp::keyPressed(int key)
{
useGrabber = !useGrabber;
}
| 29.41844 | 80 | 0.558824 | bakercp |
143d3ed578059bea38c83507a971f792460e3402 | 751 | cpp | C++ | chest/base-utils/jdk/src/main/cpp/util/cases.cpp | lgoldstein/communitychest | 5d4f4b58324cd9dbd07223e2ea68ff738bd32459 | [
"Apache-2.0"
] | 1 | 2020-08-12T07:40:11.000Z | 2020-08-12T07:40:11.000Z | chest/base-utils/jdk/src/main/cpp/util/cases.cpp | lgoldstein/communitychest | 5d4f4b58324cd9dbd07223e2ea68ff738bd32459 | [
"Apache-2.0"
] | null | null | null | chest/base-utils/jdk/src/main/cpp/util/cases.cpp | lgoldstein/communitychest | 5d4f4b58324cd9dbd07223e2ea68ff738bd32459 | [
"Apache-2.0"
] | null | null | null |
/*---------------------------------------------------------------------------*/
#include <string.h>
#include <_types.h>
#include <util/string.h>
#include <util/tables.h>
#include <util/memory.h>
/*---------------------------------------------------------------------------*/
void xlate_to_lowercase (BYTE buf[], WORD buf_len)
{
if (buf_len == 0) return;
translate(buf, buf, buf_len, (BYTE *) &lower_case_chars_tbl[0]);
}
/*---------------------------------------------------------------------------*/
void xlate_to_uppercase (BYTE buf[], WORD buf_len)
{
if (buf_len == 0) return;
translate(buf, buf, buf_len, (BYTE *) &upper_case_chars_tbl[0]);
}
/*---------------------------------------------------------------------------*/
| 25.033333 | 79 | 0.383489 | lgoldstein |
143d6400b7d00609416d1bb395a72455de6afc8e | 916 | cpp | C++ | HiveWE/Texture.cpp | Retera/HiveWE | 82d757ed13420fcd31e63b23670bf09ce3cf82f0 | [
"MIT"
] | 3 | 2019-07-18T07:32:25.000Z | 2021-08-18T20:04:40.000Z | HiveWE/Texture.cpp | Retera/HiveWE | 82d757ed13420fcd31e63b23670bf09ce3cf82f0 | [
"MIT"
] | null | null | null | HiveWE/Texture.cpp | Retera/HiveWE | 82d757ed13420fcd31e63b23670bf09ce3cf82f0 | [
"MIT"
] | 1 | 2020-01-20T12:00:34.000Z | 2020-01-20T12:00:34.000Z | #include "stdafx.h"
Texture::Texture(const fs::path& path) {
BinaryReader reader = hierarchy.open_file(path);
if (path.extension() == ".blp" || path.extension() == ".BLP") {
auto blp = blp::BLP(reader);
auto[w, h, d] = blp.mipmaps.front();
data = d;
width = w;
height = h;
channels = 4;
// ToDo does this really belong here? Only a few textures have a minimap color
int mipmap_number = std::log2(width) - 2;
if (mipmap_number < blp.mipmaps.size() - 1) {
auto[mipw, miph, mipmap] = blp.mipmaps[mipmap_number];
minimap_color = *reinterpret_cast<glm::u8vec4*>(mipmap.data());
std::swap(minimap_color.r, minimap_color.b);
}
} else {
uint8_t* image_data = SOIL_load_image_from_memory(reader.buffer.data(), reader.buffer.size(), &width, &height, &channels, SOIL_LOAD_AUTO);
data = std::vector<uint8_t>(image_data, image_data + width * height * channels);
delete image_data;
}
} | 33.925926 | 140 | 0.673581 | Retera |
1443498f0797478c730a2b61074a231b22663824 | 11,335 | cpp | C++ | electron/browser/api/ApiApp.cpp | fy0/miniblink49 | 53cf81bcf80c7afa7ba8410d679a256b040d59ad | [
"MIT"
] | null | null | null | electron/browser/api/ApiApp.cpp | fy0/miniblink49 | 53cf81bcf80c7afa7ba8410d679a256b040d59ad | [
"MIT"
] | null | null | null | electron/browser/api/ApiApp.cpp | fy0/miniblink49 | 53cf81bcf80c7afa7ba8410d679a256b040d59ad | [
"MIT"
] | null | null | null |
#include "browser/api/ApiApp.h"
#include "common/NodeRegisterHelp.h"
#include "common/api/EventEmitter.h"
#include "common/ThreadCall.h"
#include "gin/object_template_builder.h"
#include "browser/api/WindowList.h"
#include "base/values.h"
#include "wke.h"
#include "nodeblink.h"
#include "base/strings/string_util.h"
#include "base/files/file_path.h"
#include <shlobj.h>
namespace atom {
App* App::m_instance = nullptr;
App* App::getInstance() {
return m_instance;
}
App::App(v8::Isolate* isolate, v8::Local<v8::Object> wrapper) {
gin::Wrappable<App>::InitWith(isolate, wrapper);
ASSERT(!m_instance);
m_instance = this;
}
App::~App() {
DebugBreak();
}
void App::init(v8::Local<v8::Object> target, v8::Isolate* isolate) {
v8::Local<v8::FunctionTemplate> prototype = v8::FunctionTemplate::New(isolate, newFunction);
prototype->SetClassName(v8::String::NewFromUtf8(isolate, "App"));
gin::ObjectTemplateBuilder builder(isolate, prototype->InstanceTemplate());
builder.SetMethod("quit", &App::quitApi);
builder.SetMethod("exit", &App::exitApi);
builder.SetMethod("focus", &App::focusApi);
builder.SetMethod("getVersion", &App::getVersionApi);
builder.SetMethod("setVersion", &App::setVersionApi);
builder.SetMethod("getName", &App::getNameApi);
builder.SetMethod("setName", &App::setNameApi);
builder.SetMethod("isReady", &App::isReadyApi);
builder.SetMethod("addRecentDocument", &App::addRecentDocumentApi);
builder.SetMethod("clearRecentDocuments", &App::clearRecentDocumentsApi);
builder.SetMethod("setAppUserModelId", &App::setAppUserModelIdApi);
builder.SetMethod("isDefaultProtocolClient", &App::isDefaultProtocolClientApi);
builder.SetMethod("setAsDefaultProtocolClient", &App::setAsDefaultProtocolClientApi);
builder.SetMethod("removeAsDefaultProtocolClient", &App::removeAsDefaultProtocolClientApi);
builder.SetMethod("setBadgeCount", &App::setBadgeCountApi);
builder.SetMethod("getBadgeCount", &App::getBadgeCountApi);
builder.SetMethod("getLoginItemSettings", &App::getLoginItemSettingsApi);
builder.SetMethod("setLoginItemSettings", &App::setLoginItemSettingsApi);
builder.SetMethod("setUserTasks", &App::setUserTasksApi);
builder.SetMethod("getJumpListSettings", &App::getJumpListSettingsApi);
builder.SetMethod("setJumpList", &App::setJumpListApi);
builder.SetMethod("setPath", &App::setPathApi);
builder.SetMethod("getPath", &App::getPathApi);
builder.SetMethod("setDesktopName", &App::setDesktopNameApi);
builder.SetMethod("getLocale", &App::getLocaleApi);
builder.SetMethod("makeSingleInstance", &App::makeSingleInstanceApi);
builder.SetMethod("releaseSingleInstance", &App::releaseSingleInstanceApi);
builder.SetMethod("relaunch", &App::relaunchApi);
builder.SetMethod("isAccessibilitySupportEnabled", &App::isAccessibilitySupportEnabled);
builder.SetMethod("disableHardwareAcceleration", &App::disableHardwareAcceleration);
constructor.Reset(isolate, prototype->GetFunction());
target->Set(v8::String::NewFromUtf8(isolate, "App"), prototype->GetFunction());
}
void App::nullFunction() {
OutputDebugStringA("nullFunction\n");
}
void quit() {
::TerminateProcess(::GetCurrentProcess(), 0);
WindowList::closeAllWindows();
ThreadCall::exitMessageLoop(ThreadCall::getBlinkThreadId());
ThreadCall::exitMessageLoop(ThreadCall::getUiThreadId());
}
void App::quitApi() {
OutputDebugStringA("quitApi\n");
quit();
if (ThreadCall::isUiThread()) {
quit();
return;
}
ThreadCall::callUiThreadAsync([] {
quit();
});
}
void App::exitApi() {
quitApi();
}
void App::focusApi() {
OutputDebugStringA("focusApi\n");
}
bool App::isReadyApi() const {
OutputDebugStringA("isReadyApi\n");
return true;
}
void App::addRecentDocumentApi(const std::string& path) {
OutputDebugStringA("addRecentDocumentApi\n");
}
void App::clearRecentDocumentsApi() {
OutputDebugStringA("clearRecentDocumentsApi\n");
}
void App::setAppUserModelIdApi(const std::string& id) {
OutputDebugStringA("setAppUserModelIdApi\n");
}
// const std::string& protocol, const std::string& path, const std::string& args
bool App::isDefaultProtocolClientApi(const v8::FunctionCallbackInfo<v8::Value>& args) {
OutputDebugStringA("isDefaultProtocolClientApi\n");
return true;
}
//const std::string& protocol, const std::string& path, const std::string& args
bool App::setAsDefaultProtocolClientApi(const v8::FunctionCallbackInfo<v8::Value>& args) {
OutputDebugStringA("setAsDefaultProtocolClientApi\n");
if (0 == args.Length())
return false;
std::string protocol;
if (!gin::ConvertFromV8(args.GetIsolate(), args[0], &protocol))
return false;
return true;
}
// const std::string& protocol, const std::string& path, const std::string& args
bool App::removeAsDefaultProtocolClientApi(const v8::FunctionCallbackInfo<v8::Value>& args) {
OutputDebugStringA("removeAsDefaultProtocolClientApi\n");
return true;
}
bool App::setBadgeCountApi(int count) {
OutputDebugStringA("setBadgeCountApi\n");
return false;
}
int App::getBadgeCountApi() {
OutputDebugStringA("getBadgeCountApi\n");
return 0;
}
// const base::DictionaryValue& obj
int App::getLoginItemSettingsApi(const v8::FunctionCallbackInfo<v8::Value>& args) {
OutputDebugStringA("getLoginItemSettingsApi\n");
DebugBreak();
return 0;
}
// const base::DictionaryValue& obj, const std::string& path, const std::string& args
void App::setLoginItemSettingsApi(const v8::FunctionCallbackInfo<v8::Value>& args) {
OutputDebugStringA("setLoginItemSettingsApi");
DebugBreak();
}
bool App::setUserTasksApi(const v8::FunctionCallbackInfo<v8::Value>& args) {
OutputDebugStringA("setUserTasksApi\n");
return true;
}
void App::setDesktopNameApi(const std::string& desktopName) {
OutputDebugStringA("App::setDesktopNameApi\n");
}
v8::Local<v8::Value> App::getJumpListSettingsApi(const v8::FunctionCallbackInfo<v8::Value>& args) {
OutputDebugStringA("getJumpListSettingsApi\n");
base::DictionaryValue obj;
obj.SetInteger("minItems", 1);
base::ListValue* removedItems = new base::ListValue();
obj.Set("removedItems", removedItems);
v8::Local<v8::Value> result = gin::Converter<base::DictionaryValue>::ToV8(args.GetIsolate(), obj);
return result;
}
// const base::DictionaryValue&
void App::setJumpListApi(const v8::FunctionCallbackInfo<v8::Value>& args) {
OutputDebugStringA("setJumpListApi\n");
}
std::string App::getLocaleApi() {
return "zh-cn";
}
void App::makeSingleInstanceApi(const v8::FunctionCallbackInfo<v8::Value>& args) {
OutputDebugStringA("makeSingleInstanceApi\n");
}
void App::releaseSingleInstanceApi() {
OutputDebugStringA("releaseSingleInstanceApi\n");
}
void App::relaunchApi(const base::DictionaryValue& options) {
OutputDebugStringA("relaunchApi\n");
}
void App::setPathApi(const std::string& name, const std::string& path) {
if (name == "userData" || name == "cache" || name == "userCache" || name == "documents"
|| name == "downloads" || name == "music" || name == "videos" || name == "pepperFlashSystemPlugin") {
m_pathMap.insert(std::make_pair(name, path));
}
}
bool getTempDir(base::FilePath* path) {
wchar_t temp_path[MAX_PATH + 1];
DWORD path_len = ::GetTempPath(MAX_PATH, temp_path);
if (path_len >= MAX_PATH || path_len <= 0)
return false;
// TODO(evanm): the old behavior of this function was to always strip the
// trailing slash. We duplicate this here, but it shouldn't be necessary
// when everyone is using the appropriate FilePath APIs.
*path = base::FilePath(temp_path).StripTrailingSeparators();
return true;
}
base::FilePath getHomeDir() {
wchar_t result[MAX_PATH];
if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_PROFILE, NULL, SHGFP_TYPE_CURRENT, result)) && result[0])
return base::FilePath(result);
// Fall back to the temporary directory on failure.
base::FilePath temp;
if (getTempDir(&temp))
return temp;
// Last resort.
return base::FilePath(L"C:\\");
}
std::string App::getPathApi(const std::string& name) const {
base::FilePath path;
std::wstring systemBuffer;
systemBuffer.assign(MAX_PATH, L'\0');
std::wstring pathBuffer;
if (name == "appData") {
if ((::SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, SHGFP_TYPE_CURRENT, &systemBuffer[0])) < 0)
return "";
} else if (name == "userData" || name == "documents"
|| name == "downloads" || name == "music" || name == "videos" || name == "pepperFlashSystemPlugin") {
std::map<std::string, std::string>::const_iterator it = m_pathMap.find(name);
if (it == m_pathMap.end())
return "";
return it->second;
} else if (name == "home")
systemBuffer = getHomeDir().value();
else if (name == "temp") {
if (!getTempDir(&path))
return "";
systemBuffer = path.value();
} else if (name == "userDesktop" || name == "desktop") {
if (FAILED(SHGetFolderPath(NULL, CSIDL_DESKTOPDIRECTORY, NULL, SHGFP_TYPE_CURRENT, &systemBuffer[0])))
return "";
} else if (name == "exe") {
::GetModuleFileName(NULL, &systemBuffer[0], MAX_PATH);
} else if (name == "module")
::GetModuleFileName(NULL, &systemBuffer[0], MAX_PATH);
else if (name == "cache" || name == "userCache") {
if ((::SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, SHGFP_TYPE_CURRENT, &systemBuffer[0])) < 0)
return "";
pathBuffer = systemBuffer.c_str();
pathBuffer += L"\\electron";
} else
return "";
pathBuffer = systemBuffer.c_str();
return base::WideToUTF8(pathBuffer);
}
void App::newFunction(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::Isolate* isolate = args.GetIsolate();
if (args.IsConstructCall()) {
new App(isolate, args.This());
args.GetReturnValue().Set(args.This());
return;
}
}
void App::onWindowAllClosed() {
if (ThreadCall::isUiThread()) {
emit("window-all-closed");
return;
}
App* self = this;
ThreadCall::callUiThreadAsync([self] {
self->emit("window-all-closed");
});
}
v8::Persistent< v8::Function> App::constructor;
gin::WrapperInfo App::kWrapperInfo = { gin::kEmbedderNativeGin };
static void initializeAppApi(v8::Local<v8::Object> target, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, const NodeNative* native) {
node::Environment* env = node::Environment::GetCurrent(context);
App::init(target, env->isolate());
}
static const char BrowserAppNative[] = "console.log('BrowserAppNative');;";
static NodeNative nativeBrowserAppNative{ "App", BrowserAppNative, sizeof(BrowserAppNative) - 1 };
NODE_MODULE_CONTEXT_AWARE_BUILTIN_SCRIPT_MANUAL(atom_browser_app, initializeAppApi, &nativeBrowserAppNative)
} | 35.092879 | 148 | 0.674548 | fy0 |
1443b3c7f825ecd2a7796a8e32b0e3220460a221 | 1,383 | cpp | C++ | wirish/wirish_math.cpp | lacklustrlabs/libmaple | a2d1169b0b5a5de68140dad26982cf0f238e877b | [
"MIT"
] | 162 | 2015-01-07T18:26:13.000Z | 2022-03-07T09:50:31.000Z | wirish/wirish_math.cpp | lacklustrlabs/libmaple | a2d1169b0b5a5de68140dad26982cf0f238e877b | [
"MIT"
] | 25 | 2015-01-24T19:03:30.000Z | 2021-12-15T15:02:50.000Z | wirish/wirish_math.cpp | lacklustrlabs/libmaple | a2d1169b0b5a5de68140dad26982cf0f238e877b | [
"MIT"
] | 112 | 2015-01-16T08:58:13.000Z | 2022-03-23T20:01:06.000Z | /*
* Modified by LeafLabs, LLC.
*
* Part of the Wiring project - http://wiring.org.co Copyright (c)
* 2004-06 Hernando Barragan Modified 13 August 2006, David A. Mellis
* for Arduino - http://www.arduino.cc/
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*/
#include <stdlib.h>
#include <wirish/wirish_math.h>
void randomSeed(unsigned int seed) {
if (seed != 0) {
srand(seed);
}
}
long random(long howbig) {
if (howbig == 0) {
return 0;
}
return rand() % howbig;
}
long random(long howsmall, long howbig) {
if (howsmall >= howbig) {
return howsmall;
}
long diff = howbig - howsmall;
return random(diff) + howsmall;
}
| 27.66 | 70 | 0.686189 | lacklustrlabs |
14454cf5f3735fa6abb2954ba2c68146ffc2c1c7 | 32,329 | cc | C++ | third_party/blink/renderer/core/layout/layout_shift_tracker.cc | iridium-browser/iridium-browser | 907e31cf5ce5ad14d832796e3a7c11e496828959 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 575 | 2015-06-18T23:58:20.000Z | 2022-03-23T09:32:39.000Z | third_party/blink/renderer/core/layout/layout_shift_tracker.cc | iridium-browser/iridium-browser | 907e31cf5ce5ad14d832796e3a7c11e496828959 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | third_party/blink/renderer/core/layout/layout_shift_tracker.cc | iridium-browser/iridium-browser | 907e31cf5ce5ad14d832796e3a7c11e496828959 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 52 | 2015-07-14T10:40:50.000Z | 2022-03-15T01:11:49.000Z | // Copyright 2018 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 "third_party/blink/renderer/core/layout/layout_shift_tracker.h"
#include "cc/layers/heads_up_display_layer.h"
#include "cc/layers/picture_layer.h"
#include "cc/trees/layer_tree_host.h"
#include "third_party/blink/public/common/features.h"
#include "third_party/blink/public/common/input/web_pointer_event.h"
#include "third_party/blink/renderer/core/dom/dom_node_ids.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/frame/local_frame_client.h"
#include "third_party/blink/renderer/core/frame/location.h"
#include "third_party/blink/renderer/core/frame/visual_viewport.h"
#include "third_party/blink/renderer/core/geometry/dom_rect_read_only.h"
#include "third_party/blink/renderer/core/layout/layout_object.h"
#include "third_party/blink/renderer/core/layout/layout_view.h"
#include "third_party/blink/renderer/core/page/chrome_client.h"
#include "third_party/blink/renderer/core/page/page.h"
#include "third_party/blink/renderer/core/timing/dom_window_performance.h"
#include "third_party/blink/renderer/core/timing/performance_entry.h"
#include "third_party/blink/renderer/core/timing/window_performance.h"
#include "third_party/blink/renderer/platform/graphics/graphics_layer.h"
#include "third_party/blink/renderer/platform/graphics/paint/geometry_mapper.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "ui/gfx/geometry/rect.h"
namespace blink {
using ReattachHookScope = LayoutShiftTracker::ReattachHookScope;
ReattachHookScope* ReattachHookScope::top_ = nullptr;
using ContainingBlockScope = LayoutShiftTracker::ContainingBlockScope;
ContainingBlockScope* ContainingBlockScope::top_ = nullptr;
namespace {
constexpr base::TimeDelta kTimerDelay = base::TimeDelta::FromMilliseconds(500);
const float kMovementThreshold = 3.0; // CSS pixels.
// Calculates the physical coordinates of the starting point in the current
// coordinate space. |paint_offset| is the physical offset of the top-left
// corner. The starting point can be any of the four corners of the box,
// depending on the writing mode and text direction. Note that the result is
// still in physical coordinates, just may be of a different corner.
// See https://wicg.github.io/layout-instability/#starting-point.
FloatPoint StartingPoint(const PhysicalOffset& paint_offset,
const LayoutBox& box,
const LayoutSize& size) {
PhysicalOffset starting_point = paint_offset;
auto writing_direction = box.StyleRef().GetWritingDirection();
if (UNLIKELY(writing_direction.IsFlippedBlocks()))
starting_point.left += size.Width();
if (UNLIKELY(writing_direction.IsRtl())) {
if (writing_direction.IsHorizontal())
starting_point.left += size.Width();
else
starting_point.top += size.Height();
}
return FloatPoint(starting_point);
}
// Returns the part a rect logically below a starting point.
PhysicalRect RectBelowStartingPoint(const PhysicalRect& rect,
const PhysicalOffset& starting_point,
LayoutUnit logical_height,
WritingDirectionMode writing_direction) {
PhysicalRect result = rect;
if (writing_direction.IsHorizontal()) {
result.ShiftTopEdgeTo(starting_point.top);
result.SetHeight(logical_height);
} else {
result.SetWidth(logical_height);
if (writing_direction.IsFlippedBlocks())
result.ShiftRightEdgeTo(starting_point.left);
else
result.ShiftLeftEdgeTo(starting_point.left);
}
return result;
}
float GetMoveDistance(const FloatPoint& old_starting_point,
const FloatPoint& new_starting_point) {
FloatSize location_delta = new_starting_point - old_starting_point;
return std::max(fabs(location_delta.Width()), fabs(location_delta.Height()));
}
bool EqualWithinMovementThreshold(const FloatPoint& a,
const FloatPoint& b,
float threshold_physical_px) {
return fabs(a.X() - b.X()) < threshold_physical_px &&
fabs(a.Y() - b.Y()) < threshold_physical_px;
}
bool SmallerThanRegionGranularity(const LayoutRect& rect) {
// Normally we paint by snapping to whole pixels, so rects smaller than half
// a pixel may be invisible.
return rect.Width() < 0.5 || rect.Height() < 0.5;
}
void RectToTracedValue(const IntRect& rect,
TracedValue& value,
const char* key = nullptr) {
if (key)
value.BeginArray(key);
else
value.BeginArray();
value.PushInteger(rect.X());
value.PushInteger(rect.Y());
value.PushInteger(rect.Width());
value.PushInteger(rect.Height());
value.EndArray();
}
void RegionToTracedValue(const LayoutShiftRegion& region, TracedValue& value) {
Region blink_region;
for (IntRect rect : region.GetRects())
blink_region.Unite(Region(rect));
value.BeginArray("region_rects");
for (const IntRect& rect : blink_region.Rects())
RectToTracedValue(rect, value);
value.EndArray();
}
bool ShouldLog(const LocalFrame& frame) {
if (!VLOG_IS_ON(1))
return false;
DCHECK(frame.GetDocument());
const String& url = frame.GetDocument()->Url().GetString();
return !url.StartsWith("devtools:");
}
} // namespace
LayoutShiftTracker::LayoutShiftTracker(LocalFrameView* frame_view)
: frame_view_(frame_view),
// This eliminates noise from the private Page object created by
// SVGImage::DataChanged.
is_active_(
!frame_view->GetFrame().GetChromeClient().IsSVGImageChromeClient()),
enable_m90_improvements_(
base::FeatureList::IsEnabled(features::kCLSM90Improvements)),
score_(0.0),
weighted_score_(0.0),
timer_(frame_view->GetFrame().GetTaskRunner(TaskType::kInternalDefault),
this,
&LayoutShiftTracker::TimerFired),
frame_max_distance_(0.0),
overall_max_distance_(0.0),
observed_input_or_scroll_(false),
most_recent_input_timestamp_initialized_(false) {}
bool LayoutShiftTracker::NeedsToTrack(const LayoutObject& object) const {
if (!is_active_)
return false;
if (object.GetDocument().IsPrintingOrPaintingPreview())
return false;
// SVG elements don't participate in the normal layout algorithms and are
// more likely to be used for animations.
if (object.IsSVGChild())
return false;
if (object.StyleRef().Visibility() != EVisibility::kVisible)
return false;
if (object.IsText()) {
if (!ContainingBlockScope::top_)
return false;
if (object.IsBR())
return false;
if (enable_m90_improvements_) {
if (To<LayoutText>(object).ContainsOnlyWhitespaceOrNbsp() ==
OnlyWhitespaceOrNbsp::kYes)
return false;
if (object.StyleRef().GetFont().ShouldSkipDrawing())
return false;
}
return true;
}
if (!object.IsBox())
return false;
const auto& box = To<LayoutBox>(object);
if (SmallerThanRegionGranularity(box.VisualOverflowRect()))
return false;
if (auto* display_lock_context = box.GetDisplayLockContext()) {
if (display_lock_context->IsAuto() && display_lock_context->IsLocked())
return false;
}
// Don't report shift of anonymous objects. Will report the children because
// we want report real DOM nodes.
if (box.IsAnonymous())
return false;
// Ignore sticky-positioned objects that move on scroll.
// TODO(skobes): Find a way to detect when these objects shift.
if (box.IsStickyPositioned())
return false;
// A LayoutView can't move by itself.
if (box.IsLayoutView())
return false;
if (Element* element = DynamicTo<Element>(object.GetNode())) {
if (element->IsSliderThumbElement())
return false;
}
if (enable_m90_improvements_ && box.IsLayoutBlock()) {
// Just check the simplest case. For more complex cases, we should suggest
// the developer to use visibility:hidden.
if (To<LayoutBlock>(box).FirstChild())
return true;
if (box.HasBoxDecorationBackground() || box.GetScrollableArea() ||
box.StyleRef().HasVisualOverflowingEffect())
return true;
return false;
}
return true;
}
void LayoutShiftTracker::ObjectShifted(
const LayoutObject& object,
const PropertyTreeStateOrAlias& property_tree_state,
const PhysicalRect& old_rect,
const PhysicalRect& new_rect,
const FloatPoint& old_starting_point,
const FloatSize& translation_delta,
const FloatSize& scroll_delta,
const FloatPoint& new_starting_point) {
// The caller should ensure these conditions.
DCHECK(!old_rect.IsEmpty());
DCHECK(!new_rect.IsEmpty());
float threshold_physical_px =
kMovementThreshold * object.StyleRef().EffectiveZoom();
if (enable_m90_improvements_) {
// Check shift of starting point, including 2d-translation and scroll
// deltas.
if (EqualWithinMovementThreshold(old_starting_point, new_starting_point,
threshold_physical_px))
return;
// Check shift of 2d-translation-indifferent starting point.
if (!translation_delta.IsZero() &&
EqualWithinMovementThreshold(old_starting_point + translation_delta,
new_starting_point, threshold_physical_px))
return;
// Check shift of scroll-indifferent starting point.
if (!scroll_delta.IsZero() &&
EqualWithinMovementThreshold(old_starting_point + scroll_delta,
new_starting_point, threshold_physical_px))
return;
}
// Check shift of 2d-translation-and-scroll-indifferent starting point.
FloatSize translation_and_scroll_delta = scroll_delta + translation_delta;
if (!translation_and_scroll_delta.IsZero() &&
EqualWithinMovementThreshold(
old_starting_point + translation_and_scroll_delta, new_starting_point,
threshold_physical_px))
return;
const auto& root_state =
object.View()->FirstFragment().LocalBorderBoxProperties();
FloatClipRect clip_rect =
GeometryMapper::LocalToAncestorClipRect(property_tree_state, root_state);
if (frame_view_->GetFrame().IsMainFrame()) {
// Apply the visual viewport clip.
clip_rect.Intersect(FloatClipRect(
frame_view_->GetPage()->GetVisualViewport().VisibleRect()));
}
// If the clip region is empty, then the resulting layout shift isn't visible
// in the viewport so ignore it.
if (clip_rect.Rect().IsEmpty())
return;
auto transform = GeometryMapper::SourceToDestinationProjection(
property_tree_state.Transform(), root_state.Transform());
// TODO(crbug.com/1187979): Shift by |scroll_delta| to keep backward
// compatibility in https://crrev.com/c/2754969. See the bug for details.
FloatPoint old_starting_point_in_root = transform.MapPoint(
old_starting_point +
(enable_m90_improvements_ ? scroll_delta : translation_and_scroll_delta));
FloatPoint new_starting_point_in_root =
transform.MapPoint(new_starting_point);
if (EqualWithinMovementThreshold(old_starting_point_in_root,
new_starting_point_in_root,
threshold_physical_px))
return;
if (enable_m90_improvements_) {
DCHECK(frame_scroll_delta_.IsZero());
} else if (EqualWithinMovementThreshold(
old_starting_point_in_root + frame_scroll_delta_,
new_starting_point_in_root, threshold_physical_px)) {
// TODO(skobes): Checking frame_scroll_delta_ is an imperfect solution to
// allowing counterscrolled layout shifts. Ideally, we would map old_rect
// to viewport coordinates using the previous frame's scroll tree.
return;
}
FloatRect old_rect_in_root(old_rect);
// TODO(crbug.com/1187979): Shift by |scroll_delta| to keep backward
// compatibility in https://crrev.com/c/2754969. See the bug for details.
old_rect_in_root.Move(
enable_m90_improvements_ ? scroll_delta : translation_and_scroll_delta);
transform.MapRect(old_rect_in_root);
FloatRect new_rect_in_root(new_rect);
transform.MapRect(new_rect_in_root);
IntRect visible_old_rect =
RoundedIntRect(Intersection(old_rect_in_root, clip_rect.Rect()));
IntRect visible_new_rect =
RoundedIntRect(Intersection(new_rect_in_root, clip_rect.Rect()));
if (visible_old_rect.IsEmpty() && visible_new_rect.IsEmpty())
return;
// If the object moved from or to out of view, ignore the shift if it's in
// the inline direction only.
if (enable_m90_improvements_ &&
(visible_old_rect.IsEmpty() || visible_new_rect.IsEmpty())) {
FloatPoint old_inline_direction_indifferent_starting_point_in_root =
old_starting_point_in_root;
if (object.IsHorizontalWritingMode()) {
old_inline_direction_indifferent_starting_point_in_root.SetX(
new_starting_point_in_root.X());
} else {
old_inline_direction_indifferent_starting_point_in_root.SetY(
new_starting_point_in_root.Y());
}
if (EqualWithinMovementThreshold(
old_inline_direction_indifferent_starting_point_in_root,
new_starting_point_in_root, threshold_physical_px)) {
return;
}
}
// Compute move distance based on unclipped rects, to accurately determine how
// much the element moved.
float move_distance =
GetMoveDistance(old_starting_point_in_root, new_starting_point_in_root);
frame_max_distance_ = std::max(frame_max_distance_, move_distance);
LocalFrame& frame = frame_view_->GetFrame();
if (ShouldLog(frame)) {
VLOG(1) << "in " << (frame.IsMainFrame() ? "" : "subframe ")
<< frame.GetDocument()->Url() << ", " << object << " moved from "
<< old_rect_in_root << " to " << new_rect_in_root
<< " (visible from " << visible_old_rect << " to "
<< visible_new_rect << ")";
if (old_starting_point_in_root != old_rect_in_root.Location() ||
new_starting_point_in_root != new_rect_in_root.Location() ||
!translation_delta.IsZero() || !scroll_delta.IsZero()) {
VLOG(1) << " (starting point from " << old_starting_point_in_root
<< " to " << new_starting_point_in_root << ")";
}
}
region_.AddRect(visible_old_rect);
region_.AddRect(visible_new_rect);
if (Node* node = object.GetNode()) {
MaybeRecordAttribution(
{DOMNodeIds::IdForNode(node), visible_old_rect, visible_new_rect});
}
}
LayoutShiftTracker::Attribution::Attribution() : node_id(kInvalidDOMNodeId) {}
LayoutShiftTracker::Attribution::Attribution(DOMNodeId node_id_arg,
IntRect old_visual_rect_arg,
IntRect new_visual_rect_arg)
: node_id(node_id_arg),
old_visual_rect(old_visual_rect_arg),
new_visual_rect(new_visual_rect_arg) {}
LayoutShiftTracker::Attribution::operator bool() const {
return node_id != kInvalidDOMNodeId;
}
bool LayoutShiftTracker::Attribution::Encloses(const Attribution& other) const {
return old_visual_rect.Contains(other.old_visual_rect) &&
new_visual_rect.Contains(other.new_visual_rect);
}
int LayoutShiftTracker::Attribution::Area() const {
int old_area = old_visual_rect.Width() * old_visual_rect.Height();
int new_area = new_visual_rect.Width() * new_visual_rect.Height();
IntRect intersection = Intersection(old_visual_rect, new_visual_rect);
int shared_area = intersection.Width() * intersection.Height();
return old_area + new_area - shared_area;
}
bool LayoutShiftTracker::Attribution::MoreImpactfulThan(
const Attribution& other) const {
return Area() > other.Area();
}
void LayoutShiftTracker::MaybeRecordAttribution(
const Attribution& attribution) {
Attribution* smallest = nullptr;
for (auto& slot : attributions_) {
if (!slot || attribution.Encloses(slot)) {
slot = attribution;
return;
}
if (slot.Encloses(attribution))
return;
if (!smallest || smallest->MoreImpactfulThan(slot))
smallest = &slot;
}
// No empty slots or redundancies. Replace smallest existing slot if larger.
if (attribution.MoreImpactfulThan(*smallest))
*smallest = attribution;
}
void LayoutShiftTracker::NotifyBoxPrePaint(
const LayoutBox& box,
const PropertyTreeStateOrAlias& property_tree_state,
const PhysicalRect& old_rect,
const PhysicalRect& new_rect,
const PhysicalOffset& old_paint_offset,
const FloatSize& translation_delta,
const FloatSize& scroll_delta,
const PhysicalOffset& new_paint_offset) {
DCHECK(NeedsToTrack(box));
ObjectShifted(box, property_tree_state, old_rect, new_rect,
StartingPoint(old_paint_offset, box, box.PreviousSize()),
translation_delta, scroll_delta,
StartingPoint(new_paint_offset, box, box.Size()));
}
void LayoutShiftTracker::NotifyTextPrePaint(
const LayoutText& text,
const PropertyTreeStateOrAlias& property_tree_state,
const LogicalOffset& old_starting_point,
const LogicalOffset& new_starting_point,
const PhysicalOffset& old_paint_offset,
const FloatSize& translation_delta,
const FloatSize& scroll_delta,
const PhysicalOffset& new_paint_offset,
LayoutUnit logical_height) {
DCHECK(NeedsToTrack(text));
auto* block = ContainingBlockScope::top_;
DCHECK(block);
auto writing_direction = text.StyleRef().GetWritingDirection();
PhysicalOffset old_physical_starting_point =
old_paint_offset + old_starting_point.ConvertToPhysical(writing_direction,
block->old_size_,
PhysicalSize());
PhysicalOffset new_physical_starting_point =
new_paint_offset + new_starting_point.ConvertToPhysical(writing_direction,
block->new_size_,
PhysicalSize());
PhysicalRect old_rect =
RectBelowStartingPoint(block->old_rect_, old_physical_starting_point,
logical_height, writing_direction);
if (old_rect.IsEmpty())
return;
PhysicalRect new_rect =
RectBelowStartingPoint(block->new_rect_, new_physical_starting_point,
logical_height, writing_direction);
if (new_rect.IsEmpty())
return;
ObjectShifted(text, property_tree_state, old_rect, new_rect,
FloatPoint(old_physical_starting_point), translation_delta,
scroll_delta, FloatPoint(new_physical_starting_point));
}
double LayoutShiftTracker::SubframeWeightingFactor() const {
LocalFrame& frame = frame_view_->GetFrame();
if (frame.IsMainFrame())
return 1;
// Map the subframe view rect into the coordinate space of the local root.
FloatClipRect subframe_cliprect =
FloatClipRect(FloatRect(FloatPoint(), FloatSize(frame_view_->Size())));
GeometryMapper::LocalToAncestorVisualRect(
frame_view_->GetLayoutView()->FirstFragment().LocalBorderBoxProperties(),
PropertyTreeState::Root(), subframe_cliprect);
auto subframe_rect = PhysicalRect::EnclosingRect(subframe_cliprect.Rect());
// Intersect with the portion of the local root that overlaps the main frame.
frame.LocalFrameRoot().View()->MapToVisualRectInRemoteRootFrame(
subframe_rect);
IntSize subframe_visible_size = subframe_rect.PixelSnappedSize();
IntSize main_frame_size = frame.GetPage()->GetVisualViewport().Size();
// TODO(crbug.com/940711): This comparison ignores page scale and CSS
// transforms above the local root.
return static_cast<double>(subframe_visible_size.Area()) /
main_frame_size.Area();
}
void LayoutShiftTracker::NotifyPrePaintFinishedInternal() {
if (!is_active_)
return;
if (region_.IsEmpty())
return;
IntRect viewport = frame_view_->GetScrollableArea()->VisibleContentRect();
if (viewport.IsEmpty())
return;
double viewport_area = double(viewport.Width()) * double(viewport.Height());
double impact_fraction = region_.Area() / viewport_area;
DCHECK_GT(impact_fraction, 0);
DCHECK_GT(frame_max_distance_, 0.0);
double viewport_max_dimension = std::max(viewport.Width(), viewport.Height());
double move_distance_factor =
(frame_max_distance_ < viewport_max_dimension)
? double(frame_max_distance_) / viewport_max_dimension
: 1.0;
double score_delta = impact_fraction * move_distance_factor;
double weighted_score_delta = score_delta * SubframeWeightingFactor();
overall_max_distance_ = std::max(overall_max_distance_, frame_max_distance_);
LocalFrame& frame = frame_view_->GetFrame();
if (ShouldLog(frame)) {
VLOG(1) << "in " << (frame.IsMainFrame() ? "" : "subframe ")
<< frame.GetDocument()->Url() << ", viewport was "
<< (impact_fraction * 100) << "% impacted with distance fraction "
<< move_distance_factor;
}
if (pointerdown_pending_data_.saw_pointerdown) {
pointerdown_pending_data_.score_delta += score_delta;
pointerdown_pending_data_.weighted_score_delta += weighted_score_delta;
} else {
ReportShift(score_delta, weighted_score_delta);
}
if (!region_.IsEmpty() && !timer_.IsActive())
SendLayoutShiftRectsToHud(region_.GetRects());
}
void LayoutShiftTracker::NotifyPrePaintFinished() {
NotifyPrePaintFinishedInternal();
// Reset accumulated state.
region_.Reset();
frame_max_distance_ = 0.0;
frame_scroll_delta_ = ScrollOffset();
attributions_.fill(Attribution());
}
LayoutShift::AttributionList LayoutShiftTracker::CreateAttributionList() const {
LayoutShift::AttributionList list;
for (const Attribution& att : attributions_) {
if (att.node_id == kInvalidDOMNodeId)
break;
list.push_back(LayoutShiftAttribution::Create(
DOMNodeIds::NodeForId(att.node_id),
DOMRectReadOnly::FromIntRect(att.old_visual_rect),
DOMRectReadOnly::FromIntRect(att.new_visual_rect)));
}
return list;
}
void LayoutShiftTracker::SubmitPerformanceEntry(double score_delta,
bool had_recent_input) const {
LocalDOMWindow* window = frame_view_->GetFrame().DomWindow();
if (!window)
return;
WindowPerformance* performance = DOMWindowPerformance::performance(*window);
DCHECK(performance);
double input_timestamp = LastInputTimestamp();
LayoutShift* entry =
LayoutShift::Create(performance->now(), score_delta, had_recent_input,
input_timestamp, CreateAttributionList());
performance->AddLayoutShiftEntry(entry);
}
void LayoutShiftTracker::ReportShift(double score_delta,
double weighted_score_delta) {
LocalFrame& frame = frame_view_->GetFrame();
bool had_recent_input = timer_.IsActive();
if (!had_recent_input) {
score_ += score_delta;
if (weighted_score_delta > 0) {
weighted_score_ += weighted_score_delta;
frame.Client()->DidObserveLayoutShift(weighted_score_delta,
observed_input_or_scroll_);
}
}
SubmitPerformanceEntry(score_delta, had_recent_input);
TRACE_EVENT_INSTANT2(
"loading", "LayoutShift", TRACE_EVENT_SCOPE_THREAD, "data",
PerFrameTraceData(score_delta, weighted_score_delta, had_recent_input),
"frame", ToTraceValue(&frame));
if (ShouldLog(frame)) {
VLOG(1) << "in " << (frame.IsMainFrame() ? "" : "subframe ")
<< frame.GetDocument()->Url().GetString() << ", layout shift of "
<< score_delta
<< (had_recent_input ? " excluded by recent input" : " reported")
<< "; cumulative score is " << score_;
}
}
void LayoutShiftTracker::NotifyInput(const WebInputEvent& event) {
const WebInputEvent::Type type = event.GetType();
const bool saw_pointerdown = pointerdown_pending_data_.saw_pointerdown;
const bool pointerdown_became_tap =
saw_pointerdown && type == WebInputEvent::Type::kPointerUp;
const bool event_type_stops_pointerdown_buffering =
type == WebInputEvent::Type::kPointerUp ||
type == WebInputEvent::Type::kPointerCausedUaAction ||
type == WebInputEvent::Type::kPointerCancel;
// Only non-hovering pointerdown requires buffering.
const bool is_hovering_pointerdown =
type == WebInputEvent::Type::kPointerDown &&
static_cast<const WebPointerEvent&>(event).hovering;
const bool should_trigger_shift_exclusion =
type == WebInputEvent::Type::kMouseDown ||
type == WebInputEvent::Type::kKeyDown ||
type == WebInputEvent::Type::kRawKeyDown ||
// We need to explicitly include tap, as if there are no listeners, we
// won't receive the pointer events.
type == WebInputEvent::Type::kGestureTap || is_hovering_pointerdown ||
pointerdown_became_tap;
if (should_trigger_shift_exclusion) {
observed_input_or_scroll_ = true;
// This cancels any previously scheduled task from the same timer.
timer_.StartOneShot(kTimerDelay, FROM_HERE);
UpdateInputTimestamp(event.TimeStamp());
}
if (saw_pointerdown && event_type_stops_pointerdown_buffering) {
double score_delta = pointerdown_pending_data_.score_delta;
if (score_delta > 0)
ReportShift(score_delta, pointerdown_pending_data_.weighted_score_delta);
pointerdown_pending_data_ = PointerdownPendingData();
}
if (type == WebInputEvent::Type::kPointerDown && !is_hovering_pointerdown)
pointerdown_pending_data_.saw_pointerdown = true;
}
void LayoutShiftTracker::UpdateInputTimestamp(base::TimeTicks timestamp) {
if (!most_recent_input_timestamp_initialized_) {
most_recent_input_timestamp_ = timestamp;
most_recent_input_timestamp_initialized_ = true;
} else if (timestamp > most_recent_input_timestamp_) {
most_recent_input_timestamp_ = timestamp;
}
LocalFrame& frame = frame_view_->GetFrame();
frame.Client()->DidObserveInputForLayoutShiftTracking(timestamp);
}
void LayoutShiftTracker::NotifyScroll(mojom::blink::ScrollType scroll_type,
ScrollOffset delta) {
if (!enable_m90_improvements_)
frame_scroll_delta_ += delta;
// Only set observed_input_or_scroll_ for user-initiated scrolls, and not
// other scrolls such as hash fragment navigations.
if (scroll_type == mojom::blink::ScrollType::kUser ||
scroll_type == mojom::blink::ScrollType::kCompositor)
observed_input_or_scroll_ = true;
}
void LayoutShiftTracker::NotifyViewportSizeChanged() {
UpdateTimerAndInputTimestamp();
}
void LayoutShiftTracker::NotifyFindInPageInput() {
UpdateTimerAndInputTimestamp();
}
void LayoutShiftTracker::NotifyChangeEvent() {
UpdateTimerAndInputTimestamp();
}
void LayoutShiftTracker::UpdateTimerAndInputTimestamp() {
// This cancels any previously scheduled task from the same timer.
timer_.StartOneShot(kTimerDelay, FROM_HERE);
UpdateInputTimestamp(base::TimeTicks::Now());
}
double LayoutShiftTracker::LastInputTimestamp() const {
LocalDOMWindow* window = frame_view_->GetFrame().DomWindow();
if (!window)
return 0.0;
WindowPerformance* performance = DOMWindowPerformance::performance(*window);
DCHECK(performance);
return most_recent_input_timestamp_initialized_
? performance->MonotonicTimeToDOMHighResTimeStamp(
most_recent_input_timestamp_)
: 0.0;
}
std::unique_ptr<TracedValue> LayoutShiftTracker::PerFrameTraceData(
double score_delta,
double weighted_score_delta,
bool input_detected) const {
auto value = std::make_unique<TracedValue>();
value->SetDouble("score", score_delta);
value->SetDouble("weighted_score_delta", weighted_score_delta);
value->SetDouble("cumulative_score", score_);
value->SetDouble("overall_max_distance", overall_max_distance_);
value->SetDouble("frame_max_distance", frame_max_distance_);
RegionToTracedValue(region_, *value);
value->SetBoolean("is_main_frame", frame_view_->GetFrame().IsMainFrame());
value->SetBoolean("had_recent_input", input_detected);
value->SetDouble("last_input_timestamp", LastInputTimestamp());
AttributionsToTracedValue(*value);
return value;
}
void LayoutShiftTracker::AttributionsToTracedValue(TracedValue& value) const {
const Attribution* it = attributions_.begin();
if (!*it)
return;
bool should_include_names;
TRACE_EVENT_CATEGORY_GROUP_ENABLED(
TRACE_DISABLED_BY_DEFAULT("layout_shift.debug"), &should_include_names);
value.BeginArray("impacted_nodes");
while (it != attributions_.end() && it->node_id != kInvalidDOMNodeId) {
value.BeginDictionary();
value.SetInteger("node_id", it->node_id);
RectToTracedValue(it->old_visual_rect, value, "old_rect");
RectToTracedValue(it->new_visual_rect, value, "new_rect");
if (should_include_names) {
Node* node = DOMNodeIds::NodeForId(it->node_id);
value.SetString("debug_name", node ? node->DebugName() : "");
}
value.EndDictionary();
it++;
}
value.EndArray();
}
void LayoutShiftTracker::SendLayoutShiftRectsToHud(
const Vector<IntRect>& int_rects) {
// Store the layout shift rects in the HUD layer.
auto* cc_layer = frame_view_->RootCcLayer();
if (cc_layer && cc_layer->layer_tree_host()) {
if (!cc_layer->layer_tree_host()->GetDebugState().show_layout_shift_regions)
return;
if (cc_layer->layer_tree_host()->hud_layer()) {
WebVector<gfx::Rect> rects;
Region blink_region;
for (IntRect rect : int_rects)
blink_region.Unite(Region(rect));
for (const IntRect& rect : blink_region.Rects())
rects.emplace_back(rect);
cc_layer->layer_tree_host()->hud_layer()->SetLayoutShiftRects(
rects.ReleaseVector());
cc_layer->layer_tree_host()->hud_layer()->SetNeedsPushProperties();
}
}
}
void LayoutShiftTracker::Trace(Visitor* visitor) const {
visitor->Trace(frame_view_);
visitor->Trace(timer_);
}
ReattachHookScope::ReattachHookScope(const Node& node) : outer_(top_) {
if (node.GetLayoutObject())
top_ = this;
}
ReattachHookScope::~ReattachHookScope() {
top_ = outer_;
}
void ReattachHookScope::NotifyDetach(const Node& node) {
if (!top_)
return;
auto* layout_object = node.GetLayoutObject();
if (!layout_object || layout_object->ShouldSkipNextLayoutShiftTracking() ||
!layout_object->IsBox())
return;
auto& map = top_->geometries_before_detach_;
auto& fragment = layout_object->GetMutableForPainting().FirstFragment();
// Save the visual rect for restoration on future reattachment.
const auto& box = To<LayoutBox>(*layout_object);
PhysicalRect visual_overflow_rect = box.PreviousPhysicalVisualOverflowRect();
if (visual_overflow_rect.IsEmpty() && box.PreviousSize().IsEmpty())
return;
bool has_paint_offset_transform = false;
if (auto* properties = fragment.PaintProperties())
has_paint_offset_transform = properties->PaintOffsetTranslation();
map.Set(&node, Geometry{fragment.PaintOffset(), box.PreviousSize(),
visual_overflow_rect, has_paint_offset_transform});
}
void ReattachHookScope::NotifyAttach(const Node& node) {
if (!top_)
return;
auto* layout_object = node.GetLayoutObject();
if (!layout_object || !layout_object->IsBox())
return;
auto& map = top_->geometries_before_detach_;
// Restore geometries that was saved during detach. Note: this does not
// affect paint invalidation; we will fully invalidate the new layout object.
auto iter = map.find(&node);
if (iter == map.end())
return;
To<LayoutBox>(layout_object)
->GetMutableForPainting()
.SetPreviousGeometryForLayoutShiftTracking(
iter->value.paint_offset, iter->value.size,
iter->value.visual_overflow_rect);
layout_object->SetShouldSkipNextLayoutShiftTracking(false);
layout_object->SetShouldAssumePaintOffsetTranslationForLayoutShiftTracking(
iter->value.has_paint_offset_translation);
}
} // namespace blink
| 38.123821 | 80 | 0.713322 | iridium-browser |
1447f17c2f49ebbb4cb5b683ee0eebe5b5b9f186 | 2,299 | cc | C++ | net/instaweb/rewriter/css_minify_main.cc | PeterDaveHello/incubator-pagespeed-mod | 885f4653e204e1152cb3928f0755d93ec5fdceae | [
"Apache-2.0"
] | null | null | null | net/instaweb/rewriter/css_minify_main.cc | PeterDaveHello/incubator-pagespeed-mod | 885f4653e204e1152cb3928f0755d93ec5fdceae | [
"Apache-2.0"
] | null | null | null | net/instaweb/rewriter/css_minify_main.cc | PeterDaveHello/incubator-pagespeed-mod | 885f4653e204e1152cb3928f0755d93ec5fdceae | [
"Apache-2.0"
] | 1 | 2020-05-20T07:09:05.000Z | 2020-05-20T07:09:05.000Z | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#include <cstdio>
#include <cstdlib>
#include "net/instaweb/rewriter/public/css_minify.h"
#include "pagespeed/kernel/base/file_message_handler.h"
#include "pagespeed/kernel/base/file_system.h"
#include "pagespeed/kernel/base/file_writer.h"
#include "pagespeed/kernel/base/stdio_file_system.h"
#include "pagespeed/kernel/base/string.h"
#include "pagespeed/kernel/base/string_util.h"
#include "pagespeed/kernel/util/gflags.h"
namespace net_instaweb {
bool MinifyCss_main(int argc, char** argv) {
StdioFileSystem file_system;
FileMessageHandler handler(stderr);
FileSystem::OutputFile* error_file = file_system.Stderr();
// Load command line args.
static const char kUsage[] = "Usage: css_minify infilename\n";
if (argc != 2) {
error_file->Write(kUsage, &handler);
return false;
}
const char* infilename = argv[1];
// Read text from file.
GoogleString in_text;
if (!file_system.ReadFile(infilename, &in_text, &handler)) {
error_file->Write(StringPrintf(
"Failed to read input file %s\n", infilename), &handler);
return false;
}
FileWriter writer(file_system.Stdout());
FileWriter error_writer(error_file);
CssMinify minify(&writer, &handler);
minify.set_error_writer(&error_writer);
return minify.ParseStylesheet(in_text);
}
} // namespace net_instaweb
int main(int argc, char** argv) {
net_instaweb::ParseGflags(argv[0], &argc, &argv);
return net_instaweb::MinifyCss_main(argc, argv) ? EXIT_SUCCESS : EXIT_FAILURE;
}
| 32.842857 | 80 | 0.741192 | PeterDaveHello |
144aaae1348e035957ce4e9aca063e1b1d7d2b91 | 476 | cpp | C++ | Dataset/Leetcode/train/55/524.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | Dataset/Leetcode/train/55/524.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | Dataset/Leetcode/train/55/524.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | class Solution {
public:
bool XXX(vector<int>& nums) {
int len = nums.size()-1;
int max = 0;
for(int i = 0;i<len;i++)
{
for(int j = i;j<=(i+nums[i]);j++)
{
max = (j+nums[j])>=(max+nums[max]) ? j : max ;
if(max!= len && nums[max]==0) return false;
if(max+nums[max]>=len) return true;
}
i = max-1;
}
return max>=len;
}
};
| 21.636364 | 62 | 0.382353 | kkcookies99 |
144ac5a16e795cef4206813168d18a72b70a4aef | 1,318 | cpp | C++ | cppLearningExercises/Main.cpp | QueeniePun/cppLearningExercises | 4c4181573d1b7de9f67acdea1b0fd6d2245b8806 | [
"MIT"
] | null | null | null | cppLearningExercises/Main.cpp | QueeniePun/cppLearningExercises | 4c4181573d1b7de9f67acdea1b0fd6d2245b8806 | [
"MIT"
] | null | null | null | cppLearningExercises/Main.cpp | QueeniePun/cppLearningExercises | 4c4181573d1b7de9f67acdea1b0fd6d2245b8806 | [
"MIT"
] | null | null | null | #include <iostream>
#include "Chapter1Helper.h"
#include "Chapter2Helper.h"
#include "Chapter3Helper.h"
#include "Chapter4Helper.h"
#include "Chapter5Helper.h"
#include "Chapter6Helper.h"
#include "Chapter7Helper.h"
#include "Chapter8Helper.h"
#include "Chapter9Helper.h"
#include "Chapter10Helper.h"
#include "Chapter11Helper.h"
#include "Chapter12Helper.h"
#include "Chapter13Helper.h"
#include "Chapter14Helper.h"
#include "Chapter15Helper.h"
#include "Chapter16Helper.h"
#include "Chapter17Helper.h"
#include "Chapter18Helper.h"
#include "Chapter19Helper.h"
#include "Chapter19Helper.h"
#include "Chapter20Helper.h"
using namespace std;
// Programming Exercises
int main()
{
Chapter1Helper chapter1;
Chapter2Helper chapter2;
Chapter3Helper chapter3;
Chapter4Helper chapter4;
Chapter5Helper chapter5;
Chapter6Helper chapter6;
Chapter7Helper chapter7;
Chapter8Helper chapter8;
Chapter9Helper chapter9;
Chapter10Helper chapter10;
Chapter11Helper chapter11;
Chapter12Helper chapter12;
Chapter13Helper chapter13;
Chapter14Helper chapter14;
Chapter15Helper chapter15;
Chapter16Helper chapter16;
Chapter17Helper chapter17;
Chapter18Helper chapter18;
Chapter19Helper chapter19;
Chapter20Helper chapter20;
chapter20.RunExercise8();
}
| 24.407407 | 30 | 0.770865 | QueeniePun |
144bfa77bc363ad9f36acb87a40149d11826edb8 | 2,402 | cpp | C++ | project2D/CollisionManager.cpp | AlexMollard/Path-Finding | 76e96db39686f05995316d5147f2bbf746d8c4a0 | [
"MIT"
] | null | null | null | project2D/CollisionManager.cpp | AlexMollard/Path-Finding | 76e96db39686f05995316d5147f2bbf746d8c4a0 | [
"MIT"
] | null | null | null | project2D/CollisionManager.cpp | AlexMollard/Path-Finding | 76e96db39686f05995316d5147f2bbf746d8c4a0 | [
"MIT"
] | null | null | null | #include "CollisionManager.h"
#include <iostream>
CollisionManager::CollisionManager()
{
}
CollisionManager::~CollisionManager()
{
}
void CollisionManager::Update(float deltaTime)
{
for (int i = 0; i < _ObjectList.size(); i++)
{
GameObject* _Object = _ObjectList[i];
Collider* _FirstCollider = _Object->GetCollider();
for (int j = 0; j < _ObjectList.size(); j++)
{
GameObject* _OtherObject = _ObjectList[j];
Collider* _OtherCollider = _OtherObject->GetCollider();
if (!_OtherCollider)
continue;
if (i == j)
continue;
Vector2 _Min = _FirstCollider->GetMin();
Vector2 _Max = _FirstCollider->GetMax();
Vector2 _OtherMin = _OtherCollider->GetMin();
Vector2 _OtherMax = _OtherCollider->GetMax();
if (_Max.x > _OtherMin.x &&_Max.y > _OtherMin.y &&
_Min.x < _OtherMax.x &&_Min.y < _OtherMax.y)
{
if (_Object->GetName() == "Space_Ship" && _OtherObject->GetName() != "Bullet" )
_Object->OnCollision(_OtherObject);
if (_Object->GetName() == "Bullet" && _OtherObject->GetName() != "Space_Ship" && _OtherObject->GetName() != "Bullet")
_Object->OnCollision(_OtherObject);
}
}
}
}
void CollisionManager::Draw(aie::Renderer2D* renderer)
{
for (int i = 0; i < _ObjectList.size(); i++)
{
Collider* _collider = _ObjectList[i]->GetCollider();
Vector2 v2Min = _collider->GetMin();
Vector2 v2Max = _collider->GetMax();
renderer->drawLine(v2Min.x, v2Min.y, v2Min.x, v2Max.y);
renderer->drawLine(v2Min.x, v2Max.y, v2Max.x, v2Max.y);
renderer->drawLine(v2Max.x, v2Max.y, v2Max.x, v2Min.y);
renderer->drawLine(v2Max.x, v2Min.y, v2Min.x, v2Min.y);
if (_ObjectList[i]->HasCollider2())
{
Collider* _collider2 = _ObjectList[i]->GetCollider2();
Vector2 v2Min2 = _collider2->GetMin();
Vector2 v2Max2 = _collider2->GetMax();
renderer->drawLine(v2Min2.x, v2Min2.y, v2Min2.x, v2Max2.y);
renderer->drawLine(v2Min2.x, v2Max2.y, v2Max2.x, v2Max2.y);
renderer->drawLine(v2Max2.x, v2Max2.y, v2Max2.x, v2Min2.y);
renderer->drawLine(v2Max2.x, v2Min2.y, v2Min2.x, v2Min2.y);
}
}
}
void CollisionManager::AddObject(GameObject* object)
{
_ObjectList.push_back(object);
}
void CollisionManager::RemoveObject()
{
_ObjectList.pop_back();
}
GameObject* CollisionManager::GetObject()
{
return _ObjectList.back();
} | 26.395604 | 122 | 0.651124 | AlexMollard |
144ed606ae798bfde4f2919d70df7aa88c1ecb0a | 799 | cpp | C++ | chap01/print-frac.cpp | PacktPublishing/CPP-20-STL-Cookbook | 9310a24a6158bbb38d67b3a3c2ebc243dc1ee1e8 | [
"MIT"
] | 9 | 2021-11-05T10:54:46.000Z | 2022-03-18T23:58:06.000Z | chap01/print-frac.cpp | PacktPublishing/CPP-20-STL-Cookbook | 9310a24a6158bbb38d67b3a3c2ebc243dc1ee1e8 | [
"MIT"
] | null | null | null | chap01/print-frac.cpp | PacktPublishing/CPP-20-STL-Cookbook | 9310a24a6158bbb38d67b3a3c2ebc243dc1ee1e8 | [
"MIT"
] | 5 | 2021-12-19T07:23:08.000Z | 2022-02-04T23:24:43.000Z | // print-frac.cpp
// as of 2021-09-04 bw [bw.org]
#include <bwprint.h>
#include <string_view>
#include <string>
// support for std:: or fmt:: (reference implementation)
// see j.bw.org/fmt
#ifdef __cpp_lib_format
#define formatter std::formatter
#else
#define formatter fmt::formatter
#endif // __cpp_lib_format
using std::string_view;
using std::string;
using std::print;
struct Frac {
long n;
long d;
};
template<>
struct formatter<Frac> {
template<typename ParseContext>
constexpr auto parse(ParseContext& ctx) {
return ctx.begin();
}
template<typename FormatContext>
auto format(const Frac& f, FormatContext& ctx) {
return format_to(ctx.out(), "{0:d}/{1:d}", f.n, f.d);
}
};
int main() {
Frac f{ 5, 3 };
print("Frac: {}\n", f);
}
| 18.581395 | 61 | 0.647059 | PacktPublishing |
144ee5325cd11c827c601c2f031704313b482f6c | 269 | cpp | C++ | src/CWSDK/common/math.cpp | Mininoob/CWLevelSystem | ee5e06bcc0d1c4417d0a7eb2cf52897fa908e903 | [
"MIT"
] | 39 | 2021-02-28T04:17:16.000Z | 2022-02-23T14:25:41.000Z | src/CWSDK/common/math.cpp | Mininoob/CWLevelSystem | ee5e06bcc0d1c4417d0a7eb2cf52897fa908e903 | [
"MIT"
] | 16 | 2021-03-12T04:44:33.000Z | 2022-03-31T14:16:16.000Z | src/CWSDK/common/math.cpp | Mininoob/CWLevelSystem | ee5e06bcc0d1c4417d0a7eb2cf52897fa908e903 | [
"MIT"
] | 3 | 2021-09-10T14:19:08.000Z | 2021-12-19T20:45:04.000Z | #include "math.h"
i64 pydiv(i64 a, i64 b) {
i64 result = a / b;
if ((a < 0) ^ (b < 0)) {
if (pymod(a, b) != 0) {
result -= 1;
}
}
return result;
}
i64 pymod(i64 a, i64 b) {
i64 result = a % b;
if (result < 0) {
result = b + result;
}
return result;
}
| 14.157895 | 25 | 0.501859 | Mininoob |